Programs & Examples On #Leaky abstraction

How to present a simple alert message in java?

If you don't like "verbosity" you can always wrap your code in a short method:

private void msgbox(String s){
   JOptionPane.showMessageDialog(null, s);
}

and the usage:

msgbox("don't touch that!");

Laravel Eloquent LEFT JOIN WHERE NULL

Although Other Answers work well, i want to give you alternate short version which i use very often:

Customer::select('customers.*')
        ->leftJoin('orders', 'customers.id', '=', 'orders.customer_id')
        ->whereNull('orders.customer_id')->first();

And as in laravel version 5.3 added one more feature which will make your work even simpler look below for example:

Customer::doesntHave('orders')->get();

Differences between C++ string == and compare()?

compare has overloads for comparing substrings. If you're comparing whole strings you should just use == operator (and whether it calls compare or not is pretty much irrelevant).

How to create a stopwatch using JavaScript?

A simple and easy clock for you and don't forget me ;)

_x000D_
_x000D_
var x;_x000D_
var startstop = 0;_x000D_
_x000D_
function startStop() { /* Toggle StartStop */_x000D_
_x000D_
  startstop = startstop + 1;_x000D_
_x000D_
  if (startstop === 1) {_x000D_
    start();_x000D_
    document.getElementById("start").innerHTML = "Stop";_x000D_
  } else if (startstop === 2) {_x000D_
    document.getElementById("start").innerHTML = "Start";_x000D_
    startstop = 0;_x000D_
    stop();_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function start() {_x000D_
  x = setInterval(timer, 10);_x000D_
} /* Start */_x000D_
_x000D_
function stop() {_x000D_
  clearInterval(x);_x000D_
} /* Stop */_x000D_
_x000D_
var milisec = 0;_x000D_
var sec = 0; /* holds incrementing value */_x000D_
var min = 0;_x000D_
var hour = 0;_x000D_
_x000D_
/* Contains and outputs returned value of  function checkTime */_x000D_
_x000D_
var miliSecOut = 0;_x000D_
var secOut = 0;_x000D_
var minOut = 0;_x000D_
var hourOut = 0;_x000D_
_x000D_
/* Output variable End */_x000D_
_x000D_
_x000D_
function timer() {_x000D_
  /* Main Timer */_x000D_
_x000D_
_x000D_
  miliSecOut = checkTime(milisec);_x000D_
  secOut = checkTime(sec);_x000D_
  minOut = checkTime(min);_x000D_
  hourOut = checkTime(hour);_x000D_
_x000D_
  milisec = ++milisec;_x000D_
_x000D_
  if (milisec === 100) {_x000D_
    milisec = 0;_x000D_
    sec = ++sec;_x000D_
  }_x000D_
_x000D_
  if (sec == 60) {_x000D_
    min = ++min;_x000D_
    sec = 0;_x000D_
  }_x000D_
_x000D_
  if (min == 60) {_x000D_
    min = 0;_x000D_
    hour = ++hour;_x000D_
_x000D_
  }_x000D_
_x000D_
_x000D_
  document.getElementById("milisec").innerHTML = miliSecOut;_x000D_
  document.getElementById("sec").innerHTML = secOut;_x000D_
  document.getElementById("min").innerHTML = minOut;_x000D_
  document.getElementById("hour").innerHTML = hourOut;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
/* Adds 0 when value is <10 */_x000D_
_x000D_
_x000D_
function checkTime(i) {_x000D_
  if (i < 10) {_x000D_
    i = "0" + i;_x000D_
  }_x000D_
  return i;_x000D_
}_x000D_
_x000D_
function reset() {_x000D_
_x000D_
_x000D_
  /*Reset*/_x000D_
_x000D_
  milisec = 0;_x000D_
  sec = 0;_x000D_
  min = 0_x000D_
  hour = 0;_x000D_
_x000D_
  document.getElementById("milisec").innerHTML = "00";_x000D_
  document.getElementById("sec").innerHTML = "00";_x000D_
  document.getElementById("min").innerHTML = "00";_x000D_
  document.getElementById("hour").innerHTML = "00";_x000D_
_x000D_
}
_x000D_
<h1>_x000D_
  <span id="hour">00</span> :_x000D_
  <span id="min">00</span> :_x000D_
  <span id="sec">00</span> :_x000D_
  <span id="milisec">00</span>_x000D_
</h1>_x000D_
_x000D_
<button onclick="startStop()" id="start">Start</button>_x000D_
<button onclick="reset()">Reset</button>
_x000D_
_x000D_
_x000D_

Ping a site in Python?

you might try socket to get ip of the site and use scrapy to excute icmp ping to the ip.

import gevent
from gevent import monkey
# monkey.patch_all() should be executed before any library that will
# standard library
monkey.patch_all()

import socket
from scapy.all import IP, ICMP, sr1


def ping_site(fqdn):
    ip = socket.gethostbyaddr(fqdn)[-1][0]
    print(fqdn, ip, '\n')
    icmp = IP(dst=ip)/ICMP()
    resp = sr1(icmp, timeout=10)
    if resp:
        return (fqdn, False)
    else:
        return (fqdn, True)


sites = ['www.google.com', 'www.baidu.com', 'www.bing.com']
jobs = [gevent.spawn(ping_site, fqdn) for fqdn in sites]
gevent.joinall(jobs)
print([job.value for job in jobs])

No function matches the given name and argument types

In my particular case the function was actually missing. The error message is the same. I am using the Postgresql plugin PostGIS and I had to reinstall that for whatever reason.

How do I find the MySQL my.cnf location

Be aware that although mariadDB loads configuration details from the various my.cnf files as listed in the other answers here, it can also load them from other files with different names.

That means that if you make a change in one of the my.cnf files, it may get overwritten by another file of a different name. To make the change stick, you need to change it in the right (last loaded) config file - or, maybe, change it in all of them.

So how do you find all the config files that might be loaded? Instead of looking for my.cnf files, try running:

grep -r datadir /etc/mysql/

This will find all the places in which datadir is mentioned. In my case, it produces this answer:

/etc/mysql/mariadb.conf.d/50-server.cnf:datadir     = /var/lib/mysql 

When I edit that file (/etc/mysql/mariadb.conf.d/50-server.cnf) to change the value for datadir, it works, whereas changing it in my.cnf does not. So whatever option you are wanting to change, try looking for it this way.

Value cannot be null. Parameter name: source

My reason was different to the rest here so I thought I'd post it for anyone else who might have this issue.

I was calling Count on an instance of DbSet with a filter of null i.e.

dbSet.Count(null);

I found that passing null here was causing the error so I now call the parameter-less method if the filter is null:

 if (filter == null)
 {
     return dbSet.Count();
 }
 else
 {
     return dbSet.Count(filter);
 }

This sorted the issue for me. This may be an issue for any other methods on DbSet as well.

SQLAlchemy equivalent to SQL "LIKE" statement

If you use native sql, you can refer to my code, otherwise just ignore my answer.

SELECT * FROM table WHERE tags LIKE "%banana%";
from sqlalchemy import text

bar_tags = "banana"

# '%' attention to spaces
query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""

# db is sqlalchemy session object
tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()

Windows 7: unable to register DLL - Error Code:0X80004005

Open the start menu and type cmd into the search box Hold Ctrl + Shift and press Enter

This runs the Command Prompt in Administrator mode.

Now type regsvr32 MyComobject.dll

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

Microsoft.ReportViewer.Common Version=12.0.0.0

Issue

Parser Error Message: Could not load file or assembly 'Microsoft.ReportViewer.WebForms / Winforms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

Cause

Microsoft ReportViewer runtime and SQL CLR Types for SQL Server 2014 is required to run and is missing from the server hosting Internet Information Services (IIS) or your application.

Resolution

Install the following packages on the IIS server and then restart the system:

Download Microsoft ReportViewer runtime

Download Microsoft SQL CLR types for SQL Server 2014

Once restarted connect to Web service / Your app again and verify that the error has been resolved.

Or you cant follow this link to read more.

How to manually reload Google Map with JavaScript

You can refresh with this:

map.panBy(0, 0);

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

How to delete files recursively from an S3 bucket

In case using AWS-SKD for ruby V2.

s3.list_objects(bucket: bucket_name, prefix: "foo/").contents.each do |obj|
  next if obj.key == "foo/" 
  resp = s3.delete_object({
    bucket: bucket_name,
    key: obj.key,
  })
end

attention please, all "foo/*" under bucket will delete.

Environment variable substitution in sed

Dealing with VARIABLES within sed

[root@gislab00207 ldom]# echo domainname: None > /tmp/1.txt

[root@gislab00207 ldom]# cat /tmp/1.txt

domainname: None

[root@gislab00207 ldom]# echo ${DOMAIN_NAME}

dcsw-79-98vm.us.oracle.com

[root@gislab00207 ldom]# cat /tmp/1.txt | sed -e 's/domainname: None/domainname: ${DOMAIN_NAME}/g'

 --- Below is the result -- very funny.

domainname: ${DOMAIN_NAME}

 --- You need to single quote your variable like this ... 

[root@gislab00207 ldom]# cat /tmp/1.txt | sed -e 's/domainname: None/domainname: '${DOMAIN_NAME}'/g'


--- The right result is below 

domainname: dcsw-79-98vm.us.oracle.com

How to pretty print XML from the command line?

This took me forever to find something that works on my mac. Here's what worked for me:

brew install xmlformat
cat unformatted.html | xmlformat

ActivityCompat.requestPermissions not showing dialog box

It could be not a problem with a single line of your code.

On some devices (I don't recall if it is in stock Android) the Permission dialog includes a check box labeled "Never ask again". If you click Deny with the box checked then you won't be prompted again for that permission, it will automatically be denied to the app. To revert this, you have to go into Settings -> App -> Permissions and re--enable that perm for the app. Then turn it off to deny it again. You may have to open the app before turning it off again, not sure.

I don't know if your Nexus has it. Maybe worth a try.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

This is because after the nextInt() finished it's execution, when the nextLine() method is called, it scans the newline character of which was present after the nextInt(). You can do this in either of the following ways:

  1. You can use another nextLine() method just after the nextInt() to move the scanner past the newline character.
  2. You can use different Scanner objects for scanning the integer and string (You can name them scan1 and scan2).
  3. You can use the next method on the scanner object as

    scan.next();

npm install error from the terminal

I came across this, and my issue was using an older version of node (3.X), when a newer version was required.

The error message actually suggested this as well:

...
Make sure you have the latest version of node.js and npm installed
...

So the solution may be as simple as upgrading node/npm. You can easily do this using nvm, the "Node Version Manager"

After you've installed nvm, you can install and use the latest version of node by simply running this command:

nvm install node

For example:

$ nvm install node                                                             
Downloading https://nodejs.org/dist/v8.2.1/node-v8.2.1-darwin-x64.tar.xz...
######################################################################## 100.0%
Now using node v8.2.1 (npm v5.3.0)

$ node --version                                                               
v8.2.1

Calling a JavaScript function returned from an Ajax response

I would like to add that there's an eval function in jQuery allowing you to eval the code globally which should get you rid of any contextual problems. The function is called globalEval() and it worked great for my purposes. Its documentation can be found here.

This is the example code provided by the jQuery API documentation:

function test()
{
  jQuery.globalEval("var newVar = true;")
}

test();
// newVar === true

This function is extremely useful when it comes to loading external scripts dynamically which you apparently were trying to do.

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

Python Brute Force algorithm

If you REALLY want to brute force it, try this, but it will take you a ridiculous amount of time:

your_list = 'abcdefghijklmnopqrstuvwxyz'
complete_list = []
for current in xrange(10):
    a = [i for i in your_list]
    for y in xrange(current):
        a = [x+i for i in your_list for x in a]
    complete_list = complete_list+a

On a smaller example, where list = 'ab' and we only go up to 5, this prints the following:

['a', 'b', 'aa', 'ba', 'ab', 'bb', 'aaa', 'baa', 'aba', 'bba', 'aab', 'bab', 'abb', 'bbb', 'aaaa', 'baaa', 'abaa', 'bbaa', 'aaba', 'baba', 'abba', 'bbba', 'aaab', 'baab', 'abab', 'bbab', 'aabb', 'babb', 'abbb', 'bbbb', 'aaaaa', 'baaaa', 'abaaa', 'bbaaa', 'aabaa', 'babaa', 'abbaa', 'bbbaa', 'aaaba','baaba', 'ababa', 'bbaba', 'aabba', 'babba', 'abbba', 'bbbba', 'aaaab', 'baaab', 'abaab', 'bbaab', 'aabab', 'babab', 'abbab', 'bbbab', 'aaabb', 'baabb', 'ababb', 'bbabb', 'aabbb', 'babbb', 'abbbb', 'bbbbb']

Complex numbers usage in python

In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:

>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)

The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)

The type of a complex number is complex, and you can use the type as a constructor if you prefer:

>>> complex(2,3)
(2+3j)

A complex number has some built-in accessors:

>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)

Several built-in functions support complex numbers:

>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)

