Programs & Examples On #Private functions

How to write unit testing for Angular / TypeScript for private methods with Jasmine

call private method using square brackets

Ts file

class Calculate{
  private total;
  private add(a: number) {
      return a + total;
  }
}

spect.ts file

it('should return 5 if input 3 and 2', () => {
    component['total'] = 2;
    let result = component['add'](3);
    expect(result).toEqual(5);
});

How can I find the current OS in Python?

import os
print os.name

This gives you the essential information you will usually need. To distinguish between, say, different editions of Windows, you will have to use a platform-specific method.

How to display raw JSON data on a HTML page

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

You have to decide if:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.

If you give more details about your stack, it's easier to provide examples or resources.

EDIT: For client side JS highlighting you can try higlight.js, for instance.

What is "stdafx.h" used for in Visual Studio?

"Stdafx.h" is a precompiled header.It include file for standard system include files and for project-specific include files that are used frequently but are changed infrequently.which reduces compile time and Unnecessary Processing.

Precompiled Header stdafx.h is basically used in Microsoft Visual Studio to let the compiler know the files that are once compiled and no need to compile it from scratch. You can read more about it

http://www.cplusplus.com/articles/1TUq5Di1/

https://docs.microsoft.com/en-us/cpp/ide/precompiled-header-files?view=vs-2017

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

jQuery $.ajax request of dataType json will not retrieve data from PHP script

Well, it might help someone. I was stupid enough to put var_dump('testing'); in the function I was requesting JSON from to be sure the request was actually received. This obviously also echo's as part for the expected json response, and with dataType set to json defined, the request fails.

Is it possible to view RabbitMQ message contents directly from the command line?

you can use RabbitMQ API to get count or messages :

/api/queues/vhost/name/get

Get messages from a queue. (This is not an HTTP GET as it will alter the state of the queue.) You should post a body looking like:

{"count":5,"requeue":true,"encoding":"auto","truncate":50000}

count controls the maximum number of messages to get. You may get fewer messages than this if the queue cannot immediately provide them.

requeue determines whether the messages will be removed from the queue. If requeue is true they will be requeued - but their redelivered flag will be set. encoding must be either "auto" (in which case the payload will be returned as a string if it is valid UTF-8, and base64 encoded otherwise), or "base64" (in which case the payload will always be base64 encoded). If truncate is present it will truncate the message payload if it is larger than the size given (in bytes). truncate is optional; all other keys are mandatory.

Please note that the publish / get paths in the HTTP API are intended for injecting test messages, diagnostics etc - they do not implement reliable delivery and so should be treated as a sysadmin's tool rather than a general API for messaging.

http://hg.rabbitmq.com/rabbitmq-management/raw-file/rabbitmq_v3_1_3/priv/www/api/index.html

How to send UTF-8 email?

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter mail($to, $subject, $message, $headers)

If you user PEAR Mail::factory() code will be:

$smtp = Mail::factory('smtp', $params);

$mail = $smtp->send($to, $headers, $body);

selecting an entire row based on a variable excel vba

One needs to make sure the space between the variables and '&' sign. Check the image. (Red one showing invalid commands)

Error

The correct solution is

Dim copyToRow: copyToRow = 5      
Rows(copyToRow & ":" & copyToRow).Select

get the value of "onclick" with jQuery?

This works for me

 var link_click = $('#google').get(0).attributes.onclick.nodeValue;
 console.log(link_click);

How to export iTerm2 Profiles

Preferences -> General -> Load preferences from a custom folder or URL

First time you choose this, it will automatically save a preferences file into this folder called "com.googlecode.iterm2.plist"

Prepend text to beginning of string

ES6:

let after = 'something after';
let text = `before text ${after}`;

How to set a Default Route (To an Area) in MVC

I guess you want user to be redirected to ~/AreaZ URL once (s)he has visited ~/ URL. I'd achieve by means of the following code within your root HomeController.

public class HomeController
{
    public ActionResult Index()
    {
        return RedirectToAction("ActionY", "ControllerX", new { Area = "AreaZ" });
    }
}

And the following route in Global.asax.

routes.MapRoute(
    "Redirection to AreaZ",
    String.Empty,
    new { controller = "Home ", action = "Index" }
);

Setting a property by reflection with a string value

Using the following code should solve your issue:

item.SetProperty(prop.Name, Convert.ChangeType(item.GetProperty(prop.Name).ToString().Trim(), prop.PropertyType));

ImportError: No module named dateutil.parser

If you are using Pipenv, you may need to add this to your Pipfile:

[packages]
python-dateutil = "*"

How to merge a specific commit in Git

You can use git cherry-pick to apply a single commit by itself to your current branch.

Example: git cherry-pick d42c389f

Changing Locale within the app itself

After a good night of sleep, I found the answer on the Web (a simple Google search on the following line "getBaseContext().getResources().updateConfiguration(mConfig, getBaseContext().getResources().getDisplayMetrics());"), here it is :

link text => this link also shows screenshots of what is happening !

Density was the issue here, I needed to have this in the AndroidManifest.xml

<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true"
/>

The most important is the android:anyDensity =" true ".

Don't forget to add the following in the AndroidManifest.xml for every activity (for Android 4.1 and below):

android:configChanges="locale"

This version is needed when you build for Android 4.2 (API level 17) explanation here:

android:configChanges="locale|layoutDirection"

How to call a SOAP web service on Android

About a year ago I was reading this thread trying to figure out how to do SOAP calls on Android - the suggestions to build my own using HttpClient resulted in me building my own SOAP library for Android:

IceSoap

Basically it allows you to build up envelopes to send via a simple Java API, then automatically parses them into objects that you define via XPath... for example:

<Dictionary>
    <Id></Id>
    <Name></Name>
</Dictionary>

Becomes:

@XMLObject("//Dictionary")
public class Dictionary {
    @XMLField("Id")
    private String id;

    @XMLField("Name")
    private String name;
}

I was using it for my own project but I figured it might help some other people so I've spent some time separating it out and documenting it. I'd really love it if some of your poor souls who stumble on this thread while googling "SOAP Android" could give it a go and get some benefit.

Android ClassNotFoundException: Didn't find class on path

In my case it was proguard minification process that removed some important classes from my production apk.

The solution was to edit the proguard-rules.pro file and add the following:

-keep class com.someimportant3rdpartypackage.** { *; }

How do you move a file?

i think in the svn browser in tortoisesvn you can just drag it from one place to another.

MetadataException: Unable to load the specified metadata resource

In my case, this issue was related to renaming my model's edmx file... correcting the app.config connection string for the csdl/ssdl/msl files fixed my issue.

If you're using the EF 4.0 designer to generate your csdl/ssdl/msl, these 3 "files" will actually be stored within the model's main edmx file. In this case, the post by Waqas is pretty much on the mark. It's important to understand that "Model_Name" in his example will need to be changed to whatever the current name of your model's .edmx file (without the .edmx).

Also, if your edmx file is not at the root level of your project, you need to preface Model_Name with the relative path, e.g.

res://*/MyModel.WidgetModel.csdl|res://*/MyModel.WidgetModel.ssdl|res://*/MyModel.WidgetModel.msl

would specify the csdl/ssdl/msl xml is stored in the model file 'WidgetModel.edmx' which is stored in a folder named 'MyModel'.

How to clear the entire array?

For deleting a dynamic array in VBA use the instruction Erase.

Example:

Dim ArrayDin() As Integer    
ReDim ArrayDin(10)    'Dynamic allocation 
Erase ArrayDin        'Erasing the Array   

Hope this help!

Loading scripts after page load?

Here is a code I am using and which is working for me.

window.onload = function(){
    setTimeout(function(){
        var scriptElement=document.createElement('script');
        scriptElement.type = 'text/javascript';
        scriptElement.src = "vendor/js/jquery.min.js";
        document.head.appendChild(scriptElement);

        setTimeout(function() {
            var scriptElement1=document.createElement('script');
            scriptElement1.type = 'text/javascript';
            scriptElement1.src = "gallery/js/lc_lightbox.lite.min.js";
            document.head.appendChild(scriptElement1);
        }, 100);
        setTimeout(function() {
            $(document).ready(function(e){
                lc_lightbox('.elem', {
                    wrap_class: 'lcl_fade_oc',
                    gallery : true, 
                    thumb_attr: 'data-lcl-thumb', 
                    slideshow_time  : 3000,
                    skin: 'minimal',
                    radius: 0,
                    padding : 0,
                    border_w: 0,
                }); 
            });
        }, 200);

    }, 150);
};

File content into unix variable with newlines

Just if someone is interested in another option:

content=( $(cat test.txt) )

