Programs & Examples On #Matroska

This tag is for questions about playback of, creation of, and programmatic interaction with Matroska files.

How to playback MKV video in web browser?

To use video extensions that are MKV. You should use video, not source

For example :

_x000D_
_x000D_
  <!-- mkv -->
  <video width="320" height="240" controls src="assets/animation.mkv"></video>
<!-- mp4 -->
  <video width="320" height="240" controls>
    <source src="assets/animation.mp4" type="video/mp4" />
  </video>
_x000D_
_x000D_
_x000D_ My answer may be incomprehensible to you, so if you do not understand, click on this

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Your code works for me. When does addSalespersonOption get called? There may be a problem with that call.

Also some of your html is a bit off (maybe copy/paste problem?), but that didn't seem to cause any problems. Your select should look like this:

<select id="salesperson"> 
    <option value="">(select)</option> 
</select>

instead of this:

<select id="salesperson" /> 
    <option value"">(select)</option> 
</select>

Edit: When does your options list get dynamically populated? Are you sure you are passing 'on' for the defSales value in your call to addSalespersonOption? Try changing that code to this:

if (selected == "on") { 
    alert('setting default selected option to ' + text);
    html = '<option value="'+value+'" selected="selected">'+text+'</option>'; 
} 

and see if the alert happens and what is says if it does happen.

Edit: Working example of my testing (the error:undefined is from jsbin, not my code).

Inverse dictionary lookup in Python

Through values in dictionary can be object of any kind they can't be hashed or indexed other way. So finding key by the value is unnatural for this collection type. Any query like that can be executed in O(n) time only. So if this is frequent task you should take a look for some indexing of key like Jon sujjested or maybe even some spatial index (DB or http://pypi.python.org/pypi/Rtree/ ).

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

Package php5 have no installation candidate (Ubuntu 16.04)

If you just want to install PHP no matter what version it is, try PHP7

sudo apt-get install php7.0 php7.0-mcrypt

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

I am working in a project Struts2+Spring. So it need a dependency slf4j-api-1.7.5.jar.

If I run the project, I am getting error like

Failed to load class "org.slf4j.impl.StaticLoggerBinder"

I solved my problem by adding the slf4j-log4j12-1.7.5.jar.

So add this jar in your project to solve the issue.

ReferenceError: $ is not defined

Your widget has Underscore.js/LoDash.js as dependency.

You can get them here: underscore, lodash

Try prepending this to your code, so you can see if it works:

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>

What is a lambda expression in C++11?

Well, one practical use I've found out is reducing boiler plate code. For example:

void process_z_vec(vector<int>& vec)
{
  auto print_2d = [](const vector<int>& board, int bsize)
  {
    for(int i = 0; i<bsize; i++)
    {
      for(int j=0; j<bsize; j++)
      {
        cout << board[bsize*i+j] << " ";
      }
      cout << "\n";
    }
  };
  // Do sth with the vec.
  print_2d(vec,x_size);
  // Do sth else with the vec.
  print_2d(vec,y_size);
  //... 
}

Without lambda, you may need to do something for different bsize cases. Of course you could create a function but what if you want to limit the usage within the scope of the soul user function? the nature of lambda fulfills this requirement and I use it for that case.

GitLab git user password

After adding the new SSH Key in GitLab, check if you have "git" group included in SSHD AllowGroups (for Debian /etc/ssh/sshd_config). If not, add it and restart sshd (systemctl restart ssh).

Test it with ssh -vT [email protected] as suggested above.

How do I get the height and width of the Android Navigation Bar programmatically?

New answer in 2021 comes to the rescue


insipred from Egis's answer:

context.navigationBarHeight

where the extension getter is

val Context.navigationBarHeight: Int
get() {
    val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager

    return if (Build.VERSION.SDK_INT >= 30) {
        windowManager
                .currentWindowMetrics
                .windowInsets
                .getInsets(WindowInsets.Type.navigationBars())
                .bottom

    } else {
        val currentDisplay = try {
            display
        } catch (e: NoSuchMethodError) {
            windowManager.defaultDisplay
        }

        val appUsableSize = Point()
        val realScreenSize = Point()
        currentDisplay?.apply {
            getSize(appUsableSize)
            getRealSize(realScreenSize)
        }

        // navigation bar on the side
        if (appUsableSize.x < realScreenSize.x) {
            return realScreenSize.x - appUsableSize.x
        }

        // navigation bar at the bottom
        return if (appUsableSize.y < realScreenSize.y) {
            realScreenSize.y - appUsableSize.y
        } else 0
    }
}

tested on:

  • emulators with navigation bars
    • pixel 3a (api 30)
    • pixel 2 (api 28)
    • pixel 3 (api 25)
    • pixel 2 (api 21)
  • Xiaomi Poco f2 pro with & without navigation bar(full display)

How to upgrade Angular CLI to the latest version

The following approach worked for me:

npm uninstall -g @angular/cli

then

npm cache verify

then

npm install -g @angular/cli

I work on Windows 10, sometimes I had to use: npm cache clean --force as well. You don't need to do if you don't have any problem during the installation.

Batch - Echo or Variable Not Working

Dont use spaces:

SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%
PAUSE

Checking if a list is empty with LINQ

myList.ToList().Count == 0. That's all

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

QString to char* conversion

Maybe

my_qstring.toStdString().c_str();

or safer, as Federico points out:

std::string str = my_qstring.toStdString();
const char* p = str.c_str();

It's far from optimal, but will do the work.

How do I escape reserved words used as column names? MySQL/Create Table

You should use back tick character (`) eg:

create table if not exists misc_info (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
`key` TEXT UNIQUE NOT NULL,
value TEXT NOT NULL)ENGINE=INNODB;

Create or update mapping in elasticsearch

In later Elasticsearch versions (7.x), types were removed. Updating a mapping can becomes:

curl -XPUT "http://localhost:9200/test/_mapping" -H 'Content-Type: application/json' -d'{
  "properties": {
    "new_geo_field": {
      "type": "geo_point"
    }
  }
}'

As others have pointed out, if the field exists, you typically have to reindex. There are exceptions, such as adding a new sub-field or changing analysis settings.

You can't "create a mapping", as the mapping is created with the index. Typically, you'd define the mapping when creating the index (or via index templates):

curl -XPUT "http://localhost:9200/test" -H 'Content-Type: application/json' -d'{
  "mappings": {
    "properties": {
      "foo_field": {
        "type": "text"
      }
    }
  }
}'

That's because, in production at least, you'd want to avoid letting Elasticsearch "guess" new fields. Which is what generated this question: geo data was read as an array of long values.

What does MissingManifestResourceException mean and how to fix it?

I've encountered this issue with managed C++ project based on WinForms after renaming global namespace (not manually, but with Rename tool of VS2017).

The solution is simple, but isn't mentioned elsewhere.

You have to change RootNamespace entry in vcxproj-file to match the C++ namespace.

How to use Visual Studio C++ Compiler?

You may be forgetting something. Before #include <iostream>, write #include <stdafx.h> and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."

How to get query parameters from URL in Angular 5?

Stumbled across this question when I was looking for a similar solution but I didn't need anything like full application level routing or more imported modules.

The following code works great for my use and requires no additional modules or imports.

  GetParam(name){
    const results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if(!results){
      return 0;
    }
    return results[1] || 0;
  }

  PrintParams() {
    console.log('param1 = ' + this.GetParam('param1'));
    console.log('param2 = ' + this.GetParam('param2'));
  }

http://localhost:4200/?param1=hello&param2=123 outputs:

param1 = hello
param2 = 123

Adding and using header (HTTP) in nginx

You can use upstream headers (named starting with $http_) and additional custom headers. For example:

add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01  txt01;

next, go to console and make request with user's header:

curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/

the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1

Resize Cross Domain Iframe Height

You need to have access as well on the site that you will be iframing. i found the best solution here: https://gist.github.com/MateuszFlisikowski/91ff99551dcd90971377

yourotherdomain.html

<script type='text/javascript' src="js/jquery.min.js"></script>
<script type='text/javascript'>
  // Size the parent iFrame
  function iframeResize() {
    var height = $('body').outerHeight(); // IMPORTANT: If body's height is set to 100% with CSS this will not work.
    parent.postMessage("resize::"+height,"*");
  }

  $(document).ready(function() {
    // Resize iframe
    setInterval(iframeResize, 1000);
  });
</script>

your website with iframe

<iframe src='example.html' id='edh-iframe'></iframe>
<script type='text/javascript'>
  // Listen for messages sent from the iFrame
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

  eventer(messageEvent,function(e) {
    // If the message is a resize frame request
    if (e.data.indexOf('resize::') != -1) {
      var height = e.data.replace('resize::', '');
      document.getElementById('edh-iframe').style.height = height+'px';
    }
  } ,false);
</script>

How To Change DataType of a DataColumn in a DataTable?

Puedes agregar una columna con tipo de dato distinto , luego copiar los datos y eliminar la columna anterior

TB.Columns.Add("columna1", GetType(Integer))    
TB.Select("id=id").ToList().ForEach(Sub(row) row("columna1") = row("columna2"))    
TB.Columns.Remove("columna2")

How to send 100,000 emails weekly?

People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.

Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.

Here's a summary of what we found...

AuthSMTP

  • Cheapest around
  • No analysis/reporting
  • No tracking for opens/clicks
  • Had slight hesitation on some sends

Postmark

  • Very cheap, but not as cheap as AuthSMTP
  • Beautiful cpanel but no tracking on opens/clicks
  • Send-level activity tracking so you can open a single email that was sent and look at how it looked and the delivery data.
  • Have to use API. Sending by SMTP was recently introduced but it's buggy. For instance, we noticed that quotes (") in the subject line are stripped.
  • Cannot send any attachment you want. Must be on approved list of file types and under a certain size. (10 MB I think)
  • Requires a set list of from names/addresses.

JangoSMTP

  • Expensive in relation to the others – more than 10 times in some cases
  • Ugly cpanel but great tracking on opens/clicks with email-level detail
  • Had hesitation, at times, when sending. On two occasions, sends took an hour to be delivered
  • Requires a set list of from name/addresses.

SendGrid

  • Not quite a cheap as AuthSMTP but still very cheap. Many customers can exist on 200 free sends per day.
  • Decent cpanel but no in-depth detail on open/click tracking
  • Lots of API options. Options (open/click tracking, etc) can be custom defined on an email-by-email basis. Inbound (reply) email can be posted to our HTTP end point.
  • Absolutely zero hesitation on sends. Every email sent landed in the inbox almost immediately.
  • Can send from any from name/address.

Conclusion

SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.

check if variable empty

you can use isset() routine .

also additionaly you can refer an range of is_type () functions like

is_string(), is_float(),is_int() etc to further specificaly test

How to merge a list of lists with same type of items to a single list of items?

Use the SelectMany extension method

list = listOfList.SelectMany(x => x).ToList();

Selenium 2.53 not working on Firefox 47

I had the same issue and found out that you need to switch drivers because support was dropped. Instead of using the Firefox Driver, you need to use the Marionette Driver in order to run your tests. I am currently working through the setup myself and can post some suggested steps if you'd like when I have a working example.

Here are the steps I followed to get this working on my Java environment on Mac (worked for me in my Linux installations (Fedora, CentOS and Ubuntu) as well):

  1. Download the nightly executable from the releases page
  2. Unpack the archive
  3. Create a directory for Marionette (i.e., mkdir -p /opt/marionette)
  4. Move the unpacked executable file to the directory you made
  5. Update your $PATH to include the executable (also, edit your .bash_profile if you want)
  6. :bangbang: Make sure you chmod +x /opt/marionette/wires-x.x.x so that it is executable
  7. In your launch, make sure you use the following code below (it is what I used on Mac)

Quick Note

Still not working as expected, but at least gets the browser launched now. Need to figure out why - right now it looks like I need to rewrite my tests to get it to work.

Java Snippet

WebDriver browser = new MarionetteDriver();
System.setProperty("webdriver.gecko.driver", "/opt/marionette/wires-0.7.1-OSX");

HTML input file selection event not firing upon selecting the same file

Set the value of the input to null on each onclick event. This will reset the input's value and trigger the onchange event even if the same path is selected.

input.onclick = function () {
    this.value = null;
};

input.onchange = function () {
    alert(this.value);
};?

Here's a DEMO.

Note: It's normal if your file is prefixed with 'C:\fakepath\'. That's a security feature preventing JavaScript from knowing the file's absolute path. The browser still knows it internally.

How to set dropdown arrow in spinner?

From the API level 16 and above, you can use following code to change the drop down icon in spinner. just goto onItemSelected in setonItemSelectedListener and change the drawable of textview selected like this.

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
  // give the color which ever you want to give to spinner item in this line of code               
//API Level 16 and above only. 
           ((TextView)parent.getChildAt(position)).setCompoundDrawablesRelativeWithIntrinsicBounds(null,null,ContextCompat.getDrawable(Activity.this,R.drawable.icon),null);
 //Basically itis changing the drawable of textview, we have change the textview left drawable.

}
        @Override
        public void onNothingSelected(AdapterView<?> parent) {

}
    });

hope it will help somebody.

@font-face not working

I had this problem recently and the problem was that my web server was not configured to serve woff files. For IIS 7, you can select your site, then select the MIME Types icon. If .woff is not in the list, you need to add it. The correct values are

File name extension: .woff
MIME type: application/font-woff

How can you use optional parameters in C#?

You could use method overloading...

GetFooBar()
GetFooBar(int a)
GetFooBar(int a, int b)

It depends on the method signatures, the example I gave is missing the "int b" only method because it would have the same signature as the "int a" method.

You could use Nullable types...

GetFooBar(int? a, int? b)

You could then check, using a.HasValue, to see if a parameter has been set.

Another option would be to use a 'params' parameter.

GetFooBar(params object[] args)

If you wanted to go with named parameters would would need to create a type to handle them, although I think there is already something like this for web apps.

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

If it writes that you had not properly shut down or that mongod.lock is not empty , only delete mongod.lock from C:\data\db\ and it will start.

How to handle click event in Button Column in Datagridview?

This solves my problem.

private void dataGridViewName_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        //Your code
    }

How to create own dynamic type or dynamic object in C#?

ExpandoObject is what are you looking for.

dynamic MyDynamic = new ExpandoObject(); // note, the type MUST be dynamic to use dynamic invoking.
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;

Difference between map, applymap and apply methods in Pandas

@jeremiahbuddha mentioned that apply works on row/columns, while applymap works element-wise. But it seems you can still use apply for element-wise computation....

frame.apply(np.sqrt)
Out[102]: 
               b         d         e
Utah         NaN  1.435159       NaN
Ohio    1.098164  0.510594  0.729748
Texas        NaN  0.456436  0.697337
Oregon  0.359079       NaN       NaN

frame.applymap(np.sqrt)
Out[103]: 
               b         d         e
Utah         NaN  1.435159       NaN
Ohio    1.098164  0.510594  0.729748
Texas        NaN  0.456436  0.697337
Oregon  0.359079       NaN       NaN

HTML5 image icon to input placeholder

<html>
<head>
<style> 
input[type=text] {
    width: 50%;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: white;
    background-image: url('searchicon.png');
    background-position: 10px 10px; 
    background-repeat: no-repeat;
    padding: 12px 20px 12px 40px;
}
</style>
</head>
<body>

<p>Input with icon:</p>

<form>
  <input type="text" name="search" placeholder="Search..">
</form>

</body>
</html>

How to copy a row and insert in same table with a autoincrement field in MySQL?

You can also pass in '0' as the value for the column to auto-increment, the correct value will be used when the record is created. This is so much easier than temporary tables.

Source: Copying rows in MySQL (see the second comment, by TRiG, to the first solution, by Lore)

Java, Shifting Elements in an Array

Instead of shifting by one position you can make this function more general using module like this.

int[] original = { 1, 2, 3, 4, 5, 6 };
int[] reordered = new int[original.length];
int shift = 1;

for(int i=0; i<original.length;i++)
     reordered[i] = original[(shift+i)%original.length];

MessageBox with YesNoCancel - No & Cancel triggers same event

This is how you can do it without a Dim, using MessageBox.Show instead of MsgBox. This is in my opinion the cleanest way of writing it!

Select Case MessageBox.Show("Message", "Title", MessageBoxButtons.YesNo)
    Case vbYes
        ' Other Code goes here
    Case vbNo
        ' Other Code goes here
End Select

You can shorten it down even further by using If:

If MessageBox.Show("Message", "Title", MessageBoxButtons.YesNo) = vbYes Then
    ' Other Code goes here
End If

move column in pandas dataframe

You can rearrange columns directly by specifying their order:

df = df[['a', 'y', 'b', 'x']]

In the case of larger dataframes where the column titles are dynamic, you can use a list comprehension to select every column not in your target set and then append the target set to the end.

>>> df[[c for c in df if c not in ['b', 'x']] 
       + ['b', 'x']]
   a  y  b   x
0  1 -1  2   3
1  2 -2  4   6
2  3 -3  6   9
3  4 -4  8  12

To make it more bullet proof, you can ensure that your target columns are indeed in the dataframe:

cols_at_end = ['b', 'x']
df = df[[c for c in df if c not in cols_at_end] 
        + [c for c in cols_at_end if c in df]]

How to change 1 char in the string?

I suggest you to use StringBuilder class for it and than parse it to string if you need.

System.Text.StringBuilder strBuilder = new System.Text.StringBuilder("valta is the best place in the World");
strBuilder[0] = 'M';
string str=strBuilder.ToString();

You can't change string's characters in this way, because in C# string isn't dynamic and is immutable and it's chars are readonly. For make sure in it try to use methods of string, for example, if you do str.ToLower() it makes new string and your previous string doesn't change.

How to change the server port from 3000?

Using Angular 4 and the cli that came with it I was able to start the server with $npm start -- --port 8000. That worked ok: ** NG Live Development Server is listening on localhost:8000, open your browser on http://localhost:8000 **

Got the tip from Here

enter image description here enter image description here

What's the best way to build a string of delimited items in Java?

You could write a little join-style utility method that works on java.util.Lists

public static String join(List<String> list, String delim) {

    StringBuilder sb = new StringBuilder();

    String loopDelim = "";

    for(String s : list) {

        sb.append(loopDelim);
        sb.append(s);            

        loopDelim = delim;
    }

    return sb.toString();
}

Then use it like so:

    List<String> list = new ArrayList<String>();

    if( condition )        list.add("elementName");
    if( anotherCondition ) list.add("anotherElementName");

    join(list, ",");

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;

ArrayList<String> recordings = new ArrayList<String>();

this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I found the solution ! Delete folder named package in project directory and then rebuild to run it.

Installing MySQL Python on Mac OS X

I used PyMySQL instead and its working fine!

sudo easy_install-3.7 pymysql

How can I upgrade NumPy?

Update numpy

For python 2

pip install numpy --upgrade

You would also needed to upgrade your tables as well for updated version of numpy. so,

pip install tables --upgrade

For python 3

pip3 install numpy --upgrade

Similarly, the tables for python3 :-

pip3 install tables --upgrade

note:

You need to check which python version are you using. pip for python 2.7+ or pip3 for python 3+

Run Batch File On Start-up

Another option would be to run the batch file as a service, and set the startup of the service to "Automatic" or "Automatic (Delayed Start)". Check this question for more information on how to do it, personally I like NSSM the most.

How to select some rows with specific rownames from a dataframe?

df <- data.frame(x=rnorm(10), y=rnorm(10))
rownames(df) <-  letters[1:10]
df[c('a','b'),]

MVC - Set selected value of SelectList

I usually use this method

        public static SelectList SetSelectedValue(SelectList list, string value)
    {
        if (value != null)
        {
            var selected = list.Where(x => x.Value == value).First();
            selected.Selected = true;
            return list;
        }
        return list;
    }

How do I write to a Python subprocess' stdin?

To clarify some points:

As jro has mentioned, the right way is to use subprocess.communicate.

Yet, when feeding the stdin using subprocess.communicate with input, you need to initiate the subprocess with stdin=subprocess.PIPE according to the docs.

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Also qed has mentioned in the comments that for Python 3.4 you need to encode the string, meaning you need to pass Bytes to the input rather than a string. This is not entirely true. According to the docs, if the streams were opened in text mode, the input should be a string (source is the same page).

If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.

So, if the streams were not opened explicitly in text mode, then something like below should work:

import subprocess
command = ['myapp', '--arg1', 'value_for_arg1']
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate(input='some data'.encode())[0]

I've left the stderr value above deliberately as STDOUT as an example.

That being said, sometimes you might want the output of another process rather than building it up from scratch. Let's say you want to run the equivalent of echo -n 'CATCH\nme' | grep -i catch | wc -m. This should normally return the number characters in 'CATCH' plus a newline character, which results in 6. The point of the echo here is to feed the CATCH\nme data to grep. So we can feed the data to grep with stdin in the Python subprocess chain as a variable, and then pass the stdout as a PIPE to the wc process' stdin (in the meantime, get rid of the extra newline character):

import subprocess

what_to_catch = 'catch'
what_to_feed = 'CATCH\nme'

# We create the first subprocess, note that we need stdin=PIPE and stdout=PIPE
p1 = subprocess.Popen(['grep', '-i', what_to_catch], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# We immediately run the first subprocess and get the result
# Note that we encode the data, otherwise we'd get a TypeError
p1_out = p1.communicate(input=what_to_feed.encode())[0]

# Well the result includes an '\n' at the end, 
# if we want to get rid of it in a VERY hacky way
p1_out = p1_out.decode().strip().encode()

# We create the second subprocess, note that we need stdin=PIPE
p2 = subprocess.Popen(['wc', '-m'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# We run the second subprocess feeding it with the first subprocess' output.
# We decode the output to convert to a string
# We still have a '\n', so we strip that out
output = p2.communicate(input=p1_out)[0].decode().strip()

This is somewhat different than the response here, where you pipe two processes directly without adding data directly in Python.

Hope that helps someone out.

Left Join without duplicate rows from left table

Using the DISTINCT flag will remove duplicate rows.

SELECT DISTINCT
C.Content_ID,
C.Content_Title,
M.Media_Id

FROM tbl_Contents C
LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
ORDER BY C.Content_DatePublished ASC

Using HTML data-attribute to set CSS background-image url

How about using some Sass? Here's what I did to achieve something like this (although note that you have to create a Sass list for each of the data-attributes).

/*
  Iterate over list and use "data-social" to put in the appropriate background-image.
*/
$social: "fb", "twitter", "youtube";

@each $i in $social {
  [data-social="#{$i}"] {
    background: url('#{$image-path}/icons/#{$i}.svg') no-repeat 0 0;
    background-size: cover; // Only seems to work if placed below background property
  }
}

Essentially, you list all of your data attribute values. Then use Sass @each to iterate through and select all the data-attributes in the HTML. Then, bring in the iterator variable and have it match up to a filename.

Anyway, as I said, you have to list all of the values, then make sure that your filenames incorporate the values in your list.

Convert to absolute value in Objective-C

Depending on the type of your variable, one of abs(int), labs(long), llabs(long long), imaxabs(intmax_t), fabsf(float), fabs(double), or fabsl(long double).

Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)

(Alas, there is no habs(short) function. Or scabs(signed char) for that matter...)


Apple's and GNU's Objective-C headers also include an ABS() macro which is type-agnostic. I don't recommend using ABS() however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++) will have an undefined result.


If you're using C++ or Objective-C++, you can bring in the <cmath> header and use std::abs(), which is templated for all the standard integer and floating-point types.

Python Anaconda - How to Safely Uninstall

Package "anaconda clean", available from Anaconda platform, should uninstall safely.

conda install anaconda-clean   # install the package anaconda clean
anaconda-clean --yes           # clean all anaconda related files and directories 
rm -rf ~/anaconda3             # removes the entire anaconda directory

rm -rf ~/.anaconda_backup       # anaconda clean creates a back_up of files/dirs, remove it 
                                # (conda list; cmd shouldn't respond after the clean up)

Refer: https://docs.anaconda.com/anaconda/install/uninstall for more details.

How do I call Objective-C code from Swift?

I wrote a simple Xcode 6 project that shows how to mix C++, Objective-C and Swift code:

https://github.com/romitagl/shared/tree/master/C-ObjC-Swift/Performance_Console

In particular, the example calls an Objective-C and a C++ function from the Swift.

The key is to create a shared header, Project-Bridging-Header.h, and put the Objective-C headers there.

Please download the project as a complete example.

How to implement a FSM - Finite State Machine in Java

Consider the easy, lightweight Java library EasyFlow. From their docs:

With EasyFlow you can:

  • implement complex logic but keep your code simple and clean
  • handle asynchronous calls with ease and elegance
  • avoid concurrency by using event-driven programming approach
  • avoid StackOverflow error by avoiding recursion
  • simplify design, programming and testing of complex java applications

JOIN queries vs multiple queries

This is way too vague to give you an answer relevant to your specific case. It depends on a lot of things. Jeff Atwood (founder of this site) actually wrote about this. For the most part, though, if you have the right indexes and you properly do your JOINs it is usually going to be faster to do 1 trip than several.

MySQL: Fastest way to count number of rows

If you need to get the count of the entire result set you can take following approach:

SELECT SQL_CALC_FOUND_ROWS * FROM table_name LIMIT 5;
SELECT FOUND_ROWS();

This isn't normally faster than using COUNT albeit one might think the opposite is the case because it's doing the calculation internally and doesn't send the data back to the user thus the performance improvement is suspected.

Doing these two queries is good for pagination for getting totals but not particularly for using WHERE clauses.

Method has the same erasure as another method in type

Define a single Method without type like void add(Set ii){}

You can mention the type while calling the method based on your choice. It will work for any type of set.

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

A great source of information I came across while trying to install everything Android SDK related from the command line, was this Dockerfile. Inside the Dockerfile you can see that the author executes a single command to install platform tools and build tools without any other interaction. In the case the OP has put forth, the command would be adapted to:

echo y | $ANDROID_HOME/tools/android update sdk --all --filter build-tools-21.1.0 --no-ui

How to make a floated div 100% height of its parent?

A similar case when you need several child elements have the same height can be solved with flexbox:

https://css-tricks.com/using-flexbox/

Set display: flex; for parent and flex: 1; for child elements, they all will have the same height.

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

I have the same issue with windows10, apache 2.2.25, php 5.2 Im trying to add GD to a working PHP.

how I turn around and change between forward and backward slash, plus trailing or not, I get some variant of ;

PHP Warning: PHP Startup: Unable to load dynamic library 'C:/php\php_gd2.dll' - Det g\xe5r inte att hitta den angivna modulen.\r\n in Unknown on line 0

(swedish translated: 'It is not possible to find the module' )

in this perticular case, the php.ini was: extension_dir = "C:/php"

the dll is put in two places C:\php and C:\php\ext

IS it possible that there is and "error" in the error log entry ? I.e. that the .dll IS found (as a file) but not of the right format, or something like that ??

What is difference between sleep() method and yield() method of multi threading?

Both methods are used to prevent thread execution. But specifically, sleep(): purpose:if a thread don't want to perform any operation for particular amount of time then we should go for sleep().for e.x. slide show . yield(): purpose:if a thread wants to pause it's execution to give chance of execution to another waiting threads of same priority.thread which requires more execution time should call yield() in between execution.

Note:some platform may not provide proper support for yield() . because underlying system may not provide support for preemptive scheduling.moreover yield() is native method.

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = user.articles.build(:title => "MainTitle")
@article.save

SQL Query - Change date format in query to DD/MM/YYYY

SELECT CONVERT(varchar(11),Getdate(),105)

Git Clone from GitHub over https with two-factor authentication

To everyone struggling, what worked for me was creating personal access token and then using it as a username AND password (in the prompt that opened).

How to get root directory in yii2

Try out this,

My installation is at D:\xampp\htdocs\advanced

\Yii::$app->basePath will give like D:\xampp\htdocs\advanced\backend.

\Yii::$app->request->BaseUrl will give like localhost\advanced\backend\web\

You may store the image using \Yii::$app->basePath and show it using \Yii::$app->request->BaseUrl

How to raise a ValueError?

>>> response='bababa'
...  if "K" in response.text:
...     raise ValueError("Not found")

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

For those looking to do this in dask. I could not find a similar option in dask but if I simply do this in same notebook for pandas it works for dask too.

import pandas as pd
import dask.dataframe as dd
pd.set_option('display.max_colwidth', -1) # This will set the no truncate for pandas as well as for dask. Not sure how it does for dask though. but it works

train_data = dd.read_csv('./data/train.csv')    
train_data.head(5)

$(form).ajaxSubmit is not a function

Ajax Submit form with out page refresh by using jquery ajax method first include library jquery.js and jquery-form.js then create form in html:

<form action="postpage.php" method="POST" id="postForm" >

<div id="flash_success"></div>

name:
<input type="text" name="name" />
password:
<input type="password" name="pass" />
Email:
<input type="text" name="email" />

<input type="submit" name="btn" value="Submit" />
</form>

<script>
  var options = { 
        target:        '#flash_success',  // your response show in this ID
        beforeSubmit:  callValidationFunction,
        success:       YourResponseFunction  
    };
    // bind to the form's submit event
        jQuery('#postForm').submit(function() { 
            jQuery(this).ajaxSubmit(options); 
            return false; 
        }); 


});
function callValidationFunction()
{
 //  validation code for your form HERE
}

function YourResponseFunction(responseText, statusText, xhr, $form)
{
    if(responseText=='success')
    {
        $('#flash_success').html('Your Success Message Here!!!');
        $('body,html').animate({scrollTop: 0}, 800);

    }else
    {
        $('#flash_success').html('Error Msg Here');

    }
}
</script>

Configure active profile in SpringBoot via Maven

In development, activating a Spring Boot profile when a specific Maven profile is activate is straight. You should use the profiles property of the spring-boot-maven-plugin in the Maven profile such as :

<project>
    <...>
    <profiles>
        <profile>
            <id>development</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <configuration>
                            <profiles>
                                <profile>development</profile>
                            </profiles>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    <profiles>
    </...>
</project>

You can run the following command to use both the Spring Boot and the Maven development profile :

mvn spring-boot:run -Pdevelopment

If you want to be able to map any Spring Boot profiles to a Maven profile with the same profile name, you could define a single Maven profile and enabling that as the presence of a Maven property is detected. This property would be the single thing that you need to specify as you run the mvn command.
The profile would look like :

    <profile>
        <id>spring-profile-active</id>
        <activation>
            <property>
                <name>my.active.spring.profiles</name>
            </property>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <profiles>
                            <profile>${my.active.spring.profiles}</profile>
                        </profiles>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

And you can run the following command to use both the Spring Boot and the Maven development profile :

mvn spring-boot:run -Dmy.active.spring.profiles=development

or :

mvn spring-boot:run -Dmy.active.spring.profiles=integration

or :

 mvn spring-boot:run -Dmy.active.spring.profiles=production

And so for...

This kind of configuration makes sense as in the generic Maven profile you rely on the my.active.spring.profiles property that is passed to perform some tasks or value some things.
For example I use this way to configure a generic Maven profile that packages the application and build a docker image specific to the environment selected.

Java Try Catch Finally blocks without Catch

how does the try block work if it encounters an exception or anything throwable

The exception is thrown out of the block, just as in any other case where it's not caught.

The finally block is executed regardless of how the try block is exited -- regardless whether there are any catches at all, regardless of whether there is a matching catch.

The catch blocks and the finally are orthogonal parts of the try block. You can have either or both. With Java 7, you'll be able to have neither!

Why cannot change checkbox color whatever I do?

I also had this problem. I use chrome to code because I'm currently a newbie. I was able to change the colour of the checkboxes and radio selectors when they were checked ONLY using CSS. The current degree that is set in the hue-rotate() turns the blue checks red. I first used the grayscale(1) with the filter: but you don't need it. However, if you just want plain flat gray, go for the grayscale value for filter.

I've ONLY tested this in Chrome but it works with just plain old HTML and CSS, let me know in the comments section if it works in other browsers.

_x000D_
_x000D_
input[type="checkbox"],
input[type="radio"] {
  filter: hue-rotate(140deg);
  }
_x000D_
<body>
  <label for="radio1">Eau de Toilette</label>
  <input type="radio" id="radio1" name="example1"><br>
  <label for="radio2">Eau de Parfum</label>
  <input type="radio" id="radio2" name="example1"><br>
  <label for="check1">Orange Zest</label>
  <input type="checkbox" id="check1" name="example2"><br>
  <label for="check2">Lemons</label>
  <input type="checkbox" id="check2" name="example2"><br>
 </body>
_x000D_
_x000D_
_x000D_

psql: could not connect to server: No such file or directory (Mac OS X)

if your postmaster.pid is gone and you can't restart or anything, do this:

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

as explained here initially

How to set a CheckBox by default Checked in ASP.Net MVC

An alternative solution is using jQuery:

    <script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            PrepareCheckbox();
        });
        function PrepareCheckbox(){
            document.getElementById("checkbox").checked = true;
        }
    </script>

How to get the scroll bar with CSS overflow on iOS

In my experience you need to make sure the element has display:block; applied for the -webkit-overflow-scrolling:touch; to work.

Why is it string.join(list) instead of list.join(string)?

Primarily because the result of a someString.join() is a string.

The sequence (list or tuple or whatever) doesn't appear in the result, just a string. Because the result is a string, it makes sense as a method of a string.

Python string.replace regular expression

You are looking for the re.sub function.

import re
s = "Example String"
replaced = re.sub('[ES]', 'a', s)
print replaced 

will print axample atring

Error: Argument is not a function, got undefined

I have encountered the same problem and in my case it was happening as a result of this problem:

I had the controllers defined in a separate module (called 'myApp.controllers') and injected to the main app module (called 'myApp') like this:

angular.module('myApp', ['myApp.controllers'])

A colleague pushed another controller module in a separate file but with the exact same name as mine (i.e. 'myApp.controllers' ) which caused this error. I think because Angular got confused between those controller modules. However the error message was not very helpful in discovering what is going wrong.

Getting the length of two-dimensional array

Assuming that the length is same for each array in the second dimension, you can use

public class B {    
 public static void main(String [] main){
    int [] [] nir= new int [2] [3];
    System.out.println(nir[0].length);
 }
}

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

You're not reading the file content:

my_file_contents = f.read()

See the docs for further infos

You could, without calling read() or readlines() loop over your file object:

f = open('goodlines.txt')
for line in f:
    print(line)

If you want a list out of it (without \n as you asked)

my_list = [line.rstrip('\n') for line in f]

How do I make a Mac Terminal pop-up/alert? Applescript?

Use osascript. For example:

osascript -e 'tell app "Finder" to display dialog "Hello World"' 

Replacing “Finder” with whatever app you desire. Note if that app is backgrounded, the dialog will appear in the background too. To always show in the foreground, use “System Events” as the app:

osascript -e 'tell app "System Events" to display dialog "Hello World"'

Read more on Mac OS X Hints.

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

List passed by ref - help me explain this behaviour

Here is an easy way to understand it

  • Your List is an object created on heap. The variable myList is a reference to that object.

  • In C# you never pass objects, you pass their references by value.

  • When you access the list object via the passed reference in ChangeList (while sorting, for example) the original list is changed.

  • The assignment on the ChangeList method is made to the value of the reference, hence no changes are done to the original list (still on the heap but not referenced on the method variable anymore).

Fastest way to Remove Duplicate Value from a list<> by lambda

List<long> distinctlongs = longs.Distinct().OrderBy(x => x).ToList();

lvalue required as left operand of assignment

Change = to == i.e if (strcmp("hello", "hello") == 0)

You want to compare the result of strcmp() to 0. So you need ==. Assigning it to 0 won't work because rvalues cannot be assigned to.

Launching Spring application Address already in use

You can resolve this following these steps:

  1. Right click on the project you are running.
  2. Click on Run as and Run Configurations from the option.
  3. A new run configuration will open. Under Spring Boot Tab see for Override properties.
  4. Add the property-value pair as server.port=8181, or any other port of your choice. This will override the default port which is 8080

Is there a "theirs" version of "git merge -s ours"?

This will merge your newBranch in existing baseBranch

git checkout <baseBranch> // this will checkout baseBranch
git merge -s ours <newBranch> // this will simple merge newBranch in baseBranch
git rm -rf . // this will remove all non references files from baseBranch (deleted in newBranch)
git checkout newBranch -- . //this will replace all conflicted files in baseBranch

Get Hours and Minutes (HH:MM) from date

If you want to display 24 hours format use:

SELECT FORMAT(GETDATE(),'HH:mm')

and to display 12 hours format use:

SELECT FORMAT(GETDATE(),'hh:mm')

How do I put double quotes in a string in vba?

Another work-around is to construct a string with a temporary substitute character. Then you can use REPLACE to change each temp character to the double quote. I use tilde as the temporary substitute character.

Here is an example from a project I have been working on. This is a little utility routine to repair a very complicated formula if/when the cell gets stepped on accidentally. It is a difficult formula to enter into a cell, but this little utility fixes it instantly.

Sub RepairFormula()
Dim FormulaString As String

FormulaString = "=MID(CELL(~filename~,$A$1),FIND(~[~,CELL(~filename~,$A$1))+1,FIND(~]~, CELL(~filename~,$A$1))-FIND(~[~,CELL(~filename~,$A$1))-1)"
FormulaString = Replace(FormulaString, Chr(126), Chr(34)) 'this replaces every instance of the tilde with a double quote.
Range("WorkbookFileName").Formula = FormulaString

This is really just a simple programming trick, but it makes entering the formula in your VBA code pretty easy.

How can I sort an ArrayList of Strings in Java?

You might sort the helper[] array directly:

java.util.Arrays.sort(helper, 1, helper.length);

Sorts the array from index 1 to the end. Leaves the first item at index 0 untouched.

See Arrays.sort(Object[] a, int fromIndex, int toIndex)

Practical uses of different data structures

The excellent book "Algorithm Design Manual" by Skienna contains a huge repository of Algorithms and Data structure.

For tons of problems, data structures and algorithm are described, compared, and discusses the practical usage. The author also provides references to implementations and the original research papers.

The book is great to have it on your desk if you search the best data structure for your problem to solve. It is also very helpful for interview preparation.

Another great resource is the NIST Dictionary of Data structures and algorithms.

Any reason not to use '+' to concatenate two strings?

When working with multiple people, it's sometimes difficult to know exactly what's happening. Using a format string instead of concatenation can avoid one particular annoyance that's happened a whole ton of times to us:

Say, a function requires an argument, and you write it expecting to get a string:

In [1]: def foo(zeta):
   ...:     print 'bar: ' + zeta

In [2]: foo('bang')
bar: bang

So, this function may be used pretty often throughout the code. Your coworkers may know exactly what it does, but not necessarily be fully up-to-speed on the internals, and may not know that the function expects a string. And so they may end up with this:

In [3]: foo(23)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/izkata/<ipython console> in <module>()

/home/izkata/<ipython console> in foo(zeta)

TypeError: cannot concatenate 'str' and 'int' objects

There would be no problem if you just used a format string:

In [1]: def foo(zeta):
   ...:     print 'bar: %s' % zeta
   ...:     
   ...:     

In [2]: foo('bang')
bar: bang

In [3]: foo(23)
bar: 23

The same is true for all types of objects that define __str__, which may be passed in as well:

In [1]: from datetime import date

In [2]: zeta = date(2012, 4, 15)

In [3]: print 'bar: ' + zeta
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/izkata/<ipython console> in <module>()

TypeError: cannot concatenate 'str' and 'datetime.date' objects

In [4]: print 'bar: %s' % zeta
bar: 2012-04-15

So yes: If you can use a format string do it and take advantage of what Python has to offer.

select records from postgres where timestamp is in certain range

SELECT * 
FROM reservations 
WHERE arrival >= '2012-01-01'
AND arrival < '2013-01-01'
   ;

BTW if the distribution of values indicates that an index scan will not be the worth (for example if all the values are in 2012), the optimiser could still choose a full table scan. YMMV. Explain is your friend.

Partly cherry-picking a commit with Git

If "partly cherry picking" means "within files, choosing some changes but discarding others", it can be done by bringing in git stash:

  1. Do the full cherry pick.
  2. git reset HEAD^ to convert the entire cherry-picked commit into unstaged working changes.
  3. Now git stash save --patch: interactively select unwanted material to stash.
  4. Git rolls back the stashed changes from your working copy.
  5. git commit
  6. Throw away the stash of unwanted changes: git stash drop.

Tip: if you give the stash of unwanted changes a name: git stash save --patch junk then if you forget to do (6) now, later you will recognize the stash for what it is.

How to exit an Android app programmatically?

It works using only moveTaskToBack(true);

How to get number of entries in a Lua table?

You could use penlight library. This has a function size which gives the actual size of the table.

It has implemented many of the function that we may need while programming and missing in Lua.

Here is the sample for using it.

> tablex = require "pl.tablex"
> a = {}
> a[2] = 2
> a[3] = 3 
> a['blah'] = 24

> #a
0

> tablex.size(a)
3

@Media min-width & max-width

The underlying issue is using max-device-width vs plain old max-width.

Using the "device" keyword targets physical dimension of the screen, not the width of the browser window.

For example:

@media only screen and (max-device-width: 480px) {
    /* STYLES HERE for DEVICES with physical max-screen width of 480px */
}

Versus

@media only screen and (max-width: 480px) {
    /* STYLES HERE for BROWSER WINDOWS with a max-width of 480px. 
       This will work on desktops when the window is narrowed.  */
}

Difference between char* and const char*?

The first you can actually change if you want to, the second you can't. Read up about const correctness (there's some nice guides about the difference). There is also char const * name where you can't repoint it.

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

On jenkins 2.x, with groovy plugin 2.0, running SystemGroovyScript I managed to get to build variables, as below:

def build = this.getProperty('binding').getVariable('build')
def listener = this.getProperty('binding').getVariable('listener')
def env = build.getEnvironment(listener)
println env.MY_VARIABLE

If you are using goovy from file, simple System.getenv('MY_VARIABLE') is sufficient

How to query the permissions on an Oracle directory?

With Oracle 11g R2 (at least with 11.2.02) there is a view named datapump_dir_objs.

SELECT * FROM datapump_dir_objs;

The view shows the NAME of the directory object, the PATH as well as READ and WRITE permissions for the currently connected user. It does not show any directory objects which the current user has no permission to read from or write to, though.

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

Convert date to day name e.g. Mon, Tue, Wed

Seems like you could use date() and the lowercase "L" format character in the following way:

$weekday_name = date("l", $timestamp);

Works well for me, here is the doc: http://php.net/manual/en/function.date.php

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

Different ways of clearing lists

There are two cases in which you might want to clear a list:

  1. You want to use the name old_list further in your code;
  2. You want the old list to be garbage collected as soon as possible to free some memory;

In case 1 you just go on with the assigment:

    old_list = []    # or whatever you want it to be equal to

In case 2 the del statement would reduce the reference count to the list object the name old list points at. If the list object is only pointed by the name old_list at, the reference count would be 0, and the object would be freed for garbage collection.

    del old_list

CSS container div not getting height

It is not that easier?

.c {
    overflow: auto;
}

Waiting for another flutter command to release the startup lock

You can try to kill all flutter processes.

TL;DR - go to point 4)

1) List of the processes:

ps aux

2) Search name containing with flutter:

ps aux | grep flutter

where output can be like there:

stackoverflow     16697   1.5  0.0  4288316    704   ??  S    10:02PM   0:15.80 bash /flutter_path/flutter/bin/flutter --no-color build apk
stackoverflow      2800   1.5  0.0  4288316    704   ??  S     9:59PM   0:18.49 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      1215   1.5  0.0  4280124    700   ??  S     9:58PM   0:18.89 bash /flutter_path/flutter/bin/flutter --no-color config --machine
stackoverflow      8449   1.5  0.0  4296508    716   ??  S    10:00PM   0:17.20 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      1326   1.4  0.0  4288316    708   ??  S     9:58PM   0:18.97 bash /flutter_path/flutter/bin/flutter daemon
stackoverflow     16687   0.0  0.0  4279100    820   ??  S    10:02PM   0:00.01 bash /flutter_path/flutter/bin/flutter --no-color build apk
stackoverflow      8431   0.0  0.0  4288316    804   ??  S    10:00PM   0:00.02 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      2784   0.0  0.0  4288316    704   ??  S     9:59PM   0:00.01 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      1305   0.0  0.0  4280124    712   ??  S     9:58PM   0:00.01 bash /flutter_path/flutter/bin/flutter daemon
stackoverflow      1205   0.0  0.0  4279100    788   ??  S     9:58PM   0:00.01 bash /flutter_path/flutter/bin/flutter --no-color config --machine
stackoverflow     11416   0.0  0.0  4268176    536 s000  R+   10:18PM   0:00.00 grep --color flutter

3) Get processes ID

We need content from second column (from above output):

ps aux | grep flutter | awk '{print $2}'

4 a) Kill "automatically":

To list, search and kill all of them you can use

kill $(ps aux | grep flutter | grep -v grep  | awk '{print $2}')

(you can run it also with sudo)

or

ps aux | grep flutter | grep -v grep | awk '{print $2}' | xargs kill -15

4 b) Kill manually

You can kill processes one-by-one using:

sudo kill -15 <process_ID>

e.g. to kill process with id 13245 use:

sudo kill -15 13245

If -15 will not work, you can try -2 or -1.

Final option it is -9 which should not be used because it prevents the process from doing any cleanup work.

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

Why did Servlet.service() for servlet jsp throw this exception?

It can be caused by a classpath contamination. Check that you /WEB-INF/lib doesn't contain something like jsp-api-*.jar.

IntelliJ how to zoom in / out

Update: This answer is old. Intellij has since added actions to adjust font size. Check out Wilker's answer for assigning the new actions to keymaps.

Try Ctrl+Mouse Wheel which can be enabled under File > Settings... > Editor > General : Change font size (Zoom) with Ctrl+Mouse Wheel

How to compare two tags with git?

For a side-by-side visual representation, I use git difftool with openDiff set to the default viewer.

Example usage:

git difftool tags/<FIRST TAG> tags/<SECOND TAG>

If you are only interested in a specific file, you can use:

git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>

As a side-note, the tags/<TAG>s can be replaced with <BRANCH>es if you are interested in diffing branches.

get the latest fragment in backstack

Kotlin

activity.supportFragmentManager.fragments.last()

Keyboard shortcut to clear cell output in Jupyter notebook

Add following at start of cell and run it:

from IPython.display import clear_output
clear_output(wait=True)

C++ Dynamic Shared Library on Linux

On top of previous answers, I'd like to raise awareness about the fact that you should use the RAII (Resource Acquisition Is Initialisation) idiom to be safe about handler destruction.

Here is a complete working example:

Interface declaration: Interface.hpp:

class Base {
public:
    virtual ~Base() {}
    virtual void foo() const = 0;
};

using Base_creator_t = Base *(*)();

Shared library content:

#include "Interface.hpp"

class Derived: public Base {
public:
    void foo() const override {}
};

extern "C" {
Base * create() {
    return new Derived;
}
}

Dynamic shared library handler: Derived_factory.hpp:

#include "Interface.hpp"
#include <dlfcn.h>

class Derived_factory {
public:
    Derived_factory() {
        handler = dlopen("libderived.so", RTLD_NOW);
        if (! handler) {
            throw std::runtime_error(dlerror());
        }
        Reset_dlerror();
        creator = reinterpret_cast<Base_creator_t>(dlsym(handler, "create"));
        Check_dlerror();
    }

    std::unique_ptr<Base> create() const {
        return std::unique_ptr<Base>(creator());
    }

    ~Derived_factory() {
        if (handler) {
            dlclose(handler);
        }
    }

private:
    void * handler = nullptr;
    Base_creator_t creator = nullptr;

    static void Reset_dlerror() {
        dlerror();
    }

    static void Check_dlerror() {
        const char * dlsym_error = dlerror();
        if (dlsym_error) {
            throw std::runtime_error(dlsym_error);
        }
    }
};

Client code:

#include "Derived_factory.hpp"

{
    Derived_factory factory;
    std::unique_ptr<Base> base = factory.create();
    base->foo();
}

Note:

  • I put everything in header files for conciseness. In real life you should of course split your code between .hpp and .cpp files.
  • To simplify, I ignored the case where you want to handle a new/delete overload.

Two clear articles to get more details:

CSS Font "Helvetica Neue"

This font is not standard on all devices. It is installed by default on some Macs, but rarely on PCs and mobile devices.

To use this font on all devices, use a @font-face declaration in your CSS to link to it on your domain if you wish to use it.

@font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); } 
@font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf'); }

Taken from css3.info

How can I replace text with CSS?

Obligatory: This is a hack: CSS isn't the right place to do this, but in some situations - eg, you have a third party library in an iframe that can only be customized by CSS - this kind of hack is the only option.

You can replace text through CSS. Let's replace a green button that has the word 'hello' with a red button that has the word 'goodbye', using CSS.

Before:

enter image description here

After:

enter image description here

See http://jsfiddle.net/ZBj2m/274/ for a live demo:

Here's our green button:

<button>Hello</button>

button {
  background-color: green;
  color: black;
  padding: 5px;
}

Now let's hide the original element, but add another block element afterwards:

button {
  visibility: hidden;
}
button:after {
  content:'goodbye'; 
  visibility: visible;
  display: block;
  position: absolute;
  background-color: red;
  padding: 5px;
  top: 2px;
}

Note:

  • We explicitly need to mark this as a block element, 'after' elements are inline by default
  • We need to compensate for the original element by adjusting the pseudo-element's position.
  • We must hide the original element and display the pseudo element using visibility. Note display: none on the original element doesn't work.

RegExp matching string not starting with my

Wouldn't it be significantly more readable to do a positive match and reject those strings - rather than match the negative to find strings to accept?

/^my/

How do I use .toLocaleTimeString() without displaying seconds?

Here's a function that will do it, with comments that explain:

  function displayNiceTime(date){
    // getHours returns the hours in local time zone from 0 to 23
    var hours = date.getHours()
    // getMinutes returns the minutes in local time zone from 0 to 59
    var minutes =  date.getMinutes()
    var meridiem = " AM"

    // convert to 12-hour time format
    if (hours > 12) {
      hours = hours - 12
      meridiem = ' PM'
    }
    else if (hours === 0){
      hours = 12
    }

    // minutes should always be two digits long
    if (minutes < 10) {
      minutes = "0" + minutes.toString()
    }
    return hours + ':' + minutes + meridiem
  }

Since, as others have noted, toLocaleTimeString() can be implemented differently in different browsers, this way gives better control.

To learn more about the Javascript Date object, this is a good resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Spring Boot @autowired does not work, classes in different package

Just put the packages inside the @SpringBootApplication tag.

@SpringBootApplication(scanBasePackages = { "com.pkg1", "com.pkg2", .....})

Let me know.

MySQL Workbench Dark Theme

FYI Dark theme is now in the Dev Version of MySQL Workbench

Update: From what I can tell it is Natively built into MySQL Workbench 8.0.15 for MAC OS X

The package I downloaded was mysql-workbench-community-8.0.15-macos-x86_64.dmg

https://dev.mysql.com/downloads/workbench/ enter image description here

Java 8 Streams FlatMap method example

This method takes one Function as an argument, this function accepts one parameter T as an input argument and return one stream of parameter R as a return value. When this function is applied on each element of this stream, it produces a stream of new values. All the elements of these new streams generated by each element are then copied to a new stream, which will be a return value of this method.

http://codedestine.com/java-8-stream-flatmap-method/

MySQL - How to select rows where value is in array?

If you use the FIND_IN_SET function:

FIND_IN_SET(a, columnname) yields all the records that have "a" in them, alone or with others

AND

FIND_IN_SET(columnname, a) yields only the records that have "a" in them alone, NOT the ones with the others

So if record1 is (a,b,c) and record2 is (a)

FIND_IN_SET(columnname, a) yields only record2 whereas FIND_IN_SET(a, columnname) yields both records.

if statements matching multiple values

How about:

if (new[] {1, 2}.Contains(value))

It's a hack though :)

Or if you don't mind creating your own extension method, you can create the following:

public static bool In<T>(this T obj, params T[] args)
{
    return args.Contains(obj);
}

And you can use it like this:

if (1.In(1, 2))

:)

Shrink to fit content in flexbox, or flex-basis: content workaround?

It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.

You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:

http://jsfiddle.net/2w157dyL/1/

However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.

So the fix is very, very simple - add enough right padding to account for the scrollbar:

http://jsfiddle.net/2w157dyL/2/

_x000D_
_x000D_
  main > section {_x000D_
    overflow-y: auto;_x000D_
    padding-right: 2em;_x000D_
  }
_x000D_
_x000D_
_x000D_

It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!

Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help

Debugging with command-line parameters in Visual Studio

Yes, it's in the Debugging section of the properties page of the project.

In Visual Studio since 2008: right-click the project, choose Properties, go to the Debugging section -- there is a box for "Command Arguments". (Tip: not solution, but project).

Calling JMX MBean method from a shell script

Take a look at JManage. It's able to execute MBean methods and get / set attributes from command line.

Convert String (UTF-16) to UTF-8 in C#

class Program
{
    static void Main(string[] args)
    {
        String unicodeString =
        "This Unicode string contains two characters " +
        "with codes outside the traditional ASCII code range, " +
        "Pi (\u03a0) and Sigma (\u03a3).";

        Console.WriteLine("Original string:");
        Console.WriteLine(unicodeString);
        UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
        byte[] utf16Bytes = unicodeEncoding.GetBytes(unicodeString);
        char[] chars = unicodeEncoding.GetChars(utf16Bytes, 2, utf16Bytes.Length - 2);
        string s = new string(chars);
        Console.WriteLine();
        Console.WriteLine("Char Array:");
        foreach (char c in chars) Console.Write(c);
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine("String from Char Array:");
        Console.WriteLine(s);

        Console.ReadKey();
    }
}

C++ - unable to start correctly (0xc0150002)

In my case, Visual Leak Detector I was using to track down memory leaks in Visual Studio 2015 was missing the Microsoft manifest file Microsoft.DTfW.DHL.manifest, see link Building Visual Leak Detector all way down. This file must be in the folder where vld.dll or vld_x64.dll is in your configuration, say C:\Program Files (x86)\Visual Leak Detector\bin\Win32, C:\Program Files (x86)\Visual Leak Detector\bin\Win64, Debug or x64/Debug.

How to pass password to scp?

steps to get sshpass For rhel/centos 6 :

# wget http://epel.mirror.net.in/epel/6/i386/epel-release-6-8.noarch.rpm
# rpm -ivh epel-release-6-8.noarch.rpm
# yum install sshpass

source: https://community.mapr.com/thread/9040

How to timeout a thread

One thing that I've not seen mentioned is that killing threads is generally a Bad Idea. There are techniques for making threaded methods cleanly abortable, but that's different to just killing a thread after a timeout.

The risk with what you're suggesting is that you probably don't know what state the thread will be in when you kill it - so you risk introducing instability. A better solution is to make sure your threaded code either doesn't hang itself, or will respond nicely to an abort request.

Removing white space around a saved image in matplotlib

I cannot claim I know exactly why or how my “solution” works, but this is what I had to do when I wanted to plot the outline of a couple of aerofoil sections — without white margins — to a PDF file. (Note that I used matplotlib inside an IPython notebook, with the -pylab flag.)

plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, 
            hspace = 0, wspace = 0)
plt.margins(0,0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.savefig("filename.pdf", bbox_inches = 'tight',
    pad_inches = 0)

I have tried to deactivate different parts of this, but this always lead to a white margin somewhere. You may even have modify this to keep fat lines near the limits of the figure from being shaved by the lack of margins.

MySQL: is a SELECT statement case sensitive?

String comparison in WHERE phrase is not case sensitive. You could try to compare using

WHERE `colname` = 'keyword'

or

WHERE `colname` = 'KeyWord'

and you will get the same result. That is default behavior of MySQL.

If you want the comparison to be case sensitive, you could add COLLATE just like this:

WHERE `colname` COLLATE latin1_general_cs = 'KeyWord'

That SQL would give different result with this one: WHERE colname COLLATE latin1_general_cs = 'keyword'

latin1_general_cs is common or default collation in most database.

Design Patterns web based applications

A bit decent web application consists of a mix of design patterns. I'll mention only the most important ones.


Model View Controller pattern

The core (architectural) design pattern you'd like to use is the Model-View-Controller pattern. The Controller is to be represented by a Servlet which (in)directly creates/uses a specific Model and View based on the request. The Model is to be represented by Javabean classes. This is often further dividable in Business Model which contains the actions (behaviour) and Data Model which contains the data (information). The View is to be represented by JSP files which have direct access to the (Data) Model by EL (Expression Language).

Then, there are variations based on how actions and events are handled. The popular ones are:

  • Request (action) based MVC: this is the simplest to implement. The (Business) Model works directly with HttpServletRequest and HttpServletResponse objects. You have to gather, convert and validate the request parameters (mostly) yourself. The View can be represented by plain vanilla HTML/CSS/JS and it does not maintain state across requests. This is how among others Spring MVC, Struts and Stripes works.

  • Component based MVC: this is harder to implement. But you end up with a simpler model and view wherein all the "raw" Servlet API is abstracted completely away. You shouldn't have the need to gather, convert and validate the request parameters yourself. The Controller does this task and sets the gathered, converted and validated request parameters in the Model. All you need to do is to define action methods which works directly with the model properties. The View is represented by "components" in flavor of JSP taglibs or XML elements which in turn generates HTML/CSS/JS. The state of the View for the subsequent requests is maintained in the session. This is particularly helpful for server-side conversion, validation and value change events. This is how among others JSF, Wicket and Play! works.

As a side note, hobbying around with a homegrown MVC framework is a very nice learning exercise, and I do recommend it as long as you keep it for personal/private purposes. But once you go professional, then it's strongly recommended to pick an existing framework rather than reinventing your own. Learning an existing and well-developed framework takes in long term less time than developing and maintaining a robust framework yourself.

In the below detailed explanation I'll restrict myself to request based MVC since that's easier to implement.


Front Controller pattern (Mediator pattern)

First, the Controller part should implement the Front Controller pattern (which is a specialized kind of Mediator pattern). It should consist of only a single servlet which provides a centralized entry point of all requests. It should create the Model based on information available by the request, such as the pathinfo or servletpath, the method and/or specific parameters. The Business Model is called Action in the below HttpServlet example.

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        Action action = ActionFactory.getAction(request);
        String view = action.execute(request, response);

        if (view.equals(request.getPathInfo().substring(1)) {
            request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);
        }
        else {
            response.sendRedirect(view); // We'd like to fire redirect in case of a view change as result of the action (PRG pattern).
        }
    }
    catch (Exception e) {
        throw new ServletException("Executing action failed.", e);
    }
}

Executing the action should return some identifier to locate the view. Simplest would be to use it as filename of the JSP. Map this servlet on a specific url-pattern in web.xml, e.g. /pages/*, *.do or even just *.html.

In case of prefix-patterns as for example /pages/* you could then invoke URL's like http://example.com/pages/register, http://example.com/pages/login, etc and provide /WEB-INF/register.jsp, /WEB-INF/login.jsp with the appropriate GET and POST actions. The parts register, login, etc are then available by request.getPathInfo() as in above example.

When you're using suffix-patterns like *.do, *.html, etc, then you could then invoke URL's like http://example.com/register.do, http://example.com/login.do, etc and you should change the code examples in this answer (also the ActionFactory) to extract the register and login parts by request.getServletPath() instead.


Strategy pattern

The Action should follow the Strategy pattern. It needs to be defined as an abstract/interface type which should do the work based on the passed-in arguments of the abstract method (this is the difference with the Command pattern, wherein the abstract/interface type should do the work based on the arguments which are been passed-in during the creation of the implementation).

public interface Action {
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
}

You may want to make the Exception more specific with a custom exception like ActionException. It's just a basic kickoff example, the rest is all up to you.

Here's an example of a LoginAction which (as its name says) logs in the user. The User itself is in turn a Data Model. The View is aware of the presence of the User.

public class LoginAction implements Action {

    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userDAO.find(username, password);

        if (user != null) {
            request.getSession().setAttribute("user", user); // Login user.
            return "home"; // Redirect to home page.
        }
        else {
            request.setAttribute("error", "Unknown username/password. Please retry."); // Store error message in request scope.
            return "login"; // Go back to redisplay login form with error.
        }
    }

}

Factory method pattern

The ActionFactory should follow the Factory method pattern. Basically, it should provide a creational method which returns a concrete implementation of an abstract/interface type. In this case, it should return an implementation of the Action interface based on the information provided by the request. For example, the method and pathinfo (the pathinfo is the part after the context and servlet path in the request URL, excluding the query string).

public static Action getAction(HttpServletRequest request) {
    return actions.get(request.getMethod() + request.getPathInfo());
}

The actions in turn should be some static/applicationwide Map<String, Action> which holds all known actions. It's up to you how to fill this map. Hardcoding:

actions.put("POST/register", new RegisterAction());
actions.put("POST/login", new LoginAction());
actions.put("GET/logout", new LogoutAction());
// ...

Or configurable based on a properties/XML configuration file in the classpath: (pseudo)

for (Entry entry : configuration) {
    actions.put(entry.getKey(), Class.forName(entry.getValue()).newInstance());
}

Or dynamically based on a scan in the classpath for classes implementing a certain interface and/or annotation: (pseudo)

for (ClassFile classFile : classpath) {
    if (classFile.isInstanceOf(Action.class)) {
       actions.put(classFile.getAnnotation("mapping"), classFile.newInstance());
    }
}

Keep in mind to create a "do nothing" Action for the case there's no mapping. Let it for example return directly the request.getPathInfo().substring(1) then.


Other patterns

Those were the important patterns so far.

To get a step further, you could use the Facade pattern to create a Context class which in turn wraps the request and response objects and offers several convenience methods delegating to the request and response objects and pass that as argument into the Action#execute() method instead. This adds an extra abstract layer to hide the raw Servlet API away. You should then basically end up with zero import javax.servlet.* declarations in every Action implementation. In JSF terms, this is what the FacesContext and ExternalContext classes are doing. You can find a concrete example in this answer.

Then there's the State pattern for the case that you'd like to add an extra abstraction layer to split the tasks of gathering the request parameters, converting them, validating them, updating the model values and execute the actions. In JSF terms, this is what the LifeCycle is doing.

Then there's the Composite pattern for the case that you'd like to create a component based view which can be attached with the model and whose behaviour depends on the state of the request based lifecycle. In JSF terms, this is what the UIComponent represent.

This way you can evolve bit by bit towards a component based framework.


See also:

PowerShell Script to Find and Replace for all Files with a Specific Extension

Here a first attempt at the top of my head.

$configFiles = Get-ChildItem . *.config -rec
foreach ($file in $configFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace "Dev", "Demo" } |
    Set-Content $file.PSPath
}

Error: stray '\240' in program

As mentioned in a previous reply, this generally comes when compiling copy pasted code. If you have a bash shell, the following command generally works:

iconv -f utf-8 -t ascii//translit input.c > output.c

Netbeans installation doesn't find JDK

Set JAVA_HOME in environment variable.

set JAVA_HOME to only JDK1.6.0_23 or whatever jdk folder you have. dont include bin folder in path.

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.

Undefined reference to `pow' and `floor'

In regards to the answer provided by Fuzzy:

I actually had to do something slightly different.

Project -> Properties -> C/C++ Build -> Settings -> GCC C Linker -> Libraries

Click the little green add icon, type m and hit ok. Everything in this window automatically has -l applied to it since it is a library.

DOUBLE vs DECIMAL in MySQL

We have just been going through this same issue, but the other way around. That is, we store dollar amounts as DECIMAL, but now we're finding that, for example, MySQL was calculating a value of 4.389999999993, but when storing this into the DECIMAL field, it was storing it as 4.38 instead of 4.39 like we wanted it to. So, though DOUBLE may cause rounding issues, it seems that DECIMAL can cause some truncating issues as well.

Can't choose class as main class in IntelliJ

The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.

https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html

Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.

Base64 Java encode and decode a string

The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries

Java 11 and up

import java.util.Base64;

public class Base64Encoding {

    public static void main(String[] args) {
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        String str = "77+9x6s=";

        // encode data using BASE64
        String encoded = enc.encodeToString(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data
        String decoded = new String(dec.decode(encoded));
        System.out.println("decoded value is \t" + decoded);
        System.out.println("original value is \t" + str);
    }
}

Java 6 - 10

import java.io.UnsupportedEncodingException;    
import javax.xml.bind.DatatypeConverter;

public class EncodeString64 {
    public static void main(String[] args) throws UnsupportedEncodingException {

        String str = "77+9x6s=";
        // encode data using BASE64
        String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data 
        String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
        System.out.println("decoded value is \t" + decoded);

        System.out.println("original value is \t" + str);
    }
}

The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.

How to create a jar with external libraries included in Eclipse?

You can right-click on the project, click on export, type 'jar', choose 'Runnable JAR File Export'. There you have the option 'Extract required libraries into generated JAR'.

Two column div layout with fluid left and fixed right column

I was recently shown this website for liquid layouts using CSS. http://matthewjamestaylor.com/blog/perfect-multi-column-liquid-layouts (Take a look at the demo pages in the links below).

The author now provides an example for fixed width layouts. Check out; http://matthewjamestaylor.com/blog/how-to-convert-a-liquid-layout-to-fixed-width.

This provides the following example(s), http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm (for two column layout like you are after I think)

http://matthewjamestaylor.com/blog/fixed-width-or-liquid-layout.htm (for three column layout).

Sorry for so many links to this guys site, but I think it is an AWESOME resource.

Is string in array?

Linq (for s&g's):

var test = "This is the string I'm looking for";
var found = strArray.Any(x=>x == test);

or, depending on requirements

var found = strArray.Any(
    x=>x.Equals(test, StringComparison.OrdinalIgnoreCase));

How can I create a correlation matrix in R?

You could use 'corrplot' package.

d <- data.frame(x1=rnorm(10),
                 x2=rnorm(10),
                 x3=rnorm(10))
M <- cor(d) # get correlations

library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix

enter image description here

More information here: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html

How to do an update + join in PostgreSQL?

The answer of Mark Byers is the optimal in this situation. Though in more complex situations you can take the select query that returns rowids and calculated values and attach it to the update query like this:

with t as (
  -- Any generic query which returns rowid and corresponding calculated values
  select t1.id as rowid, f(t2, t2) as calculatedvalue
  from table1 as t1
  join table2 as t2 on t2.referenceid = t1.id
)
update table1
set value = t.calculatedvalue
from t
where id = t.rowid

This approach lets you develop and test your select query and in two steps convert it to the update query.

So in your case the result query will be:

with t as (
    select v.id as rowid, s.price_per_vehicle as calculatedvalue
    from vehicles_vehicle v 
    join shipments_shipment s on v.shipment_id = s.id 
)
update vehicles_vehicle
set price = t.calculatedvalue
from t
where id = t.rowid

Note that column aliases are mandatory otherwise PostgreSQL will complain about the ambiguity of the column names.

How to execute a raw update sql with dynamic binding in rails

It doesn't look like the Rails API exposes methods to do this generically. You could try accessing the underlying connection and using it's methods, e.g. for MySQL:

st = ActiveRecord::Base.connection.raw_connection.prepare("update table set f1=? where f2=? and f3=?")
st.execute(f1, f2, f3)
st.close

I'm not sure if there are other ramifications to doing this (connections left open, etc). I would trace the Rails code for a normal update to see what it's doing aside from the actual query.

Using prepared queries can save you a small amount of time in the database, but unless you're doing this a million times in a row, you'd probably be better off just building the update with normal Ruby substitution, e.g.

ActiveRecord::Base.connection.execute("update table set f1=#{ActiveRecord::Base.sanitize(f1)}")

or using ActiveRecord like the commenters said.

Interactive shell using Docker Compose

You need to include the following lines in your docker-compose.yml:

version: "3"
services:
  app:
    image: app:1.2.3
    stdin_open: true # docker run -i
    tty: true        # docker run -t

The first corresponds to -i in docker run and the second to -t.

How can I make my layout scroll both horizontally and vertically?

You can do this by using below code

<HorizontalScrollView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
                    <ScrollView
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent">
                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">
                            
                        </LinearLayout>
                    </ScrollView>
    </HorizontalScrollView>

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

Run VisualStudio with administrator privilegies and run the project. Then close VisualStudio and all errors and run VisualStudio again with the normal user.

This did it for me.

Looks like that IIS has to write something to some config with admin privilegies (port 80 didn't work with normal user but port 6767 worked fine).

When should I use a trailing slash in my URL?

Who says a file name needs an extension?? take a look on a *nix machine sometime...
I agree with your friend, no trailing slash.

error: cast from 'void*' to 'int' loses precision

There's no proper way to cast this to int in general case. C99 standard library provides intptr_t and uintptr_t typedefs, which are supposed to be used whenever the need to perform such a cast comes about. If your standard library (even if it is not C99) happens to provide these types - use them. If not, check the pointer size on your platform, define these typedefs accordingly yourself and use them.

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

First off, if you're using savefig, be aware that it will override the figure's background color when saving unless you specify otherwise (e.g. fig.savefig('blah.png', transparent=True)).

However, to remove the axes' and figure's background on-screen, you'll need to set both ax.patch and fig.patch to be invisible.

E.g.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

for item in [fig, ax]:
    item.patch.set_visible(False)

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

(Of course, you can't tell the difference on SO's white background, but everything is transparent...)

If you don't want to show anything other than the line, turn the axis off as well using ax.axis('off'):

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

fig.patch.set_visible(False)
ax.axis('off')

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

In that case, though, you may want to make the axes take up the full figure. If you manually specify the location of the axes, you can tell it to take up the full figure (alternately, you can use subplots_adjust, but this is simpler for the case of a single axes).

import matplotlib.pyplot as plt

fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.plot(range(10))

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

What's the valid way to include an image with no src?

As written in comments, this method is wrong.

I didn't find this answer before, but acording to W3 Specs valid empty src tag would be an anchor link #.

Example: src="#", src="#empty"

Page validates successfully and no extra request are made.

Get the date (a day before current time) in Bash

Well this is a late answer,but this seems to work!!

     YESTERDAY=`TZ=GMT+24 date +%d-%m-%Y`;
     echo $YESTERDAY;

How to escape comma and double quote at same time for CSV file?

Thanks to both Tony and Paul for the quick feedback, its very helpful. I actually figure out a solution through POJO. Here it is:

if (cell_value.indexOf("\"") != -1 || cell_value.indexOf(",") != -1) {
    cell_value = cell_value.replaceAll("\"", "\"\"");
    row.append("\"");
    row.append(cell_value);
    row.append("\"");
} else {
    row.append(cell_value);
}

in short if there is special character like comma or double quote within the string in side the cell, then first escape the double quote("\"") by adding additional double quote (like "\"\""), then put the whole thing into a double quote (like "\""+theWholeThing+"\"" )

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

If you are to encounter the error that says Microsoft.CSharp.Core.targets not found, these are the steps I took to correct mine:

  1. Open any previous working projects folder and navigate to the link showed in the error, that is Projects/(working project name)/packages/Microsoft.Net.Compilers.1.3.2/tools/ and search for Microsoft.CSharp.Core.targets file.

  2. Copy this file and put it in the non-working project tools folder (that is, navigating to the tools folder in the non-working project as shown above)

  3. Now close your project (if it was open) and reopen it.

It should be working now.

Also, to make sure everything is working properly in your now open Visual Studio Project, Go to Tools > NuGetPackage Manager > Manage NuGet Packages For Solution. Here, you might find an error that says, CodeAnalysis.dll is being used by another application.

Again, go to the tools folder, find the specified file and delete it. Come back to Manage NuGet Packages For Solution. You will find a link that will ask you to Reload, click it and everything gets re-installed.

Your project should be working properly now.

Putting images with options in a dropdown list

This code will work only in Firefox:

<select>
    <option value="volvo" style="background-image:url(images/volvo.png);">Volvo</option>
    <option value="saab"  style="background-image:url(images/saab.png);">Saab</option>
    <option value="honda" style="background-image:url(images/honda.png);">Honda</option>
    <option value="audi"  style="background-image:url(images/audi.png);">Audi</option>
</select>

Edit (April 2018):

Firefox does not support this anymore.

Get content of a DIV using JavaScript

(1) Your <script> tag should be placed before the closing </body> tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet.
(2) Your assignment of HTML content looks jumbled.
(3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2'
(4) User lower case for 'document' object (credit: ThatOtherPerson)

<body>
<div id="DIV1">
 // Some content goes here.
</div>

<div id="DIV2">
</div>
<script type="text/javascript">

   var MyDiv1 = document.getElementById('DIV1');
   var MyDiv2 = document.getElementById('DIV2');
   MyDiv2.innerHTML = MyDiv1.innerHTML;

</script>
</body>

How do I check if a property exists on a dynamic anonymous type in c#?

Merging and fixing answers from Serj-TM and user3359453 so that it works with both ExpandoObject and DynamicJsonObject. This works for me.

public static bool HasPropertyExist(dynamic settings, string name)
{
    if (settings is System.Dynamic.ExpandoObject)
        return ((IDictionary<string, object>)settings).ContainsKey(name);

    if (settings is System.Web.Helpers.DynamicJsonObject)
    try
    {
        return settings[name] != null;
    }
    catch (KeyNotFoundException)
    {
        return false;
    }


    return settings.GetType().GetProperty(name) != null;
}

How do I create a comma-separated list using a SQL query?

Using COALESCE to Build Comma-Delimited String in SQL Server
http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string

Example:

DECLARE @EmployeeList varchar(100)

SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
   CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1

SELECT @EmployeeList

Create XML in Javascript

Simply use

var xmlString = '<?xml version="1.0" ?><root />';
var xml = jQuery.parseXML(xml);

It's jQuery.parseXML, so no need to worry about cross-browser tricks. Use jQuery as like HTML, it's using the native XML engine.

Find all files with name containing string

grep -R "somestring" | cut -d ":" -f 1

How to know installed Oracle Client is 32 bit or 64 bit?

One thing that was super easy and worked well for me was doing a TNSPing from a cmd prompt:

TNS Ping Utility for 32-bit Windows: Version 11.2.0.3.0 - Production on 13-MAR-2015 16:35:32

Get connection status on Socket.io client

Track the state of the connection yourself. With a boolean. Set it to false at declaration. Use the various events (connect, disconnect, reconnect, etc.) to reassign the current boolean value. Note: Using undocumented API features (e.g., socket.connected), is not a good idea; the feature could get removed in a subsequent version without the removal being mentioned.

Self-references in object literals / initializers

Some closure should deal with this;

var foo = function() {
    var a = 5;
    var b = 6;
    var c = a + b;

    return {
        a: a,
        b: b,
        c: c
    }
}();

All the variables declared within foo are private to foo, as you would expect with any function declaration and because they are all in scope, they all have access to each other without needing to refer to this, just as you would expect with a function. The difference is that this function returns an object that exposes the private variables and assigns that object to foo. In the end, you return just the interface you want to expose as an object with the return {} statement.

The function is then executed at the end with the () which causes the entire foo object to be evaluated, all the variables within instantiated and the return object added as properties of foo().

Convert seconds to HH-MM-SS with JavaScript?

below is the given code which will convert seconds into hh-mm-ss format:

var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);

Get alternative method from Convert seconds to HH-MM-SS format in JavaScript

inherit from two classes in C#

Make two interfaces IA and IB:

public interface IA
{
    public void methodA(int value);
}

public interface IB
{
    public void methodB(int value);
}

Next make A implement IA and B implement IB.

public class A : IA
{
    public int fooA { get; set; }
    public void methodA(int value) { fooA = value; }
}

public class B : IB
{
    public int fooB { get; set; }
    public void methodB(int value) { fooB = value; }
}

Then implement your C class as follows:

public class C : IA, IB
{
    private A _a;
    private B _b;

    public C(A _a, B _b)
    {
        this._a = _a;
        this._b = _b;
    }

    public void methodA(int value) { _a.methodA(value); }
    public void methodB(int value) { _b.methodB(value); }
}

Generally this is a poor design overall because you can have both A and B implement a method with the same name and variable types such as foo(int bar) and you will need to decide how to implement it, or if you just call foo(bar) on both _a and _b. As suggested elsewhere you should consider a .A and .B properties instead of combining the two classes.

Using only CSS, show div on hover over <a>

I would like to offer this general purpose template solution that expands on the correct solution provided by Yi Jiang's.

The additional benefits include:

  • support for hovering over any element type, or multiple elements;
  • the popup can be any element type or set of elements, including objects;
  • self-documenting code;
  • ensures the pop-up appears over the other elements;
  • a sound basis to follow if you are generating html code from a database.

In the html you place the following structure:

<div class="information_popup_container">
<div class="information">
<!-- The thing or things you want to hover over go here such as images, tables, 
     paragraphs, objects other divisions etc. --> 
</div>
<div class="popup_information">
<!-- The thing or things you want to popup go here such as images, tables, 
     paragraphs, objects other divisions etc. --> 
</div>
</div>

In the css you place the following structure:

div.information_popup_container {
position: absolute;
width:0px;
height:0px;
/* Position Information */
/* Appearance Information */
}
div.information_popup_container > div.information {
/* Position Information */
/* Appearance Information */
}
div.information_popup_container > div.popup_information {
position: fixed;
visibility: hidden;
/* Position Information */
/* Appearance Information */
}
div.information_popup_container > div.information:hover + div.popup_information {
visibility: visible;
z-index: 200;
}

A few points to note are:

  1. Because the position of the div.popup is set to fixed (would also work with absolute) the content is not inside the normal flow of the document which allows the visible attribute to work well.
  2. z-index is set to ensure that the div.popup appears above the other page elements.
  3. The information_popup_container is set to a small size and thus cannot be hovered over.
  4. This code only supports hovering over the div.information element. To support hovering over both the div.information and div.popup then see Hover Over The Popup below.
  5. It has been tested and works as expected in Opera 12.16 Internet Explorer 10.0.9200, Firefox 18.0 and Google Chrome 28.0.15.

Hover Over The Popup

As additional information. When the popup contains information that you might want to cut and paste or contains an object that you might want to interact with then first replace:

div.information_popup_container > div.information:hover + div.popup_information {
visibility: visible;
z-index: 200;
}

with

div.information_popup_container > div.information:hover + div.popup_information 
,div.information_popup_container > div.popup_information:hover {
visibility: visible;
z-index: 200;
}

And second, adjust the position of div.popup so that there is an overlap with div.information. A few pixels is sufficient to ensure that the div.popup is can receive the hover when moving the cusor off div.information.

This does not work as expected with Internet Explorer 10.0.9200 and does work as expected with Opera 12.16, Firefox 18.0 and Google Chrome 28.0.15.

See fiddle http://jsfiddle.net/F68Le/ for a complete example with a popup multilevel menu.

In Git, what is the difference between origin/master vs origin master?

There are actually three things here: origin master is two separate things, and origin/master is one thing. Three things total.

Two branches:

  • master is a local branch
  • origin/master is a remote branch (which is a local copy of the branch named "master" on the remote named "origin")

One remote:

  • origin is a remote

Example: pull in two steps

Since origin/master is a branch, you can merge it. Here's a pull in two steps:

Step one, fetch master from the remote origin. The master branch on origin will be fetched and the local copy will be named origin/master.

git fetch origin master

Then you merge origin/master into master.

git merge origin/master

Then you can push your new changes in master back to origin:

git push origin master

More examples

You can fetch multiple branches by name...

git fetch origin master stable oldstable

You can merge multiple branches...

git merge origin/master hotfix-2275 hotfix-2276 hotfix-2290

AngularJS - Building a dynamic table based on a json

Here's an example of one with dynamic columns and rows with angularJS: http://plnkr.co/edit/0fsRUp?p=preview

How do I exit from a function?

There are two ways to exit a method early (without quitting the program):

i) Use the return keyword.
ii) Throw an exception.

Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.

If your method returns void then you can write return without a value:

return;

How do you add a JToken to an JObject?

TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)


The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.

  • JToken = The mother of all other types. It can be A JValue, JProperty, JArray, or JObject. This is to provide a modular design to the parsing mechanism.
  • JValue = any Json value type (string, int, boolean).
  • JProperty = any JValue or JContainer (see below) paired with a name (identifier). For example "name":"value".
  • JContainer = The mother of all types which contain other types (JObject, JValue).
  • JObject = a JContainer type that holds a collection of JProperties
  • JArray = a JContainer type that holds a collection JValue or JContainer.

Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.

What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name"), and then create another JProperty of your desire and then add it after this using AddAfterSelf method. You are done then.

For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

This is the code I modified.

public class Program
{
  public static void Main()
  {
    try
    {
      string jsonText = @"
      {
        ""food"": {
          ""fruit"": {
            ""apple"": {
              ""colour"": ""red"",
              ""size"": ""small""
            },
            ""orange"": {
              ""colour"": ""orange"",
              ""size"": ""large""
            }
          }
        }
      }";

      var foodJsonObj = JObject.Parse(jsonText);
      var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");

      var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
      fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));

      Console.WriteLine(foodJsonObj.ToString());
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
  }
}

XML Parser for C

For C++ I suggest using CMarkup.

Add empty columns to a dataframe with specified names from a vector

set.seed(1)
example <- data.frame(col1 = rnorm(10, 0, 1), col2 = rnorm(10, 2, 3))
namevector <- c("col3", "col4")
example[ , namevector] <- NA

example
#          col1       col2 col3 col4
# 1  -0.6264538  6.5353435   NA   NA
# 2   0.1836433  3.1695297   NA   NA
# 3  -0.8356286  0.1362783   NA   NA
# 4   1.5952808 -4.6440997   NA   NA
# 5   0.3295078  5.3747928   NA   NA
# 6  -0.8204684  1.8651992   NA   NA
# 7   0.4874291  1.9514292   NA   NA
# 8   0.7383247  4.8315086   NA   NA
# 9   0.5757814  4.4636636   NA   NA
# 10 -0.3053884  3.7817040   NA   NA

jQuery UI themes and HTML tables

I've got a one liner to make HTML Tables look BootStrapped:

<table class="table table-striped table-bordered table-hover">

The theme suits other controls and it supports alternate row highlighting.

Integration Testing POSTing an entire object to Spring MVC controller

One of the main purposes of integration testing with MockMvc is to verify that model objects are correclty populated with form data.

In order to do it you have to pass form data as they're passed from actual form (using .param()). If you use some automatic conversion from NewObject to from data, your test won't cover particular class of possible problems (modifications of NewObject incompatible with actual form).

For-loop vs while loop in R

And about timing:

fn1 <- function (N) {
    for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
    i=1
    while (i <= N) {
        y <- i*i
        i <- i + 1
    }
}

system.time(fn1(60000))
# user  system elapsed 
# 0.06    0.00    0.07 
system.time(fn2(60000))
# user  system elapsed 
# 0.12    0.00    0.13

And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.

How to add constraints programmatically using Swift

This is one way to adding constraints programmatically

override func viewDidLoad() {
            super.viewDidLoad()


let myLabel = UILabel()
        myLabel.labelFrameUpdate(label: myLabel, text: "Welcome User", font: UIFont(name: "times new roman", size: 40)!, textColor: UIColor.red, textAlignment: .center, numberOfLines: 0, borderWidth: 2.0, BorderColor: UIColor.red.cgColor)
        self.view.addSubview(myLabel)


         let myLabelhorizontalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
        let myLabelverticalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
        let mylabelLeading = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 10)
        let mylabelTrailing = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -10)
        let myLabelheightConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 50)
        NSLayoutConstraint.activate(\[myLabelhorizontalConstraint, myLabelverticalConstraint, myLabelheightConstraint,mylabelLeading,mylabelTrailing\])
}

extension UILabel
{
    func labelFrameUpdate(label:UILabel,text:String = "This is sample Label",font:UIFont = UIFont(name: "times new roman", size: 20)!,textColor:UIColor = UIColor.red,textAlignment:NSTextAlignment = .center,numberOfLines:Int = 0,borderWidth:CGFloat = 2.0,BorderColor:CGColor = UIColor.red.cgColor){
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = text
        label.font = font
        label.textColor = textColor
        label.textAlignment = textAlignment
        label.numberOfLines = numberOfLines
        label.layer.borderWidth = borderWidth
        label.layer.borderColor = UIColor.red.cgColor
    }
}

enter image description here

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

How to reset Django admin password?

You may try through console:

python manage.py shell

then use following script in shell

from django.contrib.auth.models import User
User.objects.filter(is_superuser=True)

will list you all super users on the system. if you recognize yur username from the list:

usr = User.objects.get(username='your username')
usr.set_password('raw password')
usr.save()

and you set a new password (:

Two arrays in foreach loop

Your code like this is incorrect as foreach only for single array:

<?php
        $codes = array('tn','us','fr');
        $names = array('Tunisia','United States','France');

        foreach( $codes as $code and $names as $name ) {
            echo '<option value="' . $code . '">' . $name . '</option>';
            }
?>

Alternative, Change to this:

<?php
        $codes = array('tn','us','fr');
        $names = array('Tunisia','United States','France');
        $count = 0;

        foreach($codes as $code) {
             echo '<option value="' . $code . '">' . $names[count] . '</option>';
             $count++;
        }

?>

How can I make PHP display the error instead of giving me 500 Internal Server Error

Try not to go

MAMP > conf > [your PHP version] > php.ini

but

MAMP > bin > php > [your PHP version] > conf > php.ini

and change it there, it worked for me...

How to insert image in mysql database(table)?

This is on mysql workbench -- give the image file path:

INSERT INTO XX_SAMPLE(id,image) VALUES(3,'/home/ganesan-pc/Documents/aios_database/confe.jpg');

How do I write data to csv file in columns and rows from a list in python?

Well, if you are writing to a CSV file, then why do you use space as a delimiter? CSV files use commas or semicolons (in Excel) as cell delimiters, so if you use delimiter=' ', you are not really producing a CSV file. You should simply construct csv.writer with the default delimiter and dialect. If you want to read the CSV file later into Excel, you could specify the Excel dialect explicitly just to make your intention clear (although this dialect is the default anyway):

example = csv.writer(open("test.csv", "wb"), dialect="excel")

vertical align middle in <div>

How about adding line-height ?

#abc{
  font:Verdana, Geneva, sans-serif;
  font-size:18px;
  text-align:left;
  background-color:#0F0;
  height:50px;
  vertical-align:middle;
  line-height: 45px;
}

Fiddle, line-height

Or padding on #abc. This is the result with padding

Update

Add in your css :

#abc img{
   vertical-align: middle;
}

The result. Hope this what you looking for.

Insert array into MySQL database with PHP

You can not insert an array directly to MySQL as MySQL doesn't understand PHP data types. MySQL only understands SQL. So to insert an array into a MySQL database you have to convert it to a SQL statement. This can be done manually or by a library. The output should be an INSERT statement.

Update for PHP7

Since PHP 5.5 mysql_real_escape_string has been deprecated and as of PHP7 it has been removed. See: php.net's documentation on the new procedure.


Original answer:

Here is a standard MySQL insert statement.

INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)

If you have a table with name fbdata with the columns which are presented in the keys of your array you can insert with this small snippet. Here is how your array is converted to this statement.

$columns = implode(", ",array_keys($insData));
$escaped_values = array_map('mysql_real_escape_string', array_values($insData));
$values  = implode(", ", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ($values)";

How to assign an exec result to a sql variable?

This will work if you wish to simply return an integer:

DECLARE @ResultForPos INT 
EXEC @ResultForPos = storedprocedureName 'InputParameter'
SELECT @ResultForPos

Does Google Chrome work with Selenium IDE (as Firefox does)?

No, Google Chrome does not work with Selenium IDE. As Selenium IDE is a Firefox plugin it works only with FF.

According to your last portion of question: Or is there any alternative tool which can work with Chrome? The possible answer is as follows:

You can use Sahi with Chrome. Sahi Test Automation tool supports Chrome, Firefox and IE. You can visit for details:

http://sahi.co.in/

Oracle date format picture ends before converting entire input string

Perhaps you should check NLS_DATE_FORMAT and use the date string conforming the format. Or you can use to_date function within the INSERT statement, like the following:

insert into visit
values(123456, 
       to_date('19-JUN-13', 'dd-mon-yy'),
       to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));

Additionally, Oracle DATE stores date and time information together.

Include another HTML file in a HTML file

My solution is similar to the one of lolo above. However, I insert the HTML code via JavaScript's document.write instead of using jQuery:

a.html:

<html> 
  <body>
  <h1>Put your HTML content before insertion of b.js.</h1>
      ...

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

      ...

  <p>And whatever content you want afterwards.</p>
  </body>
</html>

b.js:

document.write('\
\
    <h1>Add your HTML code here</h1>\
\
     <p>Notice however, that you have to escape LF's with a '\', just like\
        demonstrated in this code listing.\
    </p>\
\
');

The reason for me against using jQuery is that jQuery.js is ~90kb in size, and I want to keep the amount of data to load as small as possible.

In order to get the properly escaped JavaScript file without much work, you can use the following sed command:

sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html

Or just use the following handy bash script published as a Gist on Github, that automates all necessary work, converting b.html to b.js: https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6

Credits to Greg Minshall for the improved sed command that also escapes back slashes and single quotes, which my original sed command did not consider.

Alternatively for browsers that support template literals the following also works:

b.js:

document.write(`

    <h1>Add your HTML code here</h1>

     <p>Notice, you do not have to escape LF's with a '\',
        like demonstrated in the above code listing.
    </p>

`);

How to add an item to a drop down list in ASP.NET?

Which specific index? If you want 'Add New' to be first on the dropdownlist you can add it though the code like this:

<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server">
     <asp:ListItem Text="Add New" Value="0" />
</asp:DropDownList>

If you want to add it at a different index, maybe the last then try:

ListItem lst = new ListItem ( "Add New" , "0" );

DropDownList1.Items.Insert( DropDownList1.Items.Count-1 ,lst);

How do I test axios in Jest?

I've done this with nock, like so:

import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'

axios.defaults.adapter = httpAdapter

describe('foo', () => {
    it('bar', () => {
        nock('https://example.com:443')
            .get('/example')
            .reply(200, 'some payload')

        // test...
    })
})

How to embed images in email

Here is how to get the code for an embedded image without worrying about any files or base64 statements or mimes (it's still base64, but you don't have to do anything to get it). I originally posted this same answer in this thread, but it may be valuable to repeat it in this one, too.

To do this, you need Mozilla Thunderbird, you can fetch the html code for an image like this:

  1. Copy a bitmap to clipboard.
  2. Start a new email message.
  3. Paste the image. (don't save it as a draft!!!)
  4. Double-click on it to get to the image settings dialogue.
  5. Look for the "image location" property.
  6. Fetch the code and wrap it in an image tag, like this:

You should end up with a string of text something like this:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaIAAAGcCAIAAAAUGTPlAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAPbklEQVR4nO3d2ZbixhJAUeku//8vcx/oxphBaMgpIvd+c7uqmqakQ6QkxHq73RaA3tZ13fNlJ5K1yhzQy860fbS/XTIHtHOla9/8jJjMARXV6No332omc0BhLdP27r1pMgeU0bduz16yJnPAVeME7uG5bDIHxTzv7bn3rAG79u7xK/in7+OArNY14QwRom7v/tf7AUASQROw07qu4f6Bjwcsc1BLuC58FDFwD/dHbtEKtWwvWl/aMeAKN27dXpjmoIyLnRqtKaM9ntPWdTXNQRWHRrmhjPzYzjHNQXnnJrsR+jLCYyjONAej6Ht4LmXg7kxzUMahTAx1wiH0udQ9ZA6G0Ct8uQN3Z9EKBeyPxThvCJshcHcJ348CFx29ou1jLz7cDmikC+Xmadxi0Qo/XS/C+8EvjWvJohX+42gCtr9+56DX0myNW0xzsMeJNHw7falx7Znm4Lyj1ThxmK9gFuds3GKagxdfPzblr+c/afWgCoj1aMtyphVevZ8uKNKIc2ds93zjTzM3brFohXc1Xvs7zhOTN24xzcFOvWKR7P5OXTg2ByRnmoO9ak9GxXdGo9yyLLfbzTQHQ9C4ekxzcECNdtTYBzXu7v7cmubggOJJMmc0IHPQTaXGGeXuHk+v6+agg3pDnMa9M83BAW3eDsF1z0+yzMFe4zfOKPeRzEFT9UqkcQ8vryUyB7sUjEiNHmncBqcg4LfiEbn/wPd7nzhsd937c2iagx9aLjPP/V1GuW2mOdhSqiCPEaPSYMjdx3FY5uCr6wV53+ue/+Tjz19Xb8EsTObgsyuNu9KpQ99rlHv27amTOfjgXD6O1q3U7dfZJnPwqvjndVX6URL5bOOpkzn4j0PtuB44h+GK2H4aXVACf3z7AOlvNj7qsNAj2mKU2880B8tybaG6ffmbea22358M6XcAZRv381uuM8o97HliTXNpeRfRTlcWqvu/t8jVcOp2jszNwkWnH51uXMviqNs3OzdpmcvJjrHH4G8g9UssReYmYqB7diIiTqEOZf/GLHNhXD/WpnEPA6ZkwIc0skMbs+vmYjh6xx5F2zBUUNa/ej+QSI5u3qa5WQjf3ThBGeeRpCdzgW0fa7v/r8ddats9rIGNUJYRHkNoJzZmmQtMvA7p3pfuDyCBc9u8zGVmv7rzPORw+nXdKYgYTvyC7dt3ngdMc2FcuQR/5xVzyd4fJnCZXNkaTXOBbezGRa59DZ2J0A+eFxdfcWUuNjvzR56WTK6vKmQuocl38sn/+ckUOXIic+HZq595NjIpdXRY5kLauOvZuaNyH78r3CkIjcuk4ObnTOu83qMQrmtkVXZTNM0lcW/WnnOvWd8rnu9fNK3iL7emuTx+7uduasL4amyHpjmWReMYQ6XtUObQOJKTudlpHIOotyk6NjeiZO8thW21t3CZG87H95ZW2g72/1jlpZIG25JFa1TXN47Tjfv4J3BCm9dLmYuheFaMY/R1u92abYQyF4MqkUnj7VnmZpQymin/Ufm0HOIeZG44tTeCIp9jPWBTHC4cXJfA3dU6hUcpz3vvxo1Jdkr56xa4wXXf6mQugG+lO7p7p/ld61ogI2x1rpsLpt41dCGujBO4EEbbeGQuntOl21j/FvxbKhG42h6/7tNP9VAbzLOxNmW++XYLzCI7/+12G/PuwdLWTPffdVUyF0OvHb7bqTGBa2WGArighK80Lr0ZGrfIXBT1NsfbX5V+/lEa18w4v/TanIKY1M9NvP0+IHAtzdO4xbG5cC62YMxft8C1NOY2UJVpbgrDbtkC19iwW0JVjs3lN+yWrXGNDbsl1GaaowOBa2/axi0yl96hjbvBRcIC197MgbuzaGVZlmVd128BKhgmjWtP4xbTXG7bm/j+6Ny/8soOI3BdaNydzM2oZXQErguBe+a6uUgOJePjb7bxZXca14Wd+oVjc7PYOPp26IdU+mJK0bh3MpfT9dupX6RxXWjcR47NZdalNQLXhcBtkLmEvt0ms4jtuwprXBfNGhfiTvrvZC6Mo9d/NCZwvexszaFb5P/8CbE4NkcBcXeA6E407v0/T4vyezfNxTDy9jTyY0ts/0TmF2Sa4xK7UBfXD4qV+rCk6z+kAZnjpCIX4nHO9Wf+RKGiRO2dd0EEoCZs2LMLf/sAzP0ePyFiMUxzENueV8GXNk3VuEXmxmeU46eql0lGb9ziTCvwUabXV9Mc5Hf0urnrx/KGYpobWqZXVEJocKP89kxzEN6JDH3MWdaXVdPcuLJuczS2Z0Pa+Jroo9wiczC57QgmaNwic8MyylHExoY0zzbm2BzEVm/gyjHKLaa5Mc3zMstFVUuU4MLgO5mDqH7Wp/h95d7/xut362zAW/eHY5RjfPduRLmK2DQHHBbrxdgpiLHE2nrgxZgbsGkOKPY+ijEXraa5gYz5SsgMTmx7YxbtI5kDluXUXe8v3q2zGWdaR2GUYxzJsmCaA14le9E1zQ0h2VZFGjn6YJoDvsrxAixzwJYEH8jrujngt3Vd39/gFWVJ69jcEKK/WhLIx13+9BYYIiAy15/G0dLpz6Iu9QPbs2iFuTyWnzs9f3HQl2SnIGA6QWt1msxBErfbrfb68f3nj79iXWQOcnjkZmfsigx0IRq3OAUxgtlWEJS1vQvP8PmEPzkFAVHtidTja2Z+NTXN9Tfz9sc5p3fbOYc7metP5tiv1A77batLGQSZG4LSsa3GfhroLucXOdMKQ2twmcizlK+4TkEM4Xa7pdy8OK3XVGWao6KUmxcnNBvf5tnkHJsbi5kuqCvzeN99MOKNlY6SuXFJXiDv92Lb+S00IHMxSN7I7ESDk7nY5K87e9D4nIIITOO607gQZC4qjYOdXDcXksZ1Z44LxDQXj8Z1p3GxyBwco3HhyFwwRrm+NC4imYO9NC4omYNdNC4umYvEirUXjQtN5sLQuF40LjrXzcFXApeDaS4Go1x7GpeGzMEHGpeJRSv8h8DlI3Pwh8BlJXMBODBXm8Dl5tgcs9O49GRudEa5qjRuBhatTErg5iFzTEfgZiNzQ7NiLUvg5iRzTEHgZiZzJCdwONM6LivW6zSOxTRHVgLHg2mOhDSOZ6a5QVmxnqBufCRzZCBwbLBoJTyNY9tqExmQFes5NmY+Ms2Rx7quXiF4J3Nko3S8kDkSUjqeydxw7KJFeBp5kDkgOZkjLQMddzIHJCdzYzGAQHEyByQnc0ByMkda3vvFncwNxIE5qEHmgORkjpysWHmQOSA5mSMhoxzPZA5ITubIxijHC5kjFY3jncwBycncKFwbfJ1Rjo9kjiQ0jm9kjgw0jg0yByT3T+8HAFf9HOVejnsa/WZjmhuC8w+nHW0cE5I5Ajs3lwnfbGSOqKw92UnmCOlK4/RxNk5BkNztdju3Sn3+LmUMzTRHPKejc7vddn7vSxkdzgtN5vqzCx1isOIomSOSE40r9Sri1SgumSOMjo0797czCJkjhsaNE7VMnGklgJaN+/iNqheazDG6Nol5r5u0pSFzjK7qsf9vP1zjMpE5ZrSdTo1LRuaYyJ7BUOPycaYV/qVxKckc/KFxWckcLIvGpSZzoHHJyRws67p6y2pizrTCH4/SvQx3PjEnOtMcvFr/+vZ/Gz8eLjLNwVeKloPM8cd9LTbVjr1n+fnxCVnX1dI1EItWluVph7f37uFZikXmOhtweppnH/ber0lYtPJhTz79aVilbJ/r7Ev4wnGIobPuO/DGBtDmsbn1ObXJXGcjZ+6h7IMsvsldfHh2gfQsWqe2cw+/eBK2dkcmPEfMIaa5zoY6BBbdxpO5ncJkzwMvTHPk8XOs+/YFz38iefm4oIRsPp44fvnP7ideaEnm5pV4bNnzT9uOHZnIHPkdHdAMdMnIXE92p2YOPdWmvGRkblK59+T9Ucv9PHAnc8xiZ/uELx8XlDCLb/3StfRMcySkXDyTuRlNWIEJ/8k8WLSSk67xYJoDkpO56RhzmI3MAcnJ3FyMckxI5oDkZG4iRjnmJHNAcjIHJCdzQHIyByQnc7Nw/oFpyRyQnMwByclcNz4IAtqQuSk4MMfMZA5ITuaA5GQuPytWJidzQHIyByQnc8lZsYLMAcnJHJCczGVmxQqLzPXinV7QjMylZZSDO5kDkpO5nIxy8CBzQHIyByQnc0ByMgckJ3MJOf8Az2SuA9cGQ0syByQnc9lYscILmQOSkzkgOZkDkpO51qqeZnVgDt7JHJCczAHJyVweVqzwkcwByclcU/XOPxjl4BuZA5KTOSA5mcvAihU2yByQnMy1U+n8g1EOtskckJzMAcnJXGxWrPCTzAHJyVwjNc4/GOVgD5kDkpM5IDmZi8qKFXaSOSA5mQvJKAf7yVwLVT/mBtgmc0ByMhePFSscInNAcjIXjFEOjpK56px/gL5kDkhO5uoqO8pZscIJMgckJ3NhGOXgHJmryMkHGIHMAcnJXAxWrHCazNVixQqDkLkAjHJwhcwByclcFQVXrEY5uEjmgORkbmhGObhO5oDkZG5cRjkoQubKc8UcDEXmBmWUg1JkrjCjHIxG5kZklIOCZA5ITuZKsmKFAclcMaUaZ8UKZcncWDQOipO5MixXYVgyNxCjHNQgcwUY5WBkMjcKoxxUInNXFRnlNA7qkTkgOZnrzygHVcncJU4+wPhk7jxH5SAEmQOSk7mTjHIQhcwBycncGc48QCAy140VK7Qhc4c5KgexyFwHGgctydwx10c5jYPGZA5ITuYOMMpBRDK3l8ZBUDK3i8ZBXDIHJCdzvxnlIDSZ+0HjIDqZ2+K9q5CAzH3lTV2Qg8wBycncZ0Y5SEPmPtA4yETmXmkcJCNz5WkcDEXm/sNVcpCPzP1L4yAlmftD4yArmVsWjYPUZM47uiC52TPn8hFIb+rMaRzMYN7MaRxMYtLMaRzMY8bMaRxMZbrMaRzMZq7MaRxM6J/eD6CRUhfHaRyEM8U0p3Ews/yZ0ziYXOZFa8F3cWkcxJV2mtM44C7nNGehCjxky5whDniRJ3Nl76ekcZBGhswJHLAhduaK3xFT4yCfwGdaNQ7YI+Q0J3DAfsEyV+NzGzQOcguTuUofTKNxkF6AzAkccMW4mav3uYICB1MZMXNVPzhV42A2Y2VO4IDiRsmcwAGV9Mxc1bTdCRzQJ3MCBzTTOnO1A6duwIsWmWswuy0CB3xRJXNtuvYgcMCGYplrnLY7gQN+upq5LnVbBA7Y7VjmekXtmcABh+zKXPe6SRtw2mvmuhftQdqAIv5kbpC6SRtQXP+6SRtQ1XqvjCvdgKzW9+L42FMgk/8DDsgw4HlIEQ0AAAAASUVORK5CYII=" alt="" height="211" width="213">

You can wrap this up into a string variable and place this absolutely anywhere that you would present an html email message - even in your email signatures. The advantage is that there are no attachments, and there are no links. (this code will display a lizard)

A picture is worth a thousand words: enter image description here

Incidentally, I did write a program to do all of this for you. It's called BaseImage, and it will create the image code as well as the html for you. Please don't consider this self-promotion; I'm just sharing a solution.

EF Code First "Invalid column name 'Discriminator'" but no inheritance

I had a similar problem, not exactly the same conditions and then i saw this post. Hope it helps someone. Apparently i was using one of my EF entity models a base class for a type that was not specified as a db set in my dbcontext. To fix this issue i had to create a base class that had all the properties common to the two types and inherit from the new base class among the two types.

Example:

//Bad Flow
    //class defined in dbcontext as a dbset
    public class Customer{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //class not defined in dbcontext as a dbset
    public class DuplicateCustomer:Customer{ 
       public object DuplicateId {get; set;}
    }


    //Good/Correct flow*
    //Common base class
    public class CustomerBase{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //entity model referenced in dbcontext as a dbset
    public class Customer: CustomerBase{

    }

    //entity model not referenced in dbcontext as a dbset
    public class DuplicateCustomer:CustomerBase{

       public object DuplicateId {get; set;}

    }

Java: Best way to iterate through a Collection (here ArrayList)

The first option is better performance wise (As ArrayList implement RandomAccess interface). As per the java doc, a List implementation should implement RandomAccess interface if, for typical instances of the class, this loop:

 for (int i=0, n=list.size(); i < n; i++)
     list.get(i);

runs faster than this loop:

 for (Iterator i=list.iterator(); i.hasNext(); )
     i.next();

I hope it helps. First option would be slow for sequential access lists.

How to re-sign the ipa file?

The answers posted here all didn't quite work for me. They mainly skipped signing embedded frameworks (or including the entitlements).

Here's what's worked for me (it assumes that one ipa file exists is in the current directory):

PROVISION="/path/to/file.mobileprovision"
CERTIFICATE="Name of certificate: To sign with" # must be in the keychain

unzip -q *.ipa
rm -rf Payload/*.app/_CodeSignature/

# Replace embedded provisioning profile
cp "$PROVISION" Payload/*.app/embedded.mobileprovision

# Extract entitlements from app
codesign -d --entitlements :entitlements.plist Payload/*.app/

# Re-sign embedded frameworks
codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app/Frameworks/*

# Re-sign the app (with entitlements)
codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app/

zip -qr resigned.ipa Payload

# Cleanup
rm entitlements.plist
rm -r Payload/