Programs & Examples On #Manchester syntax

Simple logical operators in Bash

very close

if [[ $varA -eq 1 ]] && [[ $varB == 't1' || $varC == 't2' ]]; 
  then 
    scale=0.05
  fi

should work.

breaking it down

[[ $varA -eq 1 ]] 

is an integer comparison where as

$varB == 't1'

is a string comparison. otherwise, I am just grouping the comparisons correctly.

Double square brackets delimit a Conditional Expression. And, I find the following to be a good reading on the subject: "(IBM) Demystify test, [, [[, ((, and if-then-else"

Resize image in PHP

This resource(broken link) is also worth considering - some very tidy code that uses GD. However, I modified their final code snippet to create this function which meets the OPs requirements...

function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
    
    $target_dir = "your-uploaded-images-folder/";
    $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
    
    $image = new SimpleImage();
    $image->load($_FILES[$html_element_name]['tmp_name']);
    $image->resize($new_img_width, $new_img_height);
    $image->save($target_file);
    return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user
    
}

You will also need to include this PHP file...

<?php
 
/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/
 
class SimpleImage {
 
   var $image;
   var $image_type;
 
   function load($filename) {
 
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {
 
         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
 
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
 
         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image,$filename);
      }
      if( $permissions != null) {
 
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image);
      }
   }
   function getWidth() {
 
      return imagesx($this->image);
   }
   function getHeight() {
 
      return imagesy($this->image);
   }
   function resizeToHeight($height) {
 
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
 
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
 
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }
 
   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }      
 
}
?>

How to call a parent method from child class in javascript?

There is a much easier and more compact solution for multilevel prototype lookup, but it requires Proxy support. Usage: SUPER(<instance>).<method>(<args>), for example, assuming two classes A and B extends A with method m: SUPER(new B).m().

function SUPER(instance) {
    return new Proxy(instance, {
        get(target, prop) {
            return Object.getPrototypeOf(Object.getPrototypeOf(target))[prop].bind(target);
        }
    });
}

React component not re-rendering on state change

I was going through same issue in React-Native where API response & reject weren't updating states