a=0
while [ $a -le ${#content[@]} ]
do
        echo ${content[$a]}
        a=$[a+1]
done

Regex to validate JSON

As was written above, if the language you use has a JSON-library coming with it, use it to try decoding the string and catch the exception/error if it fails! If the language does not (just had such a case with FreeMarker) the following regex could at least provide some very basic validation (it's written for PHP/PCRE to be testable/usable for more users). It's not as foolproof as the accepted solution, but also not that scary =):

~^\{\s*\".*\}$|^\[\n?\{\s*\".*\}\n?\]$~s

short explanation:

// we have two possibilities in case the string is JSON
// 1. the string passed is "just" a JSON object, e.g. {"item": [], "anotheritem": "content"}
// this can be matched by the following regex which makes sure there is at least a {" at the
// beginning of the string and a } at the end of the string, whatever is inbetween is not checked!

^\{\s*\".*\}$

// OR (character "|" in the regex pattern)
// 2. the string passed is a JSON array, e.g. [{"item": "value"}, {"item": "value"}]
// which would be matched by the second part of the pattern above

^\[\n?\{\s*\".*\}\n?\]$

// the s modifier is used to make "." also match newline characters (can happen in prettyfied JSON)

if I missed something that would break this unintentionally, I'm grateful for comments!

Determine function name from within that function (without using traceback)

I do my own approach used for calling super with safety inside multiple inheritance scenario (I put all the code)

def safe_super(_class, _inst):
    """safe super call"""
    try:
        return getattr(super(_class, _inst), _inst.__fname__)
    except:
        return (lambda *x,**kx: None)


def with_name(function):
    def wrap(self, *args, **kwargs):
        self.__fname__ = function.__name__
        return function(self, *args, **kwargs)
return wrap

sample usage:

class A(object):

    def __init__():
        super(A, self).__init__()

    @with_name
    def test(self):
        print 'called from A\n'
        safe_super(A, self)()

class B(object):

    def __init__():
        super(B, self).__init__()

    @with_name
    def test(self):
        print 'called from B\n'
        safe_super(B, self)()

class C(A, B):

    def __init__():
        super(C, self).__init__()

    @with_name
    def test(self):
        print 'called from C\n'
        safe_super(C, self)()

testing it :

a = C()
a.test()

output:

called from C
called from A
called from B

Inside each @with_name decorated method you have access to self.__fname__ as the current function name.

How to read HDF5 files in Python

Reading the file

import h5py

f = h5py.File(file_name, mode)

Studying the structure of the file by printing what HDF5 groups are present

for key in f.keys():
    print(key) #Names of the groups in HDF5 file.

Extracting the data

#Get the HDF5 group
group = f[key]

#Checkout what keys are inside that group.
for key in group.keys():
    print(key)

data = group[some_key_inside_the_group].value
#Do whatever you want with data

#After you are done
f.close()

ASP.NET Web API : Correct way to return a 401/unauthorised response

Just return the following:

return Unauthorized();

How to prevent a dialog from closing when a button is clicked

Here's something if you are using DialogFragment - which is the recommended way to handle Dialogs anyway.

What happens with AlertDialog's setButton() method (and I imagine the same with AlertDialogBuilder's setPositiveButton() and setNegativeButton()) is that the button you set (e.g. AlertDialog.BUTTON_POSITIVE) with it will actually trigger TWO different OnClickListener objects when pressed.

The first being DialogInterface.OnClickListener, which is a parameter to setButton(), setPositiveButton(), and setNegativeButton().

The other is View.OnClickListener, which will be set to automatically dismiss your AlertDialog when any of its button is pressed - and is set by AlertDialog itself.

What you can do is to use setButton() with null as the DialogInterface.OnClickListener, to create the button, and then call your custom action method inside View.OnClickListener. For example,

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    AlertDialog alertDialog = new AlertDialog(getActivity());
    // set more items...
    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", null);

    return alertDialog;
}

Then, you may override the default AlertDialog's buttons' View.OnClickListener (which would otherwise dismiss the dialog) in the DialogFragment's onResume() method:

@Override
public void onResume()
{
    super.onResume();
    AlertDialog alertDialog = (AlertDialog) getDialog();
    Button okButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
    okButton.setOnClickListener(new View.OnClickListener() { 
        @Override
        public void onClick(View v)
        {
            performOkButtonAction();
        }
    });
}

private void performOkButtonAction() {
    // Do your stuff here
}

You will need to set this in the onResume() method because getButton() will return null until after the dialog has been shown!

This should cause your custom action method to only be called once, and the dialog won't be dismissed by default.

Convert number to varchar in SQL with formatting

You can try this

DECLARE @Table TABLE(
        Val INT
)

INSERT INTO @Table SELECT 3
INSERT INTO @Table SELECT 30

DECLARE @NumberPrefix INT
SET @NumberPrefix = 2
SELECT  REPLICATE('0', @NumberPrefix - LEN(Val)) + CAST(Val AS VARCHAR(10))
FROM    @Table

Moment.js - two dates difference in number of days

_x000D_
_x000D_
$('#test').click(function() {_x000D_
  var todayDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
  var endDate = moment("08.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
  var result = 'Diff: ' + todayDate.diff(endDate, 'days');_x000D_
_x000D_
  $('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #ffb;_x000D_
  padding: 10px;_x000D_
  border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
_x000D_
_x000D_

SQL Server convert select a column and convert it to a string

Use LISTAGG function, ex. SELECT LISTAGG(colmn) FROM table_name;

Count number of rows matching a criteria

With dplyr package, Use

 nrow(filter(mydata, sCode == "CA")),

All the solutions provided here gave me same error as multi-sam but that one worked.

Difference in days between two dates in Java?

The diff / (24 * etc) does not take Timezone into account, so if your default timezone has a DST in it, it can throw the calculation off.

This link has a nice little implementation.

Here is the source of the above link in case the link goes down:

/** Using Calendar - THE CORRECT WAY**/  
public static long daysBetween(Calendar startDate, Calendar endDate) {  
  //assert: startDate must be before endDate  
  Calendar date = (Calendar) startDate.clone();  
  long daysBetween = 0;  
  while (date.before(endDate)) {  
    date.add(Calendar.DAY_OF_MONTH, 1);  
    daysBetween++;  
  }  
  return daysBetween;  
}  

and

/** Using Calendar - THE CORRECT (& Faster) WAY**/  
public static long daysBetween(final Calendar startDate, final Calendar endDate)
{
  //assert: startDate must be before endDate  
  int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;  
  long endInstant = endDate.getTimeInMillis();  
  int presumedDays = 
    (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);  
  Calendar cursor = (Calendar) startDate.clone();  
  cursor.add(Calendar.DAY_OF_YEAR, presumedDays);  
  long instant = cursor.getTimeInMillis();  
  if (instant == endInstant)  
    return presumedDays;

  final int step = instant < endInstant ? 1 : -1;  
  do {  
    cursor.add(Calendar.DAY_OF_MONTH, step);  
    presumedDays += step;  
  } while (cursor.getTimeInMillis() != endInstant);  
  return presumedDays;  
}

Styling Google Maps InfoWindow

Google wrote some code to assist with this. Here are some examples: Example using InfoBubble, Styled markers and Info Window Custom (using OverlayView).

The code in the links above take different routes to achieve similar results. The gist of it is that it is not easy to style InfoWindows directly, and it might be easier to use the additional InfoBubble class instead of InfoWindow, or to override GOverlay. Another option would be to modify the elements of the InfoWindow using javascript (or jQuery), like later ATOzTOA suggested.

Possibly the simplest of these examples is using InfoBubble instead of InfoWindow. InfoBubble is available by importing this file (which you should host yourself): http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/src/infobubble.js

InfoBubble's Github project page.

InfoBubble is very stylable, compared to InfoWindow:

 infoBubble = new InfoBubble({
      map: map,
      content: '<div class="mylabel">The label</div>',
      position: new google.maps.LatLng(-32.0, 149.0),
      shadowStyle: 1,
      padding: 0,
      backgroundColor: 'rgb(57,57,57)',
      borderRadius: 5,
      arrowSize: 10,
      borderWidth: 1,
      borderColor: '#2c2c2c',
      disableAutoPan: true,
      hideCloseButton: true,
      arrowPosition: 30,
      backgroundClassName: 'transparent',
      arrowStyle: 2
});

infoBubble.open();

You can also call it with a given map and marker to open on:

infoBubble.open(map, marker);

As another example, the Info Window Custom example extends the GOverlay class from the Google Maps API and uses this as a base for creating a more flexible info window. It first creates the class:

/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Map} map The map on which to display this InfoBox.
 * @param {Object} opts Passes configuration options - content,
 *   offsetVertical, offsetHorizontal, className, height, width
 */
function InfoBox(opts) {
  google.maps.OverlayView.call(this);
  this.latlng_ = opts.latlng;
  this.map_ = opts.map;
  this.offsetVertical_ = -195;
  this.offsetHorizontal_ = 0;
  this.height_ = 165;
  this.width_ = 266;

  var me = this;
  this.boundsChangedListener_ =
    google.maps.event.addListener(this.map_, "bounds_changed", function() {
      return me.panMap.apply(me);
    });

  // Once the properties of this OverlayView are initialized, set its map so
  // that we can display it.  This will trigger calls to panes_changed and
  // draw.
  this.setMap(this.map_);
}

after which it proceeds to override GOverlay:

InfoBox.prototype = new google.maps.OverlayView();

You should then override the methods you need: createElement, draw, remove and panMap. It gets rather involved, but in theory you are just drawing a div on the map yourself now, instead of using a normal Info Window.

How do you do relative time in Rails?

I've written this, but have to check the existing methods mentioned to see if they are better.

module PrettyDate
  def to_pretty
    a = (Time.now-self).to_i

    case a
      when 0 then 'just now'
      when 1 then 'a second ago'
      when 2..59 then a.to_s+' seconds ago' 
      when 60..119 then 'a minute ago' #120 = 2 minutes
      when 120..3540 then (a/60).to_i.to_s+' minutes ago'
      when 3541..7100 then 'an hour ago' # 3600 = 1 hour
      when 7101..82800 then ((a+99)/3600).to_i.to_s+' hours ago' 
      when 82801..172000 then 'a day ago' # 86400 = 1 day
      when 172001..518400 then ((a+800)/(60*60*24)).to_i.to_s+' days ago'
      when 518400..1036800 then 'a week ago'
      else ((a+180000)/(60*60*24*7)).to_i.to_s+' weeks ago'
    end
  end
end

Time.send :include, PrettyDate

Search and replace a particular string in a file using Perl

Quick and dirty:

#!/usr/bin/perl -w

use strict;

open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);

foreach(@lines) {
   $_ =~ s/<PREF>/ABCD/g;
}

open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);

Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

Unfortunately the link in the exception text, http://go.microsoft.com/fwlink/?LinkId=70353, is broken. However, it used to lead to http://msdn.microsoft.com/en-us/library/ms733768.aspx which explains how to set the permissions.

It basically informs you to use the following command:

netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

You can get more help on the details using the help of netsh

For example: netsh http add ?

Gives help on the http add command.

Plot a bar using matplotlib using a dictionary

Why not just:

import seaborn as sns

sns.barplot(list(D.keys()), list(D.values()))

WCF service maxReceivedMessageSize basicHttpBinding issue

Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:

<services>
  <service name="Service.IService">
    <clear />
    <endpoint binding="basicHttpBinding" contract="Service.IService" />
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
        maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </binding>
  </basicHttpBinding>
  <webHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
  </webHttpBinding>
</bindings>

Also note that I removed the bindingConfiguration attribute from the endpoint node. Otherwise you would get an exception.

This same solution was found here : Problem with large requests in WCF

How do I redirect a user when a button is clicked?

If, like me, you don't like to rely on JavaScript for links on buttons. You can also use a anchor and style it like your buttons using CSS.

<a href="/Controller/View" class="Button">Text</a>

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

Read/Parse text file line by line in VBA

You Can use this code to read line by line in text file and You could also check about the first character is "*" then you can leave that..

Public Sub Test()

    Dim ReadData as String

    Open "C:\satheesh\myfile\file.txt" For Input As #1

    Do Until EOF(1) 
       Line Input #1, ReadData 'Adding Line to read the whole line, not only first 128 positions
    If Not Left(ReadData, 1) = "*" then
       '' you can write the variable ReadData into the database or file
    End If 

    Loop

    Close #1

End Sub

How do I add slashes to a string in Javascript?

A string can be escaped comprehensively and compactly using JSON.stringify. It is part of JavaScript as of ECMAScript 5 and supported by major newer browser versions.

str = JSON.stringify(String(str));
str = str.substring(1, str.length-1);

Using this approach, also special chars as the null byte, unicode characters and line breaks \r and \n are escaped properly in a relatively compact statement.

How to drop columns using Rails migration

Generate a migration to remove a column such that if it is migrated (rake db:migrate), it should drop the column. And it should add column back if this migration is rollbacked (rake db:rollback).

The syntax:

remove_column :table_name, :column_name, :type

Removes column, also adds column back if migration is rollbacked.

Example:

remove_column :users, :last_name, :string

Note: If you skip the data_type, the migration will remove the column successfully but if you rollback the migration it will throw an error.

Refresh Page C# ASP.NET

You shouldn't use:

Page.Response.Redirect(Page.Request.Url.ToString(), true);

because this might cause a runtime error.

A better approach is:

Page.Response.Redirect(Page.Request.Url.ToString(), false);
        Context.ApplicationInstance.CompleteRequest();

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

Unable to open debugger port in IntelliJ

I had the same problem and this solution also did the trick for me: Provide the IP 127.0.0.1 in the Intellij Debug configuration instead of the host name "localhost", in case you're using this hostname.

Can I call a function of a shell script from another shell script?

If you define

    #!/bin/bash
        fun1(){
          echo "Fun1 from file1 $1"
        }
fun1 Hello
. file2 
fun1 Hello
exit 0

in file1(chmod 750 file1) and file2

   fun1(){
      echo "Fun1 from file2 $1"
    }
    fun2(){
      echo "Fun1 from file1 $1"
    }

and run ./file2 you'll get Fun1 from file1 Hello Fun1 from file2 Hello Surprise!!! You overwrite fun1 in file1 with fun1 from file2... So as not to do so you must

declare -f pr_fun1=$fun1
. file2
unset -f fun1
fun1=$pr_fun1
unset -f pr_fun1
fun1 Hello

it's save your previous definition for fun1 and restore it with the previous name deleting not needed imported one. Every time you import functions from another file you may remember two aspects:

  1. you may overwrite existing ones with the same names(if that the thing you want you must preserve them as described above)
  2. import all content of import file(functions and global variables too) Be careful! It's dangerous procedure

What I can do to resolve "1 commit behind master"?

  1. Clone your fork:

  2. Add remote from original repository in your forked repository:

    • cd into/cloned/fork-repo
    • git remote add upstream git://github.com/ORIGINAL-DEV-USERNAME/REPO-YOU-FORKED-FROM.git
    • git fetch upstream
  3. Updating your fork from original repo to keep up with their changes:

    • git pull upstream master
    • git push

Could not load file or assembly 'System.Data.SQLite'

In our case didn't work because our production server has missing

Microsoft Visual C++ 2010 SP1 Redistributable Package (x86)

We installed it and all work fine. The Application Pool must have Enable 32-bit Applications set to true and you must the x86 version of the library

json parsing error syntax error unexpected end of input

This error occurs on an empty JSON file reading.

To avoid this error in NodeJS I'm checking the file's size:

const { size } = fs.statSync(JSON_FILE);
const content = size ? JSON.parse(fs.readFileSync(JSON_FILE)) : DEFAULT_VALUE;

String to HtmlDocument

For those who don't want to use HTML agility pack and want to get HtmlDocument from string using native .net code only here is a good article on how to convert string to HtmlDocument

Here is the code block to use

public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
        {
            WebBrowser browser = new WebBrowser();
            browser.ScriptErrorsSuppressed = true;
            browser.DocumentText = html;
            browser.Document.OpenNew(true);
            browser.Document.Write(html);
            browser.Refresh();
            return browser.Document;
        }

How to connect mySQL database using C++

Found here:

/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

/*
  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
   AS _message'..." << endl;

try {
  sql::Driver *driver;
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;

  /* Create a connection */
  driver = get_driver_instance();
  con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
  /* Connect to the MySQL test database */
  con->setSchema("test");

  stmt = con->createStatement();
  res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
  while (res->next()) {
    cout << "\t... MySQL replies: ";
    /* Access column data by alias or column name */
    cout << res->getString("_message") << endl;
    cout << "\t... MySQL says it again: ";
    /* Access column fata by numeric offset, 1 is the first column */
    cout << res->getString(1) << endl;
  }
  delete res;
  delete stmt;
  delete con;

} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line " »
     << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}

cout << endl;

return EXIT_SUCCESS;
}

Creating a LINQ select from multiple tables

change

select op) 

to

select new { op, pg })

Android Studio: Can't start Git

In Android Studio, goto File->Settings->Version Control->Git. Set the 'Path to Git Executable' to point to git.exe. Verify by clicking Test.

How to change legend title in ggplot

None of the above code worked for me.

Here's what I found and it worked.

labs(color = "sale year")

You can also give a space between the title and the display by adding \n at the end.

labs(color = 'sale year\n")

jQuery click event not working after adding class

Based on @Arun P Johny this is how you do it for an input:

<input type="button" class="btEdit" id="myButton1">

This is how I got it in jQuery:

$(document).on('click', "input.btEdit", function () {
    var id = this.id;
    console.log(id);
});

This will log on the console: myButton1. As @Arun said you need to add the event dinamically, but in my case you don't need to call the parent first.

UPDATE

Though it would be better to say:

$(document).on('click', "input.btEdit", function () {
    var id = $(this).id;
    console.log(id);
});

Since this is JQuery's syntax, even though both will work.

Recreate the default website in IIS

I suppose you want to publish and access your applications/websites from LAN; probably as virtual directories under the default website.The steps could vary depending on your IIS version, but basically it comes down to these steps:

Restore your "Default Website" Website :

  1. create a new website

  2. set "Default Website" as its name

  3. In the Binding section (bottom panel), enter your local IP address in the "IP Address" edit.

  4. Keep the "Host" edit empty

that's it: now whenever you type your local ip address in your browser, you will get the website you just added. Now if you want to access any of your other webapplications/websites from LAN, just add a virtual application under your default website pointing to the directory containing your published application/website. Now you can type : http://yourLocalIPAddress/theNameOfYourApplication to access it from your LAN.

What is the difference between Cloud, Grid and Cluster?

Cloud: the hardware running the application scales to meet the demand (potentially crossing multiple machines, networks, etc).

Grid: the application scales to take as much hardware as possible (for example in the hope of finding extra-terrestrial intelligence).

Cluster: this is an old term referring to one OS instance or one DB instance installed across multiple machines. It was done with special OS handling, proprietary drivers, low latency network cards with fat cables, and various hardware bedfellows.

(We love you SGI, but notice that "Cloud" and "Grid" are available to the little guy and your NUMAlink never has been...)

Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

^[0-9][0-9]?[^A-Za-z0-9]?po$

You can test it here: http://www.regextester.com/

To use this in C#,

Regex r = new Regex(@"^[0-9][0-9]?[^A-Za-z0-9]?po$");
if (r.Match(someText).Success) {
   //Do Something
}

Remember, @ is a useful symbol that means the parser takes the string literally (eg, you don't need to write \\ for one backslash)

Why does this AttributeError in python occur?

AttributeError is raised when attribute of the object is not available.

An attribute reference is a primary followed by a period and a name:

attributeref ::= primary "." identifier

To return a list of valid attributes for that object, use dir(), e.g.:

dir(scipy)

So probably you need to do simply: import scipy.sparse

MySQL user DB does not have password columns - Installing MySQL on OSX

This error happens if you did not set the password on install, in this case the mysql using unix-socket plugin.

But if delete the plugin link from settings (table mysql.user) will other problem. This does not fix the problem and creates another problem. To fix the deleted link and set password ("PWD") do:

1) Run with --skip-grant-tables as said above.

If it doesnt works then add the string skip-grant-tables in section [mysqld] of /etc/mysql/mysql.conf.d/mysqld.cnf. Then do sudo service mysql restart.

2) Run mysql -u root -p, then (change "PWD"):

