Programs & Examples On #Data serialization

Clear Cache in Android Application programmatically

The answer from dhams is correct (after having been edited several times), but as the many edits of the code shows, it is difficult to write correct and robust code for deleting a directory (with sub-dirs) yourself. So I strongly suggest using Apache Commons IO, or some other API that does this for you:

import org.apache.commons.io.FileUtils;

...

// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());

PS: Also delete the directory returned by context.getExternalCacheDir() if you use that.

To be able to use Apache Commons IO, add this to your build.gradle file, in the dependencies part:

compile 'commons-io:commons-io:2.4'

Bootstrap change div order with pull-right, pull-left on 3 columns

Bootstrap 3

Using Bootstrap 3's grid system:

<div class="container">
  <div class="row">
    <div class="col-xs-4">Menu</div>
    <div class="col-xs-8">
      <div class="row">
        <div class="col-md-4 col-md-push-8">Right Content</div>
        <div class="col-md-8 col-md-pull-4">Content</div>
      </div>
    </div>
  </div>
</div>

Working example: http://bootply.com/93614

Explanation

First, we set two columns that will stay in place no matter the screen resolution (col-xs-*).

Next, we divide the larger, right hand column in to two columns that will collapse on top of each other on tablet sized devices and lower (col-md-*).

Finally, we shift the display order using the matching class (col-md-[push|pull]-*). You push the first column over by the amount of the second, and pull the second by the amount of the first.

Place a button right aligned

If the button is the only element on the block:

_x000D_
_x000D_
.border {_x000D_
  border: 2px blue dashed;_x000D_
}_x000D_
_x000D_
.mr-0 {_x000D_
  margin-right: 0;_x000D_
}_x000D_
.ml-auto {_x000D_
  margin-left:auto;_x000D_
}_x000D_
.d-block {_x000D_
  display:block;_x000D_
}
_x000D_
<p class="border">_x000D_
  <input type="button" class="d-block mr-0 ml-auto" value="The Button">_x000D_
</p>
_x000D_
_x000D_
_x000D_

If there are other elements on the block:

_x000D_
_x000D_
.border {_x000D_
  border: 2px indigo dashed;_x000D_
}_x000D_
_x000D_
.d-table {_x000D_
  display:table;_x000D_
}_x000D_
_x000D_
.d-table-cell {_x000D_
  display:table-cell;_x000D_
}_x000D_
_x000D_
.w-100 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.tar {_x000D_
  text-align: right;_x000D_
}
_x000D_
<div class="border d-table w-100">_x000D_
  <p class="d-table-cell">The paragraph.....lorem ipsum...etc.</p>_x000D_
  <div class="d-table-cell tar">_x000D_
    <button >The Button</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

With flex-box:

_x000D_
_x000D_
.flex-box {_x000D_
  display:flex;_x000D_
  justify-content:space-between;_x000D_
  outline: 2px dashed blue;_x000D_
}_x000D_
_x000D_
.flex-box-2 {_x000D_
  display:flex;_x000D_
  justify-content: flex-end;_x000D_
  outline: 2px deeppink dashed;_x000D_
}
_x000D_
<h1>Button with Text</h1>_x000D_
<div class="flex-box">_x000D_
<p>Once upon a time in a ...</p>_x000D_
<button>Read More...</button>_x000D_
</div>_x000D_
_x000D_
<h1>Only Button</h1>_x000D_
<div class="flex-box-2">_x000D_
  <button>The Button</button>_x000D_
</div>_x000D_
_x000D_
<h1>Multiple Buttons</h1>_x000D_
<div class="flex-box-2">_x000D_
  <button>Button 1</button>_x000D_
  <button>Button 2</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Good Luck...

Stretch horizontal ul to fit width of div

People hate on tables for non-tabular data, but what you're asking for is exactly what tables are good at. <table width="100%">

Java decimal formatting using String.format?

NumberFormat and DecimalFormat are definitely what you want. Also, note the NumberFormat.setRoundingMode() method. You can use it to control how rounding or truncation is applied during formatting.

Setting width to wrap_content for TextView through code

I am posting android Java base multi line edittext.

EditText editText = findViewById(R.id.editText);/* edittext access */

ViewGroup.LayoutParams params  =  editText.getLayoutParams(); 
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
editText.setLayoutParams(params); /* Gives as much height for multi line*/

editText.setSingleLine(false); /* Makes it Multi line */

Custom Date Format for Bootstrap-DatePicker

I'm sure you are using a old version. You must use the last version available at master branch:

https://github.com/eternicode/bootstrap-datepicker

How can the Euclidean distance be calculated with NumPy?

import numpy as np
# any two python array as two points
a = [0, 0]
b = [3, 4]

You first change list to numpy array and do like this: print(np.linalg.norm(np.array(a) - np.array(b))). Second method directly from python list as: print(np.linalg.norm(np.subtract(a,b)))

How to delete directory content in Java?

You have to do this for each File:

public static void deleteFolder(File folder) {
    File[] files = folder.listFiles();
    if(files!=null) { //some JVMs return null for empty dirs
        for(File f: files) {
            if(f.isDirectory()) {
                deleteFolder(f);
            } else {
                f.delete();
            }
        }
    }
    folder.delete();
}

Then call

deleteFolder(outputFolder);

Change button background color using swift language

Swift 4:

You can easily use hex code:

self.backgroundColor = UIColor(hexString: "#ff259F6C")

self.layer.shadowColor = UIColor(hexString: "#08259F6C").cgColor

Extension for hex color code

extension UIColor {
    convenience init(hexString: String, alpha: CGFloat = 1.0) {
        let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)
        if (hexString.hasPrefix("#")) {
            scanner.scanLocation = 1
        }
        var color: UInt32 = 0
        scanner.scanHexInt32(&color)
        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        self.init(red:red, green:green, blue:blue, alpha:alpha)
    }
    func toHexString() -> String {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: &a)
        let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
        return String(format:"#%06x", rgb)
    }
}

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

I had this same problem and had to refer to the php manual which told me the mysql and mysqli extensions require libmysql.dll to load. I searched for it under C:\windows\system32 (windows 7) and could not find, so I downloaded it here and placed it in my C:\windows\system32. I restarted Apache and everything worked fine. Took me 3 days to figure out, hope it helps.

Rails: select unique values from a column

If anyone is looking for the same with Mongoid, that is

Model.distinct(:rating)

Microsoft.ReportViewer.Common Version=12.0.0.0

Issue

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

Cause

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

Resolution

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

Download Microsoft ReportViewer runtime

Download Microsoft SQL CLR types for SQL Server 2014

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

Or you cant follow this link to read more.

Javascript/DOM: How to remove all events of a DOM object?

You can add a helper function that clears event listener for example

function clearEventListener(element) {
 const clonedElement = element.cloneNode(true);
element.replaceWith(clonedElement);
return clonedElement;
}

just pass in the element to the function and that's it...

Change first commit of project with Git?

If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?

And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History

Replacing values from a column using a condition in R

I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful

library(dplyr)
iris %>% 
  mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))

Using NOT operator in IF conditions

try like this

if (!(a | b)) {
    //blahblah
}

It's same with

if (a | b) {}
else {
    // blahblah
}

Get all rows from SQLite

Cursor cursor = myDb.viewData();

        if (cursor.moveToFirst()){
              do {
                 String itemname=cursor.getString(cursor.getColumnIndex(myDb.col_2));
                 String price=cursor.getString(cursor.getColumnIndex(myDb.col_3));
                 String quantity=cursor.getString(cursor.getColumnIndex(myDb.col_4));
                 String table_no=cursor.getString(cursor.getColumnIndex(myDb.col_5));

                 }while (cursor.moveToNext());

                }

                cursor.requery();

.NET - Get protocol, host, and port

Request.Url will return you the Uri of the request. Once you have that, you can retrieve pretty much anything you want. To get the protocol, call the Scheme property.

Sample:

Uri url = Request.Url;
string protocol = url.Scheme;

Hope this helps.

What is the difference between Cloud, Grid and Cluster?

There's some pretty good answers here but I want to elaborate on all topics:

Cloud: shailesh's answer is awesome, nothing to add there! Basically, An application that's served seamlessly over the network can be considered a Cloud application. Cloud isn't a new invention and it's very similar to Grid computing, but it's more of a buzzword with the spike of recent popularity.

Grid: Grid is defined as a large collection as machines connected by a private network and offers a set of services to users, it acts as a sort of supercomputer by sharing processing power across the machines. Source: Tenenbaum, Andrew.

Cluster: A cluster is different from those two. Clusters are two or more computers who share a network connection that acts as a heart-beat. Clusters are configurable in Active-Active or Active-Passive ways. Active-Active being that each computer runs it's own set of services (Say, one runs a SQL instance, the other runs a web server) and they share some resources such as storage. If one of the computers in a cluster goes down the service fails over to the other node and almost seamlessly starts running there. Active-Passive is similar, but only one machine runs these services and only takes over once there's a failure.

How to install PostgreSQL's pg gem on Ubuntu?

I was trying to setup a Rails project in my freshly installed Ubuntu 16.04. I ran into the same issue while running bundle. Running

sudo apt-get install aptitude

followed by

sudo apt-get install libpq-dev

Solved it for me.

jQuery send HTML data through POST

_x000D_
_x000D_
jQuery.post(post_url,{ content: "John" } )_x000D_
 .done(function( data ) {_x000D_
   _x000D_
   _x000D_
 });_x000D_
 
_x000D_
_x000D_
_x000D_

I used the technique what u have replied above, it works fine but my problem is i need to generate a pdf conent using john as text . I have been able to echo the passed data. but getting empty in when generating pdf uisng below content ples check

_x000D_
_x000D_
ob_start();_x000D_
        _x000D_
   include_once(JPATH_SITE .'/components/com_gaevents/pdfgenerator.php');_x000D_
   $content = ob_get_clean();_x000D_
   _x000D_
  _x000D_
  _x000D_
    $test = $_SESSION['content'] ;_x000D_
  _x000D_
   require_once(JPATH_SITE.'/html2pdf/html2pdf.class.php');_x000D_
            $html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8',0 );   _x000D_
    $html2pdf->setDefaultFont('Arial');_x000D_
    $html2pdf->WriteHTML($test);
_x000D_
_x000D_
_x000D_

"Uncaught TypeError: Illegal invocation" in Chrome

In your code you are assigning a native method to a property of custom object. When you call support.animationFrame(function () {}) , it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window.

So the correct usage here is support.animationFrame.call(window, function() {});.

The same happens with alert too:

var myObj = {
  myAlert : alert //copying native alert to an object
};

myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window 

Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.

var _raf = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;

var support = {
   animationFrame: _raf ? _raf.bind(window) : null
};

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

How to reset sequence in postgres and fill id column with new data?

The best way to reset a sequence to start back with number 1 is to execute the following:

ALTER SEQUENCE <tablename>_<id>_seq RESTART WITH 1

So, for example for the users table it would be:

ALTER SEQUENCE users_id_seq RESTART WITH 1

How to display text in pygame?

There's also the pygame.freetype module which is more modern, works with more fonts and offers additional functionality.

Create a font object with pygame.freetype.SysFont() or pygame.freetype.Font if the font is inside of your game directory.

You can render the text either with the render method similarly to the old pygame.font.Font.render or directly onto the target surface with render_to.

import pygame
import pygame.freetype  # Import the freetype module.


pygame.init()
screen = pygame.display.set_mode((800, 600))
GAME_FONT = pygame.freetype.Font("your_font.ttf", 24)
running =  True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((255,255,255))
    # You can use `render` and then blit the text surface ...
    text_surface, rect = GAME_FONT.render("Hello World!", (0, 0, 0))
    screen.blit(text_surface, (40, 250))
    # or just `render_to` the target surface.
    GAME_FONT.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))

    pygame.display.flip()

pygame.quit()

Capitalize or change case of an NSString in Objective-C

In case anyone needed the above in swift :

SWIFT 3.0 and above :

this will capitalize your string, make the first letter capital :

viewNoteDateMonth.text  = yourString.capitalized

this will uppercase your string, make all the string upper case :

viewNoteDateMonth.text  = yourString.uppercased()

How to tell if a file is git tracked (by shell exit code)?

try:

git ls-files --error-unmatch <file name>

will exit with 1 if file is not tracked

How can a Javascript object refer to values in itself?

That's not a JSON object, that's a Javascript object created via object literal notation. (JSON is a textual notation for data exchange (more). If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON.)