apiCall().then(function(resp) { this.setState({data: resp}) // wasn't updating }

I solved the problem by changing function with the arrow function

apiCall().then((resp) => {
    this.setState({data: resp}) // rendering the view as expected
}

For me, it was a binding issue. Using arrow functions solved it because arrow function doesn't create its's own this, its always bounded to its outer context where it comes from

Android: how to make an activity return results to the activity which calls it?

UPDATE Feb. 2021

As in Activity v1.2.0 and Fragment v1.3.0, the new Activity Result APIs have been introduced.

The Activity Result APIs provide components for registering for a result, launching the result, and handling the result once it is dispatched by the system.

So there is no need of using startActivityForResult and onActivityResult anymore.

In order to use the new API, you need to create an ActivityResultLauncher in your origin Activity, specifying the callback that will be run when the destination Activity finishes and returns the desired data:

private val intentLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->

        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.getStringExtra("streetkey")
            result.data?.getStringExtra("citykey")
            result.data?.getStringExtra("homekey")
        }
    }

and then, launching your intent whenever you need to:

intentLauncher.launch(Intent(this, YourActivity::class.java))

And to return data from the destination Activity, you just have to add an intent with the values to return to the setResult() method:

val data = Intent()
data.putExtra("streetkey", "streetname")
data.putExtra("citykey", "cityname")
data.putExtra("homekey", "homename")

setResult(Activity.RESULT_OK, data)
finish()

For any additional information, please refer to Android Documentation

Access restriction on class due to restriction on required library rt.jar?

Sorry for updating an old POST. I got the reported problem and I solved it as said below.

Assuming you are using Eclipse + m2e maven plugin, if you get this access restriction error, right click on the project/module in which you have the error --> Properties --> Build Path --> Library --> Replace JDK/JRE to the one that is used in eclipse workspace.

I followed the above steps and the issue is resolved.

How to change background color in the Notepad++ text editor?

You may need admin access to do it on your system.

  1. Create a folder 'themes' in the Notepad++ installation folder i.e. C:\Program Files (x86)\Notepad++
  2. Search or visit pages like http://timtrott.co.uk/notepad-colour-schemes/ to download the favourite theme. It will be an SML file.
    • Note: I prefer Neon any day.
  3. Download the themes from the site and drag them to the themes folder.
    • Note: I was unable to copy-paste or create new files in 'themes' folder so I used drag and that worked.
  4. Follow the steps provided by @triforceofcourage to select the new theme in Notepad++ preferences.

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

I encountered the same problem , my resolution was to rename the the folder name under the workspace folder. i.e. com.ibm.collaboration.realtime.alertmanager.embedded was renamed to com.ibm.collaboration.realtime.alertmanager.2embeddedxx and rebuilt my project.

Negate if condition in bash script

Better

if ! wget -q --spider --tries=10 --timeout=20 google.com
then
  echo 'Sorry you are Offline'
  exit 1
fi

Add two textbox values and display the sum in a third textbox automatically

Try this: Open given fiddle in CHROME

function sum() {
      var txtFirstNumberValue = document.getElementById('txt1').value;
      var txtSecondNumberValue = document.getElementById('txt2').value;
      var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
      if (!isNaN(result)) {
         document.getElementById('txt3').value = result;
      }
}

HTML

<input type="text" id="txt1"  onkeyup="sum();" />
<input type="text" id="txt2"  onkeyup="sum();" />
<input type="text" id="txt3" />

DEMO HERE

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

For languages not specifying a memory model, you are writing code for the language and the memory model specified by the processor architecture. The processor may choose to re-order memory accesses for performance. So, if your program has data races (a data race is when it's possible for multiple cores / hyper-threads to access the same memory concurrently) then your program is not cross platform because of its dependence on the processor memory model. You may refer to the Intel or AMD software manuals to find out how the processors may re-order memory accesses.

Very importantly, locks (and concurrency semantics with locking) are typically implemented in a cross platform way... So if you are using standard locks in a multithreaded program with no data races then you don't have to worry about cross platform memory models.

Interestingly, Microsoft compilers for C++ have acquire / release semantics for volatile which is a C++ extension to deal with the lack of a memory model in C++ http://msdn.microsoft.com/en-us/library/12a04hfd(v=vs.80).aspx. However, given that Windows runs on x86 / x64 only, that's not saying much (Intel and AMD memory models make it easy and efficient to implement acquire / release semantics in a language).

JavaScript closures vs. anonymous functions

I would like to share my example and an explanation about closures. I made a python example, and two figures to demonstrate stack states.

def maker(a, b, n):
    margin_top = 2
    padding = 4
    def message(msg):
        print('\n’ * margin_top, a * n, 
            ' ‘ * padding, msg, ' ‘ * padding, b * n)
    return message

f = maker('*', '#', 5)
g = maker('?', '?’, 3)
…
f('hello')
g(‘good bye!')

The output of this code would be as follows:

*****      hello      #####

???      good bye!    ???

Here are two figures to show stacks and the closure attached to the function object.

when the function is returned from maker

when the function is called later

When the function is called through a parameter or a nonlocal variable, the code needs local variable bindings such as margin_top, padding as well as a, b, n. In order to ensure the function code to work, the stack frame of the maker function which was gone away long ago should be accessible, which is backed up in the closure we can find along with the function message object.

How to export all collections in MongoDB?

You can do it using the mongodump command

Step 1 : Open command prompt

Step 2 : go to bin folder of your mongoDB installation (C:\Program Files\MongoDB\Server\4.0\bin)

Step 3 : then execute the following command

mongodump -d your_db_name -o destination_path

your_db_name = test

destination_path = C:\Users\HP\Desktop

Exported files will be created in destination_path\your_db_name folder (in this example C:\Users\HP\Desktop\test)

References : o7planning

How to execute a Python script from the Django shell?

Try this if you are using virtual enviroment :-

python manage.py shell

for using those command you must be inside virtual enviroment. for this use :-

workon vir_env_name

for example :-

dc@dc-comp-4:~/mysite$ workon jango
(jango)dc@dc-comp-4:~/mysite$ python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

Note :- Here mysite is my website name and jango is my virtual enviroment name

How to insert a newline in front of a pattern?

This works in bash and zsh, tested on Linux and OS X:

sed 's/regexp/\'$'\n/g'

In general, for $ followed by a string literal in single quotes bash performs C-style backslash substitution, e.g. $'\t' is translated to a literal tab. Plus, sed wants your newline literal to be escaped with a backslash, hence the \ before $. And finally, the dollar sign itself shouldn't be quoted so that it's interpreted by the shell, therefore we close the quote before the $ and then open it again.

Edit: As suggested in the comments by @mklement0, this works as well:

sed $'s/regexp/\\\n/g'

What happens here is: the entire sed command is now a C-style string, which means the backslash that sed requires to be placed before the new line literal should now be escaped with another backslash. Though more readable, in this case you won't be able to do shell string substitutions (without making it ugly again.)

Data binding for TextBox

You can't databind to a property and then explictly assign a value to the databound property.

Download a file by jQuery.Ajax

function downloadURI(uri, name) 
{
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.click();
}

Xcode error "Could not find Developer Disk Image"

This error occurs when the version of Xcode predates that of the device.

For example, attempting to run a build on a device running iOS 9.3 in Xcode 7.2 results in this error; Could not find Developer Disk Image.

Why an error message that actually describes what the hell is going on can't be provided is beyond me (Apple, I'm looking at you ).

Update to the latest version of Xcode through the App Store or via direct download to guarantee interoperability with connected iOS hardware.

Java : How to determine the correct charset encoding of a stream

For ISO8859_1 files, there is not an easy way to distinguish them from ASCII. For Unicode files however one can generally detect this based on the first few bytes of the file.

UTF-8 and UTF-16 files include a Byte Order Mark (BOM) at the very beginning of the file. The BOM is a zero-width non-breaking space.

Unfortunately, for historical reasons, Java does not detect this automatically. Programs like Notepad will check the BOM and use the appropriate encoding. Using unix or Cygwin, you can check the BOM with the file command. For example:

$ file sample2.sql 
sample2.sql: Unicode text, UTF-16, big-endian

For Java, I suggest you check out this code, which will detect the common file formats and select the correct encoding: How to read a file and automatically specify the correct encoding

SQLite - UPSERT *not* INSERT or REPLACE

SELECT COUNT(*) FROM table1 WHERE id = 1;

if COUNT(*) = 0

INSERT INTO table1(col1, col2, cole) VALUES(var1,var2,var3);

else if COUNT(*) > 0

UPDATE table1 SET col1 = var4, col2 = var5, col3 = var6 WHERE id = 1;

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

WPF Data Binding and Validation Rules Best Practices

personaly, i'm using exceptions to handle validation. it requires following steps:

  1. in your data binding expression, you need to add "ValidatesOnException=True"
  2. in you data object you are binding to, you need to add DependencyPropertyChanged handler where you check if new value fulfills your conditions - if not - you restore to the object old value (if you need to) and you throw exception.
  3. in your control template you use for displaying invalid value in the control, you can access Error collection and display exception message.

the trick here, is to bind only to objects which derive from DependencyObject. simple implementation of INotifyPropertyChanged wouldn't work - there is a bug in the framework, which prevents you from accessing error collection.

Is there a “not in” operator in JavaScript for checking object properties?

As already said by Jordão, just negate it:

if (!(id in tutorTimes)) { ... }

Note: The above test if tutorTimes has a property with the name specified in id, anywhere in the prototype chain. For example "valueOf" in tutorTimes returns true because it is defined in Object.prototype.

If you want to test if a property doesn't exist in the current object, use hasOwnProperty:

if (!tutorTimes.hasOwnProperty(id)) { ... }

Or if you might have a key that is hasOwnPropery you can use this:

if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }

How can I create a small color box using html and css?

You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.

_x000D_
_x000D_
.foo {_x000D_
  float: left;_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  margin: 5px;_x000D_
  border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
  background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
  background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
  background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
_x000D_
_x000D_

Best way to use PHP to encrypt and decrypt passwords?

One thing you should be very aware of when dealing with encryption:

Trying to be clever and inventing your own thing usually will leave you with something insecure.

You'd probably be best off using one of the cryptography extensions that come with PHP.

How to set the maxAllowedContentLength to 500MB while running on IIS7?

IIS v10 (but this should be the same also for IIS 7.x)

Quick addition for people which are looking for respective max values

Max for maxAllowedContentLength is: UInt32.MaxValue 4294967295 bytes : ~4GB

Max for maxRequestLength is: Int32.MaxValue 2147483647 bytes : ~2GB

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <!-- ~ 2GB -->
    <httpRuntime maxRequestLength="2147483647" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- ~ 4GB -->
        <requestLimits maxAllowedContentLength="4294967295" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

What does "for" attribute do in HTML <label> tag?

The <label> tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:

One way is to wrap the label element around the input element:

<label>Input here:
    <input type='text' name='theinput' id='theinput'>
</label>

The other way is to use the for attribute, giving it the ID of the associated input:

<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>

This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.

Read more about this element in MDN.

Get login username in java

inspired by @newacct's answer, a code that can be compiled in any platform:

String osName = System.getProperty( "os.name" ).toLowerCase();
String className = null;
String methodName = "getUsername";

if( osName.contains( "windows" ) ){
    className = "com.sun.security.auth.module.NTSystem";
    methodName = "getName";
}
else if( osName.contains( "linux" ) ){
    className = "com.sun.security.auth.module.UnixSystem";
}
else if( osName.contains( "solaris" ) || osName.contains( "sunos" ) ){
    className = "com.sun.security.auth.module.SolarisSystem";
}

if( className != null ){
    Class<?> c = Class.forName( className );
    Method method = c.getDeclaredMethod( methodName );
    Object o = c.newInstance();
    System.out.println( method.invoke( o ) );
}

Convert string to a variable name

You can use do.call:

 do.call("<-",list(parameter_name, parameter_value))

PDOException “could not find driver”

If you are using sqlite for testing you will need php sqlite pdo drive. You can install them as below.

For Ubuntu 14.04

sudo apt-get install php5-sqlite
sudo service apache2 restart

In ubuntu 16.04 there is no php5-sqlite

sudo apt-get install php7.0-sqlite
sudo service apache2 restart

Android difference between Two Dates

Short & Sweet:

/**
 * Get a diff between two dates
 *
 * @param oldDate the old date
 * @param newDate the new date
 * @return the diff value, in the days
 */
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
    try {
        return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

Usage:

int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);

Output:

dateDifference: 2

Kotlin Version:

@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
    return try {
        DurationUnit.DAYS.convert(
            format.parse(newDate).time - format.parse(oldDate).time,
            DurationUnit.MILLISECONDS
        )
    } catch (e: Exception) {
        e.printStackTrace()
        0
    }
}

Differences between Emacs and Vim

Its like apples and oranges. Both have different design and philosphy. Vim is a Text Editor while Emacs is a Lisp Interpreter that does Text Editing.

I use Vim because its fast, sleak, and really good at manipulating texts. It has a composable natural key binding that can make your development tasks really harmonic. Vim is based on the simple *nix philiosphy of doing one thing really well - i.e Text Manipulation.

Extending Vim using bash/zsh and tmux is usually easy and allows you learn a lot of things. IMHO this is a good learning curve. The key thing is to learn how to integrate these things to get a larger working application. With Vim you'll need to learn integration because it doesn't naturally integrate unless you tell it how to. Another worthwhile extension which I use is Tig . Its an ncurses based Git frontend . I just have a binding that opens Tig silently and then I do all the Git stuff there.

Its up to the end user to decide what works best. That Emacs and Vim has stood the test of time is proof of their worthiness. Eventually a good programmer needs nothing more than a pen and a paper to be creative. Good algorithms don't need editors to back them. So try them both and see what makes you more productive. And learn design patterns from both these softwares as there are plenty to learn and discover!

excel plot against a date time x series

There is an easy workaround for this problem

What you need to do, is format your dates as DD/MM/YYYY (or whichever way around you like)

Insert a column next to the time and date columns, put a formula in this column that adds them together. e.g. =A5+B5.

Format this inserted column into DD/MM/YYYY hh:mm:ss which can be found in the custom category on the formatting section

Plot a scatter graph

Badabing badaboom

If you are unhappy with this workaround, learn to use GNUplot :)

How can I get device ID for Admob

Works to this way:

InterstitialAd mInterstitial = new InterstitialAd(this);
    mInterstitial.setAdUnitId("your id");
    AdRequest adRequest = new AdRequest.Builder()
    .addTestDevice("some words")
    .build();
    mInterstitial.loadAd(adRequest);

After run the app... Go in Logcat put in Verbose put in the search field AdRequest, so the id device shows donw.

enter image description here

.addTestDevice("put the id here");

I hope have helped;

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

This error also happens if you're using a self-signed certificate with a keyUsage missing the value keyCertSign.

How to upload a project to Github

The best way to git is to actually start Gitting. Try out this website which makes you go step by step on what are the essential ways for performing functions on command line for pushing a Project on GitHub

This is called try.github.io or you could also take up a course on codeAcademy

How do I use T-SQL's Case/When?

SELECT
   CASE 
   WHEN xyz.something = 1 THEN 'SOMETEXT'
   WHEN xyz.somethingelse = 1 THEN 'SOMEOTHERTEXT'
   WHEN xyz.somethingelseagain = 2 THEN 'SOMEOTHERTEXTGOESHERE'
   ELSE 'SOMETHING UNKNOWN'
   END AS ColumnName;

psql: server closed the connection unexepectedly

Solved by setting a password for the user first.

In terminal

sudo -u <username> psql

ALTER USER <username> PASSWORD 'SetPassword';
# ALTER ROLE

\q

In pgAdmin

**Connection**

Host name/address: 127.0.0.1
Port: 5432
Maintenance database: postgres
username: postgres
password: XXXXXX

Recommended method for escaping HTML in Java

On android (API 16 or greater) you can:

Html.escapeHtml(textToScape);

or for lower API:

TextUtils.htmlEncode(textToScape);

Difference between 'cls' and 'self' in Python classes?

This is very good question but not as wanting as question. There is difference between 'self' and 'cls' used method though analogically they are at same place

def moon(self, moon_name):
    self.MName = moon_name

#but here cls method its use is different 

@classmethod
def moon(cls, moon_name):
    instance = cls()
    instance.MName = moon_name

Now you can see both are moon function but one can be used inside class while other function name moon can be used for any class.

For practical programming approach :

While designing circle class we use area method as cls instead of self because we don't want area to be limited to particular class of circle only .

How to exit a 'git status' list in a terminal?

Before pressing exit commands(q, etc..) check current input language: if it isn't English commands may not work.

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

'setInterval' vs 'setTimeout'

setTimeout():

It is a function that execute a JavaScript statement AFTER x interval.

setTimeout(function () {
    something();
}, 1000); // Execute something() 1 second later.

setInterval():

It is a function that execute a JavaScript statement EVERY x interval.

setInterval(function () {
    somethingElse();
}, 2000); // Execute somethingElse() every 2 seconds.

The interval unit is in millisecond for both functions.

Jquery Smooth Scroll To DIV - Using ID value from Link

Ids are meant to be unique, and never use an id that starts with a number, use data-attributes instead to set the target like so :

<div id="searchbycharacter">
    <a class="searchbychar" href="#" data-target="numeric">0-9 |</a> 
    <a class="searchbychar" href="#" data-target="A"> A |</a> 
    <a class="searchbychar" href="#" data-target="B"> B |</a> 
    <a class="searchbychar" href="#" data-target="C"> C |</a> 
    ... Untill Z
</div>

As for the jquery :

$(document).on('click','.searchbychar', function(event) {
    event.preventDefault();
    var target = "#" + this.getAttribute('data-target');
    $('html, body').animate({
        scrollTop: $(target).offset().top
    }, 2000);
});

How do I generate sourcemaps when using babel and webpack?

Even same issue I faced, in browser it was showing compiled code. I have made below changes in webpack config file and it is working fine now.

 devtool: '#inline-source-map',
 debug: true,

and in loaders I kept babel-loader as first option

loaders: [
  {
    loader: "babel-loader",
    include: [path.resolve(__dirname, "src")]
  },
  { test: /\.js$/, exclude: [/app\/lib/, /node_modules/], loader: 'ng-annotate!babel' },
  { test: /\.html$/, loader: 'raw' },
  {
    test: /\.(jpe?g|png|gif|svg)$/i,
    loaders: [
      'file?hash=sha512&digest=hex&name=[hash].[ext]',
      'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
    ]
  },
  {test: /\.less$/, loader: "style!css!less"},
  { test: /\.styl$/, loader: 'style!css!stylus' },
  { test: /\.css$/, loader: 'style!css' }
]

How do I verify/check/test/validate my SSH passphrase?

ssh-keygen -y

ssh-keygen -y will prompt you for the passphrase (if there is one).

    If you input the correct passphrase, it will show you the associated public key.
    If you input the wrong passphrase, it will display load failed.
    If the key has no passphrase, it will not prompt you for a passphrase and will immediately show you the associated public key.

e.g.,

Create a new public/private key pair, with or without a passphrase:

$ ssh-keygen -f /tmp/my_key
...

Now see if you can access the key pair:

$ ssh-keygen -y -f /tmp/my_key

Following is an extended example, showing output.

Create a new public/private key pair, with or without a passphrase:

$ ssh-keygen -f /tmp/my_key
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /tmp/my_key.
Your public key has been saved in /tmp/my_key.pub.
The key fingerprint is:
de:24:1b:64:06:43:ca:76:ba:81:e5:f2:59:3b:81:fe [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
|     .+          |
|   . . o         |
|    = . +        |
|   = + +         |
|  o = o S .      |
|   + = + *       |
|    = o o .      |
|     . .         |
|      E          |
+-----------------+

Attempt to access the key pair by inputting the correct passphrase. Note that the public key will be shown and the exit status ($?) will be 0 to indicate success:

$ ssh-keygen -y -f /tmp/my_key
Enter passphrase:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBJhVYDYxXOvcQw0iJTPY64anbwSyzI58hht6xCGJ2gzGUJDIsr1NDQsclka6s0J9TNhUEBBzKvh9nTAYibXwwhIqBwJ6UwWIfA3HY13WS161CUpuKv2A/PrfK0wLFBDBlwP6WjwJNfi4NwxA21GUS/Vcm/SuMwaFid9bM2Ap4wZIahx2fxyJhmHugGUFF9qYI4yRJchaVj7TxEmquCXgVf4RVWnOSs9/MTH8YvH+wHP4WmUzsDI+uaF1SpCyQ1DpazzPWAQPgZv9R8ihOrItLXC1W6TPJkt1CLr/YFpz6vapdola8cRw6g/jTYms00Yxf2hn0/o8ORpQ9qBpcAjJN
$ echo $?
0

Attempt to access the key pair by inputting an incorrect passphrase. Note that the "load failed" error message will be displayed (message may differ depending on OS) and the exit status ($?) will be 1 to indicate an error:

$ ssh-keygen -y -f /tmp/my_key
Enter passphrase:
load failed
$ echo $?
1

Attempt to access a key pair that has no passphrase. Note that there is no prompt for the passphrase, the public key will be displayed, and the exit status ($?) will be 0 to indicate success:

$ ssh-keygen -y -f /tmp/my_key_with_no_passphrase
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLinxx9T4HE6Brw2CvFacvFrYcOSoQUmwL4Cld4enpg8vEiN8DB2ygrhFtKVo0qMAiGWyqz9gXweXhdmAIsVXqhOJIQvD8FqddA/SMgqM++2M7GxgH68N+0V+ih7EUqf8Hb2PIeubhkQJQGzB3FjYkvRLZqE/oC1Q5nL4B1L1zDQYPSnQKneaRNG/NGIaoVwsy6gcCZeqKHywsXBOHLF4F5nf/JKqfS6ojStvzajf0eyQcUMDVhdxTN/hIfEN/HdYbOxHtwDoerv+9f6h2OUxZny1vRNivZxTa+9Qzcet4tkZWibgLmqRyFeTcWh+nOJn7K3puFB2kKoJ10q31Tq19
$ echo $?
0

Note that the order of arguments is important. -y must come before -f input_keyfile, else you will get the error Too many arguments..

Substring in VBA

Test for ':' first, then take test string up to ':' or end, depending on if it was found

Dim strResult As String

' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
    ' : found, so take up to :
    strResult = Left(strTest, intPos - 1)
Else
    ' : not found, so take whole string
    strResult = strTest
End If

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0

How to list all AWS S3 objects in a bucket using Java

This worked for me.

Thread thread = new Thread(new Runnable(){
    @Override
    public void run() {
        try {
            List<String> listing = getObjectNamesForBucket(bucket, s3Client);
            Log.e(TAG, "listing "+ listing);

        }
        catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "Exception found while listing "+ e);
        }
    }
});