The standard module cmath has more functions that handle complex numbers:

>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)

How can I divide two integers stored in variables in Python?

Use this line to get the division behavior you want:

from __future__ import division

Alternatively, you could use modulus:

if (a % b) == 0: #do something

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

If you get this error due to foreach and you really need to save one entity first inside loop and use generated identity further in loop, as was in my case, the easiest solution is to use another DBContext to insert entity which will return Id and use this Id in outer context

For example

    using (var context = new DatabaseContext())
    {
        ...
        using (var context1 = new DatabaseContext())
        {
            ...
               context1.SaveChanges();
        }                         
        //get id of inserted object from context1 and use is.   
      context.SaveChanges();
   }

How to input a path with a white space?

SOME_PATH=/mnt/someProject/some\ path

should work

How can I INSERT data into two tables simultaneously in SQL Server?

Try this:

insert into [table] ([data])
output inserted.id, inserted.data into table2
select [data] from [external_table]

UPDATE: Re:

Denis - this seems very close to what I want to do, but perhaps you could fix the following SQL statement for me? Basically the [data] in [table1] and the [data] in [table2] represent two different/distinct columns from [external_table]. The statement you posted above only works when you want the [data] columns to be the same.

INSERT INTO [table1] ([data]) 
OUTPUT [inserted].[id], [external_table].[col2] 
INTO [table2] SELECT [col1] 
FROM [external_table] 

It's impossible to output external columns in an insert statement, so I think you could do something like this

merge into [table1] as t
using [external_table] as s
on 1=0 --modify this predicate as necessary
when not matched then insert (data)
values (s.[col1])
output inserted.id, s.[col2] into [table2]
;

How to use Jackson to deserialise an array of objects

First create a mapper :

import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();

As Array:

MyClass[] myObjects = mapper.readValue(json, MyClass[].class);

As List:

List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});

Another way to specify the List type:

List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));

Using Django time/date widgets in custom form

The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that.

That said, here's what you have to do if you're determined to make this work:

  1. Define your own ModelForm subclass for your model (best to put it in forms.py in your app), and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace 'mydate' etc with the proper field names from your model):

    from django import forms
    from my_app.models import Product
    from django.contrib.admin import widgets                                       
    
    class ProductForm(forms.ModelForm):
        class Meta:
            model = Product
        def __init__(self, *args, **kwargs):
            super(ProductForm, self).__init__(*args, **kwargs)
            self.fields['mydate'].widget = widgets.AdminDateWidget()
            self.fields['mytime'].widget = widgets.AdminTimeWidget()
            self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()
    
  2. Change your URLconf to pass 'form_class': ProductForm instead of 'model': Product to the generic create_object view (that'll mean "from my_app.forms import ProductForm" instead of "from my_app.models import Product", of course).

  3. In the head of your template, include {{ form.media }} to output the links to the Javascript files.

  4. And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above {{ form.media }} you'll need:

    <script type="text/javascript" src="/my_admin/jsi18n/"></script>
    <script type="text/javascript" src="/media/admin/js/core.js"></script>
    

    You may also wish to use the following admin CSS (thanks Alex for mentioning this):

    <link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/>
    <link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/>
    <link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/>
    <link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/>
    

This implies that Django's admin media (ADMIN_MEDIA_PREFIX) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question.

This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript_catalog view (or null_javascript_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks Jeremy for pointing this out). Sample code for your URLconf:

(r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'),

Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media:

{% load adminmedia %} /* At the top of the template. */

/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";
</script>

Thanks lupefiasco for this addition.

Activating Anaconda Environment in VsCode

Simply use

  1. shift + cmd + P
  2. Search Select Interpreter

pyhton : Select Interpreter

  1. Select it and it will show you the list of your virtual environment created via conda and other python versions

Activating conda virtual environment

  1. select the environment and you are ready to go.

Quoting the 'Select and activate an environment' docs

Selecting an interpreter from the list adds an entry for python.pythonPath with
the path to the interpreter inside your Workspace Settings.

How to Cast Objects in PHP

You can opt for this example below. Hope it will help.

/** @var ClassName $object */

$object->whateverMethod() // any method defined in the class can be accessed by $object

I know this is not a cast but it can be useful sometimes.

How to check if a textbox is empty using javascript

The most simple way to do it without using javascript is using required=""

<input type="text" ID="txtName"  Width="165px" required=""/>

Limiting Powershell Get-ChildItem by File Creation Date Range

Use Where-Object, like:

Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") | 
Where-Object { $_.CreationTime -gt "03/01/2013" -and $_.CreationTime -lt "03/31/2013" }
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv 'PATH\scans.csv'

Check if string contains only digits

Well, you can use the following regex:

^\d+$

How to select a drop-down menu value with Selenium using Python?

The best way to use selenium.webdriver.support.ui.Select class to work to with dropdown selection but some time it does not work as expected due to designing issue or other issues of the HTML.

In this type of situation you can also prefer as alternate solution using execute_script() as below :-

option_visible_text = "Banana"
select = driver.find_element_by_id("fruits01")

#now use this to select option from dropdown by visible text 
driver.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, option_visible_text);

How to do a SOAP wsdl web services call from the command line

For Windows:

Save the following as MSFT.vbs:

set SOAPClient = createobject("MSSOAP.SOAPClient")
SOAPClient.mssoapinit "https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc?wsdl"
WScript.Echo "MSFT = " & SOAPClient.GetQuote("MSFT")

Then from a command prompt, run:

C:\>MSFT.vbs

Reference: http://blogs.msdn.com/b/bgroth/archive/2004/10/21/246155.aspx

Restrict varchar() column to specific values?

You want a check constraint.

CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range.

You want something like:

ALTER TABLE dbo.Table ADD CONSTRAINT CK_Table_Frequency
    CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))

You can also implement check constraints with scalar functions, as described in the link above, which is how I prefer to do it.

How to convert php array to utf8?

$utfEncodedArray = array_map("utf8_encode", $inputArray );

Does the job and returns a serialized array with numeric keys (not an assoc).

Get value from text area

Use val():

 if ($("textarea").val()!== "") {
        alert($("textarea").val());
    }

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

We can apply the project deployment target to all pods target. Resolved by adding this code block below to end of your Podfile:

post_install do |installer|
  fix_deployment_target(installer)
end

def fix_deployment_target(installer)
  return if !installer
  project = installer.pods_project
  project_deployment_target = project.build_configurations.first.build_settings['IPHONEOS_DEPLOYMENT_TARGET']

  puts "Make sure all pods deployment target is #{project_deployment_target.green}"
  project.targets.each do |target|
    puts "  #{target.name}".blue
    target.build_configurations.each do |config|
      old_target = config.build_settings['IPHONEOS_DEPLOYMENT_TARGET']
      new_target = project_deployment_target
      next if old_target == new_target
      puts "    #{config.name}: #{old_target.yellow} -> #{new_target.green}"
      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = new_target
    end
  end
end

Results log:

fix pods deployment target version warning

Detect WebBrowser complete page loading

Using the DocumentCompleted event with a page with multiple nested frames didn't work for me.

I used the Interop.SHDocVW library to cast the WebBrowser control like this:

public class webControlWrapper
{
    private bool _complete;
    private WebBrowser _webBrowserControl;

    public webControlWrapper(WebBrowser webBrowserControl)
    {
        _webBrowserControl = webBrowserControl;
    }

    public void NavigateAndWaitForComplete(string url)
    {
        _complete = false;

        _webBrowserControl.Navigate(url);

        var webBrowser = (SHDocVw.WebBrowser) _webBrowserControl.ActiveXInstance;

        if (webBrowser != null)
            webBrowser.DocumentComplete += WebControl_DocumentComplete;

        //Wait until page is complete
        while (!_complete)
        {
            Application.DoEvents();
        }
    }