There's no way within the object initializer to refer to another key of the object being initialized, because there's no way to get a reference to the object being created until the initializer is finished. (There's no keyword akin to this or something for this situation.)

how to overlap two div in css?

See demo here you need to introduce an additiona calss for second div

.overlap{
    top: -30px;
position: relative;
left: 30px;
}

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

T_PAAMAYIM_NEKUDOTAYIM is the double colon scope resolution thingy PHP uses - ::

Quick glance at your code, I think this line:

return $cnf::getConfig($key);

should be

return $cnf->getConfig($key);

The first is the way to call a method statically - this code would be valid if $cnf contained a string that was also a valid class. The -> syntax is for calling a method on an instance of a class/object.

A variable modified inside a while loop is not remembered

I use stderr to store within a loop, and read from it outside. Here var i is initially set and read inside the loop as 1.

# reading lines of content from 2 files concatenated
# inside loop: write value of var i to stderr (before iteration)
# outside: read var i from stderr, has last iterative value

f=/tmp/file1
g=/tmp/file2
i=1
cat $f $g | \
while read -r s;
do
  echo $s > /dev/null;  # some work
  echo $i > 2
  let i++
done;
read -r i < 2
echo $i

Or use the heredoc method to reduce the amount of code in a subshell. Note the iterative i value can be read outside the while loop.

i=1
while read -r s;
do
  echo $s > /dev/null
  let i++
done <<EOT
$(cat $f $g)
EOT
let i--
echo $i

Add quotation at the start and end of each line in Notepad++

  1. Put your cursor at the begining of line 1.
  2. click Edit>ColumnEditor. Put " in the text and hit enter.
  3. Repeat 2 but put the cursor at the end of line1 and put ", and hit enter.

Getting 400 bad request error in Jquery Ajax POST

The question is a bit old... but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.

You have to get name and value from craft in your template :

<script type="text/javascript">
    window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
    window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>

and pass them in your request

data: window.csrfTokenName+"="+window.csrfTokenValue

Checking if a variable exists in javascript

I found this shorter and much better:

    if(varName !== (undefined || null)) { //do something }

Where is Maven Installed on Ubuntu

Depends on what you are looking for. If you are looking for the executable :

$ whereis mvn

If you are looking for the libs and repo :

$ locate maven

With the locate command, you could also pipe it to grep to find a particular library, i.e.

$ locate maven | grep 'jetty'

HTH

How to access JSON decoded array in PHP

$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"


$data = json_decode($json);
echo $data[0]->c_name;      // "John"

Intellij idea cannot resolve anything in maven

I had the very same problem as author!

To solve my issue I had to add Maven Integration Plugin: File | Settings | Plugins

Like this:

Maven Integration Plugin

After that Intellij downloaded all the dependencies from pom.xml file.

Now if I want to create a project based on maven model, I just choose Open on the first Intellij window and choose the pom.xml file:

enter image description here

How to make java delay for a few seconds?

 new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    if (getActivity() != null)
                        getActivity().runOnUiThread(() -> tvCovidAlert.startAnimation(animBounce));
                }
            }, DELAY_TIME_MILI_SECONDS);

WPF Databinding: How do I access the "parent" data context?

This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

I have never set any passwords to my keystore and alias, so how are they created?

Signing in Debug Mode

The Android build tools provide a debug signing mode that makes it easier for you to develop and debug your application, while still meeting the Android system requirement for signing your APK. When using debug mode to build your app, the SDK tools invoke Keytool to automatically create a debug keystore and key. This debug key is then used to automatically sign the APK, so you do not need to sign the package with your own key.

The SDK tools create the debug keystore/key with predetermined names/passwords:

Keystore name: "debug.keystore"
Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"
CN: "CN=Android Debug,O=Android,C=US"

If necessary, you can change the location/name of the debug keystore/key or supply a custom debug keystore/key to use. However, any custom debug keystore/key must use the same keystore/key names and passwords as the default debug key (as described above). (To do so in Eclipse/ADT, go to Windows > Preferences > Android > Build.)

Caution: You cannot release your application to the public when signed with the debug certificate.

Source: Developer.Android

RESTful API methods; HEAD & OPTIONS

OPTIONS tells you things such as "What methods are allowed for this resource".

HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.

Sort ObservableCollection<string> through C#

The argument to OrderByDescending is a function returning a key to sort with. In your case, the key is the string itself:

var result = _animals.OrderByDescending(a => a);

If you wanted to sort by length for example, you'll write:

var result = _animals.OrderByDescending(a => a.Length);

Datetime current year and month in Python

Try this solution:

from datetime import datetime

currentSecond= datetime.now().second
currentMinute = datetime.now().minute
currentHour = datetime.now().hour

currentDay = datetime.now().day
currentMonth = datetime.now().month
currentYear = datetime.now().year

Show DataFrame as table in iPython Notebook

This answer is based on the 2nd tip from this blog post: 28 Jupyter Notebook tips, tricks and shortcuts

You can add the following code to the top of your notebook

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

This tells Jupyter to print the results for any variable or statement on it’s own line. So you can then execute a cell solely containing

df1
df2

and it will "print out the beautiful tables for both datasets".

How to remove focus without setting focus to another control?

android:descendantFocusability="beforeDescendants"

using the following in the activity with some layout options below seemed to work as desired.

 getWindow().getDecorView().findViewById(android.R.id.content).clearFocus();

in connection with the following parameters on the root view.

<?xml
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:descendantFocusability="beforeDescendants" />

https://developer.android.com/reference/android/view/ViewGroup#attr_android:descendantFocusability

Answer thanks to: https://forums.xamarin.com/discussion/1856/how-to-disable-auto-focus-on-edit-text

About windowSoftInputMode

There's yet another point of contention to be aware of. By default, Android will automatically assign initial focus to the first EditText or focusable control in your Activity. It naturally follows that the InputMethod (typically the soft keyboard) will respond to the focus event by showing itself. The windowSoftInputMode attribute in AndroidManifest.xml, when set to stateAlwaysHidden, instructs the keyboard to ignore this automatically-assigned initial focus.

<activity
    android:name=".MyActivity"
    android:windowSoftInputMode="stateAlwaysHidden"/>

great reference

Tools to search for strings inside files without indexing

If you don't want to install Non-Microsoft tools, please download STRINGS.EXE from Microsoft Sysinternals and make a procedure like this one:

@echo off
if '%1' == '' goto NOPARAM
if '%2' == '' goto NOPARAM
if not exist %1 goto NOFOLDER

echo ------------------------------------------
echo - %1 : folder
echo - %2 : string to be searched in the folder
echo - PLEASE WAIT FOR THE RESULTS ...
strings -s %1\* | findstr /i %2 > grep.txt
notepad.exe grep.txt

goto END

:NOPARAM rem - input command not correct
echo ====================================
echo Usage of GREP.CMD:
echo   Grep "SearchFolder" SearchString
echo Please specify all parameters
echo ====================================
goto END

:NOFOLDER
echo Folder %1 does not exist
goto END

:END rem - exit

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

To all who have faced this issue/ will face it in the future:

Click on Build menu -> Select Build Variant -> restore to 'debug'

Outcomment on debuggable in module:app /* debug { debuggable true }*/

Go to Build menu -> generate signed apk -> .... -> build it

How do I fix "The expression of type List needs unchecked conversion...'?

If you look at the javadoc for the class SyndFeed (I guess you are referring to the class com.sun.syndication.feed.synd.SyndFeed), the method getEntries() doesn't return java.util.List<SyndEntry>, but returns just java.util.List.

So you need an explicit cast for this.

How to convert OutputStream to InputStream?

You will need an intermediate class which will buffer between. Each time InputStream.read(byte[]...) is called, the buffering class will fill the passed in byte array with the next chunk passed in from OutputStream.write(byte[]...). Since the sizes of the chunks may not be the same, the adapter class will need to store a certain amount until it has enough to fill the read buffer and/or be able to store up any buffer overflow.

This article has a nice breakdown of a few different approaches to this problem:

http://blog.ostermiller.org/convert-java-outputstream-inputstream

Dynamically adding properties to an ExpandoObject

i think this add new property in desired type without having to set a primitive value, like when property defined in class definition

var x = new ExpandoObject();
x.NewProp = default(string)

Common elements in two lists

You can get the common elements between two lists using the method "retainAll". This method will remove all unmatched elements from the list to which it applies.

Ex.: list.retainAll(list1);

In this case from the list, all the elements which are not in list1 will be removed and only those will be remaining which are common between list and list1.

List<Integer> list = new ArrayList<>();
list.add(10);
list.add(13);
list.add(12);
list.add(11);

List<Integer> list1 = new ArrayList<>();
list1.add(10);
list1.add(113);
list1.add(112);
list1.add(111);
//before retainAll
System.out.println(list);
System.out.println(list1);
//applying retainAll on list
list.retainAll(list1);
//After retainAll
System.out.println("list::"+list);
System.out.println("list1::"+list1);

Output:

[10, 13, 12, 11]
[10, 113, 112, 111]
list::[10]
list1::[10, 113, 112, 111]

NOTE: After retainAll applied on the list, the list contains common element between list and list1.

sql - insert into multiple tables in one query

Multiple SQL statements must be executed with the mysqli_multi_query() function.

Example (MySQLi Object-oriented):

    <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";

if ($conn->multi_query($sql) === TRUE) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

What to do if i have to processed even more that 500000 records ?

There are a few ways, to increase the java heap size for your app where a few have suggested already. Your app need to remove the elements from your adddressMap as your app add new element into it and so you won't encounter oom if there are more records coming in. Look for producer-consumer if you are interested.

Create a zip file and download it

but the file i am getting from server after download it gives the size of 226 bytes

This is the size of a ZIP header. Apparently there is no data in the downloaded ZIP file. So, can you verify that the files to be added into the ZIP file are, indeed, there (relative to the path of the download PHP script)?

Consider adding a check on addFile too:

foreach($file_names as $file)
{
    $inputFile = $file_path . $file;
    if (!file_exists($inputFile))
        trigger_error("The input file $inputFile does not exist", E_USER_ERROR);
    if (!is_readable($inputFile))
        trigger_error("The input file $inputFile exists, but has wrong permissions or ownership", E_USER_ERROR);
    if (!$zip->addFile($inputFile, $file))
        trigger_error("Could not add $inputFile to ZIP file", E_USER_ERROR);
}

The observed behaviour is consistent with some problem (path error, permission problems, ...) preventing the files from being added to the ZIP file. On receiving an "empty" ZIP file, the client issues an error referring to the ZIP central directory missing (the actual error being that there is no directory, and no files).

Package opencv was not found in the pkg-config search path

From your question I guess you are using Ubuntu (or a derivate). If you use:

apt-file search opencv.pc

then you see that you have to install libopencv-dev.

After you do so, pkg-config --cflags opencv and pkg-config --libs opencv should work as expected.

What's the difference between REST & RESTful

A "REST service" and a "RESTful service" are one and the same.

A RESTful system is any system that follows the REST conventions as defined in the original document that created the idea of RESTful networked applications.

It's worth noting there are varying levels of RESTfulness. Overall, REST is a style, not a standard, so there is room for interpretation based on needs. one example is hierarchical resource URLs (e.g. /things/ID/relatedthings) vs flat URLs (e.g. /things/ID and /relatedthings?thing=ID)

Big-oh vs big-theta

Because there are algorithms whose best-case is quick, and thus it's technically a big O, not a big Theta.

Big O is an upper bound, big Theta is an equivalence relation.

Bash: Syntax error: redirection unexpected

do it the simpler way,

direc=$(basename `pwd`)

Or use the shell

$ direc=${PWD##*/}

Send mail via CMD console

From Linux you can use 'swaks' which is available as an official packages on many distros including Debian/Ubuntu and Redhat/CentOS on EPEL:

swaks -f [email protected] -t [email protected] \
    --server mail.example.com

How to clone object in C++ ? Or Is there another solution?

The typical solution to this is to write your own function to clone an object. If you are able to provide copy constructors and copy assignement operators, this may be as far as you need to go.

class Foo
{ 
public:
  Foo();
  Foo(const Foo& rhs) { /* copy construction from rhs*/ }
  Foo& operator=(const Foo& rhs) {};
};

// ...

Foo orig;
Foo copy = orig;  // clones orig if implemented correctly

Sometimes it is beneficial to provide an explicit clone() method, especially for polymorphic classes.

class Interface
{
public:
  virtual Interface* clone() const = 0;
};

class Foo : public Interface
{
public:
  Interface* clone() const { return new Foo(*this); }
};

class Bar : public Interface
{
public:
  Interface* clone() const { return new Bar(*this); }
};


Interface* my_foo = /* somehow construct either a Foo or a Bar */;
Interface* copy = my_foo->clone();

EDIT: Since Stack has no member variables, there's nothing to do in the copy constructor or copy assignment operator to initialize Stack's members from the so-called "right hand side" (rhs). However, you still need to ensure that any base classes are given the opportunity to initialize their members.

You do this by calling the base class:

Stack(const Stack& rhs) 
: List(rhs)  // calls copy ctor of List class
{
}

Stack& operator=(const Stack& rhs) 
{
  List::operator=(rhs);
  return * this;
};

How to present UIAlertController when not in a view controller?

Seems to work:

static UIViewController *viewControllerForView(UIView *view) {
    UIResponder *responder = view;
    do {
        responder = [responder nextResponder];
    }
    while (responder && ![responder isKindOfClass:[UIViewController class]]);
    return (UIViewController *)responder;
}

-(void)showActionSheet {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"Do it" style:UIAlertActionStyleDefault handler:nil]];
    [viewControllerForView(self) presentViewController:alertController animated:YES completion:nil];
}

Python String and Integer concatenation

NOTE:

The method used in this answer (backticks) is deprecated in later versions of Python 2, and removed in Python 3. Use the str() function instead.


You can use :

string = 'string'
for i in range(11):
    string +=`i`
print string

It will print string012345678910.

To get string0, string1 ..... string10 you can use this as @YOU suggested