thread.start();



  private List<String> getObjectNamesForBucket(String bucket, AmazonS3 s3Client) {
        ObjectListing objects=s3Client.listObjects(bucket);
        List<String> objectNames=new ArrayList<String>(objects.getObjectSummaries().size());
        Iterator<S3ObjectSummary> oIter=objects.getObjectSummaries().iterator();
        while (oIter.hasNext()) {
            objectNames.add(oIter.next().getKey());
        }
        while (objects.isTruncated()) {
            objects=s3Client.listNextBatchOfObjects(objects);
            oIter=objects.getObjectSummaries().iterator();
            while (oIter.hasNext()) {
                objectNames.add(oIter.next().getKey());
            }
        }
        return objectNames;
}

Yarn install command error No such file or directory: 'install'

I believe all relevant solutions have been provided but here is a subtle situatuion: know that if you don't close and open your terminal again you will not see the effect.

Close your terminal and open then type in your terminal

yarn --version

Cheers!

How to re import an updated package while in Python Interpreter?

So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.

Yes, just saying import again gives you the existing copy of the module from sys.modules.

You can say reload(module) to update sys.modules and get a new copy of that single module, but if any other modules have a reference to the original module or any object from the original module, they will keep their old references and Very Confusing Things will happen.

So if you've got a module a, which depends on module b, and b changes, you have to ‘reload b’ followed by ‘reload a’. If you've got two modules which depend on each other, which is extremely common when those modules are part of the same package, you can't reload them both: if you reload p.a it'll get a reference to the old p.b, and vice versa. The only way to do it is to unload them both at once by deleting their items from sys.modules, before importing them again. This is icky and has some practical pitfalls to do with modules entries being None as a failed-relative-import marker.

And if you've got a module which passes references to its objects to system modules — for example it registers a codec, or adds a warnings handler — you're stuck; you can't reload the system module without confusing the rest of the Python environment.

In summary: for all but the simplest case of one self-contained module being loaded by one standalone script, reload() is very tricky to get right; if, as you imply, you are using a ‘package’, you will probably be better off continuing to cycle the interpreter.

Passing JavaScript array to PHP through jQuery $.ajax

Use the PHP built-in functionality of the appending the array operand to the desired variable name.

If we add values to a Javascript array as follows:

acitivies.push('Location Zero');
acitivies.push('Location One');
acitivies.push('Location Two');

It can be sent to the server as follows:

$.ajax({        
       type: 'POST',
       url: 'tourFinderFunctions.php',
       'activities[]': activities
       success: function() {
            $('#lengthQuestion').fadeOut('slow');        
       }
});

Notice the quotes around activities[]. The values will be available as follows:

$_POST['activities'][0] == 'Location Zero';
$_POST['activities'][1] == 'Location One';
$_POST['activities'][2] == 'Location Two';

How to add headers to a multicolumn listbox in an Excel userform using VBA

You can give this a try. I am quite new to the forum but wanted to offer something that worked for me since I've gotten so much help from this site in the past. This is essentially a variation of the above, but I found it simpler.

Just paste this into the Userform_Initialize section of your userform code. Note you must already have a listbox on the userform or have it created dynamically above this code. Also please note the Array is a list of headings (below as "Header1", "Header2" etc. Replace these with your own headings. This code will then set up a heading bar at the top based on the column widths of the list box. Sorry it doesn't scroll - it's fixed labels.

More senior coders - please feel free to comment or improve this.

    Dim Mywidths As String
    Dim Arrwidths, Arrheaders As Variant
    Dim ColCounter, Labelleft As Long
    Dim theLabel As Object                

    [Other code here that you would already have in the Userform_Initialize section]

    Set theLabel = Me.Controls.Add("Forms.Label.1", "Test" & ColCounter, True)
            With theLabel
                    .Left = ListBox1.Left
                    .Top = ListBox1.Top - 10
                    .Width = ListBox1.Width - 1
                    .Height = 10
                    .BackColor = RGB(200, 200, 200)
            End With
            Arrheaders = Array("Header1", "Header2", "Header3", "Header4")

            Mywidths = Me.ListBox1.ColumnWidths
            Mywidths = Replace(Mywidths, " pt", "")
            Arrwidths = Split(Mywidths, ";")
            Labelleft = ListBox1.Left + 18
            For ColCounter = LBound(Arrwidths) To UBound(Arrwidths)
                        If Arrwidths(ColCounter) > 0 Then
                                Header = Header + 1
                                Set theLabel = Me.Controls.Add("Forms.Label.1", "Test" & ColCounter, True)

                                With theLabel
                                    .Caption = Arrheaders(Header - 1)
                                    .Left = Labelleft
                                    .Width = Arrwidths(ColCounter)
                                    .Height = 10
                                    .Top = ListBox1.Top - 10
                                    .BackColor = RGB(200, 200, 200)
                                    .Font.Bold = True
                                End With
                                 Labelleft = Labelleft + Arrwidths(ColCounter)

                        End If
             Next

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

Yes, you're missing using cursors

DECLARE
  CURSOR foo_cur IS 
    SELECT NEEDED_FIELD WHERE condition ;
BEGIN
  OPEN foo_cur;
  FETCH foo_cur INTO foo_rec;
  IF foo_cur%FOUND THEN
     ...
  END IF;
  CLOSE foo_cur;
EXCEPTION
  WHEN OTHERS THEN
    CLOSE foo_cur;
    RAISE;
END ;

admittedly this is more code, but it doesn't use EXCEPTIONs as flow-control which, having learnt most of my PL/SQL from Steve Feuerstein's PL/SQL Programming book, I believe to be a good thing.

Whether this is faster or not I don't know (I do very little PL/SQL nowadays).

How to install Android SDK Build Tools on the command line?

ADB Build-Tools Will Not be downloaded automatically, by command android update sdk --no-ui

So for installing Buil-Tool type (in console):

android list sdk --all

Remember the number that is listed before the item and execute the following:

android update sdk -u --all --filter <number>

commands should be typed in /YourFolder/android-sdk-linux/tools

Also for remote folder (server opened by ssh for example) type:

**./android** list sdk --all
**./android** update sdk -u --all --filter <number>

For simple list of ADB packages type in terminal:

android list sdk

for install all packages:

android update sdk --no-ui

Or with filters (comma is separator):

android update sdk --no-ui --filter 3,5,8,14

How to properly compare two Integers in Java?

this method compares two Integer with null check, see tests

public static boolean compare(Integer int1, Integer int2) {
    if(int1!=null) {
        return int1.equals(int2);
    } else {
        return int2==null;
    }
    //inline version:
    //return (int1!=null) ? int1.equals(int2) : int2==null;
}

//results:
System.out.println(compare(1,1));           //true
System.out.println(compare(0,1));           //false
System.out.println(compare(1,0));           //false
System.out.println(compare(null,0));        //false
System.out.println(compare(0,null));        //false
System.out.println(compare(null,null));     //true

Start / Stop a Windows Service from a non-Administrator user account

I use the SubInACL utility for this. For example, if I wanted to give the user job on the computer VMX001 the ability to start and stop the World Wide Web Publishing Service (also know as w3svc), I would issue the following command as an Administrator:

subinacl.exe /service w3svc /grant=VMX001\job=PTO

The permissions you can grant are defined as follows (list taken from here):

F : Full Control
R : Generic Read
W : Generic Write
X : Generic eXecute
L : Read controL
Q : Query Service Configuration
S : Query Service Status
E : Enumerate Dependent Services
C : Service Change Configuration
T : Start Service
O : Stop Service
P : Pause/Continue Service
I : Interrogate Service 
U : Service User-Defined Control Commands

So, by specifying PTO, I am entitling the job user to Pause/Continue, Start, and Stop the w3svc service.

How to send list of file in a folder to a txt file in Linux

you can just use

ls > filenames.txt

(usually, start a shell by using "Terminal", or "shell", or "Bash".) You may need to use cd to go to that folder first, or you can ls ~/docs > filenames.txt

When does socket.recv(recv_size) return?

It'll have the same behavior as the underlying recv libc call see the man page for an official description of behavior (or read a more general description of the sockets api).

how to align text vertically center in android

In relative layout you need specify textview height:

android:layout_height="100dp"

Or specify lines attribute:

android:lines="3"

initialize a numpy array

numpy.zeros

Return a new array of given shape and type, filled with zeros.

or

numpy.ones

Return a new array of given shape and type, filled with ones.

or

numpy.empty

Return a new array of given shape and type, without initializing entries.


However, the mentality in which we construct an array by appending elements to a list is not much used in numpy, because it's less efficient (numpy datatypes are much closer to the underlying C arrays). Instead, you should preallocate the array to the size that you need it to be, and then fill in the rows. You can use numpy.append if you must, though.

Find maximum value of a column and return the corresponding row values using Pandas

The country and place is the index of the series, if you don't need the index, you can set as_index=False:

df.groupby(['country','place'], as_index=False)['value'].max()

Edit:

It seems that you want the place with max value for every country, following code will do what you want:

df.groupby("country").apply(lambda df:df.irow(df.value.argmax()))

Use dynamic variable names in `dplyr`

While I enjoy using dplyr for interactive use, I find it extraordinarily tricky to do this using dplyr because you have to go through hoops to use lazyeval::interp(), setNames, etc. workarounds.

Here is a simpler version using base R, in which it seems more intuitive, to me at least, to put the loop inside the function, and which extends @MrFlicks's solution.

multipetal <- function(df, n) {
   for (i in 1:n){
      varname <- paste("petal", i , sep=".")
      df[[varname]] <- with(df, Petal.Width * i)
   }
   df
}
multipetal(iris, 3) 

Convert Uri to String and String to Uri

Try this to convert string to uri

String mystring="Hello"
Uri myUri = Uri.parse(mystring);

Uri to String

Uri uri;
String uri_to_string;
uri_to_string= uri.toString();

How to create jar file with package structure?

This is what I do inside .sh file, let's consider install.sh

#!/bin/sh
echo Installing
cd .../Your_Project_Directory/com/cdy/ws/
jar cfe X.jar Main *.class
cd .../Your_Project_Directory/
ln -s .../Your_Project_Directory/com/cdy/ws/X.jar X
echo Testing...
java -jar X
echo You are Good to Go...Use hapily
#etc.

Creating Executable Jar file at the Class directory and creating a SymLink at anywhere you want.

Run it using,

$ sh install.sh[ENTER]
$ java -jar X[ENTER]

How do I perform the SQL Join equivalent in MongoDB?

Before 3.2.6, Mongodb does not support join query as like mysql. below solution which works for you.

 db.getCollection('comments').aggregate([
        {$match : {pid : 444}},
        {$lookup: {from: "users",localField: "uid",foreignField: "uid",as: "userData"}},
   ])

Remove leading and trailing spaces?

Starting file:

     line 1
   line 2
line 3  
      line 4 

Code:

with open("filename.txt", "r") as f:
    lines = f.readlines()
    for line in lines:
        stripped = line.strip()
        print(stripped)

Output:

line 1
line 2
line 3
line 4

How to return a PNG image from Jersey REST service method to the browser

If you have a number of image resource methods, it is well worth creating a MessageBodyWriter to output the BufferedImage:

@Produces({ "image/png", "image/jpg" })
@Provider
public class BufferedImageBodyWriter implements MessageBodyWriter<BufferedImage>  {
  @Override
  public boolean isWriteable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return type == BufferedImage.class;
  }

  @Override
  public long getSize(BufferedImage t, Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return -1; // not used in JAX-RS 2
  }

  @Override
  public void writeTo(BufferedImage image, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException {
    ImageIO.write(image, mt.getSubtype(), out);
  } 
}

This MessageBodyWriter will be used automatically if auto-discovery is enabled for Jersey, otherwise it needs to be returned by a custom Application sub-class. See JAX-RS Entity Providers for more info.

Once this is set up, simply return a BufferedImage from a resource method and it will be be output as image file data:

@Path("/whatever")
@Produces({"image/png", "image/jpg"})
public Response getFullImage(...) {
  BufferedImage image = ...;
  return Response.ok(image).build();
}

A couple of advantages to this approach:

  • It writes to the response OutputSteam rather than an intermediary BufferedOutputStream
  • It supports both png and jpg output (depending on the media types allowed by the resource method)

Converting .NET DateTime to JSON

Thought i'd add my solution that i've been using.

If you're using the System.Web.Script.Serialization.JavaScriptSerializer() then the time returned isn't going to be specific to your timezone. To fix this you'll also want to use dte.getTimezoneOffset() to get it back to your correct time.

String.prototype.toDateFromAspNet = function() {
    var dte = eval("new " + this.replace(/\//g, '') + ";");
    dte.setMinutes(dte.getMinutes() - dte.getTimezoneOffset());
    return dte;
}

now you'll just call

"/Date(1245398693390)/".toDateFromAspNet();

Fri Jun 19 2009 00:04:53 GMT-0400 (Eastern Daylight Time) {}

Java Serializable Object to Byte Array

Spring Framework org.springframework.util.SerializationUtils

byte[] data = SerializationUtils.serialize(obj);

How to check if a key exists in Json Object and get its value

Please try this one..

JSONObject jsonObject= null;
try {
     jsonObject = new JSONObject("result........");
     String labelDataString=jsonObject.getString("LabelData");
     JSONObject labelDataJson= null;
     labelDataJson= new JSONObject(labelDataString);
     if(labelDataJson.has("video")&&labelDataJson.getString("video")!=null){
       String video=labelDataJson.getString("video");
     }
    } catch (JSONException e) {
      e.printStackTrace();
 }

HttpServletRequest - how to obtain the referring URL?

It's available in the HTTP referer header. You can get it in a servlet as follows:

String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.

You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.

For the interested, background about the misspelling can be found in Wikipedia.

Authenticating in PHP using LDAP through Active Directory

PHP has libraries: http://ca.php.net/ldap

PEAR also has a number of packages: http://pear.php.net/search.php?q=ldap&in=packages&x=0&y=0

I haven't used either, but I was going to at one point and they seemed like they should work.

How to read single Excel cell value

It is better to use .Value2() instead of .Value(). This is faster and gives the exact value in the cell. For certain type of data, truncation can be observed when .Value() is used.

Encoding conversion in java

You don't need a library beyond the standard one - just use Charset. (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.)

EDIT: As pointed out in comments, you can still use Charset instances but have the ease of use of the String methods: new String(bytes, charset) and String.getBytes(charset).

See "URL Encoding (or: 'What are those "%20" codes in URLs?')".

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

  1. Make a jar file from your applet class and META-INF/MANIFEST.MF file.
  2. Sign your jar file with your certificate.
  3. Configure your local site permissions as > file:///C:/ or http: //localhost:8080
  4. Then run your html document on Intenet Explorer on Windows.(Not Google Chrome !)

Write to text file without overwriting in Java

Here is a simple example of how it works, best practice to put a try\catch into it but for basic use this should do the trick. For this you have a string and file path and apply thus to the FileWriter and the BufferedWriter. This will write "Hello World"(Data variable) and then make a new line. each time this is run it will add the Data variable to the next line.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;


String Data = "Hello World";
File file = new File("C:/Users/stuff.txt");
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Data);
bw.newLine();
bw.close();

How to get a tab character?

I use <span style="display: inline-block; width: 2ch;">&#9;</span> for a two characters wide tab.

How do I get the first n characters of a string without checking the size or going out of bounds?

Here's a neat solution:

String upToNCharacters = s.substring(0, Math.min(s.length(), n));

Opinion: while this solution is "neat", I think it is actually less readable than a solution that uses if / else in the obvious way. If the reader hasn't seen this trick, he/she has to think harder to understand the code. IMO, the code's meaning is more obvious in the if / else version. For a cleaner / more readable solution, see @paxdiablo's answer.

Collection was modified; enumeration operation may not execute in ArrayList

Don't modify the list inside of a loop which iterates through the list.

Instead, use a for() or while() with an index, going backwards through the list. (This will let you delete things without getting an invalid index.)

var foo = new List<Bar>();

for(int i = foo.Count-1; i >= 0; --i)
{
  var item = foo[i];
  // do something with item
}

This certificate has an invalid issuer Apple Push Services

In Apple's Developer's portal, add a new certificate, and when asked "What type of certificate do you need?" choose "WorldWide developer relations certificate". Generate the new certificate, download and install. The moment you do that, you will no longer see the message you have described.

Edit:
The certificate can be downloaded from the following page: https://www.apple.com/certificateauthority/ You can choose one of the following two certificates: "WWDR Certificate (Expiring 02/07/23)" or "WWDR Certificate (Expiring 02/14/16)"

How do you keep parents of floated elements from collapsing?

The main problem you may find with changing overflow to auto or hidden is that everything can become scrollable with the middle mouse buttom and a user can mess up the entire site layout.

Run a php app using tomcat?

A tad late, but here goes.

How about http://wiki.apache.org/tomcat/UsingPhp if you just want to run the real php on tomcat.

Concerning running tomcat on port 80 there's always jsvc, just google jsvc + tomcat.

Origin http://localhost is not allowed by Access-Control-Allow-Origin

By localhost you have to use the null origin. I recommend you to create a list of allowed hosts and check the request's Host header. If it is contained by the list, then by localhost send back an

res.header('Access-Control-Allow-Origin', "null");

by any other domain an

res.header('Access-Control-Allow-Origin', hostSentByTheRequestHeader);

If it is not contained by the list, then send back the servers host name, so the browser will hide the response by those requests.

This is much more secure, because by allow origin * and allow credentials everybody will be capable of for example stealing profile data of a logged in user, etc...

So to summarize something like this:

if (reqHost in allowedHosts)
    if (reqHost == "http://localhost")
        res.header('Access-Control-Allow-Origin', "null");
    else
        res.header('Access-Control-Allow-Origin', reqHost);
else
    res.header('Access-Control-Allow-Origin', serverHost);

is the most secure solution if you want to allow multiple other domains to access your page. (I guess you can figure out how the get the host request header and the server host by node.js.)

Remove trailing zeros from decimal in SQL Server

SELECT REVERSE(ROUND(REVERSE(2.5500),1))

prints:

2.55

CSS vertical alignment of inline/inline-block elements

For fine tuning the position of an inline-block item, use top and left:

  position: relative;
  top: 5px;
  left: 5px;

Thanks CSS-Tricks!

C++ - struct vs. class

Ok, POD means plain old data. That usually refers to structs without any methods because these types are then used to structure multiple data that belong together.

As for structs not having methods: I have seen more than once that a struct had methods, and I don't feel that this would be unnatural.

How to get the current TimeStamp?

I think you are looking for this function:

http://doc.qt.io/qt-5/qdatetime.html#toTime_t

uint QDateTime::toTime_t () const

Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).

On systems that do not support time zones, this function will behave as if local time were Qt::UTC.

See also setTime_t().

Check whether a variable is a string in Ruby

You can do:

foo.instance_of?(String)

And the more general:

foo.kind_of?(String)

HTML input textbox with a width of 100% overflows table cells

With some Javascript you can get the exact width of the containing TD and then assign that directly to the input element.

The following is raw javascript but jQuery would make it cleaner...

var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++)
{
    var el = inputs[i];
    if (el.style.width == '100%')
    {
        var pEl = el.parentNode;  // Assumes the parent node is the TD...
        el.style.width = pEl.offsetWidth;
    }
}

The issues with this solution are:

1) If you have your inputs contained in another element such as a SPAN then you will need loop up and find the TD because elements like SPANs will wrap the input and show its size rather then being limited to the size of the TD.

2) If you have padding or margins added at different levels then you might have to explicitly subtract that from [pEl.offsetWidth]. Depending on your HTML structure that can be calculated.

3) If the table columns are sized dynamically then changing the size of one element will cause the table to reflow in some browsers and you might get a stepped effect as you sequentially "fix" the input sizes. The solution is to assign specific widths to the column either as percentages or pixels OR collect the new widths and set them after. See the code below..

var inputs = document.getElementsByTagName('input');
var newSizes = [];
for (var i = 0; i < inputs.length; i++)
{
    var el = inputs[i];
    if (el.style.width == '100%')
    {
        var pEl = el.parentNode;  // Assumes the parent node is the TD...
        newSizes.push( { el: el, width: pEl.offsetWidth });
    }
}

// Set the sizes AFTER to avoid stepping...
for (var i = 0; i < newSizes.length; i++)
{
    newSizes[i].el.style.width = newSizes[i].width;
}

Connecting to TCP Socket from browser using javascript

The solution you are really looking for is web sockets. However, the chromium project has developed some new technologies that are direct TCP connections TCP chromium

How do I find which rpm package supplies a file I'm looking for?

You go to http://www.rpmfind.net and search for the file.

You'll get results for a lot of different distros and versions, but quite likely Fedora and/or CentOS will pop up too and you'll know the package name to install with yum

Grid of responsive squares

Now we can easily do this using the aspect-ratio ref property

_x000D_
_x000D_
.container {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr)); /* 3 columns */
  grid-gap: 10px;
}

.container>* {
  aspect-ratio: 1 / 1; /* a square ratio */
  border: 1px solid;
  
  /* center content */
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

img {
  max-width: 100%;
  display: block;
}
_x000D_
<div class="container">
  <div> some content here </div>
  <div><img src="https://picsum.photos/id/25/400/400"></div>
  <div>
    <h1>a title</h1>
  </div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
_x000D_
_x000D_

Also like below where we can have a variable number of columns

_x000D_
_x000D_
.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  grid-gap: 10px;
}

.container>* {
  aspect-ratio: 1 / 1; /* a square ratio */
  border: 1px solid;
  
  /* center content */
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

img {
  max-width: 100%;
  display: block;
}
_x000D_
<div class="container">
  <div> some content here </div>
  <div><img src="https://picsum.photos/id/25/400/400"></div>
  <div>
    <h1>a title</h1>
  </div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
_x000D_
_x000D_

Inject service in app.config

Using $injector to call service methods in config

I had a similar issue and resolved it by using the $injector service as shown above. I tried injecting the service directly but ended up with a circular dependency on $http. The service displays a modal with the error and I am using ui-bootstrap modal which also has a dependency on $https.

    $httpProvider.interceptors.push(function($injector) {
    return {
        "responseError": function(response) {

            console.log("Error Response status: " + response.status);

            if (response.status === 0) {
                var myService= $injector.get("myService");
                myService.showError("An unexpected error occurred. Please refresh the page.")
            }
        }
    }

Changing Font Size For UITableView Section Headers

For iOS 7 I use this,


-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;

    header.textLabel.font = [UIFont boldSystemFontOfSize:10.0f];
    header.textLabel.textColor = [UIColor orangeColor];
}

Here is Swift 3.0 version with header resizing

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let header = view as? UITableViewHeaderFooterView {
        header.textLabel!.font = UIFont.systemFont(ofSize: 24.0)
        header.textLabel!.textColor = UIColor.orange          
    }
}

How to determine if a type implements an interface with C# reflection

I just did:

public static bool Implements<I>(this Type source) where I : class
{
  return typeof(I).IsAssignableFrom(source);
}

I wish I could have said where I : interface, but interface is not a generic parameter constraint option. class is as close as it gets.

Usage:

if(MyType.Implements<IInitializable>())
  MyCollection.Initialize();

I just said Implements because that's more intuitive. I always get IsAssignableFrom flip-flopped.

MySQL how to join tables on two fields

JOIN t2 ON t1.id=t2.id AND t1.date=t2.date

How to get the number of columns in a matrix?

When want to get row size with size() function, below code can be used:

size(A,1)

Another usage for it:

[height, width] = size(A)

So, you can get 2 dimension of your matrix.

Importing the private-key/public-certificate pair in the Java KeyStore

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

How to check if a column exists in a SQL Server table?

One of the most simple and understandable solution is:

IF COL_LENGTH('Table_Name','Column_Name') IS NULL
 BEGIN
    -- Column Not Exists, implement your logic
 END 
ELSE
 BEGIN
    -- Column Exists, implement your logic
 END

How to add elements of a Java8 stream into an existing List

The short answer is no (or should be no). EDIT: yeah, it's possible (see assylias' answer below), but keep reading. EDIT2: but see Stuart Marks' answer for yet another reason why you still shouldn't do it!

The longer answer:

The purpose of these constructs in Java 8 is to introduce some concepts of Functional Programming to the language; in Functional Programming, data structures are not typically modified, instead, new ones are created out of old ones by means of transformations such as map, filter, fold/reduce and many others.

If you must modify the old list, simply collect the mapped items into a fresh list:

final List<Integer> newList = list.stream()
                                  .filter(n -> n % 2 == 0)
                                  .collect(Collectors.toList());

and then do list.addAll(newList) — again: if you really must.

(or construct a new list concatenating the old one and the new one, and assign it back to the list variable—this is a little bit more in the spirit of FP than addAll)

As to the API: even though the API allows it (again, see assylias' answer) you should try to avoid doing that regardless, at least in general. It's best not to fight the paradigm (FP) and try to learn it rather than fight it (even though Java generally isn't a FP language), and only resort to "dirtier" tactics if absolutely needed.

The really long answer: (i.e. if you include the effort of actually finding and reading an FP intro/book as suggested)

To find out why modifying existing lists is in general a bad idea and leads to less maintainable code—unless you're modifying a local variable and your algorithm is short and/or trivial, which is out of the scope of the question of code maintainability—find a good introduction to Functional Programming (there are hundreds) and start reading. A "preview" explanation would be something like: it's more mathematically sound and easier to reason about to not modify data (in most parts of your program) and leads to higher level and less technical (as well as more human friendly, once your brain transitions away from the old-style imperative thinking) definitions of program logic.

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

How to calculate Date difference in Hive

I would try this first

select * from employee where month(current_date)-3 = month(joining_date)

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

How to check if any fields in a form are empty in php

Specify POST method in form
<form name="registrationform" action="register.php" method="post">


your form code

</form>

How to go to each directory and execute a command?

for p in [0-9][0-9][0-9];do
    (
        cd $p
        for f in [0-9][0-9][0-9][0-9]*.txt;do
            ls $f; # Your operands
        done
    )
done

Asp.net - Add blank item at top of dropdownlist

ddlCategory.DataSource = ds;
ddlCategory.DataTextField = "CatName";
ddlCategory.DataValueField = "CatID";

Cách 1:

ddlCategory.Items.Add(new ListItem("--please select--", "-1"));
ddlCategory.AppendDataBoundItems = true;
ddlCategory.SelectedIndex = -1;

ddlCategory.DataBind();

Cách 2:

ddlCategory.Items.Insert(0, new ListItem("-- please select --", "0"));

(Tested OK)

How to outline text in HTML / CSS

Try this:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
 font: Tahoma, Geneva, sans-serif;_x000D_
 font-size: 64px;_x000D_
    color: white;_x000D_
    text-shadow:_x000D_
    /* Outline */_x000D_
    -1px -1px 0 #000000,_x000D_
    1px -1px 0 #000000,_x000D_
    -1px 1px 0 #000000,_x000D_
    1px 1px 0 #000000,  _x000D_
    -2px 0 0 #000000,_x000D_
    2px 0 0 #000000,_x000D_
    0 2px 0 #000000,_x000D_
    0 -2px 0 #000000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

...and you might also want to do this too:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
 font: Tahoma, Geneva, sans-serif;_x000D_
 font-size: 64px;_x000D_
    color: white;_x000D_
    text-shadow:_x000D_
    /* Outline 1 */_x000D_
    -1px -1px 0 #000000,_x000D_
    1px -1px 0 #000000,_x000D_
    -1px 1px 0 #000000,_x000D_
    1px 1px 0 #000000,  _x000D_
    -2px 0 0 #000000,_x000D_
    2px 0 0 #000000,_x000D_
    0 2px 0 #000000,_x000D_
    0 -2px 0 #000000, _x000D_
    /* Outline 2 */_x000D_
    -2px -2px 0 #ff0000,_x000D_
    2px -2px 0 #ff0000,_x000D_
    -2px 2px 0 #ff0000,_x000D_
    2px 2px 0 #ff0000,  _x000D_
    -3px 0 0 #ff0000,_x000D_
    3px 0 0 #ff0000,_x000D_
    0 3px 0 #ff0000,_x000D_
    0 -3px 0 #ff0000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

You can do as many Outlines as you like, and there's enough scope for coming up with lots of creative ideas.

Have fun!

Upload file to FTP using C#

public void UploadFtpFile(string folderName, string fileName)
{

    FtpWebRequest request;

    string folderName; 
    string fileName;
    string absoluteFileName = Path.GetFileName(fileName);

    request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}/{2}", "127.0.0.1", folderName, absoluteFileName))) as FtpWebRequest;
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UseBinary = 1;
    request.UsePassive = 1;
    request.KeepAlive = 1;
    request.Credentials =  new NetworkCredential(user, pass);
    request.ConnectionGroupName = "group"; 

    using (FileStream fs = File.OpenRead(fileName))
    {
        byte[] buffer = new byte[fs.Length];
        fs.Read(buffer, 0, buffer.Length);
        fs.Close();
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(buffer, 0, buffer.Length);
        requestStream.Flush();
        requestStream.Close();
    }
}

How to use

UploadFtpFile("testFolder", "E:\\filesToUpload\\test.img");

use this in your foreach

and you only need to create folder one time

to create a folder

request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}/", "127.0.0.1", "testFolder"))) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse ftpResponse = (FtpWebResponse)request.GetResponse();

Simple mediaplayer play mp3 from file path?

2020 - NOV

This worked for me:

final File file = new File(getFilesDir(), "test.wav");//OR path to existing file
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.fromFile(file));
mediaPlayer.start();

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

Change

<serviceMetadata httpsGetEnabled="true"/>

to

<serviceMetadata httpsGetEnabled="false"/>

You're telling WCF to use https for the metadata endpoint and I see that your'e exposing your service on http, and then you get the error in the title.

You also have to set <security mode="None" /> if you want to use HTTP as your URL suggests.

Android screen size HDPI, LDPI, MDPI

You should read Supporting multiple screens. You must define dpi on your emulator. 240 is hdpi, 160 is mdpi and below that are usually ldpi.

Extract from Android Developer Guide link above:

320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).  
480dp: a tweener tablet like the Streak (480x800 mdpi).  
600dp: a 7” tablet (600x1024 mdpi).  
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

json_decode() expects parameter 1 to be string, array given

here is the solution for similar problem which i was facing while extracting name from user profile facebook json object

$uname=json_encode($userprof);
$uname=json_decode($uname);
echo "Welcome " . $uname -> name  ;

How does facebook, gmail send the real time notification?

According to a slideshow about Facebook's Messaging system, Facebook uses the comet technology to "push" message to web browsers. Facebook's comet server is built on the open sourced Erlang web server mochiweb.

In the picture below, the phrase "channel clusters" means "comet servers".

System overview

Many other big web sites build their own comet server, because there are differences between every company's need. But build your own comet server on a open source comet server is a good approach.

You can try icomet, a C1000K C++ comet server built with libevent. icomet also provides a JavaScript library, it is easy to use as simple as:

var comet = new iComet({
    sign_url: 'http://' + app_host + '/sign?obj=' + obj,
    sub_url: 'http://' + icomet_host + '/sub',
    callback: function(msg){
        // on server push
        alert(msg.content);
    }
});

icomet supports a wide range of Browsers and OSes, including Safari(iOS, Mac), IEs(Windows), Firefox, Chrome, etc.

how to convert 2d list to 2d numpy array?

Just pass the list to np.array:

a = np.array(a)

You can also take this opportunity to set the dtype if the default is not what you desire.

a = np.array(a, dtype=...)

Is it possible to program iPhone in C++

You have to use Objective C to interface with the Cocoa API, so there is no choice. Of course, you can use as much C++ as you like behind the scenes (Objective C++ makes this easy).

It is an insane language indeed, but it's also... kind of fun to use once you're a bit used to it. :-)

Generic List - moving an item within the list

I would expect either:

// Makes sure item is at newIndex after the operation
T item = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, item);

... or:

// Makes sure relative ordering of newIndex is preserved after the operation, 
// meaning that the item may actually be inserted at newIndex - 1 
T item = list[oldIndex];
list.RemoveAt(oldIndex);
newIndex = (newIndex > oldIndex ? newIndex - 1, newIndex)
list.Insert(newIndex, item);

... would do the trick, but I don't have VS on this machine to check.

What does the PHP error message "Notice: Use of undefined constant" mean?

You missed putting single quotes around your array keys:

$_POST[email]

should be:

$_POST['email']

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Interestingly:

_dbContext.Set<T>().AddOrUpdate(entityToBeUpdatedWithId);

Or if you still is not generic:

_dbContext.Set<UserEntity>().AddOrUpdate(entityToBeUpdatedWithId);

seems to solved my problem smoothly.

How to debug external class library projects in visual studio?

Try disabling Just My Code (JMC).

  • Tools -> Options -> Debugger
  • Uncheck "Enable Just my Code"

By default the debugger tries to restrict the view of the world to code that is only contained within your solution. This is really heplful at times but when you want to debug code which is not in your solution (as is your situation) you need to disable JMC in order to see it. Otherwise the code will be treated as external and largely hidden from your view.

EDIT

When you're broken in your code try the following.

  • Debug -> Windows -> Modules
  • Find the DLL for the project you are interested in
  • Right Click -> Load Symbols -> Select the Path to the .PDB for your other project

Javascript + Regex = Nothing to repeat error?

You need to double the backslashes used to escape the regular expression special characters. However, as @Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:

The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:

"[\\[\\]?*+|{}\\\\()@.\n\r]"

Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to @Bohemian's string, and works correctly.

How to define several include path in Makefile

Make's substitutions feature is nice and helped me to write

%.i: src/%.c $(INCLUDE)
        gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@

You might find this useful, because it asks make to check for changes in include folders too

Height of status bar in Android

Out of all the code samples I've used to get the height of the status bar, the only one that actually appears to work in the onCreate method of an Activity is this:

public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

Apparently the actual height of the status bar is kept as an Android resource. The above code can be added to a ContextWrapper class (e.g. an Activity).

Found at http://mrtn.me/blog/2012/03/17/get-the-height-of-the-status-bar-in-android/

Do you get charged for a 'stopped' instance on EC2?

No.

You get charged for:

  1. Online time
  2. Storage space (assumably you store the image on S3 [EBS])
  3. Elastic IP addresses
  4. Bandwidth

So... if you stop the EC2 instance you will only have to pay for the storage of the image on S3 (assuming you store an image ofcourse) and any IP addresses you've reserved.

How to get the selected value from drop down list in jsp?

I've got one more additional option to get value by id:

var idElement = document.getElementById("idName");
var selectedValue = idElement.options[idElement.selectedIndex].value;

It's a simple JavaScript solution.

Angular JS POST request not sending JSON data

If you are serializing your data object, it will not be a proper json object. Take what you have, and just wrap the data object in a JSON.stringify().

$http({
    url: '/user_to_itsr',
    method: "POST",
    data: JSON.stringify({application:app, from:d1, to:d2}),
    headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
    $scope.users = data.users; // assign  $scope.persons here as promise is resolved here 
}).error(function (data, status, headers, config) {
    $scope.status = status + ' ' + headers;
});

Can I force a UITableView to hide the separator between empty cells?

If you use iOS 7 SDK, this is very simple.

Just add this line in your viewDidLoad method:

self.yourTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

Facebook Oauth Logout

For Python developers that want to log user out straight from the backend

At the moment I'm writing this, the trick with m.facebook.com no longer works (at least for me) and user is redirected to the mobile FB login page which obviously is not good for UX.

Fortunately, FB PHP SDK has a semi-documented solution (in case the link doesn't lead to getLogoutUrl() function, just search look for it on that page). This is also mentioned in at least one other on StackOverflow: Facebook php SDK getLogoutUrl() problem.

BTW I've just noticed that Zach Greenberg got it right in this question, but I'm adding my answer as a summary for Python developers.

The module ".dll" was loaded but the entry-point was not found

I found the answer: I need to add a new application to the service components in my computer and then add the right DLL's.

Thanks! If anyone has the same problem, I'll be happy to help.

How to get Locale from its String representation in Java?

Method that returns locale from string exists in commons-lang library: LocaleUtils.toLocale(localeAsString)

How to config routeProvider and locationProvider in angularJS?

Following is how one can configure $locationProvider using requireBase=false flag to avoid setting base href <head><base href="/"></head>:

var app = angular.module("hwapp", ['ngRoute']);

app.config(function($locationProvider){
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    }) 
});

Is there any boolean type in Oracle databases?

DECLARE
error_flag  BOOLEAN := false;
BEGIN

error_flag := true;
--error_flag := 13;--expression is of wrong type

  IF error_flag THEN 

UPDATE table_a SET id= 8 WHERE id = 1;

END IF;
END;

How to make ng-repeat filter out duplicate results

This might be overkill, but it works for me.

Array.prototype.contains = function (item, prop) {
var arr = this.valueOf();
if (prop == undefined || prop == null) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == item) {
            return true;
        }
    }
}
else {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i][prop] == item) return true;
    }
}
return false;
}

Array.prototype.distinct = function (prop) {
   var arr = this.valueOf();
   var ret = [];
   for (var i = 0; i < arr.length; i++) {
       if (!ret.contains(arr[i][prop], prop)) {
           ret.push(arr[i]);
       }
   }
   arr = [];
   arr = ret;
   return arr;
}

The distinct function depends on the contains function defined above. It can be called as array.distinct(prop); where prop is the property you want to be distinct.

So you could just say $scope.places.distinct("category");

How to get anchor text/href on click using jQuery?

Without jQuery:

You don't need jQuery when it is so simple to do this using pure JavaScript. Here are two options:

  • Method 1 - Retrieve the exact value of the href attribute:

    Select the element and then use the .getAttribute() method.

    This method does not return the full URL, instead it retrieves the exact value of the href attribute.

    _x000D_
    _x000D_
    var anchor = document.querySelector('a'),_x000D_
        url = anchor.getAttribute('href');_x000D_
    _x000D_
    alert(url);
    _x000D_
    <a href="/relative/path.html"></a>
    _x000D_
    _x000D_
    _x000D_


  • Method 2 - Retrieve the full URL path:

    Select the element and then simply access the href property.

    This method returns the full URL path.

    In this case: http://stacksnippets.net/relative/path.html.

    _x000D_
    _x000D_
    var anchor = document.querySelector('a'),_x000D_
        url = anchor.href;_x000D_
    _x000D_
    alert(url);
    _x000D_
    <a href="/relative/path.html"></a>
    _x000D_
    _x000D_
    _x000D_


As your title implies, you want to get the href value on click. Simply select an element, add a click event listener and then return the href value using either of the aforementioned methods.

_x000D_
_x000D_
var anchor = document.querySelector('a'),_x000D_
    button = document.getElementById('getURL'),_x000D_
    url = anchor.href;_x000D_
_x000D_
button.addEventListener('click', function (e) {_x000D_
  alert(url);_x000D_
});
_x000D_
<button id="getURL">Click me!</button>_x000D_
<a href="/relative/path.html"></a>
_x000D_
_x000D_
_x000D_

Right align and left align text in same HTML table cell

Tor Valamo's answer with a little contribution form my side: use the attribute "nowrap" in the "td" element, and you can remove the "width" specification. Hope it helps.

<td nowrap>
  <div style="float:left;">this is left</div>
  <div style="float:right;">this is right</div>
</td>

PHP absolute path to root

This is my way to find the rootstart. Create at ROOT start a file with name mainpath.php

<?php 
## DEFINE ROOTPATH
$check_data_exist = ""; 

$i_surf = 0;

// looking for mainpath.php at the aktiv folder or higher folder

while (!file_exists($check_data_exist."mainpath.php")) {
  $check_data_exist .= "../"; 
  $i_surf++;
  // max 7 folder deep
  if ($i_surf == 7) { 
   return false;
  }
}

define("MAINPATH", ($check_data_exist ? $check_data_exist : "")); 
?>

For me is that the best and easiest way to find them. ^^

What to do about Eclipse's "No repository found containing: ..." error messages?

I just got it when installing Maven support in Eclipse for Java EE developers Helios. Solution was just to run Eclipse as Administrator, update went fine after

Getting the IP address of the current machine using Java

A rather simplistic approach that seems to be working...

String getPublicIPv4() throws UnknownHostException, SocketException{
    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    String ipToReturn = null;
    while(e.hasMoreElements())
    {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        Enumeration<InetAddress> ee = n.getInetAddresses();
        while (ee.hasMoreElements())
        {
            InetAddress i = (InetAddress) ee.nextElement();
            String currentAddress = i.getHostAddress();
            logger.trace("IP address "+currentAddress+ " found");
            if(!i.isSiteLocalAddress()&&!i.isLoopbackAddress() && validate(currentAddress)){
                ipToReturn = currentAddress;    
            }else{
                System.out.println("Address not validated as public IPv4");
            }

        }
    }

    return ipToReturn;
}

private static final Pattern IPv4RegexPattern = Pattern.compile(
        "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");

public static boolean validate(final String ip) {
    return IPv4RegexPattern.matcher(ip).matches();
}

Base64 PNG data to HTML5 canvas

By the looks of it you need to actually pass drawImage an image object like so

_x000D_
_x000D_
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
  ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

I've tried it in chrome and it works fine.

php: loop through json array

Set the second function parameter to true if you require an associative array

Some versions of php require a 2nd paramter of true if you require an associative array

$json  = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );

Dynamically load a JavaScript file

You may write dynamic script tags (using Prototype):

new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});

The problem here is that we do not know when the external script file is fully loaded.

We often want our dependant code on the very next line and like to write something like:

if (iNeedSomeMore) {
    Script.load("myBigCodeLibrary.js"); // includes code for myFancyMethod();
    myFancyMethod(); // cool, no need for callbacks!
}

There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a synchronous AJAX request and eval the script on global level.

If you use Prototype the Script.load method looks like this:

var Script = {
    _loadedScripts: [],
    include: function(script) {
        // include script only once
        if (this._loadedScripts.include(script)) {
            return false;
        }
        // request file synchronous
        var code = new Ajax.Request(script, {
            asynchronous: false,
            method: "GET",
            evalJS: false,
            evalJSON: false
        }).transport.responseText;
        // eval code on global level
        if (Prototype.Browser.IE) {
            window.execScript(code);
        } else if (Prototype.Browser.WebKit) {
            $$("head").first().insert(Object.extend(
                new Element("script", {
                    type: "text/javascript"
                }), {
                    text: code
                }
            ));
        } else {
            window.eval(code);
        }
        // remember included script
        this._loadedScripts.push(script);
    }
};

Execution sequence of Group By, Having and Where clause in SQL Server?

WHERE is first, then you GROUP the result of the query, and last but not least HAVING-clause is taken to filter the grouped result. This is the "logical" order, I don't know how this is technically implemented in the engine.

How to vertically center an image inside of a div element in HTML using CSS?

As I too am constantly being let down by cross-browser CSS, I'd like to offer a JQuery solution here. This takes the height of each image's parent div, divide it by two and set it as a top margin between the image and the div:

$('div img').each(function() {
 m = Math.floor(($(this).parent('div').height() - $(this).height())/2);
 mp = m+"px";
 $(this).css("margin-top",mp);
});

Throughput and bandwidth difference?

Here is another example to help you imagine what the difference could be depending on the situation.

Imagine

  • You have a 1 MB file (say a photo) that you would like to share with 3 friends.
  • Each of them, however, uses different cloud storage application - Google Drive, Microsoft OneDrive and Dropbox. Therefore they all create a folder and give you access so you can upload the file to their folder.
  • You open the URLs to these three folders in your browser (say in 3 different tabs) and drag-n-drop the file (more or less at the same time) to each tab so to upload it.
  • You are connected to the Internet via a fiber-optic cable which gives you the ability to transfer at speed of 1 Gb per second (i.e. this is your bandwidth - the max capacity that you can utilise your connection).

Knowing that, theoretically (assuming no data lost, no big protocol overhead, connection to the cloud storage services offers at least the same bandwidth, etc.) you can transfer one 1 MB file over the 1 Gbps connection for roughly: 1MB / 1 Gbps = 1 x 10^3 x 8 / 1x10^9 which gives about 8x10^-6 seconds or say roughly 10 ms. Now, you have 1 file that you want to upload to 3 destinations, your connection bandwidth is big enough so you can transfer the same file to 3 destinations at the same time (we can also assume you have a modern laptop equipped with multi-core CPU so data transfer over the 3 connections to Google Drive, MS OneDrive and Dropbox can be done in parallel). Therefore, instead of waiting for 30ms to transfer the same file to 3 different destinations you only have to wait for 10ms as you have a very good bandwidth.

Now let's consider what protocol is being used and what implications that brings. As you use your browser to upload the file, the protocol that is being used is HTTP/S which is running on top of the TCP protocol. An important property of the TCP protocol is that it makes sure that a batch of data has reached any destination successfully before sending the next batch of data. That is being done by the TCP sender waiting for acknowledgement (for short an ACK) that the first batch of data has been received before it starts sending the second batch of data. What this means is that if it takes 0.5s to transfer 1 batch of data one direction and then 0.5s to received an ACK then you need to wait for 1 second until 1 batch of data is transferred and successfully confirmed to have been received (again, let's assume no data lost, therefore no need to re-transfer the same batch). Because of this round trip needed by the TCP protocol there appears to be a blocker. The blocker is the delay you experience for one round trip which includes transferring 1 batch of data and its successful acknowledgement. With that in mind we need to see how big is one batch of data. This can vary but it's usually 64KB. So your actual traffic to 1 destination (i.e, the throughput) is bound by this delay (i.e., latency) and the batch size by the following equation:

throughput = batch size / latency

In our example the throughput is 64KB/s and as we can split 1 MB in roughly 15.6 batches of 64KB size, you will need about 15.6 seconds to transfer 1 MB of file. That is a major slowdown compared to the bandwidth-only based calculations we made early.

How to detect chrome and safari browser (webkit)

I am trying to detect the chrome and safari browser using jquery or javascript.

Use jQuery.browser

I thought we are not supposed to use jQuery.browser.

That's because detecting browsers is a bad idea. It is still the best way to detect the browser (when jQuery is involved) if you really intend to do that.

What are the dark corners of Vim your mom never told you about?

Variation of sudo write:

into .vimrc

cmap w!! w !sudo tee % >/dev/null

After reload vim you can do "sudo save" as

:w!!

NodeJS / Express: what is "app.use"?

As the name suggests, it acts as a middleware in your routing.

Let's say for any single route, you want to call multiple url or perform multiple functions internally before sending the response. you can use this middleware and pass your route and perform all internal operations.

syntax:
app.use( function(req, res, next) {
  // code
 next();
})

next is optional, you can use to pass the result using this parameter to the next function.

jQuery Validation using the class instead of the name value

Here's my solution (requires no jQuery... just JavaScript):

function argsToArray(args) {
  var r = []; for (var i = 0; i < args.length; i++)
    r.push(args[i]);
  return r;
}
function bind() {
  var initArgs = argsToArray(arguments);
  var fx =        initArgs.shift();
  var tObj =      initArgs.shift();
  var args =      initArgs;
  return function() {
    return fx.apply(tObj, args.concat(argsToArray(arguments)));
  };
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
  checkbox.addEventListener('change', bind(function(checkbox, salutation) {
    var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
    if (numChecked >= 4)
      checkbox.checked = false;
  }, null, checkbox, salutation), false);
});

Put this in a script block at the end of <body> and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).

Here, I'll even give you a test page (paste it into a file and try it):

<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
    function argsToArray(args) {
      var r = []; for (var i = 0; i < args.length; i++)
        r.push(args[i]);
      return r;
    }
    function bind() {
      var initArgs = argsToArray(arguments);
      var fx =        initArgs.shift();
      var tObj =      initArgs.shift();
      var args =      initArgs;
      return function() {
        return fx.apply(tObj, args.concat(argsToArray(arguments)));
      };
    }
    var salutation = argsToArray(document.getElementsByClassName('salutation'));
    salutation.forEach(function(checkbox) {
      checkbox.addEventListener('change', bind(function(checkbox, salutation) {
        var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
        if (numChecked >= 3)
          checkbox.checked = false;
      }, null, checkbox, salutation), false);
    });
</script></body></html>

How can I define an array of objects?

What you really want may simply be an enumeration

If you're looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don't want to misspell (e.g. name vs naaame), you're better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.

enum TestStatus {
    Available,     // 0
    Ready,         // 1
    Started,       // 2
}

class Test {
    status: TestStatus
}

var test = new Test();
test.status = TestStatus.Available; // type and spelling is checked for you,
                                    // and the sequence ID is automatic

The values above will be automatically mapped, e.g. "0" for "Available", and you can access them using TestStatus.Available. And Typescript will enforce the type when you pass those around.

If you insist on defining a new type as an array of your custom type

You wanted an array of objects, (not exactly an object with keys "0", "1" and "2"), so let's define the type of the object, first, then a type of a containing array.

class TestStatus {
    id: number
    name: string

    constructor(id, name){
        this.id = id;
        this.name = name;
    }
}

type Statuses = Array<TestStatus>;

var statuses: Statuses = [
    new TestStatus(0, "Available"),
    new TestStatus(1, "Ready"),
    new TestStatus(2, "Started")
]

How to read file contents into a variable in a batch file?

To get all the lines of the file loaded into the variable, Delayed Expansion is needed, so do the following:

SETLOCAL EnableDelayedExpansion

for /f "Tokens=* Delims=" %%x in (version.txt) do set Build=!Build!%%x

There is a problem with some special characters, though especially ;, % and !

Which Python memory profiler is recommended?

Muppy is (yet another) Memory Usage Profiler for Python. The focus of this toolset is laid on the identification of memory leaks.

Muppy tries to help developers to identity memory leaks of Python applications. It enables the tracking of memory usage during runtime and the identification of objects which are leaking. Additionally, tools are provided which allow to locate the source of not released objects.

Basic Ajax send/receive with node.js

Here is a fully functional example of what you are trying to accomplish. I created the example inside of hyperdev rather than jsFiddle so that you could see the server-side and client-side code.

View Code: https://hyperdev.com/#!/project/destiny-authorization

View Working Application: https://destiny-authorization.hyperdev.space/

This code creates a handler for a get request that returns a random string:

app.get("/string", function(req, res) {
    var strings = ["string1", "string2", "string3"]
    var n = Math.floor(Math.random() * strings.length)
    res.send(strings[n])
});

This jQuery code then makes the ajax request and receives the random string from the server.

$.get("/string", function(string) {
  $('#txtString').val(string);
});

Note that this example is based on code from Jamund Ferguson's answer so if you find this useful be sure to upvote him as well. I just thought this example would help you to see how everything fits together.

How do I zip two arrays in JavaScript?

Use the map method:

_x000D_
_x000D_
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
  return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
_x000D_
_x000D_

DEMO

Best way to display data via JSON using jQuery

You can create a jQuery object from a JSON object:

$.getJSON(url, data, function(json) {
    $(json).each(function() {
        /* YOUR CODE HERE */
    });
});

What is the difference between MacVim and regular Vim?

It's all about the key bindings which one can simply achieve from .vimrc configurations. As far as clipboard is concerned you can use :set clipboard unnamed and the yank from vim will go to system clipboard. Anyways, whichever one you end up using I suggest using this vimrc config , it contains a whole lot of plugins and bindings which will make your experience smooth.

Change CSS class properties with jQuery

You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.

Dynamically Load CSS from a File

function updateStyleSheet(filename) {
    newstylesheet = "style_" + filename + ".css";

    if ($("#dynamic_css").length == 0) {
        $("head").append("<link>")
        css = $("head").children(":last");

        css.attr({
          id: "dynamic_css",
          rel:  "stylesheet",
          type: "text/css",
          href: newstylesheet
        });
    } else {
        $("#dynamic_css").attr("href",newstylesheet);
    }
}

The example above is copied from:

Dynamically Add a Style Element

$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');

The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.

How to resize superview to fit all subviews with autolayout?

Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.

Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.

//
//  ViewController.m
//  AutoLayoutDynamicVerticalContainerHeight
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end

@implementation ViewController