    private void WebControl_DocumentComplete(object pDisp, ref object URL)
    {
        // Test if it's the main frame who called the event.
        if (pDisp == _webBrowserControl.ActiveXInstance)
            _complete = true;
    }

This code works for me when navigating to a defined URL using the webBrowserControl.Navigate(url) method, but I don't know how to control page complete when a html button is clicked using the htmlElement.InvokeMember("click").

How do I clear this setInterval inside a function?

Simplest way I could think of: add a class.

Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.

_x000D_
_x000D_
var i = 0;_x000D_
this.setInterval(function() {_x000D_
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
    console.log('Counting...');_x000D_
    $('#counter').html(i++); //just for explaining and showing_x000D_
  } else {_x000D_
    console.log('Stopped counting');_x000D_
  }_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
    $(this).addClass('pauseInterval');_x000D_
  },function() { //mouse leave_x000D_
    $(this).removeClass('pauseInterval');_x000D_
  }_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
  $('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
  background-color: #eee;_x000D_
  font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
  width: 50%;_x000D_
  background: #ddd;_x000D_
  border: 2px solid #009afd;_x000D_
  border-radius: 5px;_x000D_
  padding: 5px;_x000D_
  text-align: center;_x000D_
  transition: .3s;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
  border-color: red;  _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter">&nbsp;</p>_x000D_
<button id="pauseInterval">Pause/unpause</button></p>
_x000D_
_x000D_
_x000D_

How can I convert a Word document to PDF?

You can use JODConverter for this purpose. It can be used to convert documents between different office formats. such as:

  1. Microsoft Office to OpenDocument, and vice versa
  2. Any format to PDF
  3. And supports many more conversion as well
  4. It can also convert MS office 2007 documents to PDF as well with almost all formats

More details about it can be found here: http://www.artofsolving.com/opensource/jodconverter

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

<hr> tag in Twitter Bootstrap not functioning correctly?

Instead of writing

<hr>

Write

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

And it will display full width as normal.

How to delete all files from a specific folder?

You can do it via FileInfo or DirectoryInfo:

DirectoryInfo di = new DirectoryInfo("TempDir");
di.Delete(true);

And then recreate the directory

phpMyAdmin on MySQL 8.0

As @kgr mentioned, MySQL 8.0.11 made some changes to the authentication method.

I've opened a phpMyAdmin bug report about this: https://github.com/phpmyadmin/phpmyadmin/issues/14220.

MySQL 8.0.4-rc was working fine for me, and I kind of think it's ridiculous for MySQL to make such a change in a patch level release.

Start an Activity with a parameter

The existing answers (pass the data in the Intent passed to startActivity()) show the normal way to solve this problem. There is another solution that can be used in the odd case where you're creating an Activity that will be started by another app (for example, one of the edit activities in a Tasker plugin) and therefore do not control the Intent which launches the Activity.

You can create a base-class Activity that has a constructor with a parameter, then a derived class that has a default constructor which calls the base-class constructor with a value, as so:

class BaseActivity extends Activity
{
    public BaseActivity(String param)
    {
        // Do something with param
    }
}

class DerivedActivity extends BaseActivity
{
    public DerivedActivity()
    {
        super("parameter");
    }
}

If you need to generate the parameter to pass to the base-class constructor, simply replace the hard-coded value with a function call that returns the correct value to pass.

How can you run a Java program without main method?

public class X { static {
  System.out.println("Main not required to print this");
  System.exit(0);
}}

Run from the cmdline with java X.

How to initialize an array of custom objects

The simplest way to initialize an array

Create array

$array = @()

Create your header

$line = "" | select name,age,phone

Fill the line

$line.name = "Leandro"
$line.age = "39"
$line.phone = "555-555555"

Add line to $array

$array += $line

Result

$array

name                                                     age                                                      phone
----                                                     ---                                                      -----
Leandro                                                  39                                                       555-555555

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

Main Class:

public class AndroidLocationActivity extends Activity {

Button btnGPSShowLocation;
Button btnNWShowLocation;

AppLocationService appLocationService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    appLocationService = new AppLocationService(
            AndroidLocationActivity.this);

    btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
    btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location gpsLocation = appLocationService
                    .getLocation(LocationManager.GPS_PROVIDER);

            if (gpsLocation != null) {
                double latitude = gpsLocation.getLatitude();
                double longitude = gpsLocation.getLongitude();
                Toast.makeText(
                        getApplicationContext(),
                        "Mobile Location (GPS): \nLatitude: " + latitude
                                + "\nLongitude: " + longitude,
                        Toast.LENGTH_LONG).show();
            } else {
                showSettingsAlert("GPS");
            }

        }
    });

    btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
    btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location nwLocation = appLocationService
                    .getLocation(LocationManager.NETWORK_PROVIDER);

            if (nwLocation != null) {
                double latitude = nwLocation.getLatitude();
                double longitude = nwLocation.getLongitude();
                Toast.makeText(
                        getApplicationContext(),
                        "Mobile Location (NW): \nLatitude: " + latitude
                                + "\nLongitude: " + longitude,
                        Toast.LENGTH_LONG).show();

            } else {
                showSettingsAlert("NETWORK");
            }

        }
    });

}

public void showSettingsAlert(String provider) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            AndroidLocationActivity.this);

    alertDialog.setTitle(provider + " SETTINGS");

    alertDialog.setMessage(provider
            + " is not enabled! Want to go to settings menu?");

    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    AndroidLocationActivity.this.startActivity(intent);
                }
            });

    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertDialog.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;

}

}

Next Class:

public class AppLocationService extends Service implements LocationListener {

protected LocationManager locationManager;
Location location;

private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

public AppLocationService(Context context) {
    locationManager = (LocationManager) context
            .getSystemService(LOCATION_SERVICE);
}

public Location getLocation(String provider) {
    if (locationManager.isProviderEnabled(provider)) {
        locationManager.requestLocationUpdates(provider,
                MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
        if (locationManager != null) {
            location = locationManager.getLastKnownLocation(provider);
            return location;
        }
    }
    return null;
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

Don't forget to add in your manifest.

<!-- to get location using GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- to get location using NetworkProvider -->
<uses-permission android:name="android.permission.INTERNET" />

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

Addressing localhost from a VirtualBox virtual machine

If you use Virtual Box you can connect Mac OSX (and I think Linux) to your virtual windows machine using one line of code --> I suggest stopping the box before running this in terminal.

VBoxManage modifyvm "YOUR VM NAME" --natdnshostresolver1 on

I will note that this is from the Dinghy docs, which I am running, but its a virtual box command so it shouldn't actually care what you use as long as its Virtual Box

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

How do I test axios in Jest?

For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:

File actions.test.js:

describe('SignInUser', () => {
  var history = {
    push: function(str) {
        expect(str).toEqual('/feed');
    }
  }

  it('Dispatches authorization', () => {
    let mock = new MockAdapter(axios);
    mock.onPost(`${ROOT_URL}/auth/signin`, {
        email: '[email protected]',
        password: 'test'
    }).reply(200, {token: 'testToken' });

    const expectedActions = [ { type: types.AUTH_USER } ];
    const store = mockStore({ auth: [] });

    return store.dispatch(actions.signInUser({
        email: '[email protected]',
        password: 'test',
      }, history)).then(() => {
        expect(store.getActions()).toEqual(expectedActions);
  });

});

In order to test a successful case for signInUser in file actions/index.js:

export const signInUser = ({ email, password }, history) => async dispatch => {
  const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
    .catch(({ response: { data } }) => {
        ...
  });

  if (res) {
    dispatch({ type: AUTH_USER });                 // Test verified this
    localStorage.setItem('token', res.data.token); // Test mocked this
    history.push('/feed');                         // Test mocked this
  }
}

Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:

const localStorageMock = {
  removeItem: jest.fn(),
  getItem: jest.fn(),
  setItem: jest.fn(),
  clear: jest.fn()
};
global.localStorage = localStorageMock;

How do I access nested HashMaps in Java?

You can do it like you assumed. But your HashMap has to be templated:

Map<String, Map<String, String>> map = 
    new HashMap<String, Map<String, String>>();

Otherwise you have to do a cast to Map after you retrieve the second map from the first.

Map map = new HashMap();
((Map)map.get( "keyname" )).get( "nestedkeyname" );

Python subprocess/Popen with a modified environment

The env parameter accepts a dictionary. You can simply take os.environ, add a key (your desired variable) (to a copy of the dict if you must) to that and use it as a parameter to Popen.

Curl error 60, SSL certificate issue: self signed certificate in certificate chain

Important: This issue drove me crazy for a couple days and I couldn't figure out what was going on with my curl & openssl installations. I finally figured out that it was my intermediate certificate (in my case, GoDaddy) which was out of date. I went back to my godaddy SSL admin panel, downloaded the new intermediate certificate, and the issue disappeared.

I'm sure this is the issue for some of you.

Apparently, GoDaddy had changed their intermediate certificate at some point, due to scurity issues, as they now display this warning:

"Please be sure to use the new SHA-2 intermediate certificates included in your downloaded bundle."

Hope this helps some of you, because I was going nuts and this cleaned up the issue on ALL my servers.

How do I get the time difference between two DateTime objects using C#?

What you need is to use the DateTime classs Subtract method, which returns a TimeSpan.

var dateOne = DateTime.Now;
var dateTwo = DateTime.Now.AddMinutes(-5);
var diff = dateTwo.Subtract(dateOne);
var res = String.Format("{0}:{1}:{2}", diff.Hours,diff.Minutes,diff.Seconds));

Create a Date with a set timezone without using a string representation

One line solution

new Date(new Date(1422524805305).getTime() - 330*60*1000)

Instead of 1422524805305, use the timestamp in milliseconds Instead of 330, use your timezone offset in minutes wrt. GMT (eg India +5:30 is 5*60+30 = 330 minutes)

jQuery .val change doesn't change input value

My similar issue was caused by having special characters (e.g. periods) in the selector.

The fix was to escape the special characters:

$("#dots\\.er\\.bad").val("mmmk");

generate model using user:references vs user_id:integer

how does rails know that user_id is a foreign key referencing user?

Rails itself does not know that user_id is a foreign key referencing user. In the first command rails generate model Micropost user_id:integer it only adds a column user_id however rails does not know the use of the col. You need to manually put the line in the Micropost model

class Micropost < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :microposts
end

the keywords belongs_to and has_many determine the relationship between these models and declare user_id as a foreign key to User model.

The later command rails generate model Micropost user:references adds the line belongs_to :user in the Micropost model and hereby declares as a foreign key.

FYI
Declaring the foreign keys using the former method only lets the Rails know about the relationship the models/tables have. The database is unknown about the relationship. Therefore when you generate the EER Diagrams using software like MySql Workbench you find that there is no relationship threads drawn between the models. Like in the following pic enter image description here

However, if you use the later method you find that you migration file looks like:

def change
    create_table :microposts do |t|
      t.references :user, index: true

      t.timestamps null: false
    end
    add_foreign_key :microposts, :users

Now the foreign key is set at the database level. and you can generate proper EER diagrams. enter image description here

error while loading shared libraries: libncurses.so.5:

On Arch Linux you can install ncurses5-compat-libs AUR package.

FYI it is mentioned in Arch Wiki android page, just in case if you'll need some other dependencies for Android Studio: https://wiki.archlinux.org/index.php/Android

Can I try/catch a warning?

Be careful with the @ operator - while it suppresses warnings it also suppresses fatal errors. I spent a lot of time debugging a problem in a system where someone had written @mysql_query( '...' ) and the problem was that mysql support was not loaded into PHP and it threw a silent fatal error. It will be safe for those things that are part of the PHP core but please use it with care.

bob@mypc:~$ php -a
Interactive shell

php > echo @something(); // this will just silently die...

No further output - good luck debugging this!

bob@mypc:~$ php -a
Interactive shell

php > echo something(); // lets try it again but don't suppress the error
PHP Fatal error:  Call to undefined function something() in php shell code on line 1
PHP Stack trace:
PHP   1. {main}() php shell code:0
bob@mypc:~$ 

This time we can see why it failed.

how to display a div triggered by onclick event

If you have the ID of the div, try this:

  <input type='submit' onclick='$("#div_id").show()'>

Using DataContractSerializer to serialize, but can't deserialize back

This best for XML Deserialize

 public static object Deserialize(string xml, Type toType)
    {

        using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
            System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
            return xSerializer.Deserialize(str);
        }

    }

jQuery change URL of form submit

Send the data from the form:

$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
  type: "PUT"
  url: url
  dataType: "script"
  data: postData

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

I don't know the answer for SQL Server but...

In MySQL save it as FLOAT( 10, 6 )

This is the official recommendation from the Google developer documentation.

CREATE TABLE `coords` (
  `lat` FLOAT( 10, 6 ) NOT NULL ,
  `lng` FLOAT( 10, 6 ) NOT NULL ,
) ENGINE = MYISAM ;

How to convert between bytes and strings in Python 3?

This is a Python 101 type question,

It's a simple question but one where the answer is not so simple.


In python3, a "bytes" object represents a sequence of bytes, a "string" object represents a sequence of unicode code points.

To convert between from "bytes" to "string" and from "string" back to "bytes" you use the bytes.decode and string.encode functions. These functions take two parameters, an encoding and an error handling policy.

Sadly there are an awful lot of cases where sequences of bytes are used to represent text, but it is not necessarily well-defined what encoding is being used. Take for example filenames on unix-like systems, as far as the kernel is concerned they are a sequence of bytes with a handful of special values, on most modern distros most filenames will be UTF-8 but there is no gaurantee that all filenames will be.

If you want to write robust software then you need to think carefully about those parameters. You need to think carefully about what encoding the bytes are supposed to be in and how you will handle the case where they turn out not to be a valid sequence of bytes for the encoding you thought they should be in. Python defaults to UTF-8 and erroring out on any byte sequence that is not valid UTF-8.

print(bytesThing)

Python uses "repr" as a fallback conversion to string. repr attempts to produce python code that will recreate the object. In the case of a bytes object this means among other things escaping bytes outside the printable ascii range.

How do you change the text in the Titlebar in Windows Forms?

For changing the Title of a form at runtime we can code as below

public partial class FormMain : Form
{
    public FormMain()
    {
        InitializeComponent();
        this.Text = "This Is My Title";
    }
}

Float to String format specifier

You can pass a format string to the ToString method, like so:

ToString("N4"); // 4 decimal points Number

If you want to see more modifiers, take a look at MSDN - Standard Numeric Format Strings

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

opencv has changed some functions and moved them to their opencv_contrib repo so you have to call the mentioned method with:

recognizer = cv2.face.createLBPHFaceRecognizer()

Note: You can see this issue about missing docs. Try using help function help(cv2.face.createLBPHFaceRecognizer) for more details.

Difference between Method and Function?

Both are same, there is no difference its just a different term for the same thing in C#.

Method:

In object-oriented programming, a method is a subroutine (or procedure or function) associated with a class.

With respect to Object Oriented programming the term "Method" is used, not functions.

How to import an existing project from GitHub into Android Studio

You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.

The github repo will be created as a new project in android studio.

How to create a shortcut using PowerShell

Beginning PowerShell 5.0 New-Item, Remove-Item, and Get-ChildItem have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.

New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"

Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.

Anyway if you want to create a Run As Administrator shortcut using Powershell you can use

$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

How do I kill an Activity when the Back button is pressed?

Simple Override onBackPressed Method:

    @Override
    public void onBackPressed() {
            super.onBackPressed();
            this.finish();
    }

Importing .py files in Google Colab

A easy way is

  1. type in from google.colab import files uploaded = files.upload()
  2. copy the code
  3. paste in colab cell

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

How to break a while loop from an if condition inside the while loop?

An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".

If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.

How do I implement onchange of <input type="text"> with jQuery?

You could simply work with the id

$("#your_id").on("change",function() {
    alert(this.value);
});

how to get list of port which are in use on the server

If you mean what ports are listening, you can open a command prompt and write:

netstat

You can write:

netstat /?

for an explanation of all options.

Is there a PowerShell "string does not contain" cmdlet or syntax?

To exclude the lines that contain any of the strings in $arrayOfStringsNotInterestedIn, you should use:

(Get-Content $FileName) -notmatch [String]::Join('|',$arrayofStringsNotInterestedIn)

The code proposed by Chris only works if $arrayofStringsNotInterestedIn contains the full lines you want to exclude.

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

Using PropertyInfo to find out the property type

Use PropertyInfo.PropertyType to get the type of the property.

public bool ValidateData(object data)
{
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            string value = propertyInfo.GetValue(data, null);

            if value is not OK
            {
                return false;
            }
        }
    }            

    return true;
}

Check for a substring in a string in Oracle without LIKE

If you were only interested in 'z', you could create a function-based index.

CREATE INDEX users_z_idx ON users (INSTR(last_name,'z'))

Then your query would use WHERE INSTR(last_name,'z') > 0.

With this approach you would have to create a separate index for each character you might want to search for. I suppose if this is something you do often, it might be worth creating one index for each letter.

Also, keep in mind that if your data has the names capitalized in the standard way (e.g., "Zaxxon"), then both your example and mine would not match names that begin with a Z. You can correct for this by including LOWER in the search expression: INSTR(LOWER(last_name),'z').

Terminating a Java Program

Because System.exit() is just another method to the compiler. It doesn't read ahead and figure out that the whole program will quit at that point (the JVM quits). Your OS or shell can read the integer that is passed back in the System.exit() method. It is standard for 0 to mean "program quit and everything went OK" and any other value to notify an error occurred. It is up to the developer to document these return values for any users.

return on the other hand is a reserved key word that the compiler knows well. return returns a value and ends the current function's run moving back up the stack to the function that invoked it (if any). In your code above it returns void as you have not supplied anything to return.

iOS - Dismiss keyboard when touching outside of UITextField

just use this code in your .m file it will resign the textfield when user tap outside of the textfield.

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  [textfield resignFirstResponder];
 }