>>> string = "string"
>>> [string+`i` for i in range(11)]

Update as per Python3

You can use :

string = 'string'
for i in range(11):
    string +=str(i)
print string

It will print string012345678910.

To get string0, string1 ..... string10 you can use this as @YOU suggested

>>> string = "string"
>>> [string+str(i) for i in range(11)]

How to run functions in parallel?

This can be done elegantly with Ray, a system that allows you to easily parallelize and distribute your Python code.

To parallelize your example, you'd need to define your functions with the @ray.remote decorator, and then invoke them with .remote.

import ray

ray.init()

dir1 = 'C:\\folder1'
dir2 = 'C:\\folder2'
filename = 'test.txt'
addFiles = [25, 5, 15, 35, 45, 25, 5, 15, 35, 45]

# Define the functions. 
# You need to pass every global variable used by the function as an argument.
# This is needed because each remote function runs in a different process,
# and thus it does not have access to the global variables defined in 
# the current process.
@ray.remote
def func1(filename, addFiles, dir):
    # func1() code here...

@ray.remote
def func2(filename, addFiles, dir):
    # func2() code here...

# Start two tasks in the background and wait for them to finish.
ray.get([func1.remote(filename, addFiles, dir1), func2.remote(filename, addFiles, dir2)]) 

If you pass the same argument to both functions and the argument is large, a more efficient way to do this is using ray.put(). This avoids the large argument to be serialized twice and to create two memory copies of it:

largeData_id = ray.put(largeData)

ray.get([func1(largeData_id), func2(largeData_id)])

Important - If func1() and func2() return results, you need to rewrite the code as follows:

ret_id1 = func1.remote(filename, addFiles, dir1)
ret_id2 = func2.remote(filename, addFiles, dir2)
ret1, ret2 = ray.get([ret_id1, ret_id2])

There are a number of advantages of using Ray over the multiprocessing module. In particular, the same code will run on a single machine as well as on a cluster of machines. For more advantages of Ray see this related post.

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

How to convert R Markdown to PDF?

If you don't want to install anything you can output html. Then open the html file - it should open in a browser window, then right click to print. In the print window, select "save as pdf" in the bottom right hand corner if you're on a Mac. Voila!

How do I retrieve an HTML element's actual width and height?

... seems CSS help to put div on center ...

<style>
 .monitor {
 position:fixed;/* ... absolute possible if on :root */
 top:0;bottom:0;right:0;left:0;
 visibility:hidden;
 }
 .wrapper {
 width:200px;/* this is size range */
 height:100px;
 position:absolute;
 left:50%;top:50%;
 visibility:hidden;
 }

 .content {
 position:absolute;
 width: 100%;height:100%;
 left:-50%;top:-50%;
 visibility:visible;
 }

</style>

 <div class="monitor">
  <div class="wrapper">
   <div class="content">

 ... so you hav div 200px*100px on center ...

  </div>
 </div>
</div>

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

The problem here are PHP namespaces. You need to learn how to use them. As your controller are in App\Http\Controllers namespace, if you refer any other class, you need to add leading backslash (or proper namespace) or add use statement at the beginning of file (before class definition).

So in your case you could use:

$headquote = \DB::table('quotation_texts')->find(176);
$headquote = \App\Quotation::find(176);

or add in your controller class use statement so the beginning of your controller class could look like this:

<?php

namespace App\Http\Controllers;

use DB;
use App\Quotation;

For more information about namespaces you could look at How to use objects from other namespaces and how to import namespaces in PHP or namespaces in PHP manual

Print time in a batch file (milliseconds)

If you're doing something like

for /l %%i in (1,1,500) do @echo %time%

or

if foo (
    echo %time%
    do_something
    echo %time%
)

then you could simply put a setlocal enabledelayedexpansion at the beginning of your batch file and use !time! instead of %time% which gets evaluated on execution, not on parsing the line (which includes complete blocks enclosed in parentheses).

Dump all documents of Elasticsearch

We can use elasticdump to take the backup and restore it, We can move data from one server/cluster to another server/cluster.

1. Commands to move one index data from one server/cluster to another using elasticdump.

# Copy an index from production to staging with analyzer and mapping:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=analyzer
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=mapping
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=data

2. Commands to move all indices data from one server/cluster to another using multielasticdump.

Backup

multielasticdump \
  --direction=dump \
  --match='^.*$' \
  --limit=10000 \
  --input=http://production.es.com:9200 \
  --output=/tmp 

Restore

multielasticdump \
  --direction=load \
  --match='^.*$' \
  --limit=10000 \
  --input=/tmp \
  --output=http://staging.es.com:9200 

Note:

  • If the --direction is dump, which is the default, --input MUST be a URL for the base location of an ElasticSearch server (i.e. http://localhost:9200) and --output MUST be a directory. Each index that does match will have a data, mapping, and analyzer file created.

  • For loading files that you have dumped from multi-elasticsearch, --direction should be set to load, --input MUST be a directory of a multielasticsearch dump and --output MUST be a Elasticsearch server URL.

  • The 2nd command will take a backup of settings, mappings, template and data itself as JSON files.

  • The --limit should not be more than 10000 otherwise, it will give an exception.

  • Get more details here.

Run a php app using tomcat?

It's quite common to run Tomcat behind Apache. In Apache you can then direct certain URLs to Tomcat, and have Apache/PHP handle the others (including the static images).

(On Unix, Tomcat itself cannot securely made to run on port 80, while Apache can. Tomcat, being a Java process, would be required to run as root, while Apache will switch to non-root privileges as soon as port 80 has been claimed. So, running Apache on port 80 and have it redirect some or all requests to Tomcat, is quite common on Unix.)

jQuery `.is(":visible")` not working in Chrome

It seems jQuery's :visible selector does not work for some inline elements in Chrome. The solution is to add a display style, like "block" or "inline-block" to make it work.

Also note that jQuery has a somewhat different definition of what is visible than many developers:

Elements are considered visible if they consume space in the document.
Visible elements have a width or height that is greater than zero.

In other words, an element must have a non-zero width and height to consume space and be visible.

Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.

On the other hand, even if its visibility is set to hidden or the opacity is zero, it's still :visible to jQuery as it consumes space, which can be confusing when the CSS explicitly says its visibility is hidden.

Elements that are not in a document are considered hidden; jQuery does not have a way to know if they will be visible when appended to a document since it depends on the applicable styles.

All option elements are considered hidden, regardless of their selected state.

During animations that hide an element, the element is considered visible until the end of the animation. During animations to show an element, the element is considered visible at the start at the animation.

The easy way to look at it, is that if you can see the element on the screen, even if you can't see its content, it's transparent etc., it's visible, i.e. it takes up space.

I cleaned up your markup a little and added a display style (i.e. setting the elements display to "block" etc), and this works for me:

FIDDLE

Official API reference for :visible


As of jQuery 3, the definition of :visible has changed slightly

jQuery 3 slightly modifies the meaning of :visible (and therefore of :hidden).
Starting with this version, elements will be considered :visible if they have any layout boxes, including those of zero width and/or height. For example, br elements and inline elements with no content will be selected by the :visible selector.

How can I keep Bootstrap popovers alive while being hovered?

Test with code snippet below:

Small modification (From the solution provided by vikas) to suit my use case.

  1. Open popover on hover event for the popover button
  2. Keep popover open when hovering over the popover box
  3. Close popover on mouseleave for either the popover button, or the popover box.

_x000D_
_x000D_
$(".pop").popover({
    trigger: "manual",
    html: true,
    animation: false
  })
  .on("mouseenter", function() {
    var _this = this;
    $(this).popover("show");
    $(".popover").on("mouseleave", function() {
      $(_this).popover('hide');
    });
  }).on("mouseleave", function() {
    var _this = this;
    setTimeout(function() {
      if (!$(".popover:hover").length) {
        $(_this).popover("hide");
      }
    }, 300);
  });
_x000D_
<!DOCTYPE html>
<html>

<head>
  <link data-require="bootstrap-css@*" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
  <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.2.0" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.js"></script>

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

</head>

<body>
  <h2 class='text-primary'>Another Great "KISS" Bootstrap Popover example!</h2>
  <p class='text-muted'>KISS = Keep It Simple S....</p>

  <p class='text-primary'>Goal:</p>
  <ul>
    <li>Open popover on hover event for the popover button</li>
    <li>Keep popover open when hovering over the popover box</li>
    <li>Close popover on mouseleave for either the popover button, or the popover box.</li>
  </ul>

  <button type="button" class="btn btn-danger pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    HOVER OVER ME
    </button>
  <br><br>
  <button type="button" class="btn btn-info pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    HOVER OVER ME... Again!
    </button><br><br>
  <button type="button" class="btn btn-success pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    Okay one more time... !
    </button>
  <br><br>
  <p class='text-info'>Hope that helps you... Drove me crazy for a while</p>
  <script src="script.js"></script>
</body>

</html>
_x000D_
_x000D_
_x000D_

Process.start: how to get the output?

How to launch a process (such as a bat file, perl script, console program) and have its standard output displayed on a windows form:

processCaller = new ProcessCaller(this);
//processCaller.FileName = @"..\..\hello.bat";
processCaller.FileName = @"commandline.exe";
processCaller.Arguments = "";
processCaller.StdErrReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.StdOutReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.Completed += new EventHandler(processCompletedOrCanceled);
processCaller.Cancelled += new EventHandler(processCompletedOrCanceled);
// processCaller.Failed += no event handler for this one, yet.

this.richTextBox1.Text = "Started function.  Please stand by.." + Environment.NewLine;

// the following function starts a process and returns immediately,
// thus allowing the form to stay responsive.
processCaller.Start();    

You can find ProcessCaller on this link: Launching a process and displaying its standard output

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

Maven compile: package does not exist

You do not include a <scope> tag in your dependency. If you add it, your dependency becomes something like:

<dependency>
     <groupId>org.openrdf.sesame</groupId>
     <artifactId>sesame-runtime</artifactId>
     <version>2.7.2</version>
     <scope> ... </scope>
</dependency>

The "scope" tag tells maven at which stage of the build your dependency is needed. Examples for the values to put inside are "test", "provided" or "runtime" (omit the quotes in your pom). I do not know your dependency so I cannot tell you what value to choose. Please consult the Maven documentation and the documentation of your dependency.

How to split a string after specific character in SQL Server and update this value to specific column

Please find the below query also split the string with delimeter.

Select Substring(@String1,0,CharIndex(@delimeter,@String1))

Clean out Eclipse workspace metadata

In some cases, I could prevent Eclipse from crashing during startup by deleting a .snap file in your workspace meta-data (.metadata/.plugins/org.eclipse.core.resources/.snap).

See also https://bugs.eclipse.org/bugs/show_bug.cgi?id=149121 (the bug has been closed, but happened to me recently)

How do I remove an array item in TypeScript?

You can use the splice method on an array to remove the elements.

for example if you have an array with the name arr use the following:

arr.splice(2, 1);

so here the element with index 2 will be the starting point and the argument 2 will determine how many elements to be deleted.

If you want to delete the last element of the array named arr then do this:

arr.splice(arr.length-1, 1);

This will return arr with the last element deleted.

Example:

var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]

Run a Python script from another Python script, passing in arguments

This is inherently the wrong thing to do. If you are running a Python script from another Python script, you should communicate through Python instead of through the OS:

import script1

In an ideal world, you will be able to call a function inside script1 directly:

for i in range(whatever):
    script1.some_function(i)

If necessary, you can hack sys.argv. There's a neat way of doing this using a context manager to ensure that you don't make any permanent changes.

import contextlib
@contextlib.contextmanager
def redirect_argv(num):
    sys._argv = sys.argv[:]
    sys.argv=[str(num)]
    yield
    sys.argv = sys._argv

with redirect_argv(1):
    print(sys.argv)

I think this is preferable to passing all your data to the OS and back; that's just silly.

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

C# Generics and Type Checking

By default know there is not a great way. Awhile back I got frustrated with this and wrote a little utility class that helped out a bit and made the syntax a bit cleaner. Essentially it turns the code into

TypeSwitcher.Do(clause[0],
  TypeSwitch.Case<int>(x => ...),  // x is an int
  TypeSwitch.Case<decimal>(d => ...), // d is a decimal 
  TypeSwitch.Case<string>(s => ...)); // s is a string

Full blog post and details on the implementation are available here

jquery mobile background image

With JQM 1.4.2 this one works for me (Change theme to the used one):

.ui-page-theme-b, .ui-page-theme-b .ui-panel-wrapper {
    background: transparent url(../img/xxx) !important;
    background-repeat:repeat !important;
}

How to use the 'replace' feature for custom AngularJS directives?

replace:true is Deprecated

From the Docs:

replace ([DEPRECATED!], will be removed in next major release - i.e. v2.0)

specify what the template should replace. Defaults to false.

  • true - the template will replace the directive's element.
  • false - the template will replace the contents of the directive's element.

-- AngularJS Comprehensive Directive API

From GitHub:

Caitp-- It's deprecated because there are known, very silly problems with replace: true, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".

-- AngularJS Issue #7636


Update

Note: replace: true is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.

Issues with replace: true

For more information, see