update mysql.user 
    set authentication_string=PASSWORD("PWD"), plugin="mysql_native_password" 
    where User='root' and Host='localhost';    
flush privileges;

quit

then sudo service mysql restart. Check: mysql -u root -p.

Before restart remove that string from file mysqld.cnf, if you set it there.

How to set Google Chrome in WebDriver

Mac OS: You have to install ChromeDriver first:

brew cask install chromedriver

It will be copied to /usr/local/bin/chromedriver. Then you can use it in java code classes.

How to use a findBy method with comparative criteria

This is an example using the Expr() Class - I needed this too some days ago and it took me some time to find out what is the exact syntax and way of usage:

/**
 * fetches Products that are more expansive than the given price
 * 
 * @param int $price
 * @return array
 */
public function findProductsExpensiveThan($price)
{
  $em = $this->getEntityManager();
  $qb = $em->createQueryBuilder();

  $q  = $qb->select(array('p'))
           ->from('YourProductBundle:Product', 'p')
           ->where(
             $qb->expr()->gt('p.price', $price)
           )
           ->orderBy('p.price', 'DESC')
           ->getQuery();

  return $q->getResult();
}

TextView bold via xml file?

Just you need to use 

//for bold
android:textStyle="bold"

//for italic
android:textStyle="italic"

//for normal
android:textStyle="normal"

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    android:text="@string/userName"
    android:layout_gravity="left"
    android:textSize="16sp"
/>

Docker - Cannot remove dead container

I got the same issue and both answers did not help.

What helped for me is just creating the directories that are missing and them remove them:

mkdir /var/lib/docker/devicemapper/mnt/656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3
mkdir /var/lib/docker/devicemapper/mnt/656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3-init
docker rm 656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3

*.h or *.hpp for your class definitions

You can call your includes whatever you like.

Just need to specify that full name in the #include.

I suggest that if you work with C to use .h and when with C++ to use .hpp.

It is in the end just a convention.

How to insert data into SQL Server

I think you lack to pass Connection object to your command object. and it is much better if you will use command and parameters for that.

using (SqlConnection connection = new SqlConnection("ConnectionStringHere"))
{
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;            // <== lacking
        command.CommandType = CommandType.Text;
        command.CommandText = "INSERT into tbl_staff (staffName, userID, idDepartment) VALUES (@staffName, @userID, @idDepart)";
        command.Parameters.AddWithValue("@staffName", name);
        command.Parameters.AddWithValue("@userID", userId);
        command.Parameters.AddWithValue("@idDepart", idDepart);

        try
        {
            connection.Open();
            int recordsAffected = command.ExecuteNonQuery();
        }
        catch(SqlException)
        {
            // error here
        }
        finally
        {
            connection.Close();
        }
    }
}

Get property value from string using reflection

The following code is a Recursive method for displaying the entire hierarchy of all of the Property Names and Values contained in an object's instance. This method uses a simplified version of AlexD's GetPropertyValue() answer above in this thread. Thanks to this discussion thread, I was able to figure out how to do this!

For example, I use this method to show an explosion or dump of all of the properties in a WebService response by calling the method as follows:

PropertyValues_byRecursion("Response", response, false);

public static object GetPropertyValue(object srcObj, string propertyName)
{
  if (srcObj == null) 
  {
    return null; 
  }
  PropertyInfo pi = srcObj.GetType().GetProperty(propertyName.Replace("[]", ""));
  if (pi == null)
  {
    return null;
  }
  return pi.GetValue(srcObj);
}

public static void PropertyValues_byRecursion(string parentPath, object parentObj, bool showNullValues)
{
  /// Processes all of the objects contained in the parent object.
  ///   If an object has a Property Value, then the value is written to the Console
  ///   Else if the object is a container, then this method is called recursively
  ///       using the current path and current object as parameters

  // Note:  If you do not want to see null values, set showNullValues = false

  foreach (PropertyInfo pi in parentObj.GetType().GetTypeInfo().GetProperties())
  {
    // Build the current object property's namespace path.  
    // Recursion extends this to be the property's full namespace path.
    string currentPath = parentPath + "." + pi.Name;

    // Get the selected property's value as an object
    object myPropertyValue = GetPropertyValue(parentObj, pi.Name);
    if (myPropertyValue == null)
    {
      // Instance of Property does not exist
      if (showNullValues)
      {
        Console.WriteLine(currentPath + " = null");
        // Note: If you are replacing these Console.Write... methods callback methods,
        //       consider passing DBNull.Value instead of null in any method object parameters.
      }
    }
    else if (myPropertyValue.GetType().IsArray)
    {
      // myPropertyValue is an object instance of an Array of business objects.
      // Initialize an array index variable so we can show NamespacePath[idx] in the results.
      int idx = 0;
      foreach (object business in (Array)myPropertyValue)
      {
        if (business == null)
        {
          // Instance of Property does not exist
          // Not sure if this is possible in this context.
          if (showNullValues)
          {
            Console.WriteLine(currentPath  + "[" + idx.ToString() + "]" + " = null");
          }
        }
        else if (business.GetType().IsArray)
        {
          // myPropertyValue[idx] is another Array!
          // Let recursion process it.
          PropertyValues_byRecursion(currentPath + "[" + idx.ToString() + "]", business, showNullValues);
        }
        else if (business.GetType().IsSealed)
        {
          // Display the Full Property Path and its Value
          Console.WriteLine(currentPath + "[" + idx.ToString() + "] = " + business.ToString());
        }
        else
        {
          // Unsealed Type Properties can contain child objects.
          // Recurse into my property value object to process its properties and child objects.
          PropertyValues_byRecursion(currentPath + "[" + idx.ToString() + "]", business, showNullValues);
        }
        idx++;
      }
    }
    else if (myPropertyValue.GetType().IsSealed)
    {
      // myPropertyValue is a simple value
      Console.WriteLine(currentPath + " = " + myPropertyValue.ToString());
    }
    else
    {
      // Unsealed Type Properties can contain child objects.
      // Recurse into my property value object to process its properties and child objects.
      PropertyValues_byRecursion(currentPath, myPropertyValue, showNullValues);
    }
  }
}

https connection using CURL from command line

I actually had this kind of problem and I solve it by these steps:

  1. Get the bundle of root CA certificates from here: https://curl.haxx.se/ca/cacert.pem and save it on local

  2. Find the php.ini file

  3. Set the curl.cainfo to be the path of the certificates. So it will something like:

curl.cainfo = /path/of/the/keys/cacert.pem

How to create a sticky footer that plays well with Bootstrap 3

I've been searching for a simple way to make the sticky footer works. I just applied a class="navbar-fixed-bottom" and it worked instantly Only thing to keep in mind it's to adjust the settings of the footer for mobile devices. Cheers!

Why does Firebug say toFixed() is not a function?

That is because Low is a string.

.toFixed() only works with a number.


Try doing:

Low = parseFloat(Low).toFixed(..);

UUID max character length

Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).

Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.

SSIS Excel Connection Manager failed to Connect to the Source

The workaround is, I I save the excel file as excel 97-2003 then it works fine

Get the IP address of the machine

As the question specifies Linux, my favourite technique for discovering the IP-addresses of a machine is to use netlink. By creating a netlink socket of the protocol NETLINK_ROUTE, and sending an RTM_GETADDR, your application will received a message(s) containing all available IP addresses. An example is provided here.

In order to simply parts of the message handling, libmnl is convenient. If you are curios in figuring out more about the different options of NETLINK_ROUTE (and how they are parsed), the best source is the source code of iproute2 (especially the monitor application) as well as the receive functions in the kernel. The man page of rtnetlink also contains useful information.

How can I format bytes a cell in Excel as KB, MB, GB etc?

I don't know of a way to make it show you binary gigabytes (multiples of 1024*1024*1024) but you can make it show you decimal gigabytes using a format like:

0.00,,,"Gb"

How can I get the browser's scrollbar sizes?

Here's the more concise and easy to read solution based on offset width difference:

function getScrollbarWidth(): number {

  // Creating invisible container
  const outer = document.createElement('div');
  outer.style.visibility = 'hidden';
  outer.style.overflow = 'scroll'; // forcing scrollbar to appear
  outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
  document.body.appendChild(outer);

  // Creating inner element and placing it in the container
  const inner = document.createElement('div');
  outer.appendChild(inner);

  // Calculating difference between container's full width and the child width
  const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);

  // Removing temporary elements from the DOM
  outer.parentNode.removeChild(outer);

  return scrollbarWidth;

}

See the JSFiddle.

PowerShell - Start-Process and Cmdline Switches

Unless the OP is using PowerShell Community Extensions which does provide a Start-Process cmdlet along with a bunch of others. If this the case then Glennular's solution works a treat since it matches the positional parameters of pscx\start-process : -path (position 1) -arguments (positon 2).

How to move an entire div element up x pixels?

$('#div_id').css({marginTop: '-=15px'});

This will alter the css for the element with the id "div_id"

To get the effect you want I recommend adding the code above to a callback function in your animation (that way the div will be moved up after the animation is complete):

$('#div_id').animate({...}, function () {
    $('#div_id').css({marginTop: '-=15px'});
});

And of course you could animate the change in margin like so:

$('#div_id').animate({marginTop: '-=15px'});

Here are the docs for .css() in jQuery: http://api.jquery.com/css/

And here are the docs for .animate() in jQuery: http://api.jquery.com/animate/

In php, is 0 treated as empty?

You need to use isset() to check whether value is set.

Regular expression matching a multiline block of text

This will work:

>>> import re
>>> rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE)
>>> rx_blanks=re.compile(r"\W+") # to remove blanks and newlines
>>> text="""Some varying text1
...
... AAABBBBBBCCCCCCDDDDDDD
... EEEEEEEFFFFFFFFGGGGGGG
... HHHHHHIIIIIJJJJJJJKKKK
...
... Some varying text 2
...
... LLLLLMMMMMMNNNNNNNOOOO
... PPPPPPPQQQQQQRRRRRRSSS
... TTTTTUUUUUVVVVVVWWWWWW
... """
>>> for match in rx_sequence.finditer(text):
...   title, sequence = match.groups()
...   title = title.strip()
...   sequence = rx_blanks.sub("",sequence)
...   print "Title:",title
...   print "Sequence:",sequence
...   print
...
Title: Some varying text1
Sequence: AAABBBBBBCCCCCCDDDDDDDEEEEEEEFFFFFFFFGGGGGGGHHHHHHIIIIIJJJJJJJKKKK

Title: Some varying text 2
Sequence: LLLLLMMMMMMNNNNNNNOOOOPPPPPPPQQQQQQRRRRRRSSSTTTTTUUUUUVVVVVVWWWWWW

Some explanation about this regular expression might be useful: ^(.+?)\n\n((?:[A-Z]+\n)+)

  • The first character (^) means "starting at the beginning of a line". Be aware that it does not match the newline itself (same for $: it means "just before a newline", but it does not match the newline itself).
  • Then (.+?)\n\n means "match as few characters as possible (all characters are allowed) until you reach two newlines". The result (without the newlines) is put in the first group.
  • [A-Z]+\n means "match as many upper case letters as possible until you reach a newline. This defines what I will call a textline.
  • ((?:textline)+) means match one or more textlines but do not put each line in a group. Instead, put all the textlines in one group.
  • You could add a final \n in the regular expression if you want to enforce a double newline at the end.
  • Also, if you are not sure about what type of newline you will get (\n or \r or \r\n) then just fix the regular expression by replacing every occurrence of \n by (?:\n|\r\n?).

convert double to int

label8.Text = "" + years.ToString("00") + " years";

when you want to send it to a label, or something, and you don't want any fractional component, this is the best way

label8.Text = "" + years.ToString("00.00") + " years";

if you want with only 2, and it's always like that

Got a NumberFormatException while trying to parse a text file for objects

NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc" value to integer..

this is valid string is eg"123". in your case split by space..

split(" "); will split line by " " by space..

What is EOF in the C programming language?

#include <stdio.h>

int main() {
    int c;
    while((c = getchar()) != EOF) { 
        putchar(c);
    }    
    printf("%d  at EOF\n", c);
}

modified the above code to give more clarity on EOF, Press Ctrl+d and putchar is used to print the char avoid using printf within while loop.

How to read all files in a folder from Java?

import java.io.File;


public class Test {

public void test1() {
    System.out.println("TEST 1");
}

public static void main(String[] args) throws SecurityException, ClassNotFoundException{

    File actual = new File("src");
    File list[] = actual.listFiles();
    for(int i=0; i<list.length; i++){
        String substring = list[i].getName().substring(0, list[i].getName().indexOf("."));
        if(list[i].isFile() && list[i].getName().contains(".java")){
                if(Class.forName(substring).getMethods()[0].getName().contains("main")){
                    System.out.println("CLASS NAME "+Class.forName(substring).getName());
                }

         }
    }

}
}

Just pass your folder it will tell you main class about the method.

I want to exception handle 'list index out of range.'

Handling the exception is the way to go:

try:
    gotdata = dlist[1]
except IndexError:
    gotdata = 'null'

Of course you could also check the len() of dlist; but handling the exception is more intuitive.

What is the difference between POST and GET?

Whilst not a description of the differences, below are a couple of things to think about when choosing the correct method.

  • GET requests can get cached by the browser which can be a problem (or benefit) when using ajax.
  • GET requests expose parameters to users (POST does as well but they are less visible).
  • POST can pass much more information to the server and can be of almost any length.

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

C# delete a folder and all files and folders within that folder

You should use:

dir.Delete(true);

for recursively deleting the contents of that folder too. See MSDN DirectoryInfo.Delete() overloads.

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

I know it's a "very long time" since this question was first asked. Just in case, if it helps someone,

Adding relationships is well supported by MS via SQL Server Compact Tool Box (https://sqlcetoolbox.codeplex.com/). Just install it, then you would get the option to connect to the Compact Database using the Server Explorer Window. Right click on the primary table , select "Table Properties". You should have the following window, which contains "Add Relations" tab allowing you to add relations.

Add Relations Tab - SQL Server Compact Tool Box

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

How to detect when WIFI Connection has been established in Android?

This code does not require permission at all. It is restricted only to Wi-Fi network connectivity state changes (any other network is not taken into account). The receiver is statically published in the AndroidManifest.xml file and does not need to be exported as it will be invoked by the system protected broadcast, NETWORK_STATE_CHANGED_ACTION, at every network connectivity state change.

AndroidManifest:

<receiver
    android:name=".WifiReceiver"
    android:enabled="true"
    android:exported="false">

    <intent-filter>
        <!--protected-broadcast: Special broadcast that only the system can send-->
        <!--Corresponds to: android.net.wifi.WifiManager.NETWORK_STATE_CHANGED_ACTION-->
        <action android:name="android.net.wifi.STATE_CHANGE" />
    </intent-filter>

</receiver>

BroadcastReceiver class:

public class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
/*
 Tested (I didn't test with the WPS "Wi-Fi Protected Setup" standard):
 In API15 (ICE_CREAM_SANDWICH) this method is called when the new Wi-Fi network state is:
 DISCONNECTED, OBTAINING_IPADDR, CONNECTED or SCANNING

 In API19 (KITKAT) this method is called when the new Wi-Fi network state is:
 DISCONNECTED (twice), OBTAINING_IPADDR, VERIFYING_POOR_LINK, CAPTIVE_PORTAL_CHECK
 or CONNECTED

 (Those states can be obtained as NetworkInfo.DetailedState objects by calling
 the NetworkInfo object method: "networkInfo.getDetailedState()")
*/
    /*
     * NetworkInfo object associated with the Wi-Fi network.
     * It won't be null when "android.net.wifi.STATE_CHANGE" action intent arrives.
     */
    NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

    if (networkInfo != null && networkInfo.isConnected()) {
        // TODO: Place the work here, like retrieving the access point's SSID

        /*
         * WifiInfo object giving information about the access point we are connected to.
         * It shouldn't be null when the new Wi-Fi network state is CONNECTED, but it got
         * null sometimes when connecting to a "virtualized Wi-Fi router" in API15.
         */
        WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
        String ssid = wifiInfo.getSSID();
    }
}
}

Permissions:

None

Why use def main()?

if the content of foo.py

print __name__
if __name__ == '__main__':
    print 'XXXX'

A file foo.py can be used in two ways.

  • imported in another file : import foo

In this case __name__ is foo, the code section does not get executed and does not print XXXX.

  • executed directly : python foo.py

When it is executed directly, __name__ is same as __main__ and the code in that section is executed and prints XXXX

One of the use of this functionality to write various kind of unit tests within the same module.

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

How to copy Outlook mail message into excel using VBA or Macros

New introduction 2

In the previous version of macro "SaveEmailDetails" I used this statement to find Inbox:

Set FolderTgt = CreateObject("Outlook.Application"). _
              GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)

I have since installed a newer version of Outlook and I have discovered that it does not use the default Inbox. For each of my email accounts, it created a separate store (named for the email address) each with its own Inbox. None of those Inboxes is the default.

This macro, outputs the name of the store holding the default Inbox to the Immediate Window:

Sub DsplUsernameOfDefaultStore()

  Dim NS As Outlook.NameSpace
  Dim DefaultInboxFldr As MAPIFolder

  Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
  Set DefaultInboxFldr = NS.GetDefaultFolder(olFolderInbox)

  Debug.Print DefaultInboxFldr.Parent.Name

End Sub

On my installation, this outputs: "Outlook Data File".

I have added an extra statement to macro "SaveEmailDetails" that shows how to access the Inbox of any store.

New introduction 1

A number of people have picked up the macro below, found it useful and have contacted me directly for further advice. Following these contacts I have made a few improvements to the macro so I have posted the revised version below. I have also added a pair of macros which together will return the MAPIFolder object for any folder with the Outlook hierarchy. These are useful if you wish to access other than a default folder.

The original text referenced one question by date which linked to an earlier question. The first question has been deleted so the link has been lost. That link was to Update excel sheet based on outlook mail (closed)

Original text

There are a surprising number of variations of the question: "How do I extract data from Outlook emails to Excel workbooks?" For example, two questions up on [outlook-vba] the same question was asked on 13 August. That question references a variation from December that I attempted to answer.

For the December question, I went overboard with a two part answer. The first part was a series of teaching macros that explored the Outlook folder structure and wrote data to text files or Excel workbooks. The second part discussed how to design the extraction process. For this question Siddarth has provided an excellent, succinct answer and then a follow-up to help with the next stage.

What the questioner of every variation appears unable to understand is that showing us what the data looks like on the screen does not tell us what the text or html body looks like. This answer is an attempt to get past that problem.

The macro below is more complicated than Siddarth’s but a lot simpler that those I included in my December answer. There is more that could be added but I think this is enough to start with.

The macro creates a new Excel workbook and outputs selected properties of every email in Inbox to create this worksheet:

Example of worksheet created by macro