How to picture "for" loop in block representation of algorithm

What's a "block scheme"?

If I were drawing it, I might draw a box with "for each x in y" written in it.

If you're drawing a flowchart, there's always a loop with a decision box.

Nassi-Schneiderman diagrams have a loop construct you could use.

C-like structures in Python

Personally, I like this variant too. It extends @dF's answer.

class struct:
    def __init__(self, *sequential, **named):
        fields = dict(zip(sequential, [None]*len(sequential)), **named)
        self.__dict__.update(fields)
    def __repr__(self):
        return str(self.__dict__)

It supports two modes of initialization (that can be blended):

# Struct with field1, field2, field3 that are initialized to None.
mystruct1 = struct("field1", "field2", "field3") 
# Struct with field1, field2, field3 that are initialized according to arguments.
mystruct2 = struct(field1=1, field2=2, field3=3)

Also, it prints nicer:

print(mystruct2)
# Prints: {'field3': 3, 'field1': 1, 'field2': 2}

COALESCE Function in TSQL

There is a lot more to coalesce than just a replacement for ISNULL. I completely agree that the official "documentation" of coalesce is vague and unhelpful. This article helps a lot. http://www.mssqltips.com/sqlservertip/1521/the-many-uses-of-coalesce-in-sql-server/

Install NuGet via PowerShell script

With PowerShell but without the need to create a script:

Invoke-WebRequest https://dist.nuget.org/win-x86-commandline/latest/nuget.exe -OutFile Nuget.exe

How to set response header in JAX-RS so that user sees download popup for Excel?

@Context ServletContext ctx;
@Context private HttpServletResponse response;

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/download/{filename}")
public StreamingOutput download(@PathParam("filename") String fileName) throws Exception {
    final File file = new File(ctx.getInitParameter("file_save_directory") + "/", fileName);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() + "\"");
    return new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException,
                WebApplicationException {
            Utils.writeBuffer(new BufferedInputStream(new FileInputStream(file)), new BufferedOutputStream(output));
        }
    };
}

How can I create an error 404 in PHP?

Immediately after that line try closing the response using exit or die()

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;

or

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
die();

How to read strings from a Scanner in a Java console application?

Replace:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.next());

with:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.nextLine());

This is because next() grabs only the next token, and the space acts as a delimiter between the tokens. By this, I mean that the scanner reads the input: "firstname lastname" as two separate tokens. So in your example, ename would be set to firstname and the scanner is attempting to set the supervisorId to lastname

How to fix error Base table or view not found: 1146 Table laravel relationship table?

You should change/add in your PostController: (and change PostsController to PostController)

public function create()
{
    $categories = Category::all();
    return view('create',compact('categories'));
}

public function store(Request $request)
{
    $post = new Posts;
    $post->title = $request->get('title'); // CHANGE THIS
    $post->body = $request->get('body'); // CHANGE THIS
    $post->save(); // ADD THIS
    $post->categories()->attach($request->get('categories_id')); // CHANGE THIS

    return redirect()->route('posts.index'); // PS ON THIS ONE
}

PS: using route() means you have named your route as such

Route::get('example', 'ExampleController@getExample')->name('getExample');

UPDATE

The comments above are also right, change your 'Posts' Model to 'Post'

Read from file in eclipse

Have you tried using an absolute path:

File file = new File(System.getProperty("user.dir") + "/file.txt");

iPhone/iOS JSON parsing tutorial

As of iOS 5.0 Apple provides the NSJSONSerialization class "to convert JSON to Foundation objects and convert Foundation objects to JSON". No external frameworks to incorporate and according to benchmarks its performance is quite good, significantly better than SBJSON.

chrome undo the action of "prevent this page from creating additional dialogs"

2 more solutions I had luck with when neither tab close + reopening the page in another tab nor closing all tabs in Chrome (and the browser) then restarting it didn't work:

1) I fixed it on my machine by closing the tab, force-closing Chrome, & restarting the browser without restoring tabs (Note: on a computer running CentOS Linux).

2) My boss (also on CentOS) had the same issue (alerts are a big part of my company's Javascript debugging process for numerous reasons e.g. legacy), but my 1st method didn't work for him. However, I managed to fix it for him with the following process:

  • a) Make an empty text file called FixChrome.sh, and paste in the following bash script:

    #! /bin/bash
    cd ~/.config/google-chrome/Default     //adjust for your Chrome install location
    rm Preferences
    rm 'Current Session'
    rm 'Current Tabs'
    rm 'Last Session'
    rm 'Last Tabs'
    
  • b) close Chrome, then open Terminal and run the script (bash FixChrome.sh).

It worked for him. Downside is that you lose all tabs from your current & previous session, but it's worth it if this matters to you.

Powershell folder size of folders without listing Subdirectories

Interesting how powerful yet how helpless PS can be in the same time, coming from a Nix learning PS. after install crgwin/gitbash, you can do any combination in one commands:

size of current folder: du -sk .

size of all files and folders under current directory du -sk *

size of all subfolders (including current folders) find ./ -type d -exec du -sk {} \;

Regex to get the words after matching string

This is a Python solution.

import re

line ="""Subject:
    Security ID:        S-1-5-21-3368353891-1012177287-890106238-22451
    Account Name:       ChamaraKer
    Account Domain:     JIC
    Logon ID:       0x1fffb

Object:
    Object Server:  Security
    Object Type:    File
    Object Name:    D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log
    Handle ID:  0x11dc"""



regex = (r'Object Name:\s+(.*)')
match1= re.findall(regex,line)
print (match1)

*** Remote Interpreter Reinitialized  ***
>>> 
['D:\\ApacheTomcat\x07pache-tomcat-6.0.36\\logs\\localhost.2013-07-01.log']
>>> 

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Add the following css to disable the default scroll:

body {
    overflow: hidden;
}

And change the #content css to this to make the scroll only on content body:

#content {
    max-height: calc(100% - 120px);
    overflow-y: scroll;
    padding: 0px 10%;
    margin-top: 60px;
}

See fiddle here.


Edit:

Actually, I'm not sure what was the issue you were facing, since it seems that your css is working. I have only added the HTML and the header css statement:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  position: absolute;_x000D_
  top: 50px;_x000D_
  bottom: 30px;_x000D_
  right: 0;_x000D_
  left: 0;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    top: 0;_x000D_
    background-color: #4C4;_x000D_
    height: 50px;_x000D_
}_x000D_
footer {_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    background-color: #4C4;_x000D_
    height: 30px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

What is the correct way of reading from a TCP socket in C/C++?

Without knowing your full application it is hard to say what the best way to approach the problem is, but a common technique is to use a header which starts with a fixed length field, which denotes the length of the rest of your message.

Assume that your header consist only of a 4 byte integer which denotes the length of the rest of your message. Then simply do the following.

// This assumes buffer is at least x bytes long,
// and that the socket is blocking.
void ReadXBytes(int socket, unsigned int x, void* buffer)
{
    int bytesRead = 0;
    int result;
    while (bytesRead < x)
    {
        result = read(socket, buffer + bytesRead, x - bytesRead);
        if (result < 1 )
        {
            // Throw your error.
        }

        bytesRead += result;
    }
}

Then later in the code

unsigned int length = 0;
char* buffer = 0;
// we assume that sizeof(length) will return 4 here.
ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&length));
buffer = new char[length];
ReadXBytes(socketFileDescriptor, length, (void*)buffer);

// Then process the data as needed.

delete [] buffer;

This makes a few assumptions:

  • ints are the same size on the sender and receiver.
  • Endianess is the same on both the sender and receiver.
  • You have control of the protocol on both sides
  • When you send a message you can calculate the length up front.

Since it is common to want to explicitly know the size of the integer you are sending across the network define them in a header file and use them explicitly such as:

// These typedefs will vary across different platforms
// such as linux, win32, OS/X etc, but the idea
// is that a Int8 is always 8 bits, and a UInt32 is always
// 32 bits regardless of the platform you are on.
// These vary from compiler to compiler, so you have to 
// look them up in the compiler documentation.
typedef char Int8;
typedef short int Int16;
typedef int Int32;

typedef unsigned char UInt8;
typedef unsigned short int UInt16;
typedef unsigned int UInt32;

This would change the above to:

UInt32 length = 0;
char* buffer = 0;

ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&length));
buffer = new char[length];
ReadXBytes(socketFileDescriptor, length, (void*)buffer);

// process

delete [] buffer;

I hope this helps.

How to view the committed files you have not pushed yet?

I'm not great with Git, but this is what I do. This does not necessarily compare with the remote repo, but you can modify the git diff with the appropriate commit hash from the remote.

Say you made one commit that you haven't pushed...

First find the last two commits...

git log -2

This shows the last commit first, and descends from there...

[jason:~/git/my_project] git log -2
commit ea7937edc8b10
Author: xyz
Date:   Wed Jul 27 14:06:41 2016 -0500

    Made a change in July

commit 52f9bf7956f0
Author: xyz
Date:   Tue Jun 14 14:29:52 2016 -0500

    Made a change in June

Now just use the two commit hashes (which I abbreviated) to run a diff:

git diff 52f9bf7956f0 ea7937edc8b10

Casting variables in Java

Casting in Java isn't magic, it's you telling the compiler that an Object of type A is actually of more specific type B, and thus gaining access to all the methods on B that you wouldn't have had otherwise. You're not performing any kind of magic or conversion when performing casting, you're essentially telling the compiler "trust me, I know what I'm doing and I can guarantee you that this Object at this line is actually an <Insert cast type here>." For example:

Object o = "str";
String str = (String)o;

The above is fine, not magic and all well. The object being stored in o is actually a string, and therefore we can cast to a string without any problems.

There's two ways this could go wrong. Firstly, if you're casting between two types in completely different inheritance hierarchies then the compiler will know you're being silly and stop you:

String o = "str";
Integer str = (Integer)o; //Compilation fails here

Secondly, if they're in the same hierarchy but still an invalid cast then a ClassCastException will be thrown at runtime:

Number o = new Integer(5);
Double n = (Double)o; //ClassCastException thrown here

This essentially means that you've violated the compiler's trust. You've told it you can guarantee the object is of a particular type, and it's not.

Why do you need casting? Well, to start with you only need it when going from a more general type to a more specific type. For instance, Integer inherits from Number, so if you want to store an Integer as a Number then that's ok (since all Integers are Numbers.) However, if you want to go the other way round you need a cast - not all Numbers are Integers (as well as Integer we have Double, Float, Byte, Long, etc.) And even if there's just one subclass in your project or the JDK, someone could easily create another and distribute that, so you've no guarantee even if you think it's a single, obvious choice!

Regarding use for casting, you still see the need for it in some libraries. Pre Java-5 it was used heavily in collections and various other classes, since all collections worked on adding objects and then casting the result that you got back out the collection. However, with the advent of generics much of the use for casting has gone away - it has been replaced by generics which provide a much safer alternative, without the potential for ClassCastExceptions (in fact if you use generics cleanly and it compiles with no warnings, you have a guarantee that you'll never get a ClassCastException.)

How to compare two List<String> to each other?

    private static bool CompareDictionaries(IDictionary<string, IEnumerable<string>> dict1, IDictionary<string, IEnumerable<string>> dict2)
    {
        if (dict1.Count != dict2.Count)
        {
            return false;
        }

        var keyDiff = dict1.Keys.Except(dict2.Keys);
        if (keyDiff.Any())
        {
            return false;
        }

        return (from key in dict1.Keys 
                let value1 = dict1[key] 
                let value2 = dict2[key] 
                select value1.Except(value2)).All(diffInValues => !diffInValues.Any());
    }

PHP Function with Optional Parameters

You can just set the default value to null.

<?php
function functionName($value, $value2 = null) {
// do stuff
}

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Serhii's suggestion works and here is some more detail.

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Hope this helps, Glenn

Best way to get application folder path

this one System.IO.Path.GetDirectory(Application.ExecutablePath) changed to System.IO.Path.GetDirectoryName(Application.ExecutablePath)

Maximum packet size for a TCP connection

One solution can be to set socket option TCP_MAXSEG (http://linux.die.net/man/7/tcp) to a value that is "safe" with underlying network (e.g. set to 1400 to be safe on ethernet) and then use a large buffer in send system call. This way there can be less system calls which are expensive. Kernel will split the data to match MSS.

This way you can avoid truncated data and your application doesn't have to worry about small buffers.

Is it possible to add dynamically named properties to JavaScript object?

I know there are several answers to this post already, but I haven't seen one wherein there are multiple properties and they are within an array. And this solution by the way is for ES6.

For illustration, let's say we have an array named person with objects inside:

 let Person = [{id:1, Name: "John"}, {id:2, Name: "Susan"}, {id:3, Name: "Jet"}]

So, you can add a property with corresponding value. Let's say we want to add a Language with a default value of EN.

Person.map((obj)=>({...obj,['Language']:"EN"}))

The Person array now would become like this:

Person = [{id:1, Name: "John", Language:"EN"}, 
{id:2, Name: "Susan", Language:"EN"}, {id:3, Name: "Jet", Language:"EN"}]

Download single files from GitHub

  1. Go to the file you want to download.
  2. Click it to view the contents within the GitHub UI.
  3. In the top right, right click the Raw button.
  4. Save as...

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

This can also occur when using the wrong import (for example when using autoimport). let's take the MatTimePickerModule as an example. This will give an error message that is similar to the one described in the question:

import { NgxMatTimepickerModule } from '@angular-material-components/datetime-picker/lib/timepicker.module';

This should instead be

import { NgxMatTimepickerModule } from '@angular-material-components/datetime-picker';

How to compare DateTime without time via LINQ?

The .Date answer is misleading since you get the error mentioned before. Another way to compare, other than mentioned DbFunctions.TruncateTime, may also be:

DateTime today = DateTime.Now.date;
var q = db.Games.Where(t => SqlFunctions.DateDiff("dayofyear", today, t.StartDate) <= 0
      && SqlFunctions.DateDiff("year", today, t.StartDate) <= 0)

It looks better(more readable) in the generated SQL query. But I admit it looks worse in the C# code XD. I was testing something and it seemed like TruncateTime was not working for me unfortunately the fault was between keyboard and chair, but in the meantime I found this alternative.

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM is the Java Virtual Machine – it actually runs Java ByteCode.

JRE is the Java Runtime Environment – it contains a JVM, among other things, and is what you need to run a Java program.

JDK is the Java Development Kit – it is the JRE, but with javac (which is what you need to compile Java source code) and other programming tools added.

OpenJDK is a specific JDK implementation.

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

I think it's too late to answer this question but I faced the same problem recently my use case was to call the paginated JSON API and get all the data from each pagination and append it to a single array.

const https = require('https');
const apiUrl = "https://example.com/api/movies/search/?Title=";
let finaldata = [];
let someCallBack = function(data){
  finaldata.push(...data);
  console.log(finaldata);
};
const getData = function (substr, pageNo=1, someCallBack) {

  let actualUrl = apiUrl + `${substr}&page=${pageNo}`;
  let mydata = []
  https.get(actualUrl, (resp) => {
    let data = '';
    resp.on('data', (chunk) => {
        data += chunk;
    });
    resp.on('end', async () => {
        if (JSON.parse(data).total_pages!==null){
          pageNo+=1;
          somCallBack(JSON.parse(data).data);
          await getData(substr, pageNo, someCallBack);
        }
    });
  }).on("error", (err) => {
      console.log("Error: " + err.message);
  });
}

getData("spiderman", pageNo=1, someCallBack);

Like @ackuser mentioned we can use other module but In my use case I had to use the node https. Hoping this will help others.

Can I assume (bool)true == (int)1 for any C++ compiler?

According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.

The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.

A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1.

Updating records codeigniter

In your Controller

public function updtitle() 
{   
    $data = array(
        'table_name' => 'your_table_name_to_update', // pass the real table name
        'id' => $this->input->post('id'),
        'title' => $this->input->post('title')
    );

    $this->load->model('Updmodel'); // load the model first
    if($this->Updmodel->upddata($data)) // call the method from the model
    {
        // update successful
    }
    else
    {
        // update not successful
    }

}

In Your Model

public function upddata($data) {
    extract($data);
    $this->db->where('emp_no', $id);
    $this->db->update($table_name, array('title' => $title));
    return true;
}

The active record query is similar to

"update $table_name set title='$title' where emp_no=$id"

How to append a date in batch files

If you have WSL enabled (Windows 10 only) you can do it with bash in a locale neutral way.

set dateFile=%TEMP%\currentDate.txt
bash -c "date +%Y%m%d" > %dateFile%
set /p today=<%dateFile%

Feel free to replace the file redirection with a "for" loop abomination suggested in other answers here and over at Windows batch assign output of a program to a variable

Is there a simple way to delete a list element by value?

If your elements are distinct, then a simple set difference will do.

c = [1,2,3,4,'x',8,6,7,'x',9,'x']
z = list(set(c) - set(['x']))
print z
[1, 2, 3, 4, 6, 7, 8, 9]

c++ parse int from string

There is no "right way". If you want a universal (but suboptimal) solution you can use a boost::lexical cast.

A common solution for C++ is to use std::ostream and << operator. You can use a stringstream and stringstream::str() method for conversion to string.

If you really require a fast mechanism (remember the 20/80 rule) you can look for a "dedicated" solution like C++ String Toolkit Library

Best Regards,
Marcin

using c# .net libraries to check for IMAP messages from gmail servers

There is no .NET framework support for IMAP. You'll need to use some 3rd party component.

Try Mail.dll email component, it's very affordable and easy to use, it also supports SSL:

using(Imap imap = new Imap())
{
    imap.ConnectSSL("imap.company.com");
    imap.Login("user", "password");

    imap.SelectInbox();
    List<long> uids = imap.Search(Flag.Unseen);
    foreach (long uid in uids)
    {
        string eml = imap.GetMessageByUID(uid);
        IMail message = new MailBuilder()
            .CreateFromEml(eml);

        Console.WriteLine(message.Subject);
        Console.WriteLine(message.Text);
    }
    imap.Close(true);
}

Please note that this is a commercial product I've created.

You can download it here: https://www.limilabs.com/mail.

Removing body margin in CSS

Just Remove The Browser Default Margin and Padding Apply Top Of Your Css.

<style>

* {
  margin: 0;
  padding: 0;
}

</style>

NOTE:

  • Try to Reset all the html elements before writing your css.

OR [ Use This In Your Case ]

<style>

  *{
        margin: 0px;
        padding: 0px;
    }

h1 {
        margin-top: 0px;
    }

</style>

DEMO:

_x000D_
_x000D_
<style>_x000D_
_x000D_
  *{_x000D_
        margin: 0px;_x000D_
        padding: 0px;_x000D_
    }_x000D_
_x000D_
h1 {_x000D_
        margin-top: 0px;_x000D_
    }_x000D_
_x000D_
</style>
_x000D_
<html>_x000D_
 <head>_x000D_
 </head>_x000D_
 <body>_x000D_
  <h1>logo</h1>_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Can you force a React component to rerender without calling setState?

When you want two React components to communicate, which are not bound by a relationship (parent-child), it is advisable to use Flux or similar architectures.

What you want to do is to listen for changes of the observable component store, which holds the model and its interface, and saving the data that causes the render to change as state in MyComponent. When the store pushes the new data, you change the state of your component, which automatically triggers the render.

Normally you should try to avoid using forceUpdate() . From the documentation:

Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render(). This makes your application much simpler and more efficient

Unable to open a file with fopen()

The output folder directory must have been configured to some other directory in IDE. Either you can change that or replace the filename with entire file path.

Hope this helps.

What is the difference between require() and library()?

You can use require() if you want to install packages if and only if necessary, such as:

if (!require(package, character.only=T, quietly=T)) {
    install.packages(package)
    library(package, character.only=T)
}

For multiple packages you can use

for (package in c('<package1>', '<package2>')) {
    if (!require(package, character.only=T, quietly=T)) {
        install.packages(package)
        library(package, character.only=T)
    }
}

Pro tips:

  • When used inside the script, you can avoid a dialog screen by specifying the repos parameter of install.packages(), such as

    install.packages(package, repos="http://cran.us.r-project.org")
    
  • You can wrap require() and library() in suppressPackageStartupMessages() to, well, suppress package startup messages, and also use the parameters require(..., quietly=T, warn.conflicts=F) if needed to keep the installs quiet.

XAMPP installation on Win 8.1 with UAC Warning

There are two things you need to check:

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC (User Account Control) as it restricts certain administrative function needed to run a web server.

To ensure that your user account has administrator privilege, run lusrmgr.msc from the Windows Start > Run menu to bring up the Local Users and Groups Windows. Double-click on your user account that appears under Users, and verifies that it is a member of Administrators.

To disable UAC (as an administrator), from Control Panel:

  1. Type UAC in the search field in the upper right corner.
  2. Click Change User Account Control settings in the search results.
  3. Drag the slider down to Never notifyand click OK.

open up the User Accounts window from Control Panel. Click on the Turn User Account Control on or off option, and un-check the checkbox.

Alternately, if you don't want to disable UAC, you will have to install XAMPP in a different folder, outside of C:\Program Files (x86), such as C:\xampp.

Hope this helps.

Generate fixed length Strings filled with whitespaces

import org.apache.commons.lang3.StringUtils;

String stringToPad = "10";
int maxPadLength = 10;
String paddingCharacter = " ";

StringUtils.leftPad(stringToPad, maxPadLength, paddingCharacter)

Way better than Guava imo. Never seen a single enterprise Java project that uses Guava but Apache String Utils is incredibly common.

C# Create New T()

Just for completion, the best solution here is often to require a factory function argument:

T GetObject<T>(Func<T> factory)
{  return factory(); }

and call it something like this:

string s = GetObject(() => "result");

You can use that to require or make use of available parameters, if needed.

how to make a jquery "$.post" request synchronous

If you want an synchronous request set the async property to false for the request. Check out the jQuery AJAX Doc

How do I print colored output with Python 3?

For lazy people:

Without installing any additional library, it is compatible with every single terminal i know.

Class approach:

First do import config as cfg.

clipped is dataframe.

            #### HEADER: ####
            print('{0:<23} {1:>24} {2:>26} {3:>26} {4:>11} {5:>11}'.format('Road name','Classification','Function','Form of road','Length','Distance') )

            #### Now row by row: ####
            for index, row in clipped.iterrows():
                rdName      = self.colorize(row['name1'],cfg.Green)
                rdClass     = self.colorize(row['roadClassification'],cfg.LightYellow)
                rdFunction  = self.colorize(row['roadFunction'],cfg.Yellow)
                rdForm      = self.colorize(row['formOfWay'],cfg.LightBlue)
                rdLength    = self.colorize(row['length'],cfg.White)
                rdDistance  = self.colorize(row['distance'],cfg.LightCyan)
                print('{0:<30} {1:>35} {2:>35} {3:>35} {4:>20} {5:>20}'.format(rdName,rdClass,rdFunction,rdForm,rdLength,rdDistance) )

Meaning of {0:<30} {1:>35} {2:>35} {3:>35} {4:>20} {5:>20}:

0, 1, 2, 3, 4, 5 -> columns, there are 6 in total in this case

30, 35, 20 -> width of column (note that you'll have to add length of \033[96m - this for Python is a string as well), just experiment :)

>, < -> justify: right, left (there is = for filling with zeros as well)

What is in config.py:

#colors
ResetAll = "\033[0m"

Bold       = "\033[1m"
Dim        = "\033[2m"
Underlined = "\033[4m"
Blink      = "\033[5m"
Reverse    = "\033[7m"
Hidden     = "\033[8m"

ResetBold       = "\033[21m"
ResetDim        = "\033[22m"
ResetUnderlined = "\033[24m"
ResetBlink      = "\033[25m"
ResetReverse    = "\033[27m"
ResetHidden     = "\033[28m"

Default      = "\033[39m"
Black        = "\033[30m"
Red          = "\033[31m"
Green        = "\033[32m"
Yellow       = "\033[33m"
Blue         = "\033[34m"
Magenta      = "\033[35m"
Cyan         = "\033[36m"
LightGray    = "\033[37m"
DarkGray     = "\033[90m"
LightRed     = "\033[91m"
LightGreen   = "\033[92m"
LightYellow  = "\033[93m"
LightBlue    = "\033[94m"
LightMagenta = "\033[95m"
LightCyan    = "\033[96m"
White        = "\033[97m"

Result:

enter image description here

ViewDidAppear is not called when opening app from background

Swift 4.2. version

Register with the NotificationCenter in viewDidLoad to be notified when the app returns from background

NotificationCenter.default.addObserver(self, selector: #selector(doSomething), name: UIApplication.willEnterForegroundNotification, object: nil)

Implement the method that should be called.

@objc private func doSomething() {
    // Do whatever you want, for example update your view.
}

You can remove the observer once the ViewController is destroyed. This is only required below iOS9 and macOS 10.11

deinit {
    NotificationCenter.default.removeObserver(self)
}

git: undo all working dir changes including new files

git reset --hard # removes staged and working directory changes

## !! be very careful with these !!
## you may end up deleting what you don't want to
## read comments and manual.
git clean -f -d # remove untracked
git clean -f -x -d # CAUTION: as above but removes ignored files like config.
git clean -fxd :/ # CAUTION: as above, but cleans untracked and ignored files through the entire repo (without :/, the operation affects only the current directory)

To see what will be deleted before-hand, without actually deleting it, use the -n flag (this is basically a test-run). When you are ready to actually delete, then remove the -n flag:

git clean -nfd

Use of alloc init instead of new

Very old question, but I've written some example just for fun — maybe you'll find it useful ;)

#import "InitAllocNewTest.h"

@implementation InitAllocNewTest

+(id)alloc{
    NSLog(@"Allocating...");
    return [super alloc];
}

-(id)init{
    NSLog(@"Initializing...");
    return [super init];
}

@end

In main function both statements:

[[InitAllocNewTest alloc] init];

and

[InitAllocNewTest new];

result in the same output:

2013-03-06 16:45:44.125 XMLTest[18370:207] Allocating...
2013-03-06 16:45:44.128 XMLTest[18370:207] Initializing...

Oracle SQL escape character (for a '&')

select 'one'||'&'||'two' from dual

Xcode 9 Swift Language Version (SWIFT_VERSION)

This can happen when you added Core Data to an existing project.
Check the:
<Name>/<Name>.xcdatamodeld/<Name>.xcdatamodel/contents
file.
This file contains an entry "sourceLanguage" that (by default) might have been set to "Swift". Change it to "Objective-C".

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

You could use RAISE_APPLICATION_ERROR like this:

DECLARE
    ex_custom       EXCEPTION;
BEGIN
    RAISE ex_custom;
EXCEPTION
    WHEN ex_custom THEN
        RAISE_APPLICATION_ERROR(-20001,'My exception was raised');
END;
/

That will raise an exception that looks like:

ORA-20001: My exception was raised

The error number can be anything between -20001 and -20999.

Android Camera Preview Stretched

Hi the getOptimalPreview() that is here didn't worked for me so I want to share my version:

private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {

    if (sizes==null) return null;

    Camera.Size optimalSize = null;
    double ratio = (double)h/w;
    double minDiff = Double.MAX_VALUE;
    double newDiff;
    for (Camera.Size size : sizes) {
        newDiff = Math.abs((double)size.width/size.height - ratio);
        if (newDiff < minDiff) {
            optimalSize = size;
            minDiff = newDiff;
        }
    }
    return optimalSize;
}

Can two or more people edit an Excel document at the same time?

The new version of SharePoint and Office (SharePoint 2010 and Office 2010) respectively are supposed to allow for this. This also includes the web based versions. I have seen Word and Excel in action do this, not sure about other client applications.

I am not sure about the specific implementation features you are asking about in terms of security though. Sorry.,=

Here is a discussion

http://blogs.msdn.com/b/sharepoint/archive/2009/10/19/sharepoint-2010.aspx

How to submit a form using Enter key in react.js?

this is how you do it if you want to listen for the "Enter" key. There is an onKeydown prop that you can use and you can read about it in react doc

and here is a codeSandbox

const App = () => {
    const something=(event)=> {
        if (event.keyCode === 13) {
            console.log('enter')
        }
    }
return (
    <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <input  type='text' onKeyDown={(e) => something(e) }/>
    </div>
);
}

What does ||= (or-equals) mean in Ruby?

x ||= y

is

x || x = y

"if x is false or undefined, then x point to y"

How to rollback a specific migration?

Rolling back last migration:

# rails < 5.0
rake db:rollback

# rails >= 5.0
rake db:rollback
# or
rails db:rollback

Rolling back last n number of migrations

# rails < 5.0
rake db:rollback STEP=2

# rails >= 5.0
rake db:rollback STEP=2
# or
rails db:rollback STEP=2

Rolling back a specific migration

# rails < 5.0
rake db:migrate:down VERSION=20100905201547

# rails >= 5.0
rake db:migrate:down VERSION=20100905201547
# or
rails db:migrate:down VERSION=20100905201547

In R, how to find the standard error of the mean?

You can use the function stat.desc from pastec package.

library(pastec)
stat.desc(x, BASIC =TRUE, NORMAL =TRUE)

you can find more about it from here: https://www.rdocumentation.org/packages/pastecs/versions/1.3.21/topics/stat.desc

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

Java generics: multiple generic parameters?

Yes - it's possible (though not with your method signature) and yes, with your signature the types must be the same.

With the signature you have given, T must be associated to a single type (e.g. String or Integer) at the call-site. You can, however, declare method signatures which take multiple type parameters

public <S, T> void func(Set<S> s, Set<T> t)

Note in the above signature that I have declared the types S and T in the signature itself. These are therefore different to and independent of any generic types associated with the class or interface which contains the function.

public class MyClass<S, T> {
   public        void foo(Set<S> s, Set<T> t); //same type params as on class
   public <U, V> void bar(Set<U> s, Set<V> t); //type params independent of class
}

You might like to take a look at some of the method signatures of the collection classes in the java.util package. Generics is really rather a complicated subject, especially when wildcards (? extends and ? super) are considered. For example, it's often the case that a method which might take a Set<Number> as a parameter should also accept a Set<Integer>. In which case you'd see a signature like this:

public void baz(Set<? extends T> s);

There are plenty of questions already on SO for you to look at on the subject!

Not sure what the point of returning an int from the function is, although you could do that if you want!

Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET

I had a similar issue using Apache 2.4 and PHP 7.

My client sent a lot of requests when refreshing (hard reloading) my application page in the browser and every time some of the last requests resulted in this error in console:

GET http://example.com/api/v1/my/resource net::ERR_CONNECTION_RESET

It turned out that my client was reaching the maximum amount of threads that was allowed. The threads exceeding this configured ceiling are simply not handled by Apache at all resulting in the connection reset error response.

The amount of threads can be easily raised by setting the ThreadsPerChild value for the module in question.
The easiest way to make such change is to uncomment the Server-pool management config file conf/extra/httpd-mpm.conf and then editing the preset values in the file to desired values.

1) Uncomment the Server-pool management file

# Server-pool management (MPM specific)
Include conf/extra/httpd-mpm.conf

2) Open and edit the file conf/extra/httpd-mpm.conf and raise the amount of threads

In my case I had to change the threads for the mpm_winnt_module:

# raised the amount of threads for mpm_winnt_module to 250
<IfModule mpm_winnt_module>
    ThreadsPerChild        250
    MaxConnectionsPerChild   0
</IfModule>

A comprehensive explanation on these Server-pool management configuration settings can be found in this post on StackOverflow.

Removing duplicates from a list of lists

a_list = [
          [1,2],
          [1,2],
          [2,3],
          [3,4]
]

print (list(map(list,set(map(tuple,a_list)))))

outputs: [[1, 2], [3, 4], [2, 3]]

How can I simulate mobile devices and debug in Firefox Browser?

I would use the "Responsive Design View" available under Tools -> Web Developer -> Responsive Design View. It will let you test your CSS against different screen sizes.

CSS3 transition events

If you simply want to detect only a single transition end, without using any JS framework here's a little convenient utility function:

function once = function(object,event,callback){
    var handle={};

    var eventNames=event.split(" ");

    var cbWrapper=function(){
        eventNames.forEach(function(e){
            object.removeEventListener(e,cbWrapper, false );
        });
        callback.apply(this,arguments);
    };

    eventNames.forEach(function(e){
        object.addEventListener(e,cbWrapper,false);
    });

    handle.cancel=function(){
        eventNames.forEach(function(e){
            object.removeEventListener(e,cbWrapper, false );
        });
    };

    return handle;
};

Usage:

var handler = once(document.querySelector('#myElement'), 'transitionend', function(){
   //do something
});

then if you wish to cancel at some point you can still do it with

handler.cancel();

It's good for other event usages as well :)

Simple conversion between java.util.Date and XMLGregorianCalendar

Why not use an external binding file to tell XJC to generate java.util.Date fields instead of XMLGregorianCalendar?

Also see How do I map xs:date to java.util.Date? Blog

Regex to check if valid URL that ends in .jpg, .png, or .gif

In general, you're better off validating URLs using built-in library or framework functions, rather than rolling your own regular expressions to do this - see What is the best regular expression to check if a string is a valid URL for details.

If you are keen on doing this, though, check out this question:

Getting parts of a URL (Regex)

Then, once you're satisfied with the URL (by whatever means you used to validate it), you could either use a simple "endswith" type string operator to check the extension, or a simple regex like

(?i)\.(jpg|png|gif)$

To get specific part of a string in c#

Something like this?

string b = a.Split(',')[0];

Nginx not running with no error message

1. Check for your configuration files by running the aforementioned command: sudo nginx -t.

2. Check for port conflicts. For instance, if apache2 (ps waux | grep apache2) or any other service is using the same ports configured for nginx (say port 80) the service will not start and will fail silently (err... the cousin of my friend had this problem...)

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Pass entire form as data in jQuery Ajax function

Use

serialize( )

var str = $("form").serialize();

Serialize a form to a query string, that could be sent to a server in an Ajax request.

using mailto to send email with an attachment

this is not possible in "mailto" function.

please go with server side coding(C#).make sure open vs in administrative permission.

Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

oMsg.Subject = "emailSubject";
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
oMsg.BCC = "emailBcc";
oMsg.To = "emailRecipient";

string body = "emailMessage";

oMsg.HTMLBody = "body";              
oMsg.Attachments.Add(Convert.ToString(@"/my_location_virtual_path/myfile.txt"), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);

oMsg.Display(false); //In order to displ

How to make a simple collection view with Swift

Delegates and Datasources of UICollectionView

//MARK: UICollectionViewDataSource

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1     //return number of sections in collection view
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10    //return number of rows in section
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath)
    configureCell(cell, forItemAtIndexPath: indexPath)
    return cell      //return your cell
}

func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.blackColor()


    //Customise your cell

}

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    let view =  collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", forIndexPath: indexPath) as UICollectionReusableView
    return view
}

//MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
      // When user selects the cell
}

override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
     // When user deselects the cell
}

What is the difference between SOAP 1.1, SOAP 1.2, HTTP GET & HTTP POST methods for Android?

Differences in SOAP versions

Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.

The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.

The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.

In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.

SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.

There is not difine POST AND GET method for particular android....but all here is differance

GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.

What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.

POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.

Link to original IBM source

Finding local IP addresses using Python's stdlib

Ok so this is Windows specific, and requires the installation of the python WMI module, but it seems much less hackish than constantly trying to call an external server. It's just another option, as there are already many good ones, but it might be a good fit for your project.

Import WMI

def getlocalip():
    local = wmi.WMI()
    for interface in local.Win32_NetworkAdapterConfiguration(IPEnabled=1):
        for ip_address in interface.IPAddress:
            if ip_address != '0.0.0.0':
                localip = ip_address
    return localip







>>>getlocalip()
u'xxx.xxx.xxx.xxx'
>>>

By the way, WMI is very powerful... if you are doing any remote admin of window machines you should definitely check out what it can do.

Copy folder recursively, excluding some folders

Use tar along with a pipe.

cd /source_directory
tar cf - --exclude=dir_to_exclude . | (cd /destination && tar xvf - )

You can even use this technique across ssh.

How to run sql script using SQL Server Management Studio?

Found this in another thread that helped me: Use xp_cmdshell and sqlcmd Is it possible to execute a text file from SQL query? - by Gulzar Nazim

EXEC xp_cmdshell  'sqlcmd -S ' + @DBServerName + ' -d  ' + @DBName + ' -i ' + @FilePathName

Search for "does-not-contain" on a DataFrame in pandas

You can use the invert (~) operator (which acts like a not for boolean data):

new_df = df[~df["col"].str.contains(word)]

, where new_df is the copy returned by RHS.

contains also accepts a regular expression...


If the above throws a ValueError, the reason is likely because you have mixed datatypes, so use na=False:

new_df = df[~df["col"].str.contains(word, na=False)]

Or,

new_df = df[df["col"].str.contains(word) == False]

css width: calc(100% -100px); alternative using jquery

100%-100px is the same

div.thediv {
  width: auto;
  margin-right:100px;
}

With jQuery:

$(window).resize(function(){
  $('.thediv').each(function(){
    $(this).css('width', $(this).parent().width()-100);
  })
});

Similar way is to use jQuery resize plugin

iPhone App Minus App Store?

After copying the the app to the iPhone in the way described by @Jason Weathered, make sure to "chmod +x" of the app, otherwise it won't run.

is vs typeof

They don't do the same thing. The first one works if obj is of type ClassA or of some subclass of ClassA. The second one will only match objects of type ClassA. The second one will be faster since it doesn't have to check the class hierarchy.

For those who want to know the reason, but don't want to read the article referenced in is vs typeof.

MySql server startup error 'The server quit without updating PID file '

Delete *.err files that you find in the directory displayed in the error and create the file mysql is complaining about, restart mysql.

Best Practice: Software Versioning

The basic answer is "It depends".

What is your objective in versioning? Many people use version.revision.build and only advertise version.revision to the world as that's a release version rather than a dev version. If you use the check-in 'version' then you'll quickly find that your version numbers become large.

If you are planning your project then I'd increment revision for releases with minor changes and increment version for releases with major changes, bug fixes or functionality/features. If you are offering beta or nightly build type releases then extend the versioning to include the build and increment that with every release.

Still, at the end of the day, it's up to you and it has to make sense to you.

How can I pipe stderr, and not stdout?

First redirect stderr to stdout — the pipe; then redirect stdout to /dev/null (without changing where stderr is going):

command 2>&1 >/dev/null | grep 'something'

For the details of I/O redirection in all its variety, see the chapter on Redirections in the Bash reference manual.

Note that the sequence of I/O redirections is interpreted left-to-right, but pipes are set up before the I/O redirections are interpreted. File descriptors such as 1 and 2 are references to open file descriptions. The operation 2>&1 makes file descriptor 2 aka stderr refer to the same open file description as file descriptor 1 aka stdout is currently referring to (see dup2() and open()). The operation >/dev/null then changes file descriptor 1 so that it refers to an open file description for /dev/null, but that doesn't change the fact that file descriptor 2 refers to the open file description which file descriptor 1 was originally pointing to — namely, the pipe.

Has anyone gotten HTML emails working with Twitter Bootstrap?

If you mean "Can I use the stylistic presentation of Bootstrap in an email?" then you can, though I don't know anybody that has done it yet. You'll need to recode everything in tables though.

If you are after functionality, it depends on where your emails are viewed. If a significant proportion of your users are on Outlook, Gmail, Yahoo or Hotmail (and these typically add up to around 75% of email clients) then a lot of Bootstrap's goodness is not possible. Mac Mail, iOS Mail and Gmail on Android are much better at rendering CSS, so if you are targeting mostly mobile devices it's not quite so bad.

  • JavaScript - completely off limits. If you try, you'll probably go straight to email hell (a.k.a. spam folder). This means that LESS is also out of bounds, although you can obviously use the resulting CSS styles if you want to.
  • Inline CSS is much safer to use than any other type of CSS (embedded is possible, linked is a definite no). Media queries are possible, so you can have some kind of responsive design. However, there is a long list of CSS attributes that don't work - essentially, the box model is largely unsupported in email clients. You need to structure everything with tables.
  • font-face - you can only use external images. All other external resources (CSS files, fonts) are excluded.
  • glyphs and sprites - because of Outlook 2007's weird implementation of background-images (VML), you cant use background-repeat or position.
  • pseudo-selectors are not possible - e.g. :hover, :active states cannot be styled separately

There are loads of answers on SO, and lots of other links on the internet at large.

Prolog "or" operator, query

you can 'invoke' alternative bindings on Y this way:

...registered(X, Y), (Y=ct101; Y=ct102; Y=ct103).

Note the parenthesis are required to keep the correct execution control flow. The ;/2 it's the general or operator. For your restricted use you could as well choice the more idiomatic

...registered(X, Y), member(Y, [ct101,ct102,ct103]).

that on backtracking binds Y to each member of the list.

edit I understood with a delay your last requirement. If you want that Y match all 3 values the or is inappropriate, use instead

...registered(X, ct101), registered(X, ct102), registered(X, ct103).

or the more compact

...findall(Y, registered(X, Y), L), sort(L, [ct101,ct102,ct103]).

findall/3 build the list in the very same order that registered/2 succeeds. Then I use sort to ensure the matching.

...setof(Y, registered(X, Y), [ct101,ct102,ct103]).

setof/3 also sorts the result list

Using Python String Formatting with Lists

Since I just learned about this cool thing(indexing into lists from within a format string) I'm adding to this old question.

s = '{x[0]} BLAH {x[1]} FOO {x[2]} BAR'
x = ['1', '2', '3']
print (s.format (x=x))

Output:

1 BLAH 2 FOO 3 BAR