Initialize a vector array of strings

 const char* args[] = {"01", "02", "03", "04"};
 std::vector<std::string> v(args, args + 4);

And in C++0x, you can take advantage of std::initializer_list<>:

http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists

How to save a pandas DataFrame table as a png

There is actually a python library called dataframe_image Just do a

pip install dataframe_image

Do the imports

import pandas as pd
import numpy as np
import dataframe_image as dfi
df = pd.DataFrame(np.random.randn(6, 6), columns=list('ABCDEF'))

and style your table if you want by:

df_styled = df.style.background_gradient() #adding a gradient based on values in cell

and finally:

dfi.export(df_styled,"mytable.png")

Recommended add-ons/plugins for Microsoft Visual Studio

Sonic File Finder for when you have loads of files in your solutions and searching for them in the solution explorer becomes a pain in the wrist.

You might also find DPack interesting. Several tools and enhancements rolled into one neat package.

How to resolve git's "not something we can merge" error

This answer is not related to the above question, but I faced a similar issue, and maybe this will be useful to someone. I am trying to merge my feature branch to master like below:

$ git merge fix-load

for this got the following error message:

merge: fix-load - not something we can merge

I looked into above all solutions, but not none of the worked.

Finally, I realized the issue cause is a spelling mistake on my branch name (actually, the merge branch name is fix-loads).

How to read line by line of a text area HTML tag

A simple regex should be efficent to check your textarea:

/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

Adding my two cents, based on a performance issue I observed.

If simple queries are getting parellelized unnecessarily, it can bring more problems than solving one. However, before adding MAXDOP into the query as "knee-jerk" fix, there are some server settings to check.

In Jeremiah Peschka - Five SQL Server Settings to Change, MAXDOP and "COST THRESHOLD FOR PARALLELISM" (CTFP) are mentioned as important settings to check.

Note: Paul White mentioned max server memory aslo as a setting to check, in a response to Performance problem after migration from SQL Server 2005 to 2012. A good kb article to read is Using large amounts of memory can result in an inefficient plan in SQL Server

Jonathan Kehayias - Tuning ‘cost threshold for parallelism’ from the Plan Cache helps to find out good value for CTFP.

Why is cost threshold for parallelism ignored?

Aaron Bertrand - Six reasons you should be nervous about parallelism has a discussion about some scenario where MAXDOP is the solution.

Parallelism-Inhibiting Components are mentioned in Paul White - Forcing a Parallel Query Execution Plan

How to place the "table" at the middle of the webpage?

The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.

That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!

<style>
  html, body {
    height: 100%;
  }
  #tableContainer-1 {
    height: 100%;
    width: 100%;
    display: table;
  }
  #tableContainer-2 {
    vertical-align: middle;
    display: table-cell;
    height: 100%;
  }
  #myTable {
    margin: 0 auto;
  }
</style>
<div id="tableContainer-1">
  <div id="tableContainer-2">
    <table id="myTable" border>
      <tr><td>Name</td><td>J W BUSH</td></tr>
      <tr><td>Proficiency</td><td>PHP</td></tr>
      <tr><td>Company</td><td>BLAH BLAH</td></tr>
    </table>
  </div>
</div>

Convert InputStream to BufferedReader

A BufferedReader constructor takes a reader as argument, not an InputStream. You should first create a Reader from your stream, like so:

Reader reader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(reader);

Preferrably, you also provide a Charset or character encoding name to the StreamReader constructor. Since a stream just provides bytes, converting these to text means the encoding must be known. If you don't specify it, the system default is assumed.

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:

  1. The fd is already closed somewhere.
  2. The fd has a wrong value, which is inconsistent with the value obtained from socket() api

How can I use xargs to copy files that have spaces and quotes in their names?

I ran into the same problem. Here's how I solved it:

find . -name '*FoooBar*' | sed 's/.*/"&"/' | xargs cp ~/foo/bar

I used sed to substitute each line of input with the same line, but surrounded by double quotes. From the sed man page, "...An ampersand (``&'') appearing in the replacement is replaced by the string matching the RE..." -- in this case, .*, the entire line.

This solves the xargs: unterminated quote error.

App.Config Transformation for projects which are not Web Projects in Visual Studio?

This works now with the Visual Studio AddIn treated in this article: SlowCheetah - Web.config Transformation Syntax now generalized for any XML configuration file.

You can right-click on your web.config and click "Add Config Transforms." When you do this, you'll get a web.debug.config and a web.release.config. You can make a web.whatever.config if you like, as long as the name lines up with a configuration profile. These files are just the changes you want made, not a complete copy of your web.config.

You might think you'd want to use XSLT to transform a web.config, but while they feels intuitively right it's actually very verbose.

Here's two transforms, one using XSLT and the same one using the XML Document Transform syntax/namespace. As with all things there's multiple ways in XSLT to do this, but you get the general idea. XSLT is a generalized tree transformation language, while this deployment one is optimized for a specific subset of common scenarios. But, the cool part is that each XDT transform is a .NET plugin, so you can make your own.

<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="@*|node()">
  <xsl:copy>           
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="/configuration/appSettings">
  <xsl:copy>
    <xsl:apply-templates select="node()|@*"/>
    <xsl:element name="add">
      <xsl:attribute name="key">NewSetting</xsl:attribute>
      <xsl:attribute name="value">New Setting Value</xsl:attribute>
    </xsl:element>
  </xsl:copy>
</xsl:template>
</xsl:stylesheet>

Or the same thing via the deployment transform:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
   <appSettings>
      <add name="NewSetting" value="New Setting Value" xdt:Transform="Insert"/>
   </appSettings>
</configuration>

Using IF ELSE statement based on Count to execute different Insert statements

There are many, many ways to code this, but here is one possible way. I'm assuming MS SQL

We'll start by getting row count (Another Quick Example) and then do if/else

-- Let's get our row count and assign it to a var that will be used
--    in our if stmt 
DECLARE @HasExistingRows int -- I'm assuming it can fit into an int
SELECT @HasExistingRows = Count(*) 
   ELSE 0 -- false
FROM
   INCIDENTS
WHERE {Your Criteria}
GROUP BY {Required Grouping}

Now we can do the If / Else Logic MSDN Docs

-- IF / Else / Begin / END Syntax
IF @HasExistingRows = 0 -- No Existing Rows
   BEGIN
      {Insert Logic for No Existing Rows}
   END
ELSE -- existing rows are found
   BEGIN
      {Insert logic for existing rows}
   END

Another faster way (inspired by Mahmoud Gamal's comment):

Forget the whole variable creation / assignment - look up "EXISTS" - MSDN Docs 2.

IF EXISTS ({SELECT Query})
   BEGIN
      {INSERT Version 1}
   END
ELSE
   BEGIN
      {INSERT version 2}
   END

Printing Exception Message in java

The output looks correct to me:

Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1

I think Invalid Javascript code: .. is the start of the exception message.

Normally the stacktrace isn't returned with the message:

try {
    throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
    System.out.println(e.getMessage()); // prints "hu?"
}

So maybe the code you are calling catches an exception and rethrows a ScriptException. In this case maybe e.getCause().getMessage() can help you.

Implementation difference between Aggregation and Composition in Java

First we must talk about what actually the difference between Aggregation and Composition is to be on the same page.

Aggregation is an association where the associated entity may exist independent of the association. For example, a Person may be associated to an Organisation but he/she may have independent existence in the system.

whereas

Composition refers to a situation when one of the associated entities is strongly related to the other and cannot exist without the other's existence. In fact the identity of that entity is always associated with the identity of the other object. For example, wheels in a car.

Now, aggregation can simply be achieved by holding a property of one entity in another as below:

class Person {
    Organisation worksFor;
}

class Organisation {
    String name;
}

class Main {
    public static void main(String args[]) {

        //Create Person object independently
        Person p = new Person();

        //Create the Organisation independently
        Organisation o = new Organisation();
        o.name = "XYZ Corporation";

        /*
          At this point both person and organisation 
          exist without any association  
        */
        p.worksFor = o;

    }
}

For Composition it is necessary that the dependent object is always created with the identity of its associated object. You can use an inner class for the same.

class Car {
    class Wheel {
        Car associatedWith;
    }
}

class Main {
    public static void main() {
        //Create Car object independently
        Car car = new Car();

        //Cannot create Wheel instance independently
        //need a reference of a Car for the same.
        Car.Wheel wheel = car.new Wheel();
    }
}

Please note that the same use case may fall under aggregation/composition depending on the application scenario. For example, the Person-Organisation case may become composition if you are developing an application for people working in some organisation and the reference to organisation is must for sign up. Similarly, if you are maintaining inventory for parts of a Car, Car-Wheel relationship can be aggregation.

String formatting: % vs. .format vs. string literal

Python 3.6.7 comparative:

#!/usr/bin/env python
import timeit

def time_it(fn):
    """
    Measure time of execution of a function
    """
    def wrapper(*args, **kwargs):
        t0 = timeit.default_timer()
        fn(*args, **kwargs)
        t1 = timeit.default_timer()
        print("{0:.10f} seconds".format(t1 - t0))
    return wrapper


@time_it
def new_new_format(s):
    print("new_new_format:", f"{s[0]} {s[1]} {s[2]} {s[3]} {s[4]}")


@time_it
def new_format(s):
    print("new_format:", "{0} {1} {2} {3} {4}".format(*s))


@time_it
def old_format(s):
    print("old_format:", "%s %s %s %s %s" % s)


def main():
    samples = (("uno", "dos", "tres", "cuatro", "cinco"), (1,2,3,4,5), (1.1, 2.1, 3.1, 4.1, 5.1), ("uno", 2, 3.14, "cuatro", 5.5),) 
    for s in samples:
        new_new_format(s)
        new_format(s)
        old_format(s)
        print("-----")


if __name__ == '__main__':
    main()

Output:

new_new_format: uno dos tres cuatro cinco
0.0000170280 seconds
new_format: uno dos tres cuatro cinco
0.0000046750 seconds
old_format: uno dos tres cuatro cinco
0.0000034820 seconds
-----
new_new_format: 1 2 3 4 5
0.0000043980 seconds
new_format: 1 2 3 4 5
0.0000062590 seconds
old_format: 1 2 3 4 5
0.0000041730 seconds
-----
new_new_format: 1.1 2.1 3.1 4.1 5.1
0.0000092650 seconds
new_format: 1.1 2.1 3.1 4.1 5.1
0.0000055340 seconds
old_format: 1.1 2.1 3.1 4.1 5.1
0.0000052130 seconds
-----
new_new_format: uno 2 3.14 cuatro 5.5
0.0000053380 seconds
new_format: uno 2 3.14 cuatro 5.5
0.0000047570 seconds
old_format: uno 2 3.14 cuatro 5.5
0.0000045320 seconds
-----

How to get item count from DynamoDB?

Similar to Java in PHP only set Select PARAMETER with value 'COUNT'

$result = $aws->query(array(
 'TableName' => 'game_table',
 'IndexName' => 'week-point-index',
 'KeyConditions' => array(
    'week' => array(
        'ComparisonOperator' => 'EQ',
        'AttributeValueList' => array(
            array(Type::STRING => $week)
        )
    ),
    'point' => array(
        'ComparisonOperator' => 'GE',
        'AttributeValueList' => array(
            array(Type::NUMBER => $my_point)
        )
    )
 ),
 'Select' => 'COUNT'
));

and acces it just like this :

echo $result['Count'];

but as Saumitra mentioned above be careful with resultsets largers than 1 MB, in that case use LastEvaluatedKey til it returns null to get the last updated count value.

PHP add elements to multidimensional array with array_push

if you want to add the data in the increment order inside your associative array you can do this:

$newdata =  array (
      'wpseo_title' => 'test',
      'wpseo_desc' => 'test',
      'wpseo_metakey' => 'test'
    );

// for recipe

$md_array["recipe_type"][] = $newdata;

//for cuisine

 $md_array["cuisine"][] = $newdata;

this will get added to the recipe or cuisine depending on what was the last index.

Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this

array_push($md_array["cuisine"],$newdata);

Set up a scheduled job?

after the part of code,I can write anything just like my views.py :)

#######################################
import os,sys
sys.path.append('/home/administrator/development/store')
os.environ['DJANGO_SETTINGS_MODULE']='store.settings'
from django.core.management impor setup_environ
from store import settings
setup_environ(settings)
#######################################

from http://www.cotellese.net/2007/09/27/running-external-scripts-against-django-models/

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

I assume the question is already answered. If above solution doesn't help in solving the issue then can use below to solve the issue.

The issue occurs if sometimes your maven user settings is not reflecting correct settings.xml file.

To update the settings file go to Windows > Preferences > Maven > User Settings and update the settings.xml to it correct location.

Once this is doen re-build the project, these should solve the issue. Thanks.

JQuery, select first row of table

Ok so if an image in a table is clicked you want the data of the first row of the table this image is in.

//image click stuff here {
$(this). // our image
closest('table'). // Go upwards through our parents untill we hit the table
children('tr:first'); // Select the first row we find

var $row = $(this).closest('table').children('tr:first');

parent() will only get the direct parent, closest should do what we want here. From jQuery docs: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

How do I get textual contents from BLOB in Oracle SQL

Barn's answer worked for me with modification because my column is not compressed. The quick and dirty solution:

select * from my_table
where dbms_lob.instr(my_UNcompressed_blob, utl_raw.cast_to_raw('MY_SEARCH_STRING'))>0;

How can I delete a newline if it is the last character in a file?

If you want to do it right, you need something like this:

use autodie qw(open sysseek sysread truncate);

my $file = shift;
open my $fh, '+>>', $file;
my $pos = tell $fh;
sysseek $fh, $pos - 1, 0;
sysread $fh, my $buf, 1 or die 'No data to read?';

if($buf eq "\n"){
    truncate $fh, $pos - 1;
}

We open the file for reading and appending; opening for appending means that we are already seeked to the end of the file. We then get the numerical position of the end of the file with tell. We use that number to seek back one character, and then we read that one character. If it's a newline, we truncate the file to the character before that newline, otherwise, we do nothing.

This runs in constant time and constant space for any input, and doesn't require any more disk space, either.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

This could actually do it without having to write code:

In your catch block, add a break point at the following line of code:

catch (Exception exception)
{

}

Now if you hover on exception or add it to the Watch and then navigate into the exception details as shown below; you will see which particular column(s) is/ are causing the problem as this error usually occurs when a table-constraint is violated..

enter image description here

Large image

Vue.js toggle class on click

If you don't need to access the toggle from outside the element, this code works without a data variable:

<a @click="e => e.target.classList.toggle('active')"></a>

How to sum all column values in multi-dimensional array?

For those who landed here and are searching for a solution that merges N arrays AND also sums the values of identical keys found in the N arrays, I've written this function that works recursively as well. (See: https://gist.github.com/Nickology/f700e319cbafab5eaedc)

Example:

$a = array( "A" => "bob", "sum" => 10, "C" => array("x","y","z" => 50) );
$b = array( "A" => "max", "sum" => 12, "C" => array("x","y","z" => 45) );
$c = array( "A" => "tom", "sum" =>  8, "C" => array("x","y","z" => 50, "w" => 1) );

print_r(array_merge_recursive_numeric($a,$b,$c));

Will result in:

Array
(
    [A] => tom
    [sum] => 30
    [C] => Array
        (
            [0] => x
            [1] => y
            [z] => 145
            [w] => 1
        )

)

Here's the code:

<?php 
/**
 * array_merge_recursive_numeric function.  Merges N arrays into one array AND sums the values of identical keys.
 * WARNING: If keys have values of different types, the latter values replace the previous ones.
 * 
 * Source: https://gist.github.com/Nickology/f700e319cbafab5eaedc
 * @params N arrays (all parameters must be arrays)
 * @author Nick Jouannem <[email protected]>
 * @access public
 * @return void
 */
function array_merge_recursive_numeric() {

    // Gather all arrays
    $arrays = func_get_args();

    // If there's only one array, it's already merged
    if (count($arrays)==1) {
        return $arrays[0];
    }

    // Remove any items in $arrays that are NOT arrays
    foreach($arrays as $key => $array) {
        if (!is_array($array)) {
            unset($arrays[$key]);
        }
    }

    // We start by setting the first array as our final array.
    // We will merge all other arrays with this one.
    $final = array_shift($arrays);

    foreach($arrays as $b) {

        foreach($final as $key => $value) {

            // If $key does not exist in $b, then it is unique and can be safely merged
            if (!isset($b[$key])) {

                $final[$key] = $value;

            } else {

                // If $key is present in $b, then we need to merge and sum numeric values in both
                if ( is_numeric($value) && is_numeric($b[$key]) ) {
                    // If both values for these keys are numeric, we sum them
                    $final[$key] = $value + $b[$key];
                } else if (is_array($value) && is_array($b[$key])) {
                    // If both values are arrays, we recursively call ourself
                    $final[$key] = array_merge_recursive_numeric($value, $b[$key]);
                } else {
                    // If both keys exist but differ in type, then we cannot merge them.
                    // In this scenario, we will $b's value for $key is used
                    $final[$key] = $b[$key];
                }

            }

        }

        // Finally, we need to merge any keys that exist only in $b
        foreach($b as $key => $value) {
            if (!isset($final[$key])) {
                $final[$key] = $value;
            }
        }

    }

    return $final;

}

?>

iPhone UITextField - Change placeholder text color

Swift version. Probably it would help someone.

class TextField: UITextField {
   override var placeholder: String? {
        didSet {
            let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
            self.attributedPlaceholder = placeholderString
        }
    }
}

Model Binding to a List MVC 4

A clean solution could be create a generic class to handle the list, so you don't need to create a different class each time you need it.

public class ListModel<T>
{
    public List<T> Items { get; set; }

    public ListModel(List<T> list) {
        Items = list;
    }
}

and when you return the View you just need to simply do:

List<customClass> ListOfCustomClass = new List<customClass>();
//Do as needed...
return View(new ListModel<customClass>(ListOfCustomClass));

then define the list in the model:

@model ListModel<customClass>

and ready to go:

@foreach(var element in Model.Items) {
  //do as needed...
}

How to get the android Path string to a file on Assets folder?

AFAIK the files in the assets directory don't get unpacked. Instead, they are read directly from the APK (ZIP) file.

So, you really can't make stuff that expects a file accept an asset 'file'.

Instead, you'll have to extract the asset and write it to a seperate file, like Dumitru suggests:

  File f = new File(getCacheDir()+"/m1.map");
  if (!f.exists()) try {

    InputStream is = getAssets().open("m1.map");
    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();


    FileOutputStream fos = new FileOutputStream(f);
    fos.write(buffer);
    fos.close();
  } catch (Exception e) { throw new RuntimeException(e); }

  mapView.setMapFile(f.getPath());

Best way to make WPF ListView/GridView sort on column-header clicking?

I made an adaptation of the Microsoft way, where I override the ListView control to make a SortableListView:

public partial class SortableListView : ListView
    {        
        private GridViewColumnHeader lastHeaderClicked = null;
        private ListSortDirection lastDirection = ListSortDirection.Ascending;       

        public void GridViewColumnHeaderClicked(GridViewColumnHeader clickedHeader)
        {
            ListSortDirection direction;

            if (clickedHeader != null)
            {
                if (clickedHeader.Role != GridViewColumnHeaderRole.Padding)
                {
                    if (clickedHeader != lastHeaderClicked)
                    {
                        direction = ListSortDirection.Ascending;
                    }
                    else
                    {
                        if (lastDirection == ListSortDirection.Ascending)
                        {
                            direction = ListSortDirection.Descending;
                        }
                        else
                        {
                            direction = ListSortDirection.Ascending;
                        }
                    }

                    string sortString = ((Binding)clickedHeader.Column.DisplayMemberBinding).Path.Path;

                    Sort(sortString, direction);

                    lastHeaderClicked = clickedHeader;
                    lastDirection = direction;
                }
            }
        }

        private void Sort(string sortBy, ListSortDirection direction)
        {
            ICollectionView dataView = CollectionViewSource.GetDefaultView(this.ItemsSource != null ? this.ItemsSource : this.Items);

            dataView.SortDescriptions.Clear();
            SortDescription sD = new SortDescription(sortBy, direction);
            dataView.SortDescriptions.Add(sD);
            dataView.Refresh();
        }
    }

The line ((Binding)clickedHeader.Column.DisplayMemberBinding).Path.Path bit handles the cases where your column names are not the same as their binding paths, which the Microsoft method does not do.

I wanted to intercept the GridViewColumnHeader.Click event so that I wouldn't have to think about it anymore, but I couldn't find a way to to do. As a result I add the following in XAML for every SortableListView:

GridViewColumnHeader.Click="SortableListViewColumnHeaderClicked"

And then on any Window that contains any number of SortableListViews, just add the following code:

private void SortableListViewColumnHeaderClicked(object sender, RoutedEventArgs e)
        {
            ((Controls.SortableListView)sender).GridViewColumnHeaderClicked(e.OriginalSource as GridViewColumnHeader);
        }

Where Controls is just the XAML ID for the namespace in which you made the SortableListView control.

So, this does prevent code duplication on the sorting side, you just need to remember to handle the event as above.

Count all duplicates of each value

SELECT   col,
         COUNT(dupe_col) AS dupe_cnt
FROM     TABLE
GROUP BY col
HAVING   COUNT(dupe_col) > 1
ORDER BY COUNT(dupe_col) DESC

Does List<T> guarantee insertion order?

The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.

According to MSDN:

...List "Represents a strongly typed list of objects that can be accessed by index."

The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.

You might be getting odd results from your code if you're moving the item later in the list, as your Remove() will move all of the other items down one place before the call to Insert().

Can you boil your code down to something small enough to post?

Opening database file from within SQLite command-line shell

I wonder why no one was able to get what the question actually asked. It stated What is the command within the SQLite shell tool to specify a database file?

A sqlite db is on my hard disk E:\ABCD\efg\mydb.db. How do I access it with sqlite3 command line interface? .open E:\ABCD\efg\mydb.db does not work. This is what question asked.

I found the best way to do the work is

  • copy-paste all your db files in 1 directory (say E:\ABCD\efg\mydbs)
  • switch to that directory in your command line
  • now open sqlite3 and then .open mydb.db

This way you can do the join operation on different tables belonging to different databases as well.

Binding value to input in Angular JS

{{widget.title}} Try this it will work

Python: URLError: <urlopen error [Errno 10060]

This is because of the proxy settings. I also had the same problem, under which I could not use any of the modules which were fetching data from the internet. There are simple steps to follow:
1. open the control panel
2. open internet options
3. under connection tab open LAN settings
4. go to advance settings and unmark everything, delete every proxy in there. Or u can just unmark the checkbox in proxy server this will also do the same
5. save all the settings by clicking ok.
you are done. try to run the programme again, it must work it worked for me at least

How to extract an assembly from the GAC?

From a Powershell script, you can try this. I only had a single version of the assembly in the GAC so this worked just fine.

cd "c:\Windows\Microsoft.NET\assembly\GAC_MSIL\"
Get-ChildItem assemblypath -Recurse -Include *.dll |  Copy-Item -Destination "c:\folder to copy to"

where the assembly path can use wildcards.

What do Clustered and Non clustered index actually mean?

With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.

With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indices, although each new index will increase the time it takes to write new records.

It is generally faster to read from a clustered index if you want to get back all the columns. You do not have to go first to the index and then to the table.

Writing to a table with a clustered index can be slower, if there is a need to rearrange the data.

How to initialize List<String> object in Java?

Depending on what kind of List you want to use, something like

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

should get you going.

List is the interface, ArrayList is one implementation of the List interface. More implementations that may better suit your needs can be found by reading the JavaDocs of the List interface.

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

For those that are not overflowing but hiding by negative margin:

$('#element').height() + -parseInt($('#element').css("margin-top"));

(ugly but only one that works so far)

How to sort List<Integer>?

You are using Lists, concrete ArrayList. ArrayList also implements Collection interface. Collection interface has sort method which is used to sort the elements present in the specified list of Collection in ascending order. This will be the quickest and possibly the best way for your case.

Sorting a list in ascending order can be performed as default operation on this way:

Collections.sort(list);

Sorting a list in descending order can be performed on this way:

Collections.reverse(list);

According to these facts, your solution has to be written like this:

public class tes 
{
    public static void main(String args[])
    {
        List<Integer> lList = new ArrayList<Integer>();
        lList.add(4);
        lList.add(1);
        lList.add(7);
        lList.add(2);
        lList.add(9);
        lList.add(1);
        lList.add(5);

        Collections.sort(lList);
        for(int i=0; i<lList.size();i++ )
        {
            System.out.println(lList.get(i));
        }
     }
}

More about Collections you can read here.

How to move an entire div element up x pixels?

you can also do this

margin-top:-30px; 
min-height:40px;

this "help" to stop the div yanking everything up a bit.

Fatal error: Call to undefined function curl_init()

Experienced this on ubuntu 16.04 running PHP 7.1.14. To resolve,first put this in a script and execute. It will return true if curl is installed and enabled,otherwise, it will return false.

<?php
    var_dump(extension_loaded('curl'));
?>

If it returns false, run

sudo apt-get install php7.1-curl

And finally,

sudo service apache2 restart

After the restart, the script will return true and hopefully, your error should be resolved.

How can I make space between two buttons in same div?

The easiest way in most situations is margin.

Where you can do :

button{
  margin: 13px 12px 12px 10px;
}

OR

button{
  margin: 13px;
}

How to delete from select in MySQL?

you can use inner join :

DELETE 
    ps 
FROM 
    posts ps INNER JOIN 
         (SELECT 
           distinct id 
         FROM 
             posts 
         GROUP BY id  
      HAVING COUNT(id) > 1 ) dubids on dubids.id = ps.id  

How can I select from list of values in SQL Server

Available only on SQL Server 2008 and over is row-constructor in this form:
You could use

SELECT DISTINCT * FROM (VALUES (1), (1), (1), (2), (5), (1), (6)) AS X(a)

Many wrote about, among them:

CSS Animation and Display None

How do I have a div not take up space until it is timed to come in (using CSS for the timing.)

Here is my solution to the same problem.

Moreover I have an onclick on the last frame loading another slideshow, and it must not be clickable until the last frame is visible.