Near the top of the macro there is a comment containing eight hashes (#). The statement below that comment must be changed because it identifies the folder in which the Excel workbook will be created.

All other comments containing hashes suggest amendments to adapt the macro to your requirements.

How are the emails from which data is to be extracted identified? Is it the sender, the subject, a string within the body or all of these? The comments provide some help in eliminating uninteresting emails. If I understand the question correctly, an interesting email will have Subject = "Task Completed".

The comments provide no help in extracting data from interesting emails but the worksheet shows both the text and html versions of the email body if they are present. My idea is that you can see what the macro will see and start designing the extraction process.

This is not shown in the screen image above but the macro outputs two versions on the text body. The first version is unchanged which means tab, carriage return, line feed are obeyed and any non-break spaces look like spaces. In the second version, I have replaced these codes with the strings [TB], [CR], [LF] and [NBSP] so they are visible. If my understanding is correct, I would expect to see the following within the second text body:

Activity[TAB]Count[CR][LF]Open[TAB]35[CR][LF]HCQA[TAB]42[CR][LF]HCQC[TAB]60[CR][LF]HAbst[TAB]50 45 5 2 2 1[CR][LF] and so on

Extracting the values from the original of this string should not be difficult.

I would try amending my macro to output the extracted values in addition to the email’s properties. Only when I have successfully achieved this change would I attempt to write the extracted data to an existing workbook. I would also move processed emails to a different folder. I have shown where these changes must be made but give no further help. I will respond to a supplementary question if you get to the point where you need this information.

Good luck.

Latest version of macro included within the original text

Option Explicit
Public Sub SaveEmailDetails()

  ' This macro creates a new Excel workbook and writes to it details
  ' of every email in the Inbox.

  ' Lines starting with hashes either MUST be changed before running the
  ' macro or suggest changes you might consider appropriate.

  Dim AttachCount As Long
  Dim AttachDtl() As String
  Dim ExcelWkBk As Excel.Workbook
  Dim FileName As String
  Dim FolderTgt As MAPIFolder
  Dim HtmlBody As String
  Dim InterestingItem As Boolean
  Dim InxAttach As Long
  Dim InxItemCrnt As Long
  Dim PathName As String
  Dim ReceivedTime As Date
  Dim RowCrnt As Long
  Dim SenderEmailAddress As String
  Dim SenderName As String
  Dim Subject As String
  Dim TextBody As String
  Dim xlApp As Excel.Application

  ' The Excel workbook will be created in this folder.
  ' ######## Replace "C:\DataArea\SO" with the name of a folder on your disc.
  PathName = "C:\DataArea\SO"

  ' This creates a unique filename.
  ' #### If you use a version of Excel 2003, change the extension to "xls".
  FileName = Format(Now(), "yymmdd hhmmss") & ".xlsx"

  ' Open own copy of Excel
  Set xlApp = Application.CreateObject("Excel.Application")
  With xlApp
    ' .Visible = True         ' This slows your macro but helps during debugging
    .ScreenUpdating = False ' Reduces flash and increases speed
    ' Create a new workbook
    ' #### If updating an existing workbook, replace with an
    ' #### Open workbook statement.
    Set ExcelWkBk = xlApp.Workbooks.Add
    With ExcelWkBk
      ' #### None of this code will be useful if you are adding
      ' #### to an existing workbook.  However, it demonstrates a
      ' #### variety of useful statements.
      .Worksheets("Sheet1").Name = "Inbox"    ' Rename first worksheet
      With .Worksheets("Inbox")
        ' Create header line
        With .Cells(1, "A")
          .Value = "Field"
          .Font.Bold = True
        End With
        With .Cells(1, "B")
          .Value = "Value"
          .Font.Bold = True
        End With
        .Columns("A").ColumnWidth = 18
        .Columns("B").ColumnWidth = 150
      End With
    End With
    RowCrnt = 2
  End With

  ' FolderTgt is the folder I am going to search.  This statement says
  ' I want to seach the Inbox.  The value "olFolderInbox" can be replaced
  ' to allow any of the standard folders to be searched.
  ' See FindSelectedFolder() for a routine that will search for any folder.
  Set FolderTgt = CreateObject("Outlook.Application"). _
              GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
  ' #### Use the following the access a non-default Inbox.
  ' #### Change "Xxxx" to name of one of your store you want to access.
  Set FolderTgt = Session.Folders("Xxxx").Folders("Inbox")

  ' This examines the emails in reverse order. I will explain why later.
  For InxItemCrnt = FolderTgt.Items.Count To 1 Step -1
    With FolderTgt.Items.Item(InxItemCrnt)
      ' A folder can contain several types of item: mail items, meeting items,
      ' contacts, etc.  I am only interested in mail items.
      If .Class = olMail Then
        ' Save selected properties to variables
        ReceivedTime = .ReceivedTime
        Subject = .Subject
        SenderName = .SenderName
        SenderEmailAddress = .SenderEmailAddress
        TextBody = .Body
        HtmlBody = .HtmlBody
        AttachCount = .Attachments.Count
        If AttachCount > 0 Then
          ReDim AttachDtl(1 To 7, 1 To AttachCount)
          For InxAttach = 1 To AttachCount
            ' There are four types of attachment:
            '  *   olByValue       1
            '  *   olByReference   4
            '  *   olEmbeddedItem  5
            '  *   olOLE           6
            Select Case .Attachments(InxAttach).Type
              Case olByValue
            AttachDtl(1, InxAttach) = "Val"
              Case olEmbeddeditem
            AttachDtl(1, InxAttach) = "Ebd"
              Case olByReference
            AttachDtl(1, InxAttach) = "Ref"
              Case olOLE
            AttachDtl(1, InxAttach) = "OLE"
              Case Else
            AttachDtl(1, InxAttach) = "Unk"
            End Select
            ' Not all types have all properties.  This code handles
            ' those missing properties of which I am aware.  However,
            ' I have never found an attachment of type Reference or OLE.
            ' Additional code may be required for them.
            Select Case .Attachments(InxAttach).Type
              Case olEmbeddeditem
                AttachDtl(2, InxAttach) = ""
              Case Else
                AttachDtl(2, InxAttach) = .Attachments(InxAttach).PathName
            End Select
            AttachDtl(3, InxAttach) = .Attachments(InxAttach).FileName
            AttachDtl(4, InxAttach) = .Attachments(InxAttach).DisplayName
            AttachDtl(5, InxAttach) = "--"
            ' I suspect Attachment had a parent property in early versions
            ' of Outlook. It is missing from Outlook 2016.
            On Error Resume Next
            AttachDtl(5, InxAttach) = .Attachments(InxAttach).Parent
            On Error GoTo 0
            AttachDtl(6, InxAttach) = .Attachments(InxAttach).Position
            ' Class 5 is attachment.  I have never seen an attachment with
            ' a different class and do not see the purpose of this property.
            ' The code will stop here if a different class is found.
            Debug.Assert .Attachments(InxAttach).Class = 5
            AttachDtl(7, InxAttach) = .Attachments(InxAttach).Class
          Next
        End If
        InterestingItem = True
      Else
        InterestingItem = False
      End If
    End With
    ' The most used properties of the email have been loaded to variables but
    ' there are many more properies.  Press F2.  Scroll down classes until
    ' you find MailItem.  Look through the members and note the name of
    ' any properties that look useful.  Look them up using VB Help.

    ' #### You need to add code here to eliminate uninteresting items.
    ' #### For example:
    'If SenderEmailAddress <> "[email protected]" Then
    '  InterestingItem = False
    'End If
    'If InStr(Subject, "Accounts payable") = 0 Then
    '  InterestingItem = False
    'End If
    'If AttachCount = 0 Then
    '  InterestingItem = False
    'End If

    ' #### If the item is still thought to be interesting I
    ' #### suggest extracting the required data to variables here.

    ' #### You should consider moving processed emails to another
    ' #### folder.  The emails are being processed in reverse order
    ' #### to allow this removal of an email from the Inbox without
    ' #### effecting the index numbers of unprocessed emails.

    If InterestingItem Then
      With ExcelWkBk
        With .Worksheets("Inbox")
          ' #### This code creates a dividing row and then
          ' #### outputs a property per row.  Again it demonstrates
          ' #### statements that are likely to be useful in the final
          ' #### version
          ' Create dividing row between emails
          .Rows(RowCrnt).RowHeight = 5
          .Range(.Cells(RowCrnt, "A"), .Cells(RowCrnt, "B")) _
                                      .Interior.Color = RGB(0, 255, 0)
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender name"
          .Cells(RowCrnt, "B").Value = SenderName
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender email address"
          .Cells(RowCrnt, "B").Value = SenderEmailAddress
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Received time"
          With .Cells(RowCrnt, "B")
            .NumberFormat = "@"
            .Value = Format(ReceivedTime, "mmmm d, yyyy h:mm")
          End With
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Subject"
          .Cells(RowCrnt, "B").Value = Subject
          RowCrnt = RowCrnt + 1
          If AttachCount > 0 Then
            .Cells(RowCrnt, "A").Value = "Attachments"
            .Cells(RowCrnt, "B").Value = "Inx|Type|Path name|File name|Display name|Parent|Position|Class"
            RowCrnt = RowCrnt + 1
            For InxAttach = 1 To AttachCount
              .Cells(RowCrnt, "B").Value = InxAttach & "|" & _
                                           AttachDtl(1, InxAttach) & "|" & _
                                           AttachDtl(2, InxAttach) & "|" & _
                                           AttachDtl(3, InxAttach) & "|" & _
                                           AttachDtl(4, InxAttach) & "|" & _
                                           AttachDtl(5, InxAttach) & "|" & _
                                           AttachDtl(6, InxAttach) & "|" & _
                                           AttachDtl(7, InxAttach)
              RowCrnt = RowCrnt + 1
            Next
          End If
          If TextBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the text body.  See below
            ' This outputs the text body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "text body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  ' The maximum size of a cell 32,767
            '  .Value = Mid(TextBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the text body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "text body"
              .VerticalAlignment = xlTop
            End With
            TextBody = Replace(TextBody, Chr(160), "[NBSP]")
            TextBody = Replace(TextBody, vbCr, "[CR]")
            TextBody = Replace(TextBody, vbLf, "[LF]")
            TextBody = Replace(TextBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              ' The maximum size of a cell 32,767
              .Value = Mid(TextBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1
          End If

          If HtmlBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the html body.  See below
            ' This outputs the html body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "Html body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  .Value = Mid(HtmlBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the html body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "Html body"
              .VerticalAlignment = xlTop
            End With
            HtmlBody = Replace(HtmlBody, Chr(160), "[NBSP]")
            HtmlBody = Replace(HtmlBody, vbCr, "[CR]")
            HtmlBody = Replace(HtmlBody, vbLf, "[LF]")
            HtmlBody = Replace(HtmlBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              .Value = Mid(HtmlBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1

          End If
        End With
      End With
    End If
  Next

  With xlApp
    With ExcelWkBk
      ' Write new workbook to disc
      If Right(PathName, 1) <> "\" Then
        PathName = PathName & "\"
      End If
      .SaveAs FileName:=PathName & FileName
      .Close
    End With
    .Quit   ' Close our copy of Excel
  End With

  Set xlApp = Nothing       ' Clear reference to Excel

End Sub

Macros not included in original post but which some users of above macro have found useful.

Public Sub FindSelectedFolder(ByRef FolderTgt As MAPIFolder, _
                              ByVal NameTgt As String, ByVal NameSep As String)

  ' This routine (and its sub-routine) locate a folder within the hierarchy and
  ' returns it as an object of type MAPIFolder

  ' NameTgt   The name of the required folder in the format:
  '              FolderName1 NameSep FolderName2 [ NameSep FolderName3 ] ...
  '           If NameSep is "|", an example value is "Personal Folders|Inbox"
  '           FolderName1 must be an outer folder name such as
  '           "Personal Folders". The outer folder names are typically the names
  '           of PST files.  FolderName2 must be the name of a folder within
  '           Folder1; in the example "Inbox".  FolderName2 is compulsory.  This
  '           routine cannot return a PST file; only a folder within a PST file.
  '           FolderName3, FolderName4 and so on are optional and allow a folder
  '           at any depth with the hierarchy to be specified.
  ' NameSep   A character or string used to separate the folder names within
  '           NameTgt.
  ' FolderTgt On exit, the required folder.  Set to Nothing if not found.

  ' This routine initialises the search and finds the top level folder.
  ' FindSelectedSubFolder() is used to find the target folder within the
  ' top level folder.

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long
  Dim TopLvlFolderList As Folders

  Set FolderTgt = Nothing   ' Target folder not found

  Set TopLvlFolderList = _
          CreateObject("Outlook.Application").GetNamespace("MAPI").Folders

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    ' I need at least a level 2 name
    Exit Sub
  End If
  NameCrnt = Mid(NameTgt, 1, Pos - 1)
  NameChild = Mid(NameTgt, Pos + 1)

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To TopLvlFolderList.Count
    If NameCrnt = TopLvlFolderList(InxFolderCrnt).Name Then
      ' Have found current name. Call FindSelectedSubFolder() to
      ' look for its children
      Call FindSelectedSubFolder(TopLvlFolderList.Item(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      Exit For
    End If
  Next

End Sub
Public Sub FindSelectedSubFolder(FolderCrnt As MAPIFolder, _
                      ByRef FolderTgt As MAPIFolder, _
                      ByVal NameTgt As String, ByVal NameSep As String)

  ' See FindSelectedFolder() for an introduction to the purpose of this routine.
  ' This routine finds all folders below the top level

  ' FolderCrnt The folder to be seached for the target folder.
  ' NameTgt    The NameTgt passed to FindSelectedFolder will be of the form:
  '               A|B|C|D|E
  '            A is the name of outer folder which represents a PST file.
  '            FindSelectedFolder() removes "A|" from NameTgt and calls this
  '            routine with FolderCrnt set to folder A to search for B.
  '            When this routine finds B, it calls itself with FolderCrnt set to
  '            folder B to search for C.  Calls are nested to whatever depth are
  '            necessary.
  ' NameSep    As for FindSelectedSubFolder
  ' FolderTgt  As for FindSelectedSubFolder

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    NameCrnt = NameTgt
    NameChild = ""
  Else
    NameCrnt = Mid(NameTgt, 1, Pos - 1)
    NameChild = Mid(NameTgt, Pos + 1)
  End If

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To FolderCrnt.Folders.Count
    If NameCrnt = FolderCrnt.Folders(InxFolderCrnt).Name Then
      ' Have found current name.
      If NameChild = "" Then
        ' Have found target folder
        Set FolderTgt = FolderCrnt.Folders(InxFolderCrnt)
      Else
        'Recurse to look for children
        Call FindSelectedSubFolder(FolderCrnt.Folders(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      End If
      Exit For
    End If
  Next

  ' If NameCrnt not found, FolderTgt will be returned unchanged.  Since it is
  ' initialised to Nothing at the beginning, that will be the returned value.

End Sub

How to sort a List<Object> alphabetically using Object name field

Here is a version of Robert B's answer that works for List<T> and sorting by a specified String property of the object using Reflection and no 3rd party libraries

/**
 * Sorts a List by the specified String property name of the object.
 * 
 * @param list
 * @param propertyName
 */
public static <T> void sortList(List<T> list, final String propertyName) {

    if (list.size() > 0) {
        Collections.sort(list, new Comparator<T>() {
            @Override
            public int compare(final T object1, final T object2) {
                String property1 = (String)ReflectionUtils.getSpecifiedFieldValue (propertyName, object1);
                String property2 = (String)ReflectionUtils.getSpecifiedFieldValue (propertyName, object2);
                return property1.compareToIgnoreCase (property2);
            }
        });
    }
}


public static Object getSpecifiedFieldValue (String property, Object obj) {

    Object result = null;

    try {
        Class<?> objectClass = obj.getClass();
        Field objectField = getDeclaredField(property, objectClass);
        if (objectField!=null) {
            objectField.setAccessible(true);
            result = objectField.get(obj);
        }
    } catch (Exception e) {         
    }
    return result;
}

public static Field getDeclaredField(String fieldName, Class<?> type) {

    Field result = null;
    try {
        result = type.getDeclaredField(fieldName);
    } catch (Exception e) {
    }       

    if (result == null) {
        Class<?> superclass = type.getSuperclass();     
        if (superclass != null && !superclass.getName().equals("java.lang.Object")) {       
            return getDeclaredField(fieldName, type.getSuperclass());
        }
    }
    return result;
}

Laravel stylesheets and javascript don't load for non-base routes

You are using relative paths for your assets, change to an absolute path and everything will work (add a slash before "css".

<link rel="stylesheet" href="/css/app.css" />

Best way to update an element in a generic List

If the list is sorted (as happens to be in the example) a binary search on index certainly works.

    public static Dog Find(List<Dog> AllDogs, string Id)
    {
        int p = 0;
        int n = AllDogs.Count;
        while (true)
        {
            int m = (n + p) / 2;
            Dog d = AllDogs[m];
            int r = string.Compare(Id, d.Id);
            if (r == 0)
                return d;
            if (m == p)
                return null;
            if (r < 0)
                n = m;
            if (r > 0)
                p = m;
        }
    }

Not sure what the LINQ version of this would be.

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

In my case,

Nothing above worked, I had a CSV file copied to Linux machine from my mac and I used all the above commands but nothing helped but the below one

tr "\015" "\n" < inputfile > outputfile

I had a file in which ^M characters were sandwitched between lines something like below

Audi,A4,35 TFSi Premium,,CAAUA4TP^MB01BNKT6TG,TRO_WBFB_500,Trico,CARS,Audi,A4,35 TFSi Premium,,CAAUA4TP^MB01BNKTG0A,TRO_WB_T500,Trico,

Check if any type of files exist in a directory using BATCH script

To check if a folder contains at least one file

>nul 2>nul dir /a-d "folderName\*" && (echo Files exist) || (echo No file found)

To check if a folder or any of its descendents contain at least one file

>nul 2>nul dir /a-d /s "folderName\*" && (echo Files exist) || (echo No file found)

To check if a folder contains at least one file or folder.
Note addition of /a option to enable finding of hidden and system files/folders.

dir /b /a "folderName\*" | >nul findstr "^" && (echo Files and/or Folders exist) || (echo No File or Folder found)

To check if a folder contains at least one folder

dir /b /ad "folderName\*" | >nul findstr "^" && (echo Folders exist) || (echo No folder found)

Undefined reference to `pow' and `floor'

For the benefit of anyone reading this later, you need to link against it as Fred said:

gcc fib.c -lm -o fibo

One good way to find out what library you need to link is by checking the man page if one exists. For example, man pow and man floor will both tell you:

Link with -lm.

An explanation for linking math library in C programming - Linking in C

How to get access to job parameters from ItemReader, in Spring Batch?

To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.

Using xml-config it would go like this:

<bean id="foo-readers" scope="step"
  class="...MyReader">
  <property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>

See further at the Spring Batch documentation.

Perhaps it works by using @Scope and defining the step scope in your xml-config:

<bean class="org.springframework.batch.core.scope.StepScope" />

How to manually install an artifact in Maven 2?

You need to indicate the groupId, the artifactId and the version for your artifact:

mvn install:install-file \
  -DgroupId=javax.transaction \
  -DartifactId=jta \
  -Dpackaging=jar \
  -Dversion=1.0.1B \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

To explain the actual problem that tslint is pointing out, a quote from the JavaScript documentation of the for...in statement:

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

So, basically this means you'll get properties you might not expect to get (from the object's prototype chain).

To solve this we need to iterate only over the objects own properties. We can do this in two different ways (as suggested by @Maxxx and @Qwertiy).

First solution

for (const field of Object.keys(this.formErrors)) {
    ...
}

Here we utilize the Object.Keys() method which returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Second solution

for (var field in this.formErrors) {
    if (this.formErrors.hasOwnProperty(field)) {
        ...
    }
}

In this solution we iterate all of the object's properties including those in it's prototype chain but use the Object.prototype.hasOwnProperty() method, which returns a boolean indicating whether the object has the specified property as own (not inherited) property, to filter the inherited properties out.

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

How can I convert a string to a number in Perl?

You don't need to convert it at all:

% perl -e 'print "5.45" + 0.1;'
5.55

Transpose a data frame

df.aree <- as.data.frame(t(df.aree))
colnames(df.aree) <- df.aree[1, ]
df.aree <- df.aree[-1, ]
df.aree$myfactor <- factor(row.names(df.aree))

Intent.putExtra List

Assuming that your List is a list of strings make data an ArrayList<String> and use intent.putStringArrayListExtra("data", data)

Here is a skeleton of the code you need:

  1. Declare List

    private List<String> test;
    
  2. Init List at appropriate place

    test = new ArrayList<String>();
    

    and add data as appropriate to test.

  3. Pass to intent as follows:

    Intent intent = getIntent();  
    intent.putStringArrayListExtra("test", (ArrayList<String>) test);
    
  4. Retrieve data as follows:

    ArrayList<String> test = getIntent().getStringArrayListExtra("test");
    

Hope that helps.

How to send email from SQL Server?

You can send email natively from within SQL Server using Database Mail. This is a great tool for notifying sysadmins about errors or other database events. You could also use it to send a report or an email message to an end user. The basic syntax for this is:

EXEC msdb.dbo.sp_send_dbmail  
@recipients='[email protected]',
@subject='Testing Email from SQL Server',
@body='<p>It Worked!</p><p>Email sent successfully</p>',
@body_format='HTML',
@from_address='Sender Name <[email protected]>',
@reply_to='[email protected]'

Before use, Database Mail must be enabled using the Database Mail Configuration Wizard, or sp_configure. A database or Exchange admin might need to help you configure this. See http://msdn.microsoft.com/en-us/library/ms190307.aspx and http://www.codeproject.com/Articles/485124/Configuring-Database-Mail-in-SQL-Server for more information.

Stock ticker symbol lookup API

You can use the "Company Search" operation in the Company Fundamentals API here: http://www.mergent.com/servius/

phonegap open link in browser

I'm using PhoneGap Build (v3.4.0), with focus on iOS, and I needed to have this entry in my config.xml for PhoneGap to recognize the InAppBrowser plug-in.

<gap:plugin name="org.apache.cordova.inappbrowser" />

After that, using window.open(url, target) should work as expected, as documented here.

Temporary tables in stored procedures

Nope. Independent instances of the temporary table will be created per each connection.

Check if a temporary table exists and delete if it exists before creating a temporary table

This worked for me: social.msdn.microsoft.com/Forums/en/transactsql/thread/02c6da90-954d-487d-a823-e24b891ec1b0?prof=required

if exists (
    select  * from tempdb.dbo.sysobjects o
    where o.xtype in ('U') 

   and o.id = object_id(N'tempdb..#tempTable')
)
DROP TABLE #tempTable;

What exactly is Spring Framework for?

The advantage is Dependency Injection (DI). It means outsourcing the task of object creation.Let me explain with an example.

public interface Lunch
{
   public void eat();
}

public class Buffet implements Lunch
{
   public void eat()
   {
      // Eat as much as you can 
   }
}

public class Plated implements Lunch
{
   public void eat()
   {
      // Eat a limited portion
   }
}

Now in my code I have a class LunchDecide as follows:

public class LunchDecide {
    private Lunch todaysLunch;
    public LunchDecide(){
        this.todaysLunch = new Buffet(); // choose Buffet -> eat as much as you want
        //this.todaysLunch = new Plated(); // choose Plated -> eat a limited portion 
    }
}

In the above class, depending on our mood, we pick Buffet() or Plated(). However this system is tightly coupled. Every time we need a different type of Object, we need to change the code. In this case, commenting out a line ! Imagine there are 50 different classes used by 50 different people. It would be a hell of a mess. In this case, we need to Decouple the system. Let's rewrite the LunchDecide class.

public class LunchDecide {
    private Lunch todaysLunch;
    public LunchDecide(Lunch todaysLunch){
        this.todaysLunch = todaysLunch
        }
    }

Notice that instead of creating an object using new keyword we passed the reference to an object of Lunch Type as a parameter to our constructor. Here, object creation is outsourced. This code can be wired either using Xml config file (legacy) or Java Annotations (modern). Either way, the decision on which Type of object would be created would be done there during runtime. An object would be injected by Xml into our code - Our Code is dependent on Xml for that job. Hence, Dependency Injection (DI). DI not only helps in making our system loosely coupled, it simplifies writing of Unit tests since it allows dependencies to be mocked. Last but not the least, DI streamlines Aspect Oriented Programming (AOP) which leads to further decoupling and increase of modularity. Also note that above DI is Constructor Injection. DI can be done by Setter Injection as well - same plain old setter method from encapsulation.

Closing Applications

What role do they play when exiting an application in C#?

The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.

But what is the difference?

One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.

Creating a list/array in excel using VBA to get a list of unique names in a column

FWIW, here's the dictionary thing. After setting a reference to MS Scripting. You can jack around with the array size of avInput to match your needs.

Sub somemacro()
Dim avInput As Variant
Dim uvals As Dictionary
Dim i As Integer
Dim rop As Range

avInput = Sheets("data").UsedRange
Set uvals = New Dictionary


For i = 1 To UBound(avInput, 1)
    If uvals.Exists(avInput(i, 1)) = False Then
        uvals.Add avInput(i, 1), 1
    Else
        uvals.Item(avInput(i, 1)) = uvals.Item(avInput(i, 1)) + 1
    End If
Next i

ReDim avInput(1 To uvals.Count)
i = 1

For Each kv In uvals.Keys
    avInput(i) = kv
    i = i + 1
Next kv

Set rop = Sheets("sheet2").Range("a1")
rop.Resize(UBound(avInput, 1), 1) = Application.Transpose(avInput)




End Sub

Credit card expiration dates - Inclusive or exclusive?

According to Visa's "Card Acceptance and Chargeback Management Guidelines for Visa Merchants"; "Good Thru" (or "Valid Thru") Date is the expiration date of the card:

A card is valid through the last day of the month shown, (e .g ., if the Good Thru date is 03/12,the card is valid through March 31, 2012 and expires on April 1, 2012 .)

It is located below the embossed account number. If the current transaction date is after the "Good Thru" date, the card has expired.

Why is there no ForEach extension method on IEnumerable?

@Coincoin

The real power of the foreach extension method involves reusability of the Action<> without adding unnecessary methods to your code. Say that you have 10 lists and you want to perform the same logic on them, and a corresponding function doesn't fit into your class and is not reused. Instead of having ten for loops, or a generic function that is obviously a helper that doesn't belong, you can keep all of your logic in one place (the Action<>. So, dozens of lines get replaced with

Action<blah,blah> f = { foo };

List1.ForEach(p => f(p))
List2.ForEach(p => f(p))

etc...

The logic is in one place and you haven't polluted your class.

How to iterate over array of objects in Handlebars?

You can pass this to each block. See here: http://jsfiddle.net/yR7TZ/1/

{{#each this}}
    <div class="row"></div>
{{/each}}

pandas three-way joining multiple dataframes on columns

You could try this if you have 3 dataframes

# Merge multiple dataframes
df1 = pd.DataFrame(np.array([
    ['a', 5, 9],
    ['b', 4, 61],
    ['c', 24, 9]]),
    columns=['name', 'attr11', 'attr12'])
df2 = pd.DataFrame(np.array([
    ['a', 5, 19],
    ['b', 14, 16],
    ['c', 4, 9]]),
    columns=['name', 'attr21', 'attr22'])
df3 = pd.DataFrame(np.array([
    ['a', 15, 49],
    ['b', 4, 36],
    ['c', 14, 9]]),
    columns=['name', 'attr31', 'attr32'])

pd.merge(pd.merge(df1,df2,on='name'),df3,on='name')

alternatively, as mentioned by cwharland

df1.merge(df2,on='name').merge(df3,on='name')

Efficient way to apply multiple filters to pandas DataFrame or Series

Since pandas 0.22 update, comparison options are available like:

  • gt (greater than)
  • lt (lesser than)
  • eq (equals to)
  • ne (not equals to)
  • ge (greater than or equals to)

and many more. These functions return boolean array. Let's see how we can use them:

# sample data
df = pd.DataFrame({'col1': [0, 1, 2,3,4,5], 'col2': [10, 11, 12,13,14,15]})

# get values from col1 greater than or equals to 1
df.loc[df['col1'].ge(1),'col1']

1    1
2    2
3    3
4    4
5    5

# where co11 values is better 0 and 2
df.loc[df['col1'].between(0,2)]

 col1 col2
0   0   10
1   1   11
2   2   12

# where col1 > 1
df.loc[df['col1'].gt(1)]

 col1 col2
2   2   12
3   3   13
4   4   14
5   5   15

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

In my case using Cascade.ALL was adding unnecessary entry to the table, which already had same object (Generating a child value without an id does just that). So I would have to work around with getting child object from repository first, and setting it into the main object instead of the one causing the issue.

Student s = studentRepo.findByName(generatedObject.getStudent().getName())
generatedObject.student(s);   

Why use pip over easy_install?

REQUIREMENTS files.

Seriously, I use this in conjunction with virtualenv every day.


QUICK DEPENDENCY MANAGEMENT TUTORIAL, FOLKS

Requirements files allow you to create a snapshot of all packages that have been installed through pip. By encapsulating those packages in a virtualenvironment, you can have your codebase work off a very specific set of packages and share that codebase with others.

From Heroku's documentation https://devcenter.heroku.com/articles/python

You create a virtual environment, and set your shell to use it. (bash/*nix instructions)

virtualenv env
source env/bin/activate

Now all python scripts run with this shell will use this environment's packages and configuration. Now you can install a package locally to this environment without needing to install it globally on your machine.

pip install flask

Now you can dump the info about which packages are installed with

pip freeze > requirements.txt

If you checked that file into version control, when someone else gets your code, they can setup their own virtual environment and install all the dependencies with:

pip install -r requirements.txt

Any time you can automate tedium like this is awesome.

Regular expression containing one word or another

You can use a single group for seconds/minutes. The following expression may suit your needs:

([0-9]+)\s*(seconds|minutes)

Online demo

Run Excel Macro from Outside Excel Using VBScript From Command Line

Hi used this thread to get the solution , then i would like to share what i did just in case someone could use it.

What i wanted was to call a macro that change some cells and erase some rows, but i needed for more than 1500 excels( approximately spent 3 minuts for each file)

Mainly problem: -when calling the macro from vbe , i got the same problem, it was imposible to call the macro from PERSONAL.XLSB, when the script oppened the excel didnt execute personal.xlsb and wasnt any option in the macro window

I solved this by keeping open one excel file with the macro loaded(a.xlsm)(before executing the script)

Then i call the macro from the excel oppened by the script

    Option Explicit
    Dim xl
    Dim counter

   counter =10



  Do

  counter = counter + 1

  Set xl = GetObject(, "Excel.Application")
  xl.Application.Workbooks.open "C:\pruebas\macroxavi\IA_030-08-026" & counter & ".xlsx"
  xl.Application.Visible = True
  xl.Application.run "'a.xlsm'!eraserow" 
  Set xl = Nothing


  Loop Until counter = 517

  WScript.Echo "Finished."
  WScript.Quit

How to select the last record from MySQL table using SQL syntax

I have used the following two:

1 - select id from table_name where id = (select MAX(id) from table_name)
2 - select id from table_name order by id desc limit 0, 1

IIS Request Timeout on long ASP.NET operation

I'm posting this here, because I've spent like 3 and 4 hours on it, and I've only found answers like those one above, that say do add the executionTime, but it doesn't solve the problem in the case that you're using ASP .NET Core. For it, this would work:

At web.config file, add the requestTimeout attribute at aspNetCore node.

<system.webServer>
  <aspNetCore requestTimeout="00:10:00" ... (other configs goes here) />
</system.webServer>

In this example, I'm setting the value for 10 minutes.

Reference: https://docs.microsoft.com/en-us/aspnet/core/hosting/aspnet-core-module#configuring-the-asp-net-core-module

checked = "checked" vs checked = true

document.getElementById('myRadio') returns you the DOM element, i'll reference it as elem in this answer.

elem.checked accesses the property named checked of the DOM element. This property is always a boolean.

When writing HTML you use checked="checked" in XHTML; in HTML you can simply use checked. When setting the attribute (this is done via .setAttribute('checked', 'checked')) you need to provide a value since some browsers consider an empty value being non-existent.

However, since you have the DOM element you have no reason to set the attribute since you can simply use the - much more comfortable - boolean property for it. Since non-empty strings are considered true in a boolean context, setting elem.checked to 'checked' or anything else that is not a falsy value (even 'false' or '0') will check the checkbox. There is not reason not to use true and false though so you should stick with the proper values.

Microsoft SQL Server 2005 service fails to start

We had a similar problem recently withour running SQL 2005 servers (more specifically: The reporting services). The windows services didn't start anymore with no real error message whatsoever.

I found out that this problem was related to some KB hotfixes that have been deployed lately. For some reason those hotfixes resulted in the services taking longer than usually for starting up.

Since by default, there is a timeout that kills the service after 30 seconds when it was not able to go beyond the start methods, this was the reason why it simply terminated.

Maybe this is what you are experiencing.

Theres a work around described on Microsoft Connect (link). Although the hotfixes listed in this article didn't match the ones that have been deployed to our systems, the workaround worked for us.

Could not find server 'server name' in sys.servers. SQL Server 2014

I had the problem due to an extra space in the name of the linked server. "SERVER1, 1234" instead of "SERVER1,1234"

Define: What is a HashSet?

A HashSet has an internal structure (hash), where items can be searched and identified quickly. The downside is that iterating through a HashSet (or getting an item by index) is rather slow.

So why would someone want be able to know if an entry already exists in a set?

One situation where a HashSet is useful is in getting distinct values from a list where duplicates may exist. Once an item is added to the HashSet it is quick to determine if the item exists (Contains operator).

Other advantages of the HashSet are the Set operations: IntersectWith, IsSubsetOf, IsSupersetOf, Overlaps, SymmetricExceptWith, UnionWith.

If you are familiar with the object constraint language then you will identify these set operations. You will also see that it is one step closer to an implementation of executable UML.

Check if a number is odd or even in python

Similarly to other languages, the fastest "modulo 2" (odd/even) operation is done using the bitwise and operator:

if x & 1:
    return 'odd'
else:
    return 'even'

Using Bitwise AND operator

  • The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.
  • If a number is odd & (bitwise AND) of the Number by 1 will be 1, because the last bit would already be set. Otherwise it will give 0 as output.

How to set ANDROID_HOME path in ubuntu?

I would like to share an answer that also demonstrates approach using the Android SDK provided by the Ubuntu repository:

Install Android SDK

sudo apt-get install android-sdk

Export environmental variables

export ANDROID_HOME="/usr/lib/android-sdk/"
export PATH="${PATH}:${ANDROID_HOME}tools/:${ANDROID_HOME}platform-tools/"

How to output MySQL query results in CSV format?

This answer uses Python and a popular third party library, PyMySQL. I'm adding it because Python's csv library is powerful enough to correctly handle many different flavors of .csv and no other answers are using Python code to interact with the database.

import contextlib
import csv
import datetime
import os

# https://github.com/PyMySQL/PyMySQL
import pymysql

SQL_QUERY = """
SELECT * FROM my_table WHERE my_attribute = 'my_attribute';
"""

# embedding passwords in code gets nasty when you use version control
# the environment is not much better, but this is an example
# https://stackoverflow.com/questions/12461484
SQL_USER = os.environ['SQL_USER']
SQL_PASS = os.environ['SQL_PASS']

connection = pymysql.connect(host='localhost',
                             user=SQL_USER,
                             password=SQL_PASS,
                             db='dbname')

with contextlib.closing(connection):
    with connection.cursor() as cursor:
        cursor.execute(SQL_QUERY)
        # Hope you have enough memory :)
        results = cursor.fetchall()

output_file = 'my_query-{}.csv'.format(datetime.datetime.today().strftime('%Y-%m-%d'))
with open(output_file, 'w', newline='') as csvfile:
    # http://stackoverflow.com/a/17725590/2958070 about lineterminator
    csv_writer = csv.writer(csvfile, lineterminator='\n')
    csv_writer.writerows(results)

How to overlay density plots in R?

That's how I do it in base (it's actually mentionned in the first answer comments but I'll show the full code here, including legend as I can not comment yet...)

First you need to get the info on the max values for the y axis from the density plots. So you need to actually compute the densities separately first

dta_A <- density(VarA, na.rm = TRUE)
dta_B <- density(VarB, na.rm = TRUE)

Then plot them according to the first answer and define min and max values for the y axis that you just got. (I set the min value to 0)

plot(dta_A, col = "blue", main = "2 densities on one plot"), 
     ylim = c(0, max(dta_A$y,dta_B$y)))  
lines(dta_B, col = "red")

Then add a legend to the top right corner

legend("topright", c("VarA","VarB"), lty = c(1,1), col = c("blue","red"))

Remove numbers from string sql server

Try below for your query. where val is your string or column name.

CASE WHEN PATINDEX('%[a-z]%', REVERSE(val)) > 1
                THEN LEFT(val, LEN(val) - PATINDEX('%[a-z]%', REVERSE(val)) + 1)
            ELSE '' END

Android: show soft keyboard automatically when focus is on an EditText

try and use:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

Google reCAPTCHA: How to get user response and validate in the server side?

Here is complete demo code to understand client side and server side process. you can copy paste it and just replace google site key and google secret key.

<?php 
if(!empty($_REQUEST))
{
      //  echo '<pre>'; print_r($_REQUEST); die('END');
        $post = [
            'secret' => 'Your Secret key',
            'response' => $_REQUEST['g-recaptcha-response'],
        ];
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec($ch);

        curl_close ($ch);
        echo '<pre>'; print_r($server_output); die('ss');
}
?>
<html>
  <head>
    <title>reCAPTCHA demo: Explicit render for multiple widgets</title>
    <script type="text/javascript">
      var site_key = 'Your Site key';
      var verifyCallback = function(response) {
        alert(response);
      };
      var widgetId1;
      var widgetId2;
      var onloadCallback = function() {
        // Renders the HTML element with id 'example1' as a reCAPTCHA widget.
        // The id of the reCAPTCHA widget is assigned to 'widgetId1'.
        widgetId1 = grecaptcha.render('example1', {
          'sitekey' : site_key,
          'theme' : 'light'
        });
        widgetId2 = grecaptcha.render(document.getElementById('example2'), {
          'sitekey' : site_key
        });
        grecaptcha.render('example3', {
          'sitekey' : site_key,
          'callback' : verifyCallback,
          'theme' : 'dark'
        });
      };
    </script>
  </head>
  <body>
    <!-- The g-recaptcha-response string displays in an alert message upon submit. -->
    <form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
      <div id="example1"></div>
      <br>
      <input type="submit" value="getResponse">
    </form>
    <br>
    <!-- Resets reCAPTCHA widgetId2 upon submit. -->
    <form action="javascript:grecaptcha.reset(widgetId2);">
      <div id="example2"></div>
      <br>
      <input type="submit" value="reset">
    </form>
    <br>
    <!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
    <form action="?" method="POST">
      <div id="example3"></div>
      <br>
      <input type="submit" value="Submit">
    </form>
    <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
        async defer>
    </script>
  </body>
</html>

Disable building workspace process in Eclipse

if needed programmatic from a PDE or JDT code:

public static void setWorkspaceAutoBuild(boolean flag) throws CoreException 
{
IWorkspace workspace = ResourcesPlugin.getWorkspace();
final IWorkspaceDescription description = workspace.getDescription();
description.setAutoBuilding(flag);
workspace.setDescription(description);
}

How to add one day to a date?

As mentioned in the Top answer, since java 8 it is possible to do:

Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);

but this can sometimes lead to an DateTimeException like this:

java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 2014-11-29T03:20:10.800Z of type java.time.Instant

It is possible to avoid this Exception by simply passing the time zone:

LocalDateTime.from(dt.toInstant().atZone(ZoneId.of("UTC"))).plusDays(1);

Create a list with initial capacity in Python

Python lists have no built-in pre-allocation. If you really need to make a list, and need to avoid the overhead of appending (and you should verify that you do), you can do this:

l = [None] * 1000 # Make a list of 1000 None's
for i in xrange(1000):
    # baz
    l[i] = bar
    # qux

Perhaps you could avoid the list by using a generator instead:

def my_things():
    while foo:
        #baz
        yield bar
        #qux

for thing in my_things():
    # do something with thing

This way, the list isn't every stored all in memory at all, merely generated as needed.

How to sort an array of associative arrays by value of a given key in PHP?

$inventory = 
    array(array("type"=>"fruit", "price"=>3.50),
          array("type"=>"milk", "price"=>2.90),
          array("type"=>"pork", "price"=>5.43),
          );

function pricesort($a, $b) {
  $a = $a['price'];
  $b = $b['price'];
  if ($a == $b)
    return 0;
  return ($a > $b) ? -1 : 1;
}

usort($inventory, "pricesort");
// uksort($inventory, "pricesort");

print("first: ".$inventory[0]['type']."\n\n");
// for usort(): prints milk (item with lowest price)
// for uksort(): prints fruit (item with key 0 in the original $inventory)

// foreach prints the same for usort and uksort.
foreach($inventory as $i){
  print($i['type'].": ".$i['price']."\n");
}

outputs:

first: pork

pork: 5.43
fruit: 3.5
milk: 2.9

Reading a column from CSV file using JAVA

If you are using Java 7+, you may want to use NIO.2, e.g.:

Code:

public static void main(String[] args) throws Exception {

    File file = new File("test.csv");

    List<String> lines = Files.readAllLines(file.toPath(), 
            StandardCharsets.UTF_8);

    for (String line : lines) {
        String[] array = line.split(",", -1);
        System.out.println(array[0]);
    }

}

Output:

a
1RW
1RW
1RW
1RW
1RW
1RW
1R1W
1R1W
1R1W

How do you compare two version Strings in Java?

I created simple utility for comparing versions on Android platform using Semantic Versioning convention. So it works only for strings in format X.Y.Z (Major.Minor.Patch) where X, Y, and Z are non-negative integers. You can find it on my GitHub.

Method Version.compareVersions(String v1, String v2) compares two version strings. It returns 0 if the versions are equal, 1 if version v1 is before version v2, -1 if version v1 is after version v2, -2 if version format is invalid.

C compile error: Id returned 1 exit status

Using code::blocks , I have solved this error by doing :

workspace properties > build target > build target files

and checking every project file.

Encrypt and Decrypt in Java

public class GenerateEncryptedPassword {

    public static void main(String[] args){

        Scanner sc= new Scanner(System.in);    
        System.out.println("Please enter the password that needs to be encrypted :");
        String input = sc.next();

        try {
            String encryptedPassword= AESencrp.encrypt(input);
            System.out.println("Encrypted password generated is :"+encryptedPassword);
        } catch (Exception ex) {
            Logger.getLogger(GenerateEncryptedPassword.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

What's the best practice for primary keys in tables?

If you really want to read through all of the back and forth on this age-old debate, do a search for "natural key" on Stack Overflow. You should get back pages of results.

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

Actually your Windows firewall is blocking the connection. You need to enter these commands into cmd.exe from Administrator.

netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=tcp
netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=udp

In case something goes wrong then you can revert by this:

netsh advfirewall firewall delete rule name="FTP" program=%SystemRoot%\System32\ftp.exe

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.

Some keypoints will be:

  1. InnoDB does ACID-compliant transaction. http://en.wikipedia.org/wiki/ACID
  2. InnoDB does Referential Integrity (foreign key relations) http://www.w3resource.com/sql/joins/joining-tables-through-referential-integrity.php
  3. MyIsam does full text search, InnoDB doesn't
  4. I have been told InnoDB is faster on executing writes but slower than MyISAM doing reads (I cannot back this up and could not find any article that analyses this, I do however have the guy that told me this in high regard), feel free to ignore this point or do your own research.
  5. Default configuration does not work very well for InnoDB needs to be tweaked accordingly, run a tool like http://mysqltuner.pl/mysqltuner.pl to help you.

Notes:

  • In my opinion the second point is probably the one were InnoDB has a huge advantage over MyISAM.
  • Full text search not working with InnoDB is a bit of a pain, You can mix different storage engines but be careful when doing so.

Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.

.htaccess not working apache

  1. Enable Apache mod_rewrite module

    a2enmod rewrite

  2. add the following code to /etc/apache2/sites-available/default

    AllowOverride All

  3. Restart apache

    /etc/init.d/apache2 restart

How to choose between Hudson and Jenkins?

Up front .. I am a Hudson committer and author of the Hudson book, but I was not involved in the whole split of the projects.

In any case here is my advice:

Check out both and see what fits your needs better.

Hudson is going to complete the migration to be a top level Eclipse projects later this year and has gotten a whole bunch of full time developers, QA and others working on the project. It is still going strong and has a lot of users and with being the default CI server at Eclipse it will continue to serve the needs of many Java developers. Looking at the roadmap and plans for the future you can see that after the Maven 3 integration accomplished with the 2.1.0 release a whole bunch of other interesting feature are ahead.

http://www.eclipse.org/hudson

Jenkins on the other side has won over many original Hudson users and has a large user community across multiple technologies and also has a whole bunch of developers working on it.

At this stage both CI servers are great tools to use and depending on your needs in terms of technology to integrate with one or the other might be better. Both products are available as open source and you can get commercial support from various companies for both.

In any case .. if you are not using a CI server yet.. start now with either of them and you will see huge benefits.

Update Jan 2013: After a long process of IP cleanup and further improvements Hudson 3.0 as the first Eclipse foundation approved release is now available.

Storing money in a decimal column - what precision and scale?

4 decimal places would give you the accuracy to store the world's smallest currency sub-units. You can take it down further if you need micropayment (nanopayment?!) accuracy.

I too prefer DECIMAL to DBMS-specific money types, you're safer keeping that kind of logic in the application IMO. Another approach along the same lines is simply to use a [long] integer, with formatting into ¤unit.subunit for human readability (¤ = currency symbol) done at the application level.

Pip error: Microsoft Visual C++ 14.0 is required

Try doing this:

py -m pip install pipwin
py -m pipwin install PyAudio

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This error occurs when you are sending JSON data to server. Maybe in your string you are trying to add new line character by using /n.

If you add / before /n, it should work, you need to escape new line character.

"Hello there //n start coding"

The result should be as following

Hello there
start coding

How do I import the javax.servlet API in my Eclipse project?

Little bit difference from Hari:

Right click on project ---> Properties ---> Java Build Path ---> Add Library... ---> Server Runtime ---> Apache Tomcat ----> Finish.

In C/C++ what's the simplest way to reverse the order of bits in a byte?

I think a lookup table has to be one of the simplest methods. However, you don't need a full lookup table.

//Index 1==0b0001 => 0b1000
//Index 7==0b0111 => 0b1110
//etc
static unsigned char lookup[16] = {
0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe,
0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf, };

uint8_t reverse(uint8_t n) {
   // Reverse the top and bottom nibble then swap them.
   return (lookup[n&0b1111] << 4) | lookup[n>>4];
}

// Detailed breakdown of the math
//  + lookup reverse of bottom nibble
//  |       + grab bottom nibble
//  |       |        + move bottom result into top nibble
//  |       |        |     + combine the bottom and top results 
//  |       |        |     | + lookup reverse of top nibble
//  |       |        |     | |       + grab top nibble
//  V       V        V     V V       V
// (lookup[n&0b1111] << 4) | lookup[n>>4]

This fairly simple to code and verify visually.
Ultimately this might even be faster than a full table. The bit arith is cheap and the table easily fits on a cache line.

python pandas convert index to datetime

Doing

df.index = pd.to_datetime(df.index, errors='coerce')

the data type of the index has changed to

dataframe information

How do I resolve `The following packages have unmet dependencies`

Installing nodejs will install npm ... so just remove nodejs then reinstall it: $ sudo apt-get remove nodejs

$ sudo apt-get --purge remove nodejs node npm
$ sudo apt-get clean
$ sudo apt-get autoclean
$ sudo apt-get -f install
$ sudo apt-get autoremove

How to return a specific status code and no contents from Controller?

This code might work for non-.NET Core MVC controllers:

this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);

TypeError: argument of type 'NoneType' is not iterable

The python error says that wordInput is not an iterable -> it is of NoneType.

If you print wordInput before the offending line, you will see that wordInput is None.

Since wordInput is None, that means that the argument passed to the function is also None. In this case word. You assign the result of pickEasy to word.

The problem is that your pickEasy function does not return anything. In Python, a method that didn't return anything returns a NoneType.

I think you wanted to return a word, so this will suffice:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

Key Listeners in python?

Although I like using the keyboard module to capture keyboard events, I don't like its record() function because it returns an array like [KeyboardEvent("A"), KeyboardEvent("~")], which I find kind of hard to read. So, to record keyboard events, I like to use the keyboard module and the threading module simultaneously, like this:

import keyboard
import string
from threading import *


# I can't find a complete list of keyboard keys, so this will have to do:
keys = list(string.ascii_lowercase)
"""
Optional code(extra keys):

keys.append("space_bar")
keys.append("backspace")
keys.append("shift")
keys.append("esc")
"""
def listen(key):
    while True:
        keyboard.wait(key)
        print("[+] Pressed",key)
threads = [Thread(target=listen, kwargs={"key":key}) for key in keys]
for thread in threads:
    thread.start()

One liner for If string is not null or empty else

You could use the ternary operator:

return string.IsNullOrEmpty(strTestString) ? "0" : strTestString

FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;

Decimal number regular expression, where digit after decimal is optional

try this. ^[0-9]\d{0,9}(\.\d{1,3})?%?$ it is tested and worked for me.

How to write a caption under an image?

<div style="margin: 0 auto; text-align: center; overflow: hidden;">
  <div style="float: left;">
    <a href="http://xyz.com/hello"><img src="hello.png" width="100px" height="100px"></a>
    caption 1
  </div>
 <div style="float: left;">
   <a href="http://xyz.com/hi"><img src="hi.png" width="100px" height="100px"></a>
   caption 2                      
 </div>
</div>

Fixed point vs Floating point number

From my understanding, fixed-point arithmetic is done using integers. where the decimal part is stored in a fixed amount of bits, or the number is multiplied by how many digits of decimal precision is needed.

For example, If the number 12.34 needs to be stored and we only need two digits of precision after the decimal point, the number is multiplied by 100 to get 1234. When performing math on this number, we'd use this rule set. Adding 5620 or 56.20 to this number would yield 6854 in data or 68.54.

If we want to calculate the decimal part of a fixed-point number, we use the modulo (%) operand.

12.34 (pseudocode):

v1 = 1234 / 100 // get the whole number
v2 = 1234 % 100 // get the decimal number (100ths of a whole).
print v1 + "." + v2 // "12.34"

Floating point numbers are a completely different story in programming. The current standard for floating point numbers use something like 23 bits for the data of the number, 8 bits for the exponent, and 1 but for sign. See this Wikipedia link for more information on this.

Change default text in input type="file"?

Here how you can do it:

jQuery:

$(function() {
  $("#labelfile").click(function() {
    $("#imageupl").trigger('click');
  });
})

css

.file {
  position: absolute;
  clip: rect(0px, 0px, 0px, 0px);
  display: block;
}
.labelfile {
  color: #333;
  background-color: #fff;
  display: inline-block;
  margin-bottom: 0;
  font-weight: 400;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  background-image: none;
  white-space: nowrap;
  padding: 6px 8px;
  font-size: 14px;
  line-height: 1.42857143;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

HTML code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div style="margin-top:4px;">
  <input name="imageupl" type="file" id="imageupl" class="file" />
  <label class="labelfile" id="labelfile"><i class="icon-download-alt"></i> Browse File</label>
</div>

Ruby - test for array

It sounds like you're after something that has some concept of items. I'd thus recommend seeing if it is Enumerable. That also guarantees the existence of #count.

For example,

[1,2,3].is_a? Enumerable
[1,2,3].count

note that, while size, length and count all work for arrays, count is the right meaning here - (for example, 'abc'.length and 'abc'.size both work, but 'abc'.count doesn't work like that).

Caution: a string is_a? Enumerable, so perhaps this isn't what you want... depends on your concept of an array like object.

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

You have to pass the route parameters to the route method, for example:

<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>

It's because, both routes have a {nickname} in the route declaration. I've used $nickname for example but make sure you change the $nickname to appropriate value/variable, for example, it could be something like the following:

<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>

What is a "slug" in Django?

slug

A short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. For example, in a typical blog entry URL:

https://www.djangoproject.com/weblog/2008/apr/12/spring/ the last bit (spring) is the slug.

How to format a floating number to fixed width in Python

In python3 the following works:

>>> v=10.4
>>> print('% 6.2f' % v)
  10.40
>>> print('% 12.1f' % v)
        10.4
>>> print('%012.1f' % v)
0000000010.4

Make div scrollable

use overflow:auto property, If overflow is clipped, a scroll-bar should be added to see the rest of the content,and mention the height

DEMO

 .itemconfiguration
    {
        height: 440px;
        width: 215px;
        overflow: auto;
        float: left;
        position: relative;
        margin-left: -5px;
    }

How do I fix the multiple-step OLE DB operation errors in SSIS?

You can use SELECT * FROM INFORMATION_SCHEMA.COLUMNS but I suspect you created the destination database from a script of the source database so it is very likely that they columns will be the same.

Some comparisons might bring something up though.

These sorts of errors sometimes come from trying to insert too much data into varchar columns too.

How to make a .NET Windows Service start right after the installation?

The easiest solution is found here install-windows-service-without-installutil-exe by @Hoàng Long

@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"

echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause

Javascript to convert UTC to local time

To format your date try the following function:

var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");

But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).

Chris

Android Call an method from another class

And, if you don't want to instantiate Class2, declare UpdateEmployee as static and call it like this:

Class2.UpdateEmployee();

However, you'll normally want to do what @parag said.

Laravel - Session store not set on request

If Cas Bloem's answer does not apply (i.e. you've definitely got the web middleware on the applicable route), you might want to check the order of middlewares in your HTTP Kernel.

The default order in Kernel.php is this:

$middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],
];

Note that VerifyCsrfToken comes after StartSession. If you've got these in a different order, the dependency between them can also lead to the Session store not set on request. exception.

Angular 2 - NgFor using numbers instead collections

Please find attached my dynamic solution if you want to increase the size of an array dynamically after clicking on a button (This is how I got to this question).

Allocation of necessary variables:

  array = [1];
  arraySize: number;

Declare the function that adds an element to the array:

increaseArrayElement() {
   this.arraySize = this.array[this.array.length - 1 ];
   this.arraySize += 1;
   this.array.push(this.arraySize);
   console.log(this.arraySize);
}

Invoke the function in html

  <button md-button (click)="increaseArrayElement()" >
      Add element to array
  </button>

Iterate through array with ngFor:

<div *ngFor="let i of array" >
  iterateThroughArray: {{ i }}
</div>

How to force view controller orientation in iOS 8?

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [UIViewController attemptRotationToDeviceOrientation];
}

IIS7 Settings File Locations

It sounds like you're looking for applicationHost.config, which is located in C:\Windows\System32\inetsrv\config.

Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config and web.config.

Global variables in Javascript across multiple files

I think you should be using "local storage" rather than global variables.

If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.

I used http://www.jstorage.info/ and I'm happy with it so far.

How to resize an image to fit in the browser window?

Update 2018-04-11

Here's a Javascript-less, CSS-only solution. The image will dynamically be centered and resized to fit the window.

<html>
<head>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .imgbox {
            display: grid;
            height: 100%;
        }
        .center-fit {
            max-width: 100%;
            max-height: 100vh;
            margin: auto;
        }
    </style>
</head>
<body>
<div class="imgbox">
    <img class="center-fit" src='pic.png'>
</div>
</body>
</html>

The [other, old] solution, using JQuery, sets the height of the image container (body in the example below) so that the max-height property on the image works as expected. The image will also automatically resize when the client window is resized.

<!DOCTYPE html>
<html>
<head>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
        .fit { /* set relative picture size */
            max-width: 100%;
            max-height: 100%;
        }
        .center {
            display: block;
            margin: auto;
        }
    </style>
</head>
<body>

<img class="center fit" src="pic.jpg" >

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="JavaScript">
    function set_body_height() { // set body height = window height
        $('body').height($(window).height());
    }
    $(document).ready(function() {
        $(window).bind('resize', set_body_height);
        set_body_height();
    });
</script>

</body>
</html>

Note: User gutierrezalex packaged a very similar solution as a JQuery plugin on this page.

jQuery autohide element after 5 seconds

$(function() {
    // setTimeout() function will be fired after page is loaded
    // it will wait for 5 sec. and then will fire
    // $("#successMessage").hide() function
    setTimeout(function() {
        $("#successMessage").hide('blind', {}, 500)
    }, 5000);
});

Note: In order to make you jQuery function work inside setTimeout you should wrap it inside

function() { ... }

RuntimeError on windows trying python multiprocessing

Try putting your code inside a main function in testMain.py

import parallelTestModule

if __name__ ==  '__main__':
  extractor = parallelTestModule.ParallelExtractor()
  extractor.runInParallel(numProcesses=2, numThreads=4)

See the docs:

"For an explanation of why (on Windows) the if __name__ == '__main__' 
part is necessary, see Programming guidelines."

which say

"Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process)."

... by using if __name__ == '__main__'

Android View shadow

I know this is stupidly hacky,
but if you want to support under v21, here are my achievements.

rectangle_with_10dp_radius_white_bg_and_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Shadow layers -->
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_1" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_2" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_3" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_4" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_5" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_6" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_7" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_8" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_9" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_10" />
        </shape>
    </item>

    <!-- Background layer -->
    <item>
        <shape>
            <solid android:color="@android:color/white" />
            <corners android:radius="10dp" />
        </shape>
    </item>

</layer-list>

rectangle_with_10dp_radius_white_bg_and_shadow.xml (v21)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white" />
    <corners android:radius="10dp" />
</shape>

view_incoming.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/rectangle_with_10dp_radius_white_bg_and_shadow"
    android:elevation="7dp"
    android:gravity="center"
    android:minWidth="240dp"
    android:minHeight="240dp"
    android:orientation="horizontal"
    android:padding="16dp"
    tools:targetApi="lollipop">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="Hello World !" />

</LinearLayout>

Here is result:

Under v21 (this is which you made with xml) enter image description here

Above v21 (real elevation rendering) enter image description here

  • The one significant difference is it will occupy the inner space from the view so your actual content area can be smaller than >= lollipop devices.

Auto refresh page every 30 seconds

If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.

javascript:

<script language="javascript">
setTimeout(function(){
   window.location.reload(1);
}, 30000);
</script>

base64 encode in MySQL

Yet another custom implementation that doesn't require support table:

drop function if exists base64_encode;
create function base64_encode(_data blob)
returns text
begin
    declare _alphabet char(64) default 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    declare _lim int unsigned default length(_data);
    declare _i int unsigned default 0;
    declare _chk3 char(6) default '';
    declare _chk3int int default 0;
    declare _enc text default '';

    while _i < _lim do
        set _chk3 = rpad(hex(binary substr(_data, _i + 1, 3)), 6, '0');
        set _chk3int = conv(_chk3, 16, 10);
        set _enc = concat(
            _enc
            ,                  substr(_alphabet, ((_chk3int >> 18) & 63) + 1, 1)
            , if (_lim-_i > 0, substr(_alphabet, ((_chk3int >> 12) & 63) + 1, 1), '=')
            , if (_lim-_i > 1, substr(_alphabet, ((_chk3int >>  6) & 63) + 1, 1), '=')
            , if (_lim-_i > 2, substr(_alphabet, ((_chk3int >>  0) & 63) + 1, 1), '=')
        );
        set _i = _i + 3;
    end while;

    return _enc;
end;

drop function if exists base64_decode;
create function base64_decode(_enc text)
returns blob
begin
    declare _alphabet char(64) default 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    declare _lim int unsigned default 0;
    declare _i int unsigned default 0;
    declare _chr1byte tinyint default 0;
    declare _chk4int int default 0;
    declare _chk4int_bits tinyint default 0;
    declare _dec blob default '';
    declare _rem tinyint default 0;
    set _enc = trim(_enc);
    set _rem = if(right(_enc, 3) = '===', 3, if(right(_enc, 2) = '==', 2, if(right(_enc, 1) = '=', 1, 0)));
    set _lim = length(_enc) - _rem;

    while _i < _lim
    do
        set _chr1byte = locate(substr(_enc, _i + 1, 1), binary _alphabet) - 1;
        if (_chr1byte > -1)
        then
            set _chk4int = (_chk4int << 6) | _chr1byte;
            set _chk4int_bits = _chk4int_bits + 6;

            if (_chk4int_bits = 24 or _i = _lim-1)
            then
                if (_i = _lim-1 and _chk4int_bits != 24)
                then
                    set _chk4int = _chk4int << 0;
                end if;

                set _dec = concat(
                    _dec
                    ,                        char((_chk4int >> (_chk4int_bits -  8)) & 0xff)
                    , if(_chk4int_bits >  8, char((_chk4int >> (_chk4int_bits - 16)) & 0xff), '\0')
                    , if(_chk4int_bits > 16, char((_chk4int >> (_chk4int_bits - 24)) & 0xff), '\0')
                );
                set _chk4int = 0;
                set _chk4int_bits = 0;
            end if;
        end if;
        set _i = _i + 1;
    end while;

    return substr(_dec, 1, length(_dec) - _rem);
end;

Gist

You should convert charset after decoding: convert(base64_decode(base64_encode('????')) using utf8)

How do I change the ID of a HTML element with JavaScript?

That seems to work for me:

<html>
<head><style>
#monkey {color:blue}
#ape {color:purple}
</style></head>
<body>
<span id="monkey" onclick="changeid()">
fruit
</span>
<script>
function changeid ()
{
var e = document.getElementById("monkey");
e.id = "ape";
}
</script>
</body>
</html>

The expected behaviour is to change the colour of the word "fruit".

Perhaps your document was not fully loaded when you called the routine?

Java - How to find the redirected url of a url?

You need to cast the URLConnection to HttpURLConnection and instruct it to not follow the redirects by setting HttpURLConnection#setInstanceFollowRedirects() to false. You can also set it globally by HttpURLConnection#setFollowRedirects().

You only need to handle redirects yourself then. Check the response code by HttpURLConnection#getResponseCode(), grab the Location header by URLConnection#getHeaderField() and then fire a new HTTP request on it.

Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?

We can give a default value for the timestamp to avoid this problem.

This post gives a detailed workaround: http://gusiev.com/2009/04/update-and-create-timestamps-with-mysql/

create table test_table( 
id integer not null auto_increment primary key, 
stamp_created timestamp default '0000-00-00 00:00:00', 
stamp_updated timestamp default now() on update now() 
);

Note that it is necessary to enter nulls into both columns during "insert":

mysql> insert into test_table(stamp_created, stamp_updated) values(null, null); 
Query OK, 1 row affected (0.06 sec)
mysql> select * from t5; 
+----+---------------------+---------------------+ 
| id | stamp_created       | stamp_updated       |
+----+---------------------+---------------------+
|  2 | 2009-04-30 09:44:35 | 2009-04-30 09:44:35 |
+----+---------------------+---------------------+
2 rows in set (0.00 sec)  
mysql> update test_table set id = 3 where id = 2; 
Query OK, 1 row affected (0.05 sec) Rows matched: 1  Changed: 1  Warnings: 0  
mysql> select * from test_table;
+----+---------------------+---------------------+
| id | stamp_created       | stamp_updated       | 
+----+---------------------+---------------------+ 
|  3 | 2009-04-30 09:44:35 | 2009-04-30 09:46:59 | 
+----+---------------------+---------------------+ 
2 rows in set (0.00 sec) 

How to get the last day of the month?

If you pass in a date range, you can use this:

def last_day_of_month(any_days):
    res = []
    for any_day in any_days:
        nday = any_day.days_in_month -any_day.day
        res.append(any_day + timedelta(days=nday))
    return res

How to disable anchor "jump" when loading a page?

None of answers do not work good enough for me, I see page jumping to anchor and then to top for some solutions, some answers do not work at all, may be things changed for years. Hope my function will help to someone.

/**
 * Prevent automatic scrolling of page to anchor by browser after loading of page.
 * Do not call this function in $(...) or $(window).on('load', ...),
 * it should be called earlier, as soon as possible.
 */
function preventAnchorScroll() {
    var scrollToTop = function () {
        $(window).scrollTop(0);
    };
    if (window.location.hash) {
        // handler is executed at most once
        $(window).one('scroll', scrollToTop);
    }

    // make sure to release scroll 1 second after document readiness
    // to avoid negative UX
    $(function () {
        setTimeout(
            function () {
                $(window).off('scroll', scrollToTop);
            },
            1000
        );
    });
}

XmlWriter to Write to a String Instead of to a File

Use StringBuilder:

var sb = new StringBuilder();
    using (XmlWriter xmlWriter = XmlWriter.Create(sb))
    {
        ...
    }
return sb.ToString();

CSS Transition doesn't work with top, bottom, left, right

I ran into this issue today. Here is my hacky solution.

I needed a fixed position element to transition up by 100 pixels as it loaded.

var delay = (ms) => new Promise(res => setTimeout(res, ms));
async function animateView(startPosition,elm){
  for(var i=0; i<101; i++){
    elm.style.top = `${(startPosition-i)}px`;
    await delay(1);
  }
}

How do I make a WinForms app go Full Screen

On the Form Move Event add this:

private void Frm_Move (object sender, EventArgs e)
{
    Top = 0; Left = 0;
    Size = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
}

MySQL Query GROUP BY day / month / year

Complete and simple solution with similarly performing yet shorter and more flexible alternative currently active:

SELECT COUNT(*) FROM stats
-- GROUP BY YEAR(record_date), MONTH(record_date), DAYOFMONTH(record_date)
GROUP BY DATE_FORMAT(record_date, '%Y-%m-%d')

jQuery function to get all unique elements from an array?

    // for numbers
    a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
    $.unique(a)
    [7, 6, 1, 8, 3, 2, 5, 4]

    // for string
    a = ["a", "a", "b"]
    $.unique(a)
    ["b", "a"]

And for dom elements there is no example is needed here I guess because you already know that!

Here is the jsfiddle link of live example: http://jsfiddle.net/3BtMc/4/

Adding link a href to an element using css

You don't need CSS for this.

     <img src="abc"/>

now with link:

     <a href="#myLink"><img src="abc"/></a>

Or with jquery, later on, you can use the wrap property, see these questions answer:

how to add a link to an image using jquery?