- (void)viewDidLoad
{
    // INVOKE SUPER
    [super viewDidLoad];

    // INIT ALL REQUIRED UI ELEMENTS
    self.contentView = [[UIView alloc] init];
    self.myLabel = [[UILabel alloc] init];
    self.myOtherLabel = [[UILabel alloc] init];
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);

    // TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // ESTABLISH VIEW HIERARCHY
    [self.view addSubview:self.contentView]; // View adds content view
    [self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
    [self.contentView addSubview:self.myOtherLabel];

    // LAYOUT

    // Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
    // Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet

    /* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
    // ^To me this is what's weird... but okay once you understand...

    // Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];

    // Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
    // Note, this is the view that we are choosing to use to drive the height (and width) of our container...

    // The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // COLOR VIEWS
    self.view.backgroundColor = [UIColor purpleColor];
    self.contentView.backgroundColor = [UIColor redColor];
    self.myLabel.backgroundColor = [UIColor orangeColor];
    self.myOtherLabel.backgroundColor = [UIColor greenColor];

    // CONFIGURE VIEWS

    // Configure MY LABEL
    self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
    self.myLabel.numberOfLines = 0; // Let it flow

    // Configure MY OTHER LABEL
    self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
    self.myOtherLabel.numberOfLines = 0;
    self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}

@end

How to resize superview to fit all subviews with autolayout.png

How can I install a .ipa file to my iPhone simulator

First of all, IPAs usually only have ARM slices because the App Store does not currently accept Simulator slices in uploads.

Secondly, as of Xcode 8.3 you can drag & drop a .app bundle into the Simulator window and it will be installed. You can find the app in your build products directory ~/Library/Developer/Xcode/DerivedData/projectname-xyzzyabcdefg/Build/Products/Debug-iphonesimulator if you want to save it or distribute it to other people.

To install from the command line use xcrun simctl install <device> <path>.

device can be the device UUID, its name, or booted which means the currently booted device.

How to call another components function in angular2

In the real world, scenario its not about calling a simple function but a function with a proper value. So let's dive in. This is the scenario A user has a requirement to fire an event from his own component and also at the end he wants to call a function of another component as well. Let's say the service file is the same for both the components

componentOne.html

    <button (click)="savePreviousWorkDetail()" data-dismiss="modal" class="btn submit-but" type="button">
          Submit
        </button>

When the user clicks on the submit button he needs to call savePreviousWorkDetail() in its own component componentOne.ts and in the end he needs to call a function of another component as well. So to do that a function in a service class can be called from componentOne.ts and when that called, the function from componentTwo will be fired.

componentOne.ts

constructor(private httpservice: CommonServiceClass) {
  }

savePreviousWorkDetail() {
// Things to be Executed in this function

this.httpservice.callMyMethod("Niroshan");
}

commontServiceClass.ts

import {Injectable,EventEmitter} from '@angular/core';

@Injectable()
export class CommonServiceClass{

  invokeMyMethod = new EventEmitter();

  constructor(private http: HttpClient) {
  }

  callMyMethod(params: any = 'Niroshan') {
    this.invokeMyMethod.emit(params);
  }

}

And Below is the componentTwo which has the function that needed to be called from componentOne. And in ngOnInit() we have to subscribe for the invoked method so when it triggers methodToBeCalled() will be called

componentTwo.ts

import {Observable,Subscription} from 'rxjs';


export class ComponentTwo implements OnInit {

 constructor(private httpservice: CommonServiceClass) {
  }

myMethodSubs: Subscription;

ngOnInit() {
    
    this.myMethodSubs = this.httpservice.invokeMyMethod.subscribe(res => {
      console.log(res);
      this.methodToBeCalled();
    });
    
methodToBeCalled(){
//what needs to done
}
  }

}

How can I start and check my MySQL log?

Its given on OFFICIAL MYSQL website.

SET GLOBAL general_log = 'ON';

You can also use custom path:

[mysqld]
# Set Slow Query Log
long_query_time = 1
slow_query_log = 1
slow_query_log_file = "C:/slowquery.log"

#Set General Log
log = "C:/genquery.log"

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

If you are returning ActionResult in .net core web api, or IHttpAction result then you can just wrap up your model in an Ok() method which will match the case on your front end and serialise it for you. No need to use JsonConvert. :)

SQL query, store result of SELECT in local variable

Here are some other approaches you can take.

1. CTE with union:

;WITH cte AS (SELECT a, b, c FROM table1)
SELECT a AS val FROM cte
UNION SELECT b AS val FROM cte
UNION SELECT c AS val FROM cte;

2. CTE with unpivot:

;WITH cte AS (SELECT a, b, c FROM table1)
SELECT DISTINCT val
FROM cte
UNPIVOT (val FOR col IN (a, b, c)) u;

How can I get System variable value in Java?

Actually the variable can be set or not, so, In Java 8 or superior its nullable value should be wrapped into an Optional object, which allows really good features. In the following example we gonna try to obtain the variable ENV_VAR1, if it doesnt exist we may throw some custom Exception to alert about it:

String ENV_VAR1 = Optional.ofNullable(System.getenv("ENV_VAR1")).orElseThrow(
  () -> new CustomException("ENV_VAR1 is not set in the environment"));

How to log request and response body with Retrofit-Android?

There doesn't appear to be a way to do basic + body, but you can use FULL and filter the headers you don't want.

RestAdapter adapter = new RestAdapter.Builder()
                          .setEndpoint(syncServer)
                          .setErrorHandler(err)
                          .setConverter(new GsonConverter(gson))
                          .setLogLevel(logLevel)
                          .setLog(new RestAdapter.Log() {
                              @Override
                              public void log(String msg) {
                                  String[] blacklist = {"Access-Control", "Cache-Control", "Connection", "Content-Type", "Keep-Alive", "Pragma", "Server", "Vary", "X-Powered-By"};
                                  for (String bString : blacklist) {
                                      if (msg.startsWith(bString)) {
                                          return;
                                      }
                                  }
                                  Log.d("Retrofit", msg);
                              }
                          }).build();

It appears that when overriding the log, the body is prefixed with a tag similar to

[ 02-25 10:42:30.317 25645:26335 D/Retrofit ]

so it should be easy to log basic + body by adjusting the custom filter. I am using a blacklist, but a whitelist could also be used depending on your needs.

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

How do I clear inner HTML

Take a look at this. a clean and simple solution using jQuery.

http://jsfiddle.net/ma2Yd/

    <h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
    <div id="goy"></div>


    <script type="text/javascript">

    $(function() {
       $("h1").on('mouseover', function() {
          $("#goy").text('The dog is in its shed');
       }).on('mouseout', function() {
          $("#goy").text("");
       });
   });

Xcode/Simulator: How to run older iOS version?

Open xcode and in the top menu go to xcode > Preferences > Downloads and you will be given the option to download old sdks to use with xcode. You can also download command line tools and Device Debugging Support.

enter image description here

Check if page gets reloaded or refreshed in JavaScript

First step is to check sessionStorage for some pre-defined value and if it exists alert user:

if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');

Second step is to set sessionStorage to some value (for example true):

sessionStorage.setItem("is_reloaded", true);

Session values kept until page is closed so it will work only if page reloaded in a new tab with the site. You can also keep reload count the same way.

how to show calendar on text box click in html

jQuery Mobile has a datepicker too. Source

Just include the following files,

  <script src="jQuery.ui.datepicker.js"></script>
  <script src="jquery.ui.datepicker.mobile.js"></script>

php, mysql - Too many connections to database error

Please check if you open up a new connection with each of your requests (mysql_connect(...)). If you do so, make sure you close the connection afterwards (using mysql_close($link)).

Also, you should consider changing this behaviour as keeping one steady connection for each user may be a better way to accomplish your task.

If you didn't already, take a look at this obvious, but nonetheless useful information resource: http://php.net/manual/function.mysql-connect.php

When to throw an exception?

One rule of thumb is to use exceptions in the case of something you couldn't normally predict. Examples are database connectivity, missing file on disk, etc. For scenarios that you can predict, ie users attempting to log in with a bad password you should be using functions that return booleans and know how to handle the situation gracefully. You don't want to abruptly end execution by throwing an exception just because someone mistyped their password.

How to solve the memory error in Python

Simplest solution: You're probably running out of virtual address space (any other form of error usually means running really slowly for a long time before you finally get a MemoryError). This is because a 32 bit application on Windows (and most OSes) is limited to 2 GB of user mode address space (Windows can be tweaked to make it 3 GB, but that's still a low cap). You've got 8 GB of RAM, but your program can't use (at least) 3/4 of it. Python has a fair amount of per-object overhead (object header, allocation alignment, etc.), odds are the strings alone are using close to a GB of RAM, and that's before you deal with the overhead of the dictionary, the rest of your program, the rest of Python, etc. If memory space fragments enough, and the dictionary needs to grow, it may not have enough contiguous space to reallocate, and you'll get a MemoryError.

Install a 64 bit version of Python (if you can, I'd recommend upgrading to Python 3 for other reasons); it will use more memory, but then, it will have access to a lot more memory space (and more physical RAM as well).

If that's not enough, consider converting to a sqlite3 database (or some other DB), so it naturally spills to disk when the data gets too large for main memory, while still having fairly efficient lookup.

Easily measure elapsed time

Internally the function will access the system's clock, which is why it returns different values each time you call it. In general with non-functional languages there can be many side effects and hidden state in functions which you can't see just by looking at the function's name and arguments.

How to use Lambda in LINQ select statement

Why not just use all Lambda syntax?

database.Stores.Where(s => s.CompanyID == curCompany.ID)
               .Select(s => new SelectListItem
                   {
                       Value = s.Name,
                       Text = s.ID
                   });

How should I print types like off_t and size_t?

I saw this post at least twice, because the accepted answer is hard to remeber for me(I rarely use z or j flags and they are seems not platform independant).

The standard never says clearly the exact data length of size_t, so I suggest you should first check the length size_t on your platform then select one of them:

if sizeof(size_t) == 4 use PRIu32
if sizeof(size_t) == 8 use PRIu64

And I suggest using stdint types instead of raw data types for consistancy.

Marquee text in Android

To get this to work, I had to use ALL three of the things (ellipsize, selected, and singleLine) mentioned already:

TextView tv = (TextView)findViewById(R.id.someTextView);
tv.setSelected(true);
tv.setEllipsize(TruncateAt.MARQUEE);
tv.setSingleLine(true):

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Had this issue on Python 2.7.9, solved by updating to Python 2.7.10 (unreleased when this question was asked and answered).

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

What is the maximum length of a Push Notification alert text?

According to updated Apple document (check my answer date):

"... When using the HTTP/2 provider API, maximum payload size is 4096 bytes. Using the legacy binary interface, maximum payload size is 2048 bytes. Apple Push Notification service (APNs) refuses any notification that exceeds the maximum size."

jQuery slide left and show

And if you want to vary the speed and include callbacks simply add them like this :

        jQuery.fn.extend({
            slideRightShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftHide: function(speed,callback) {
                return this.each(function() {
                    $(this).hide('slide', {direction: 'left'}, speed, callback);
                });
            },
            slideRightHide: function(speed,callback) {
                return this.each(function() {  
                    $(this).hide('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'left'}, speed, callback);
                });
            }
        });

disable Bootstrap's Collapse open/close animation

If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...

Just add this somewhere in your code:

$(document).ready(
    $('.collapse').on('show.bs.collapse hide.bs.collapse', function(e) {
        e.preventDefault();
    }),
    $('[data-toggle="collapse"]').on('click', function(e) {
        e.preventDefault();
        $($(this).data('target')).toggleClass('in');
    })
);

Docker compose, running containers in net:host

Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.

Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none

version: '3.7'
services:
  app:
    image: ramansharma/einwohnertomcat:v0.0.1
    deploy:
      replicas: 1
      ports:
       - '8080:8080'
    volumes:
     - type: bind
       source: /proc
       target: /hostfs/proc
       read_only: true
     - type: bind
       source: /sys/fs/cgroup
       target: /hostfs/sys/fs/cgroup
       read_only: true
     - type: bind
       source: /
       target: /hostfs
       read_only: true
    networks:
     hostnet: {}
    networks:
     - einwohner_net
     - elk_elk_net
networks:
 einwohner_net:
 elk_elk_net:
   external: true
 hostnet:
   external: true
   name: host

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

Do this:

sudo rm /var/lib/mongodb/mongod.lock
sudo service mongod restart

If you are on Ubuntu 16.04 which you can figure out by runnign this:

lsb_release -a

You need to Create a new file at /lib/systemd/system/mongod.service with the following contents:

[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target
Documentation=https://docs.mongodb.org/manual

[Service]
User=mongodb
Group=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

[Install]
WantedBy=multi-user.target

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

Javascript/jQuery: Set Values (Selection) in a multiple Select

Basically do a values.split(',') and then loop through the resulting array and set the Select.

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

date.ToString("o") // The Round-trip ("O", "o") Format Specifier
date.ToString("s") // The Sortable ("s") Format Specifier, conforming to ISO86801

MSDN Standard Date and Time Format Strings

Difference between JSON.stringify and JSON.parse

Firstly, JSON.stringify() function converts a JavaScript value to a JavaScript Object Notation (JSON) string. JSON.parse() function converts a JavaScript Object Notation (JSON) string into an object. For more information about these two functions, please refer to the following links.

https://msdn.microsoft.com/library/cc836459(v=vs.94).aspx https://msdn.microsoft.com/library/cc836466(v=vs.94).aspx

Secondly, the following sample will be helpful for you to understand these two functions.

<form id="form1" runat="server">
    <div>
        <div id="result"></div>
    </div>
</form>

<script>
    $(function () {
        //define a json object
        var employee = { "name": "John Johnson", "street": "Oslo West 16", "phone": "555 1234567" };

        //use JSON.stringify to convert it to json string
        var jsonstring = JSON.stringify(employee);
        $("#result").append('<p>json string: ' + jsonstring + '</p>');

        //convert json string to json object using JSON.parse function
        var jsonobject = JSON.parse(jsonstring);
        var info = '<ul><li>Name:' + jsonobject.name + '</li><li>Street:' + jsonobject.street + '</li><li>Phone:' + jsonobject.phone + '</li></ul>';

        $("#result").append('<p>json object:</p>');
        $("#result").append(info);
    });
</script>

ORA-00918: column ambiguously defined in SELECT *

You can also see this error when selecting for a union where corresponding columns can be null.

select * from (select D.dept_no, D.nullable_comment
                  from dept D
       union
               select R.dept_no, NULL
                 from redundant_dept R
)

This apparently confuses the parser, a solution is to assign a column alias to the always null column.

select * from (select D.dept_no, D.comment
                  from dept D
       union
               select R.dept_no, NULL "nullable_comment"
                 from redundant_dept R
)

The alias does not have to be the same as the corresponding column, but the column heading in the result is driven by the first query from among the union members, so it's probably a good practice.

How to read a text file from server using JavaScript?

I used Rafid's suggestion of using AJAX.

This worked for me:

var url = "http://www.example.com/file.json";

var jsonFile = new XMLHttpRequest();
    jsonFile.open("GET",url,true);
    jsonFile.send();

    jsonFile.onreadystatechange = function() {
        if (jsonFile.readyState== 4 && jsonFile.status == 200) {
            document.getElementById("id-of-element").innerHTML = jsonFile.responseText;
        }
     }

I basically(almost literally) copied this code from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get2 so credit to them for everything.

I dont have much knowledge of how this works but you don't have to know how your brakes work to use them ;)

Hope this helps!

Compute row average in pandas

I think this is what you are looking for:

df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)

Create an Oracle function that returns a table

I think you want a pipelined table function.

Something like this:

CREATE OR REPLACE PACKAGE test AS

    TYPE measure_record IS RECORD(
       l4_id VARCHAR2(50), 
       l6_id VARCHAR2(50), 
       l8_id VARCHAR2(50), 
       year NUMBER, 
       period NUMBER,
       VALUE NUMBER);

    TYPE measure_table IS TABLE OF measure_record;

    FUNCTION get_ups(foo NUMBER)
        RETURN measure_table
        PIPELINED;
END;

CREATE OR REPLACE PACKAGE BODY test AS

    FUNCTION get_ups(foo number)
        RETURN measure_table
        PIPELINED IS

        rec            measure_record;

    BEGIN
        SELECT 'foo', 'bar', 'baz', 2010, 5, 13
          INTO rec
          FROM DUAL;

        -- you would usually have a cursor and a loop here   
        PIPE ROW (rec);

        RETURN;
    END get_ups;
END;

For simplicity I removed your parameters and didn't implement a loop in the function, but you can see the principle.

Usage:

SELECT *
  FROM table(test.get_ups(0));



L4_ID L6_ID L8_ID       YEAR     PERIOD      VALUE
----- ----- ----- ---------- ---------- ----------
foo   bar   baz         2010          5         13
1 row selected.

How to disable or enable viewpager swiping in android

In my case, the simplified solution worked fine. The override method must be in your custom viewpager adapter to override TouchEvent listeners and make'em freeze;

@Override
public boolean onTouchEvent(MotionEvent event) {
    return this.enabled && super.onTouchEvent(event);

}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    return this.enabled && super.onInterceptTouchEvent(event);

}

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

I want to add one thing with the answer given by Softcoder. I have seen some people couldn't give their debug.keystore path correctly on the command line. They see that they are doing the exact process accepted above, but it is not working. At that point try to drag the debug.keystore and drop it on the command line. It will help if the accepted answer is not working for you. Do the full process without any hesitation. It was a nice answer.