Basically my solution is to keep the div 1 pixel high using a scale(0.001), zooming it when I need it. If you don't like the zoom effect you can restore the opacity to 1 after zooming the slide.

#Slide_TheEnd {

    -webkit-animation-delay: 240s;
    animation-delay: 240s;

    -moz-animation-timing-function: linear;
    -webkit-animation-timing-function: linear;
    animation-timing-function: linear;

    -moz-animation-duration: 20s;
    -webkit-animation-duration: 20s;
    animation-duration: 20s;

    -moz-animation-name: Slide_TheEnd;
    -webkit-animation-name: Slide_TheEnd;
    animation-name: Slide_TheEnd;

    -moz-animation-iteration-count: 1;
    -webkit-animation-iteration-count: 1;
    animation-iteration-count: 1;

    -moz-animation-direction: normal;
    -webkit-animation-direction: normal;
    animation-direction: normal;

    -moz-animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;

    transform: scale(0.001);
    background: #cf0;
    text-align: center;
    font-size: 10vh;
    opacity: 0;
}

@-moz-keyframes Slide_TheEnd {
    0% { opacity: 0;  transform: scale(0.001); }
    10% { opacity: 1; transform: scale(1); }
    95% { opacity: 1; transform: scale(1); }
    100% { opacity: 0;  transform: scale(0.001); }
}

Other keyframes are removed for the sake of bytes. Please disregard the odd coding, it is made by a php script picking values from an array and str_replacing a template: I'm too lazy to retype everything for every proprietary prefix on a 100+ divs slideshow.

How to call Stored Procedure in Entity Framework 6 (Code-First)?

object[] xparams = {
            new SqlParameter("@ParametterWithNummvalue", DBNull.Value),
            new SqlParameter("@In_Parameter", "Value"),
            new SqlParameter("@Out_Parameter", SqlDbType.Int) {Direction = ParameterDirection.Output}};

        YourDbContext.Database.ExecuteSqlCommand("exec StoreProcedure_Name @ParametterWithNummvalue, @In_Parameter, @Out_Parameter", xparams);
        var ReturnValue = ((SqlParameter)params[2]).Value;  

PuTTY Connection Manager download?

I've found version 0.7.1 Alpha of PuTTY Connection Manager to be the most stable (it was previously hidden on the forums). It's available from PuTTY Connection Manager – Website Down.

Append an int to a std::string

You cannot cast an int to a char* to get a string. Try this:

std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();

stringstream reference

Is it bad to have my virtualenv directory inside my git repository?

It's not a good idea to include any environment-dependent component or setting in your repos as one of the key aspects of using a repo, is perhaps, sharing it with other developers. Here is how I would setup my development environment on a Windows PC (say, Win10).

  1. Open Pycharm and on the first page, choose to check out the project from your Source Control System (in my case, I am using github)

  2. In Pycharm, navigate to settings and choose "Project Interpreter" and choose the option to add a new virtual environment , you can call it "venv".

  3. Choose the base python interpreter which is located at C:\Users{user}\AppData\Local\Programs\Python\Python36 (make sure you choose the appropriate version of Python based on what you have installed)

  4. Note that Pycharm will create the new virtual environment and copy python binaries and required libraries under your venv folder inside your project folder.

  5. Let Pycharm complete its scanning as it needs to rebuild/refresh your project skeleton

  6. exclude venv folder from your git interactions (add venv\ to .gitignore file in your project folder)

Bonus: If you want people to easily (well, almost easily) install all the libraries your software needs, you can use

pip freeze > requirements.txt

and put the instruction on your git so people can use the following command to download all required libraries at once.

pip install -r requirements.txt 

python setup.py uninstall

I think you can open the setup.py, locate the package name, and then ask pip to uninstall it.

Assuming the name is available in a 'METADATA' variable:

pip uninstall $(python -c "from setup import METADATA; print METADATA['name']")

Stop form from submitting , Using Jquery

A different approach could be

    <script type="text/javascript">
    function CheckData() {
    //you may want to check something here and based on that wanna return true and false from the         function.
    if(MyStuffIsokay)
     return true;//will cause form to postback to server.
    else
      return false;//will cause form Not to postback to server
    }
    </script>
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
    {
    .........
    .........
    .........
    .........
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/>
    }

Updating an object with setState in React

try this,it should work fine

this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

How do I seed a random class to avoid getting duplicate random values

You should not create a new Random instance in a loop. Try something like:

var rnd = new Random();
for(int i = 0; i < 100; ++i) 
   Console.WriteLine(rnd.Next(1, 100));

The sequence of random numbers generated by a single Random instance is supposed to be uniformly distributed. By creating a new Random instance for every random number in quick successions, you are likely to seed them with identical values and have them generate identical random numbers. Of course, in this case, the generated sequence will be far from uniform distribution.

For the sake of completeness, if you really need to reseed a Random, you'll create a new instance of Random with the new seed:

rnd = new Random(newSeed);

Retrieving a List from a java.util.stream.Stream in Java 8

To collect in a mutable list:

targetList = sourceList.stream()
                       .filter(i -> i > 100) //apply filter
                       .collect(Collectors.toList());

To collect in a immutable list:

targetList = sourceList.stream()
                       .filter(i -> i > 100) //apply filter
                       .collect(Collectors.toUnmodifiableList());

Explanation of collect from the JavaDoc:

Performs a mutable reduction operation on the elements of this stream using a Collector. A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer), allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning. If the stream is parallel, and the Collector is concurrent, and either the stream is unordered or the collector is unordered, then a concurrent reduction will be performed (see Collector for details on concurrent reduction.)

This is a terminal operation.

When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is needed for a parallel reduction.

How to create a hidden <img> in JavaScript?

You can hide an image using javascript like this:

document.images['imageName'].style.visibility = hidden;

If that isn't what you are after, you need to explain yourself more clearly.

Random alpha-numeric string in JavaScript?

Another variation of answer suggested by JAR.JAR.beans

(Math.random()*1e32).toString(36)

By changing multiplicator 1e32 you can change length of random string.

How to set DialogFragment's width and height?

Here is kotlin version

    override fun onResume() {
        super.onResume()

        val params:ViewGroup.LayoutParams = dialog.window.attributes
        params.width = LinearLayout.LayoutParams.MATCH_PARENT
        params.height = LinearLayout.LayoutParams.MATCH_PARENT
        dialog.window.attributes = params as android.view.WindowManager.LayoutParams
    }

How do I upload a file with metadata using a REST web service?

To build on ccleve's answer, if you are using superagent / express / multer, on the front end side build your multipart request doing something like this:

superagent
    .post(url)
    .accept('application/json')
    .field('myVeryRelevantJsonData', JSON.stringify({ peep: 'Peep Peep!!!' }))
    .attach('myFile', file);

cf https://visionmedia.github.io/superagent/#multipart-requests.

On the express side, whatever was passed as field will end up in req.body after doing:

app.use(express.json({ limit: '3MB' }));

Your route would include something like this:

const multerMemStorage = multer.memoryStorage();
const multerUploadToMem = multer({
  storage: multerMemStorage,
  // Also specify fileFilter, limits...
});

router.post('/myUploads',
  multerUploadToMem.single('myFile'),
  async (req, res, next) => {
    // Find back myVeryRelevantJsonData :
    logger.verbose(`Uploaded req.body=${JSON.stringify(req.body)}`);

    // If your file is text:
    const newFileText = req.file.buffer.toString();
    logger.verbose(`Uploaded text=${newFileText}`);
    return next();
  },
  ...

One thing to keep in mind though is this note from the multer doc, concerning disk storage:

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

I guess this means it would be unreliable to, say, compute the target dir/filename based on json metadata passed along the file

How do I test a single file using Jest?

At this time, I did it by using:

yarn test TestFileName.spec.js

You shouldn't put the complete path. That works for me on a Windows 10 machine.

How do I clone into a non-empty directory?

I have used this a few moments ago, requires the least potentially destructive commands:

cd existing-dir
git clone --bare repo-to-clone .git
git config --unset core.bare
git remote rm origin
git remote add origin repo-to-clone
git reset

And voilá!

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

The same problem Error while retrieving information from server. [RPC:S-5:AEC-0] was resolved after these steps:

  1. Change password of your Google account via web.
  2. Wait for a Sign-in error notification on your device.
  3. Type new password and problem should disappeared.

Actually, this helps me.

How to remove a build from itunes connect?

Dang this is hard. Here is what I did to reject/delete/replace my ios build before it was released. The app was approved how ever I found found a bug I wanted to fix before releasing

  1. I set release to "manual" and saved
  2. I tried to create and app release
  3. got an error message something like "you can only have one release at a time"
  4. where the save button was there was not an option to cancel release
  5. the version of the app is not marked "developer rejected" with a red dot

To replace the bad build I did the following

  1. if you click on the "+ version or platform" to create a new version you will not be be able to create a new iOS version
  2. you need to upload a new build
  3. in your rejected app, select the new build
  4. save
  5. submit for review

How to get primary key of table?

Here is the Primary key Column Name

SELECT k.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING(constraint_name,table_schema,table_name)
WHERE t.constraint_type='PRIMARY KEY'
  AND t.table_schema='YourDatabase'
  AND t.table_name='YourTable';

Setting a minimum/maximum character count for any character using a regular expression

If you want to set Min 1 count and no Max length,

^.{1,}$

Counting null and non-null values in a single query

usually i use this trick

select sum(case when a is null then 0 else 1 end) as count_notnull,
       sum(case when a is null then 1 else 0 end) as count_null
from tab
group by a

How to set auto increment primary key in PostgreSQL?

If you want to use numbers in a sequence, define a new sequence with something like

CREATE SEQUENCE public.your_sequence
    INCREMENT 1
    START 1
    MINVALUE 1
;

and then alter the table to use the sequence for the id:

ALTER TABLE ONLY table ALTER COLUMN id SET DEFAULT nextval('your_sequence'::regclass);

SQL use CASE statement in WHERE IN clause

No you can't use case and in like this. But you can do

SELECT * FROM Product P    
WHERE @Status='published' and P.Status IN (1,3)
or @Status='standby' and P.Status IN  (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)

BTW you can reduce that to

SELECT * FROM Product P    
WHERE @Status='standby' and P.Status IN (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)

since or P.Status IN (1,3) gives you also all records of @Status='published' and P.Status IN (1,3)

How do I set a cookie on HttpClient's HttpRequestMessage

For me the simple solution works to set cookies in HttpRequestMessage object.

protected async Task<HttpResponseMessage> SendRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
    requestMessage.Headers.Add("Cookie", $"<Cookie Name 1>=<Cookie Value 1>;<Cookie Name 2>=<Cookie Value 2>");

    return await _httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
}

How to dump a table to console?

The table.tostring metehod of metalua is actually very complete. It deals with nested tables, the indentation level is changeable, ... See https://github.com/fab13n/metalua/blob/master/src/lib/metalua/table2.lua

Returning a value even if no result

As you are looking for 1 record, (LIMIT 1) then this will work.

(SELECT field1 FROM table WHERE id = 123) 
UNION 
(SELECT 'default_value_if_no_record')
LIMIT 1;

Can be a handy way to display default values, or indicate no results found. I use it for reports.

See also http://blogs.uoregon.edu/developments/2011/03/31/add-a-header-row-to-mysql-query-results/ for a way to use this to create headers in reports.

How to get cumulative sum

select t1.id, t1.SomeNumt, SUM(t2.SomeNumt) as sum
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.SomeNumt
order by t1.id

SQL Fiddle example

Output

| ID | SOMENUMT | SUM |
-----------------------
|  1 |       10 |  10 |
|  2 |       12 |  22 |
|  3 |        3 |  25 |
|  4 |       15 |  40 |
|  5 |       23 |  63 |