However, I still haven't figured out how to do slicing(inside of the format string '"{x[2:4]}".format...,) and would love to figure it out if anyone has an idea, however I suspect that you simply cannot do that.

JavaScript Promises - reject vs. throw

TLDR: A function is hard to use when it sometimes returns a promise and sometimes throws an exception. When writing an async function, prefer to signal failure by returning a rejected promise

Your particular example obfuscates some important distinctions between them:

Because you are error handling inside a promise chain, thrown exceptions get automatically converted to rejected promises. This may explain why they seem to be interchangeable - they are not.

Consider the situation below:

checkCredentials = () => {
    let idToken = localStorage.getItem('some token');
    if ( idToken ) {
      return fetch(`https://someValidateEndpoint`, {
        headers: {
          Authorization: `Bearer ${idToken}`
        }
      })
    } else {
      throw new Error('No Token Found In Local Storage')
    }
  }

This would be an anti-pattern because you would then need to support both async and sync error cases. It might look something like:

try {
  function onFulfilled() { ... do the rest of your logic }
  function onRejected() { // handle async failure - like network timeout }
  checkCredentials(x).then(onFulfilled, onRejected);
} catch (e) {
  // Error('No Token Found In Local Storage')
  // handle synchronous failure
} 

Not good and here is exactly where Promise.reject ( available in the global scope ) comes to the rescue and effectively differentiates itself from throw. The refactor now becomes:

checkCredentials = () => {
  let idToken = localStorage.getItem('some_token');
  if (!idToken) {
    return Promise.reject('No Token Found In Local Storage')
  }
  return fetch(`https://someValidateEndpoint`, {
    headers: {
      Authorization: `Bearer ${idToken}`
    }
  })
}

This now lets you use just one catch() for network failures and the synchronous error check for lack of tokens:

checkCredentials()
      .catch((error) => if ( error == 'No Token' ) {
      // do no token modal
      } else if ( error === 400 ) {
      // do not authorized modal. etc.
      }

PHP get domain name

Similar question has been asked in stackoverflow before.

See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:

  • no DNS support
  • misconfigured
  • behind load balancing software

Source: http://discussion.dreamhost.com/thread-4388.html

reading from app.config file

Try to rebuild your project - It copies the content of App.config to "<YourProjectName.exe>.config" in the build library.

MySQL my.cnf file - Found option without preceding group

it is because of letters or digit infront of [mysqld] just check the leeters or digit anything is not required before [mysqld]

it may be something like

0[mysqld] then this error will occur

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

A weird thing I found was that the environment variable SYSTEMROOT must be set otherwise getaddrinfo() will fail on Windows 10.

Error running android: Gradle project sync failed. Please fix your project and try again

If your got timeout, Check Gradle Scripts -> gradle.properties in Android Studio, I found that I do have set a socket proxy in Android Studio settings, but in this gradle.properties file, my proxy became to http, so I just removed this http proxy setting lines, and finally works.

Firing a Keyboard Event in Safari, using JavaScript

I am not very good with this but KeyboardEvent => see KeyboardEvent is initialized with initKeyEvent .
Here is an example for emitting event on <input type="text" /> element

_x000D_
_x000D_
document.getElementById("txbox").addEventListener("keypress", function(e) {_x000D_
  alert("Event " + e.type + " emitted!\nKey / Char Code: " + e.keyCode + " / " + e.charCode);_x000D_
}, false);_x000D_
_x000D_
document.getElementById("btn").addEventListener("click", function(e) {_x000D_
  var doc = document.getElementById("txbox");_x000D_
  var kEvent = document.createEvent("KeyboardEvent");_x000D_
  kEvent.initKeyEvent("keypress", true, true, null, false, false, false, false, 74, 74);_x000D_
  doc.dispatchEvent(kEvent);_x000D_
}, false);
_x000D_
<input id="txbox" type="text" value="" />_x000D_
<input id="btn" type="button" value="CLICK TO EMIT KEYPRESS ON TEXTBOX" />
_x000D_
_x000D_
_x000D_

Running Groovy script from the command line

It will work on Linux kernel 2.6.28 (confirmed on 4.9.x). It won't work on FreeBSD and other Unix flavors.

Your /usr/local/bin/groovy is a shell script wrapping the Java runtime running Groovy.

See the Interpreter Scripts section of EXECVE(2) and EXECVE(2).

FFmpeg: How to split video efficiently?

The ffmpeg wiki links back to this page in reference to "How to split video efficiently". I'm not convinced this page answers that question, so I did as @AlcubierreDrive suggested…

echo "Two commands" 
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:00:00 -t 00:30:00 -sn test1.mkv
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:30:00 -t 01:00:00 -sn test2.mkv
echo "One command" 
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:00:00 -t 00:30:00 \
  -sn test3.mkv -vcodec copy -acodec copy -ss 00:30:00 -t 01:00:00 -sn test4.mkv

Which outputs...

Two commands
real    0m16.201s
user    0m1.830s
sys 0m1.301s

real    0m43.621s
user    0m4.943s
sys 0m2.908s

One command
real    0m59.410s
user    0m5.577s
sys 0m3.939s

I tested a SD & HD file, after a few runs & a little maths.

Two commands SD 0m53.94 #2 wins  
One command  SD 0m49.63  

Two commands SD 0m55.00  
One command  SD 0m52.26 #1 wins 

Two commands SD 0m58.60 #2 wins  
One command  SD 0m58.61 

Two commands SD 0m54.60  
One command  SD 0m50.51 #1 wins 

Two commands SD 0m53.94  
One command  SD 0m49.63 #1 wins  

Two commands SD 0m55.00  
One command  SD 0m52.26 #1 wins 

Two commands SD 0m58.71  
One command  SD 0m58.61 #1 wins

Two commands SD 0m54.63  
One command  SD 0m50.51 #1 wins  

Two commands SD 1m6.67s #2 wins  
One command  SD 1m20.18  

Two commands SD 1m7.67  
One command  SD 1m6.72 #1 wins

Two commands SD 1m4.92  
One command  SD 1m2.24 #1 wins

Two commands SD 1m1.73  
One command  SD 0m59.72 #1 wins

Two commands HD 4m23.20  
One command  HD 3m40.02 #1 wins

Two commands SD 1m1.30  
One command  SD 0m59.59 #1 wins  

Two commands HD 3m47.89  
One command  HD 3m29.59 #1 wins  

Two commands SD 0m59.82  
One command  SD 0m59.41 #1 wins  

Two commands HD 3m51.18  
One command  HD 3m30.79 #1 wins  

SD file = 1.35GB DVB transport stream
HD file = 3.14GB DVB transport stream

Conclusion

The single command is better if you are handling HD, it agrees with the manuals comments on using -ss after the input file to do a 'slow seek'. SD files have a negligible difference.

The two command version should be quicker by adding another -ss before the input file for the a 'fast seek' followed by the more accurate slow seek.

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

Can I dynamically add HTML within a div tag from C# on load event?

Remember using

myDiv.InnerHtml = "something";

will replace all HTML elements in myDIV. you need to append text to avoid that.In that this may help

myDiv.InnerHtml = "something" + myDiv.InnerText;

any html control in myDiv but not ASP html controls(as they are not rendered yet).

In Java, how do I call a base class's method from the overriding method in a derived class?

Answer is as follows:

super.Mymethod();
super();                // calls base class Superclass constructor.
super(parameter list);          // calls base class parameterized constructor.
super.method();         // calls base class method.

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

how to insert value into DataGridView Cell?

You can access any DGV cell as follows :

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

But usually it's better to use databinding : you bind the DGV to a data source (DataTable, collection...) through the DataSource property, and only work on the data source itself. The DataGridView will automatically reflect the changes, and changes made on the DataGridView will be reflected on the data source

How do I configure different environments in Angular.js?

You could use lvh.me:9000 to access your AngularJS app, (lvh.me just points to 127.0.0.1) and then specify a different endpoint if lvh.me is the host:

app.service("Configuration", function() {
  if (window.location.host.match(/lvh\.me/)) {
    return this.API = 'http://localhost\\:7080/myapi/';
  } else {
    return this.API = 'http://localhost\\:8099/hisapi/';
  }
});

And then inject the Configuration service and use Configuration.API wherever you need to access the API:

$resource(Configuration.API + '/endpoint/:id', {
  id: '@id'
});

A tad clunky, but works fine for me, albeit in a slightly different situation (API endpoints differ in production and development).

Insert Unicode character into JavaScript

Although @ruakh gave a good answer, I will add some alternatives for completeness:

You could in fact use even var Omega = '&#937;' in JavaScript, but only if your JavaScript code is:

  • inside an event attribute, as in onclick="var Omega = '&#937'; alert(Omega)" or
  • in a script element inside an XHTML (or XHTML + XML) document served with an XML content type.

In these cases, the code will be first (before getting passed to the JavaScript interpreter) be parsed by an HTML parser so that character references like &#937; are recognized. The restrictions make this an impractical approach in most cases.

You can also enter the O character as such, as in var Omega = 'O', but then the character encoding must allow that, the encoding must be properly declared, and you need software that let you enter such characters. This is a clean solution and quite feasible if you use UTF-8 encoding for everything and are prepared to deal with the issues created by it. Source code will be readable, and reading it, you immediately see the character itself, instead of code notations. On the other hand, it may cause surprises if other people start working with your code.

Using the \u notation, as in var Omega = '\u03A9', works independently of character encoding, and it is in practice almost universal. It can however be as such used only up to U+FFFF, i.e. up to \uffff, but most characters that most people ever heard of fall into that area. (If you need “higher” characters, you need to use either surrogate pairs or one of the two approaches above.)

You can also construct a character using the String.fromCharCode() method, passing as a parameter the Unicode number, in decimal as in var Omega = String.fromCharCode(937) or in hexadecimal as in var Omega = String.fromCharCode(0x3A9). This works up to U+FFFF. This approach can be used even when you have the Unicode number in a variable.

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

I encounter this problem when trying to use matlab eng to call m functions from c code. which occurs with command mex -f .. ..

My solution:

strings /usr/lib/i386-<tab>/libstdc++.so.6 | grep GLIBC

I found it includes 3.4.15

so my system has the newest libs.

the problem comes from matlab itself, it calls its own libstdc++.so.6 from {MATLAB}/bin

so, just replace it with the updated system lib.

How can I convert an Int to a CString?

Here's one way:

CString str;
str.Format("%d", 5);

In your case, try _T("%d") or L"%d" rather than "%d"

oracle varchar to number

You have to use the TO_NUMBER function:

select * from exception where exception_value = to_number('105')

Recommendation for compressing JPG files with ImageMagick

Just saying for those who using Imagick class in PHP:

$im -> gaussianBlurImage(0.8, 10);      //blur
$im -> setImageCompressionQuality(85);  //set compress quality to 85

How do I keep CSS floats in one line?

Solution 1:

display:table-cell (not widely supported)

Solution 2:

tables

(I hate hacks.)

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

just right click on your project, hover maven then click update project.. done!!

Difference between socket and websocket?

Regarding your question (b), be aware that the Websocket specification hasn't been finalised. According to the W3C:

Implementors should be aware that this specification is not stable.

Personally I regard Websockets to be waaay too bleeding edge to use at present. Though I'll probably find them useful in a year or so.

Is there any sizeof-like method in Java?

There's a class/jar available on SourceForge.net that uses Java instrumentation to calculate the size of any object. Here's a link to the description: java.sizeOf

Codeigniter $this->input->post() empty while $_POST is working correctly

My issue was with an ajax call. I was using this:

type: 'posts',

instead of

type: 'post',

Syntax, D'oh!