Edit: this is a generalized solution that will work across most db platforms. When there is a better solution available for your specific platform (e.g., gareth's), use it!

How to open a new tab using Selenium WebDriver

To open a new tab in the existing Chrome browser using Selenium WebDriver you can use this code:

driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");        
string newTabInstance = driver.WindowHandles[driver.WindowHandles.Count-1].ToString();
driver.SwitchTo().Window(newTabInstance);
driver.Navigate().GoToUrl(url);

How to check a string for specific characters?

Quick comparison of timings in response to the post by Abbafei:

import timeit

def func1():
    phrase = 'Lucky Dog'
    return any(i in 'LD' for i in phrase)

def func2():
    phrase = 'Lucky Dog'
    if ('L' in phrase) or ('D' in phrase):
        return True
    else:
        return False

if __name__ == '__main__': 
    func1_time = timeit.timeit(func1, number=100000)
    func2_time = timeit.timeit(func2, number=100000)
    print('Func1 Time: {0}\nFunc2 Time: {1}'.format(func1_time, func2_time))

Output:

Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371

So the code is more compact with any, but faster with the conditional.


EDIT : TL;DR -- For long strings, if-then is still much faster than any!

I decided to compare the timing for a long random string based on some of the valid points raised in the comments:

# Tested in Python 2.7.14

import timeit
from string import ascii_letters
from random import choice

def create_random_string(length=1000):
    random_list = [choice(ascii_letters) for x in range(length)]
    return ''.join(random_list)

def function_using_any(phrase):
    return any(i in 'LD' for i in phrase)

def function_using_if_then(phrase):
    if ('L' in phrase) or ('D' in phrase):
        return True
    else:
        return False

if __name__ == '__main__':
    random_string = create_random_string(length=2000)
    func1_time = timeit.timeit(stmt="function_using_any(random_string)",
                               setup="from __main__ import function_using_any, random_string",
                               number=200000)
    func2_time = timeit.timeit(stmt="function_using_if_then(random_string)",
                               setup="from __main__ import function_using_if_then, random_string",
                               number=200000)
    print('Time for function using any: {0}\nTime for function using if-then: {1}'.format(func1_time, func2_time))

Output:

Time for function using any: 0.1342546
Time for function using if-then: 0.0201827

If-then is almost an order of magnitude faster than any!

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

This is the shortest:

echo '<pre>',print_r($arr,1),'</pre>';

The closing tag can also be omitted.

How to use random in BATCH script?

If you will divide by some large value you will get a huge amount of duplicates one after other. What you need to do is to take modulo of the %RANDOM% value:

@echo off
REM 
SET maxvalue=10
SET minvalue=1

SETLOCAL 
SET /A tmpRandom=((%RANDOM%)%%(%maxvalue%))+(%minvalue%)
echo "Tmp random: %tmpRandom%"
echo "Random:  %RANDOM%"
ENDLOCAL

how do you view macro code in access?

This did the trick for me: I was able to find which macro called a particular query. Incidentally, the reason someone who does know how to code in VBA would want to write something like this is when they've inherited something macro-ish written by someone who doesn't know how to code in VBA.

Function utlFindQueryInMacro
       ( strMacroNameLike As String
       , strQueryName As String
       ) As String 
    ' (c) 2012 Doug Den Hoed 
    ' NOTE: requires reference to Microsoft Scripting Library
    Dim varItem As Variant
    Dim strMacroName As String
    Dim oFSO As New FileSystemObject
    Dim oFS   
    Dim strFileContents As String
    Dim strMacroNames As String
    For Each varItem In CurrentProject.AllMacros
    strMacroName = varItem.Name
    If Len(strMacroName) = 0 _
    Or InStr(strMacroName, strMacroNameLike) > 0 Then
        'Debug.Print "*** MACRO *** "; strMacroName
        Application.SaveAsText acMacro, strMacroName, "c:\temp.txt"
        Set oFS = oFSO.OpenTextFile("c:\temp.txt")
        strFileContents = ""
        Do Until oFS.AtEndOfStream
            strFileContents = strFileContents & oFS.ReadLine
        Loop
        Set oFS = Nothing
        Set oFSO = Nothing
        Kill "c:\temp.txt"
        'Debug.Print strFileContents
        If InStr(strFileContents, strQueryName)     0 Then
            strMacroNames = strMacroNames & strMacroName & ", "
        End If
    End If
    Next varItem
    MsgBox strMacroNames
    utlFindQueryInMacro = strMacroNames
 End Function

Python 3 print without parenthesis

I finally figured out the regex to change these all in old Python2 example scripts. Otherwise use 2to3.py.

Try it out on Regexr.com, doesn't work in NP++(?):

find:     (?<=print)( ')(.*)(')
replace: ('$2')

for variables:

(?<=print)( )(.*)(\n)
('$2')\n

for label and variable:

(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n

How to compare binary files to check if they are the same?

For finding flash memory defects, I had to write this script which shows all 1K blocks which contain differences (not only the first one as cmp -b does)

#!/bin/sh

f1=testinput.dat
f2=testoutput.dat

size=$(stat -c%s $f1)
i=0
while [ $i -lt $size ]; do
  if ! r="`cmp -n 1024 -i $i -b $f1 $f2`"; then
    printf "%8x: %s\n" $i "$r"
  fi
  i=$(expr $i + 1024)
done

Output:

   2d400: testinput.dat testoutput.dat differ: byte 3, line 1 is 200 M-^@ 240 M- 
   2dc00: testinput.dat testoutput.dat differ: byte 8, line 1 is 327 M-W 127 W
   4d000: testinput.dat testoutput.dat differ: byte 37, line 1 is 270 M-8 260 M-0
   4d400: testinput.dat testoutput.dat differ: byte 19, line 1 is  46 &  44 $

Disclaimer: I hacked the script in 5 min. It doesn't support command line arguments nor does it support spaces in file names

Why does z-index not work?

Your elements need to have a position attribute. (e.g. absolute, relative, fixed) or z-index won't work.

Remove and Replace Printed items

import sys
import time

a = 0  
for x in range (0,3):  
    a = a + 1  
    b = ("Loading" + "." * a)
    # \r prints a carriage return first, so `b` is printed on top of the previous line.
    sys.stdout.write('\r'+b)
    time.sleep(0.5)
print (a)

Note that you might have to run sys.stdout.flush() right after sys.stdout.write('\r'+b) depending on which console you are doing the printing to have the results printed when requested without any buffering.

Sorting using Comparator- Descending order (User defined classes)

package com.test;

import java.util.Arrays;

public class Person implements Comparable {

private int age;

private Person(int age) {
    super();
    this.age = age;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

@Override
public int compareTo(Object o) {
    Person other = (Person)o;
    if (this == other)
        return 0;
    if (this.age < other.age) return 1;
    else if (this.age == other.age) return 0;
    else return -1;

}

public static void main(String[] args) {

    Person[] arr = new Person[4];
    arr[0] = new Person(50);
    arr[1] = new Person(20);
    arr[2] = new Person(10);
    arr[3] = new Person(90);

    Arrays.sort(arr);

    for (int i=0; i < arr.length; i++ ) {
        System.out.println(arr[i].age);
    }
}

}

Here is one way of doing it.

importing go files in same folder

Any number of files in a directory are a single package; symbols declared in one file are available to the others without any imports or qualifiers. All of the files do need the same package foo declaration at the top (or you'll get an error from go build).

You do need GOPATH set to the directory where your pkg, src, and bin directories reside. This is just a matter of preference, but it's common to have a single workspace for all your apps (sometimes $HOME), not one per app.

Normally a Github path would be github.com/username/reponame (not just github.com/xxxx). So if you want to have main and another package, you may end up doing something under workspace/src like

github.com/
  username/
    reponame/
      main.go   // package main, importing "github.com/username/reponame/b"
      b/
        b.go    // package b

Note you always import with the full github.com/... path: relative imports aren't allowed in a workspace. If you get tired of typing paths, use goimports. If you were getting by with go run, it's time to switch to go build: run deals poorly with multiple-file mains and I didn't bother to test but heard (from Dave Cheney here) go run doesn't rebuild dirty dependencies.

Sounds like you've at least tried to set GOPATH to the right thing, so if you're still stuck, maybe include exactly how you set the environment variable (the command, etc.) and what command you ran and what error happened. Here are instructions on how to set it (and make the setting persistent) under Linux/UNIX and here is the Go team's advice on workspace setup. Maybe neither helps, but take a look and at least point to which part confuses you if you're confused.

window.close and self.close do not close the window in Chrome

In tampermonkey now you can use

// @grant        window.close

And then just simply call

window.close();

Removing duplicate rows from table in Oracle

Use the rowid pseudocolumn.

DELETE FROM your_table
WHERE rowid not in
(SELECT MIN(rowid)
FROM your_table
GROUP BY column1, column2, column3);

Where column1, column2, and column3 make up the identifying key for each record. You might list all your columns.

Most Pythonic way to provide global configuration variables in config.py?

A small variation on Husky's idea that I use. Make a file called 'globals' (or whatever you like) and then define multiple classes in it, as such:

#globals.py

class dbinfo :      # for database globals
    username = 'abcd'
    password = 'xyz'

class runtime :
    debug = False
    output = 'stdio'

Then, if you have two code files c1.py and c2.py, both can have at the top

import globals as gl

Now all code can access and set values, as such:

gl.runtime.debug = False
print(gl.dbinfo.username)

People forget classes exist, even if no object is ever instantiated that is a member of that class. And variables in a class that aren't preceded by 'self.' are shared across all instances of the class, even if there are none. Once 'debug' is changed by any code, all other code sees the change.

By importing it as gl, you can have multiple such files and variables that lets you access and set values across code files, functions, etc., but with no danger of namespace collision.

This lacks some of the clever error checking of other approaches, but is simple and easy to follow.

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

There was no year 0000 and there is no month 00 or day 00. I suggest you try

0001-01-01 00:00:00

While a year 0 has been defined in some standards, it is more likely to be confusing than useful IMHO.

Force re-download of release dependency using Maven

If you really want to force-download all dependencies, you can try to re-initialise the entire maven repository. Like in this article already described, you could use:

mvn -Dmaven.repo.local=$HOME/.my/other/repository clean install

How do I get PHP errors to display?

You might want to use this code:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

How do MySQL indexes work?

Adding some visual representation to the list of answers. enter image description here

MySQL uses an extra layer of indirection: secondary index records point to primary index records, and the primary index itself holds the on-disk row locations. If a row offset changes, only the primary index needs to be updated.

Caveat: Disk data structure looks flat in the diagram but actually is a B+ tree.

Source: link

How to count digits, letters, spaces for a string in Python?

Following code replaces any nun-numeric character with '', allowing you to count number of such characters with function len.

import re
len(re.sub("[^0-9]", "", my_string))

Alphabetical:

import re
len(re.sub("[^a-zA-Z]", "", my_string))

More info - https://docs.python.org/3/library/re.html

JQUERY ajax passing value from MVC View to Controller

Here's an alternative way to do the same call. And your type should always be in CAPS, eg. type:"GET" / type:"POST".

$.ajax({
      url:/ControllerName/ActionName,
      data: "id=" + Id + "&param2=" + param2,
      type: "GET",
      success: function(data){
            // code here
      },
      error: function(passParams){
           // code here
      }
});

Another alternative will be to use the data-ajax on a link.

<a href="/ControllerName/ActionName/" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#_content">Click Me!</a>

Assuming u had a div with the I'd _content, this will call the action and replace the content inside that div with the data returned from that action.

<div id="_content"></div>

Not really a direct answer to ur question but its some info u should be aware of ;).

How to set selected value on select using selectpicker plugin from bootstrap

$('.selectpicker').selectpicker('val', '0');

With the '0' being the value of the item you want selected

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

The onunload event is not called in all browsers. Worse, you cannot check the return value of onbeforeunload event. That prevents us from actually preforming a logout function.

However, you can hack around this.

Call logout first thing in the onbeforeunload event. then prompt the user. If the user cancels their logout, automatically login them back in, by using the onfocus event. Kinda backwards, but I think it should work.

'use strict';

var reconnect = false;

window.onfocus = function () {
  if (reconnect) {
    reconnect = false;
    alert("Perform an auto-login here!");
  }
};

window.onbeforeunload = function () {
  //logout();
  var msg = "Are you sure you want to leave?";
  reconnect = true;
  return msg;
};

Android TextView padding between lines

You can use TextView.setLineSpacing(n,m) function.

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

How to get a variable type in Typescript?

Type guards in typescript

To determine the type of a variable after a conditional statement you can use type guards. A type guard in typescript is the following:

An expression which allows you to narrow down the type of something within a conditional block.

In other words it is an expression within a conditional block from where the typescript compiler has enough information to narrow down the type. The type will be more specific within the block of the type guard because the compiler has inferred more information about the type.

Example

declare let abc: number | string;

// typeof abc === 'string' is a type guard
if (typeof abc === 'string') {
    // abc: string
    console.log('abc is a string here')
} else {
    // abc: number, only option because the previous type guard removed the option of string
    console.log('abc is a number here')
}

Besides the typeof operator there are built in type guards like instanceof, in and even your own type guards.

How to generate keyboard events?

user648852's idea at least for me works great for OS X, here is the code to do it:

#!/usr/bin/env python

import time
from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost

# Python releases things automatically, using CFRelease will result in a scary error
#from Quartz.CoreGraphics import CFRelease

from Quartz.CoreGraphics import kCGHIDEventTap

# From http://stackoverflow.com/questions/281133/controlling-the-mouse-from-python-in-os-x
# and from https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/index.html#//apple_ref/c/func/CGEventCreateKeyboardEvent


def KeyDown(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)

def KeyUp(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

def KeyPress(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)



# From http://stackoverflow.com/questions/3202629/where-can-i-find-a-list-of-mac-virtual-key-codes

def toKeyCode(c):
    shiftKey = False
    # Letter
    if c.isalpha():
        if not c.islower():
            shiftKey = True
            c = c.lower()

    if c in shiftChars:
        shiftKey = True
        c = shiftChars[c]
    if c in keyCodeMap:
        keyCode = keyCodeMap[c]
    else:
        keyCode = ord(c)
    return keyCode, shiftKey

shiftChars = {
    '~': '`',
    '!': '1',
    '@': '2',
    '#': '3',
    '$': '4',
    '%': '5',
    '^': '6',
    '&': '7',
    '*': '8',
    '(': '9',
    ')': '0',
    '_': '-',
    '+': '=',
    '{': '[',
    '}': ']',
    '|': '\\',
    ':': ';',
    '"': '\'',
    '<': ',',
    '>': '.',
    '?': '/'
}


keyCodeMap = {
    'a'                 : 0x00,
    's'                 : 0x01,
    'd'                 : 0x02,
    'f'                 : 0x03,
    'h'                 : 0x04,
    'g'                 : 0x05,
    'z'                 : 0x06,
    'x'                 : 0x07,
    'c'                 : 0x08,
    'v'                 : 0x09,
    'b'                 : 0x0B,
    'q'                 : 0x0C,
    'w'                 : 0x0D,
    'e'                 : 0x0E,
    'r'                 : 0x0F,
    'y'                 : 0x10,
    't'                 : 0x11,
    '1'                 : 0x12,
    '2'                 : 0x13,
    '3'                 : 0x14,
    '4'                 : 0x15,
    '6'                 : 0x16,
    '5'                 : 0x17,
    '='                 : 0x18,
    '9'                 : 0x19,
    '7'                 : 0x1A,
    '-'                 : 0x1B,
    '8'                 : 0x1C,
    '0'                 : 0x1D,
    ']'                 : 0x1E,
    'o'                 : 0x1F,
    'u'                 : 0x20,
    '['                 : 0x21,
    'i'                 : 0x22,
    'p'                 : 0x23,
    'l'                 : 0x25,
    'j'                 : 0x26,
    '\''                : 0x27,
    'k'                 : 0x28,
    ';'                 : 0x29,
    '\\'                : 0x2A,
    ','                 : 0x2B,
    '/'                 : 0x2C,
    'n'                 : 0x2D,
    'm'                 : 0x2E,
    '.'                 : 0x2F,
    '`'                 : 0x32,
    'k.'                : 0x41,
    'k*'                : 0x43,
    'k+'                : 0x45,
    'kclear'            : 0x47,
    'k/'                : 0x4B,
    'k\n'               : 0x4C,
    'k-'                : 0x4E,
    'k='                : 0x51,
    'k0'                : 0x52,
    'k1'                : 0x53,
    'k2'                : 0x54,
    'k3'                : 0x55,
    'k4'                : 0x56,
    'k5'                : 0x57,
    'k6'                : 0x58,
    'k7'                : 0x59,
    'k8'                : 0x5B,
    'k9'                : 0x5C,

    # keycodes for keys that are independent of keyboard layout
    '\n'                : 0x24,
    '\t'                : 0x30,
    ' '                 : 0x31,
    'del'               : 0x33,
    'delete'            : 0x33,
    'esc'               : 0x35,
    'escape'            : 0x35,
    'cmd'               : 0x37,
    'command'           : 0x37,
    'shift'             : 0x38,
    'caps lock'         : 0x39,
    'option'            : 0x3A,
    'ctrl'              : 0x3B,
    'control'           : 0x3B,
    'right shift'       : 0x3C,
    'rshift'            : 0x3C,
    'right option'      : 0x3D,
    'roption'           : 0x3D,
    'right control'     : 0x3E,
    'rcontrol'          : 0x3E,
    'fun'               : 0x3F,
    'function'          : 0x3F,
    'f17'               : 0x40,
    'volume up'         : 0x48,
    'volume down'       : 0x49,
    'mute'              : 0x4A,
    'f18'               : 0x4F,
    'f19'               : 0x50,
    'f20'               : 0x5A,
    'f5'                : 0x60,
    'f6'                : 0x61,
    'f7'                : 0x62,
    'f3'                : 0x63,
    'f8'                : 0x64,
    'f9'                : 0x65,
    'f11'               : 0x67,
    'f13'               : 0x69,
    'f16'               : 0x6A,
    'f14'               : 0x6B,
    'f10'               : 0x6D,
    'f12'               : 0x6F,
    'f15'               : 0x71,
    'help'              : 0x72,
    'home'              : 0x73,
    'pgup'              : 0x74,
    'page up'           : 0x74,
    'forward delete'    : 0x75,
    'f4'                : 0x76,
    'end'               : 0x77,
    'f2'                : 0x78,
    'page down'         : 0x79,
    'pgdn'              : 0x79,
    'f1'                : 0x7A,
    'left'              : 0x7B,
    'right'             : 0x7C,
    'down'              : 0x7D,
    'up'                : 0x7E
}

Visual c++ can't open include file 'iostream'

I got this error when I created an 'Empty' console application in Visual Studio 2015. I re-created the application, leaving the 'Empty' box unchecked, it added all of the necessary libraries.

Fragments onResume from back stack

The following section at Android Developers describes a communication mechanism Creating event callbacks to the activity. To quote a line from it:

A good way to do that is to define a callback interface inside the fragment and require that the host activity implement it. When the activity receives a callback through the interface, it can share the information with other fragments in the layout as necessary.

Edit: The fragment has an onStart(...) which is invoked when the fragment is visible to the user. Similarly an onResume(...) when visible and actively running. These are tied to their activity counterparts. In short: use onResume()

Use tnsnames.ora in Oracle SQL Developer

This excellent answer to a similar question (that I could not find before, unfortunately) helped me solve the problem.

Copying Content from referenced answer :

SQL Developer will look in the following location in this order for a tnsnames.ora file

$HOME/.tnsnames.ora
$TNS_ADMIN/tnsnames.ora
TNS_ADMIN lookup key in the registry
/etc/tnsnames.ora ( non-windows )
$ORACLE_HOME/network/admin/tnsnames.ora
LocalMachine\SOFTWARE\ORACLE\ORACLE_HOME_KEY
LocalMachine\SOFTWARE\ORACLE\ORACLE_HOME

If your tnsnames.ora file is not getting recognized, use the following procedure:

Define an environmental variable called TNS_ADMIN to point to the folder that contains your tnsnames.ora file.

In Windows, this is done by navigating to Control Panel > System > Advanced system settings > Environment Variables...
In Linux, define the TNS_ADMIN variable in the .profile file in your home directory.

Confirm the os is recognizing this environmental variable

From the Windows command line: echo %TNS_ADMIN%

From linux: echo $TNS_ADMIN

Restart SQL Developer Now in SQL Developer right click on Connections and select New Connection.... Select TNS as connection type in the drop down box. Your entries from tnsnames.ora should now display here.

Typescript empty object for a typed variable

Really depends on what you're trying to do. Types are documentation in typescript, so you want to show intention about how this thing is supposed to be used when you're creating the type.

Option 1: If Users might have some but not all of the attributes during their lifetime

Make all attributes optional

type User = {
  attr0?: number
  attr1?: string
}

Option 2: If variables containing Users may begin null

type User = {
...
}
let u1: User = null;

Though, really, here if the point is to declare the User object before it can be known what will be assigned to it, you probably want to do let u1:User without any assignment.

Option 3: What you probably want

Really, the premise of typescript is to make sure that you are conforming to the mental model you outline in types in order to avoid making mistakes. If you want to add things to an object one-by-one, this is a habit that TypeScript is trying to get you not to do.

More likely, you want to make some local variables, then assign to the User-containing variable when it's ready to be a full-on User. That way you'll never be left with a partially-formed User. Those things are gross.

let attr1: number = ...
let attr2: string = ...
let user1: User = {
  attr1: attr1,
  attr2: attr2
}

How to remove a column from an existing table?

This can also be done through the SSMS GUI. The nice thing about this method is it warns you if there are any relationships on that column and can also automatically delete those as well.

  1. Put table in Design view (right click on table) like so:

enter image description here

  1. Right click on column in table's Design view and click "Delete Column"

enter image description here

As I stated before, if there are any relationships that would also need to be deleted, it will ask you at this point if you would like to delete those as well. You will likely need to do so to delete the column.

SQL: capitalize first letter only

Please check the query without using a function:

declare @T table(Insurance varchar(max))

insert into @T values ('wezembeek-oppem')
insert into @T values ('roeselare')
insert into @T values ('BRUGGE')
insert into @T values ('louvain-la-neuve')

select (
       select upper(T.N.value('.', 'char(1)'))+
                lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+(CASE WHEN RIGHT(T.N.value('.', 'varchar(max)'), 1)='-' THEN '' ELSE ' ' END)
       from X.InsXML.nodes('/N') as T(N)
       for xml path(''), type
       ).value('.', 'varchar(max)') as Insurance
from 
  (
  select cast('<N>'+replace(
            replace(
                Insurance, 
                ' ', '</N><N>'),
            '-', '-</N><N>')+'</N>' as xml) as InsXML
  from @T
  ) as X

How to amend older Git commit?

I've used another way for a few times. In fact, it is a manual git rebase -i and it is useful when you want to rearrange several commits including squashing or splitting some of them. The main advantage is that you don't have to decide about every commit's destiny at a single moment. You'll also have all Git features available during the process unlike during a rebase. For example, you can display the log of both original and rewritten history at any time, or even do another rebase!

I'll refer to the commits in the following way, so it's readable easily:

C # good commit after a bad one
B # bad commit
A # good commit before a bad one

Your history in the beginning looks like this:

x - A - B - C
|           |
|           master
|
origin/master

We'll recreate it to this way:

x - A - B*- C'
|           |
|           master
|
origin/master

Procedure

git checkout B       # get working-tree to the state of commit B
git reset --soft A   # tell Git that we are working before commit B
git checkout -b rewrite-history   # switch to a new branch for alternative history

Improve your old commit using git add (git add -i, git stash etc.) now. You can even split your old commit into two or more.

git commit           # recreate commit B (result = B*)
git cherry-pick C    # copy C to our new branch (result = C')

Intermediate result:

x - A - B - C 
|    \      |
|     \     master
|      \
|       B*- C'
|           |
|           rewrite-history
|
origin/master

Let's finish:

git checkout master
git reset --hard rewrite-history  # make this branch master

Or using just one command:

git branch -f master  # make this place the new tip of the master branch

That's it, you can push your progress now.

The last task is to delete the temporary branch:

git branch -d rewrite-history

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Converting VARCHAR2 to CLOB

In PL/SQL a CLOB can be converted to a VARCHAR2 with a simple assignment, SUBSTR, and other methods. A simple assignment will only work if the CLOB is less then or equal to the size of the VARCHAR2. The limit is 32767 in PL/SQL and 4000 in SQL (although 12c allows 32767 in SQL).

For example, this code converts a small CLOB through a simple assignment and then coverts the beginning of a larger CLOB.

declare
    v_small_clob clob := lpad('0', 1000, '0');
    v_large_clob clob := lpad('0', 32767, '0') || lpad('0', 32767, '0');
    v_varchar2   varchar2(32767);
begin
    v_varchar2 := v_small_clob;
    v_varchar2 := substr(v_large_clob, 1, 32767);
end;

LONG?

The above code does not convert the value to a LONG. It merely looks that way because of limitations with PL/SQL debuggers and strings over 999 characters long.

For example, in PL/SQL Developer, open a Test window and add and debug the above code. Right-click on v_varchar2 and select "Add variable to Watches". Step through the code and the value will be set to "(Long Value)". There is a ... next to the text but it does not display the contents. PLSQL Developer Long Value

C#?

I suspect the real problem here is with C# but I don't know how enough about C# to debug the problem.

How to check if a subclass is an instance of a class at runtime?

Class.isAssignableFrom() - works for interfaces as well. If you don't want that, you'll have to call getSuperclass() and test until you reach Object.

jQuery UI DatePicker to show year only

use this code for jquery time picker.

_x000D_
_x000D_
$(function() { _x000D_
   $('#datepicker1').datepicker( {_x000D_
        changeMonth: false,_x000D_
        changeYear: true,_x000D_
        showButtonPanel: false,_x000D_
        dateFormat: 'yy',_x000D_
        onClose: function(dateText, inst) { _x000D_
              $(this).datepicker('setDate', new Date('2017'));_x000D_
        }_x000D_
    }).focus(function () {_x000D_
                $(".ui-datepicker-month").hide();_x000D_
                $(".ui-datepicker-calendar").hide();_x000D_
            });_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>_x000D_
  <script src="https://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>_x000D_
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />_x000D_
_x000D_
<input type="text" id="datepicker1"/>
_x000D_
_x000D_
_x000D_

How do I get the command-line for an Eclipse run configuration?

Scan your workspace .metadata directory for files called *.launch. I forget which plugin directory exactly holds these records, but it might even be the most basic org.eclipse.plugins.core one.

Convert char to int in C#

char c = '1';
int i = (int)(c-'0');

and you can create a static method out of it:

static int ToInt(this char c)
{
    return (int)(c - '0');
}

Form content type for a json HTTP POST?

I have wondered the same thing. Basically it appears that the html spec has different content types for html and form data. Json only has a single content type.

According to the spec, a POST of json data should have the content-type:
application/json

Relevant portion of the HTML spec

6.7 Content types (MIME types)
...
Examples of content types include "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic".

17.13.4 Form content types
...
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows

Relevant portion of the JSON spec

  1. IANA Considerations
    The MIME media type for JSON text is application/json.

Git: Find the most recent common ancestor of two branches

With gitk you can view the two branches graphically:

gitk branch1 branch2

And then it's easy to find the common ancestor in the history of the two branches.

Iterating over a numpy array

I think you're looking for the ndenumerate.

>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
...  print x,y
... 
0 0
0 1
1 0
1 1
2 0
2 1

Regarding the performance. It is a bit slower than a list comprehension.

X = np.zeros((100, 100, 100))

%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop

%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop

If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords attribute of the flat iterator.

a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop