Programs & Examples On #Pycard

How do I run a node.js app as a background service?

UPDATE: i updated to include the latest from pm2:

for many use cases, using a systemd service is the simplest and most appropriate way to manage a node process. for those that are running numerous node processes or independently-running node microservices in a single environment, pm2 is a more full featured tool.

https://github.com/unitech/pm2

http://pm2.io

  • it has a really useful monitoring feature -> pretty 'gui' for command line monitoring of multiple processes with pm2 monit or process list with pm2 list
  • organized Log management -> pm2 logs
  • other stuff:
    • Behavior configuration
    • Source map support
    • PaaS Compatible
    • Watch & Reload
    • Module System
    • Max memory reload
    • Cluster Mode
    • Hot reload
    • Development workflow
    • Startup Scripts
    • Auto completion
    • Deployment workflow
    • Keymetrics monitoring
    • API

Git merge is not possible because I have unmerged files

Another potential cause for this (Intellij was involved in my case, not sure that mattered though): trying to merge in changes from a main branch into a branch off of a feature branch.

In other words, merging "main" into "current" in the following arrangement:

main
  |
  --feature
      |
      --current

I resolved all conflicts and GiT reported unmerged files and I was stuck until I merged from main into feature, then feature into current.

New line character in VB.Net?

you can solve that problem in visual basic .net without concatenating your text, you can use this as a return type of your overloaded Tostring:

System.Text.RegularExpressions.Regex.Unescape(String.format("FirstName:{0} \r\n LastName: {1}", "Nordanne", "Isahac"))

Android Studio: Gradle: error: cannot find symbol variable

If you are using a String build config field in your project, this might be the case:

buildConfigField "String", "source", "play"

If you declare your String like above it will cause the error to happen. The fix is to change it to:

buildConfigField "String", "source", "\"play\""

Rename Pandas DataFrame Index

In Pandas version 0.13 and greater the index level names are immutable (type FrozenList) and can no longer be set directly. You must first use Index.rename() to apply the new index level names to the Index and then use DataFrame.reindex() to apply the new index to the DataFrame. Examples:

For Pandas version < 0.13

df.index.names = ['Date']

For Pandas version >= 0.13

df = df.reindex(df.index.rename(['Date']))

how to read System environment variable in Spring applicationContext

Yes, you can do <property name="defaultLocale" value="#{ systemProperties['user.region']}"/> for instance.

The variable systemProperties is predefined, see 6.4.1 XML based configuration.

C# "must declare a body because it is not marked abstract, extern, or partial"

Try this:

private int hour;
public int Hour
{
    get { return hour; }
    set
    {
        //make sure hour is positive
        if (value < MIN_HOUR)
        {
            hour = 0;
            MessageBox.Show("Hour value " + value.ToString() + " cannot be negative. Reset to " + MIN_HOUR.ToString(),
            "Invalid Hour", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else
        {
            //take the modulus to ensure always less than 24 hours
            //works even if the value is already within range, or value equal to 24
            hour = value % MAX_HOUR;
        }
    }
}

What does auto do in margin:0 auto?

When you have specified a width on the object that you have applied margin: 0 auto to, the object will sit centrally within it's parent container.

Specifying auto as the second parameter basically tells the browser to automatically determine the left and right margins itself, which it does by setting them equally. It guarantees that the left and right margins will be set to the same size. The first parameter 0 indicates that the top and bottom margins will both be set to 0.

margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;

Therefore, to give you an example, if the parent is 100px and the child is 50px, then the auto property will determine that there's 50px of free space to share between margin-left and margin-right:

var freeSpace = 100 - 50;
var equalShare = freeSpace / 2;

Which would give:

margin-left:25;
margin-right:25;

Have a look at this jsFiddle. You do not have to specify the parent width, only the width of the child object.

How do I export (and then import) a Subversion repository?

If you do not have file access to the repository, I prefer rsvndump (remote Subversion repository dump) to make the dump file.

C# equivalent to Java's charAt()?

string sample = "ratty";
Console.WriteLine(sample[0]);

And

Console.WriteLine(sample.Chars(0));
Reference: http://msdn.microsoft.com/en-us/library/system.string.chars%28v=VS.71%29.aspx

The above is same as using indexers in c#.

How to redirect 'print' output to a file using python?

Don't use print, use logging

You can change sys.stdout to point to a file, but this is a pretty clunky and inflexible way to handle this problem. Instead of using print, use the logging module.

With logging, you can print just like you would to stdout, or you can also write the output to a file. You can even use the different message levels (critical, error, warning, info, debug) to, for example, only print major issues to the console, but still log minor code actions to a file.

A simple example

Import logging, get the logger, and set the processing level:

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # process everything, even if everything isn't printed

If you want to print to stdout:

ch = logging.StreamHandler()
ch.setLevel(logging.INFO) # or any other level
logger.addHandler(ch)

If you want to also write to a file (if you only want to write to a file skip the last section):

fh = logging.FileHandler('myLog.log')
fh.setLevel(logging.DEBUG) # or any level you want
logger.addHandler(fh)

Then, wherever you would use print use one of the logger methods:

# print(foo)
logger.debug(foo)

# print('finishing processing')
logger.info('finishing processing')

# print('Something may be wrong')
logger.warning('Something may be wrong')

# print('Something is going really bad')
logger.error('Something is going really bad')

To learn more about using more advanced logging features, read the excellent logging tutorial in the Python docs.

how to reference a YAML "setting" from elsewhere in the same YAML file?

In some languages, you can use an alternative library, For example, tampax is an implementation of YAML handling variables:

const tampax = require('tampax');

const yamlString = `
dude:
  name: Arthur
weapon:
  favorite: Excalibur
  useless: knife
sentence: "{{dude.name}} use {{weapon.favorite}}. The goal is {{goal}}."`;

const r = tampax.yamlParseString(yamlString, { goal: 'to kill Mordred' });
console.log(r.sentence);

// output : "Arthur use Excalibur. The goal is to kill Mordred."

Editor's Note: poster is also the author of this package.

What are the differences between .so and .dylib on osx?

The difference between .dylib and .so on mac os x is how they are compiled. For .so files you use -shared and for .dylib you use -dynamiclib. Both .so and .dylib are interchangeable as dynamic library files and either have a type as DYLIB or BUNDLE. Heres the readout for different files showing this.

libtriangle.dylib:
Mach header
      magic cputype cpusubtype  caps    filetype ncmds sizeofcmds      flags
MH_MAGIC_64  X86_64        ALL  0x00       DYLIB    17       1368   NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS



libtriangle.so:
Mach header
      magic cputype cpusubtype  caps    filetype ncmds sizeofcmds      flags
MH_MAGIC_64  X86_64        ALL  0x00       DYLIB    17       1256   NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS

triangle.so:
Mach header
      magic cputype cpusubtype  caps    filetype ncmds sizeofcmds      flags
MH_MAGIC_64  X86_64        ALL  0x00      BUNDLE    16       1696   NOUNDEFS DYLDLINK TWOLEVEL

The reason the two are equivalent on Mac OS X is for backwards compatibility with other UNIX OS programs that compile to the .so file type.

Compilation notes: whether you compile a .so file or a .dylib file you need to insert the correct path into the dynamic library during the linking step. You do this by adding -install_name and the file path to the linking command. If you dont do this you will run into the problem seen in this post: Mac Dynamic Library Craziness (May be Fortran Only).

Mac zip compress without __MACOSX folder?

Can be fixed after the fact by zip -d filename.zip __MACOSX/\*

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

Convert Unix timestamp into human readable date using MySQL

What's missing from the other answers (as of this writing) and not directly obvious is that from_unixtime can take a second parameter to specify the format like so:

SELECT
  from_unixtime(timestamp, '%Y %D %M %H:%i:%s')
FROM 
  your_table

How to embed a Facebook page's feed into my website

In new page-plugin you can do multiple tabs in your website. The Page plugin lets you easily embed and promote any Facebook Page on your website. Just like on Facebook, your visitors can like and share the Page without leaving your site.

  1. Include the JavaScript SDK on your page once, ideally right after the opening <body> tag.

_x000D_
_x000D_
<div id="fb-root"></div>_x000D_
<script>(function(d, s, id) {_x000D_
  var js, fjs = d.getElementsByTagName(s)[0];_x000D_
  if (d.getElementById(id)) return;_x000D_
  js = d.createElement(s); js.id = id;_x000D_
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5&appId={APP_ID}";_x000D_
  fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));</script>
_x000D_
_x000D_
_x000D_

  1. Place the code for your plugin wherever you want the plugin to appear on your page.

_x000D_
_x000D_
<div class="fb-page" _x000D_
     data-href="https://www.facebook.com/YourPageName" _x000D_
     data-tabs="timeline" _x000D_
     data-small-header="false" _x000D_
     data-adapt-container-width="true" _x000D_
     data-hide-cover="false" _x000D_
     data-show-facepile="true">_x000D_
  <div class="fb-xfbml-parse-ignore">_x000D_
    <blockquote cite="https://www.facebook.com/facebook">_x000D_
      <a href="https://www.facebook.com/facebook">Facebook</a>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can also change the following settings:

enter image description here

Also You can now have timeline, events and messages tabs with the new page plugin:

  • Timeline Tab: Will show the most recent posts of your Facebook Page timeline.
  • Events Tab: People can follow your page events and subscribe to events from the plugin.
  • Messages Tab: People can message your page directly from your website. People need to be logged in to use this feature.

_x000D_
_x000D_
<div class="fb-page" _x000D_
  data-tabs="timeline,events,messages"_x000D_
  data-href="https://www.facebook.com/YourPageName"_x000D_
  data-width="380" _x000D_
  data-hide-cover="false">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between return 1, return 0, return -1 and exit?

return from main() is equivalent to exit

the program terminates immediately execution with exit status set as the value passed to return or exit

return in an inner function (not main) will terminate immediately the execution of the specific function returning the given result to the calling function.

exit from anywhere on your code will terminate program execution immediately.


status 0 means the program succeeded.

status different from 0 means the program exited due to error or anomaly.

If you exit with a status different from 0 you're supposed to print an error message to stderr so instead of using printf better something like

if(errorOccurred) {
    fprintf(stderr, "meaningful message here\n");
    return -1;
}

note that (depending on the OS you're on) there are some conventions about return codes.

Google for "exit status codes" or similar and you'll find plenty of information on SO and elsewhere.


Worth mentioning that the OS itself may terminate your program with specific exit status codes if you attempt to do some invalid operations like reading memory you have no access to.

git: fatal: I don't handle protocol '??http'

My solution:

  1. Type: git clone .
  2. Copy the repository url and paste it after of git clone .
  3. Move the cursor to position between git clone and https://... .
  4. Delete space if it had between git clone and https://... until have git clonehttps://...
  5. Re-add the space and press Enter.

Location of the android sdk has not been setup in the preferences in mac os?

I had the same problem when I was trying to upgrade from ADT 20.0.x to ADT 23.0.x on Eclipse Indigo.

To fix the issue, I had to uninstall the ADT plugin (remove feature) from Eclipse, then reinstall the newer versions.

This maybe done by going to Help->Install New Software. Then at the bottom of the page, click What is already installed?

All what is left now is to install the newer versions as usual from help->Install New Software.

SelectSingleNode returning null for known good xml node path using XPath

Roisgoen's answer worked for me, but to make it more general, you can use a RegEx:

//Substitute "My_RootNode" for whatever your root node is
string strRegex = @"<My_RootNode(?<xmlns>\s+xmlns([\s]|[^>])*)>";
var myMatch = new Regex(strRegex, RegexOptions.None).Match(myXmlDoc.InnerXml);
if (myMatch.Success)
{
    var grp = myMatch.Groups["xmlns"];
    if (grp.Success)
    {
        myXmlDoc.InnerXml = myXmlDoc.InnerXml.Replace(grp.Value, "");
    }
}

I fully admit that this is not a best-practice answer, but but it's an easy fix and sometimes that's all we need.

SQL WHERE ID IN (id1, id2, ..., idn)

Try this

SELECT Position_ID , Position_Name
FROM 
position
WHERE Position_ID IN (6 ,7 ,8)
ORDER BY Position_Name

Check file extension in upload form in PHP

use this function

 function check_image_extension($image){

        $images_extentions = array("jpg","JPG","jpeg","JPEG","png","PNG");

        $image_parts = explode(".",$image);

        $image_end_part = end($image_parts);

        if(in_array($image_end_part,$images_extentions ) == true){

            return time() . "." . $image_end_part;


        }else{

            return false;
        }


    }

How to get the mysql table columns data type?

SHOW COLUMNS FROM mytable

Self contained complete examples are often useful.

<?php
  // The server where your database is hosted                 localhost
  // The name of your database                                mydatabase
  // The user name of the database user                       databaseuser
  // The password of the database user                        thesecretpassword
  // Most web pages are in utf-8 so should be the database    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
  try
  {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "databaseuser", "thesecretpassword", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));  
  }
    catch(PDOException $e)
  {
    die('Could not connect: ' . $e->getMessage());
  }

  $sql   = "SHOW COLUMNS FROM mytable";
  $query = $pdo->prepare($sql);
  $query->execute();

  $err = $query->errorInfo();
  $bug = $err[2];

  if ($bug != "") { echo "<p>$bug</p>"; }

  while ($row = $query->fetch(PDO::FETCH_ASSOC))
  {
    echo "<pre>" . print_r($row, true) . "</pre>";
  }

  /* OUTPUT SAMPLE  
  Array
  (
      [Field] => page_id
      [Type] => char(40)
      [Null] => NO
      [Key] => 
      [Default] => 
      [Extra] => 
  )

  Array
  (  
      [Field] => last_name
      [Type] => char(50)
      More ...
  */
?>

How to save user input into a variable in html and js

It doesn't work because name is a reserved word in JavaScript. Change the function name to something else.

See http://www.quackit.com/javascript/javascript_reserved_words.cfm

<form id="form" onsubmit="return false;">
    <input style="position:absolute; top:80%; left:5%; width:40%;" type="text" id="userInput" />
    <input style="position:absolute; top:50%; left:5%; width:40%;" type="submit" onclick="othername();" />
</form>

function othername() {
    var input = document.getElementById("userInput").value;
    alert(input);
}

Variable name as a string in Javascript

var x = 2;
for(o in window){ 
   if(window[o] === x){
      alert(o);
   }
}

However, I think you should do like "karim79"

Commenting out a set of lines in a shell script

This Perl one-liner comments out lines 1 to 3 of the file orig.sh inclusive (where the first line is numbered 0), and writes the commented version to cmt.sh.

perl -n -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh > cmt.sh

Obviously you can change the boundary numbers as required.

If you want to edit the file in place, it's even shorter:

perl -in -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh

Demo

$ cat orig.sh 
a
b
c
d
e
f

$ perl -n -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh > cmt.sh

$ cat cmt.sh 
a
#b
#c
#d
e
f

How to create an empty array in PHP with predefined size?

PHP provides two types of array.

  • normal array
  • SplFixedArray

normal array : This array is dynamic.

SplFixedArray : this is a standard php library which provides the ability to create array of fix size.

jQuery: click function exclude children.

My solution:

jQuery('.foo').on('click',function(event){
    if ( !jQuery(event.target).is('.foo *') ) {
        // code goes here
    } 
});

'Incomplete final line' warning when trying to read a .csv file into R

In various European locales, as the comma character serves as decimal point, the read.csv2 function should be used instead.

Convert string to decimal number with 2 decimal places in Java

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));

System.out.println("liters of petrol before putting in editor : "+litersOfPetrol);

You print Float here, that has no format at all.

To print formatted float, just use

String formatted = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : " + formatted);

How to use a class object in C++ as a function parameter

If you want to pass class instances (objects), you either use

 void function(const MyClass& object){
   // do something with object  
 }

or

 void process(MyClass& object_to_be_changed){
   // change member variables  
 }

On the other hand if you want to "pass" the class itself

template<class AnyClass>
void function_taking_class(){
   // use static functions of AnyClass
   AnyClass::count_instances();
   // or create an object of AnyClass and use it
   AnyClass object;
   object.member = value;
}
// call it as 
function_taking_class<MyClass>();
// or 
function_taking_class<MyStruct>();

with

class MyClass{
  int member;
  //...
};
MyClass object1;

How do you log all events fired by an element in jQuery?

There is a nice generic way using the .data('events') collection:

function getEventsList($obj) {
    var ev = new Array(),
        events = $obj.data('events'),
        i;
    for(i in events) { ev.push(i); }
    return ev.join(' ');
}

$obj.on(getEventsList($obj), function(e) {
    console.log(e);
});

This logs every event that has been already bound to the element by jQuery the moment this specific event gets fired. This code was pretty damn helpful for me many times.

Btw: If you want to see every possible event being fired on an object use firebug: just right click on the DOM element in html tab and check "Log Events". Every event then gets logged to the console (this is sometimes a bit annoying because it logs every mouse movement...).

java.lang.IllegalArgumentException: View not attached to window manager

First of all do error handling where ever you trying to dismiss the dialog.

 if ((progressDialog != null) && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }

If that doesn't fix then dismiss it in onStop() Method of the activity.

 @Override
    protected void onStop() {
        super.onStop();
        if ((progressDialog != null) && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

how do I join two lists using linq or lambda expressions

The way to do this using the Extention Methods, instead of the linq query syntax would be like this:

var results = workOrders.Join(plans,
  wo => wo.WorkOrderNumber,
  p => p.WorkOrderNumber,
  (order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

MySQL: Fastest way to count number of rows

I've always understood that the below will give me the fastest response times.

SELECT COUNT(1) FROM ... WHERE ...

Jquery: Checking to see if div contains text, then action

You might want to try the contains selector:

if ($("#field > div.field-item:contains('someText')").length) {
    $("#somediv").addClass("thisClass");
}

Also, as other mentioned, you must use == or === rather than =.

Android canvas draw rectangle

Try paint.setStyle(Paint.Style.STROKE)?

How do I get the value of text input field using JavaScript?

There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):

Method 1:

document.getElementById('textbox_id').value to get the value of desired box

For example, document.getElementById("searchTxt").value;

 

Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0], for the second one use 1, and so on...

Method 2:

Use document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection

For example, document.getElementsByClassName("searchField")[0].value; if this is the first textbox in your page.

Method 3:

Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection

For example, document.getElementsByTagName("input")[0].value;, if this is the first textbox in your page.

Method 4:

document.getElementsByName('name')[whole_number].value which also >returns a live NodeList

For example, document.getElementsByName("searchTxt")[0].value; if this is the first textbox with name 'searchtext' in your page.

Method 5:

Use the powerful document.querySelector('selector').value which uses a CSS selector to select the element

For example, document.querySelector('#searchTxt').value; selected by id
document.querySelector('.searchField').value; selected by class
document.querySelector('input').value; selected by tagname
document.querySelector('[name="searchTxt"]').value; selected by name

Method 6:

document.querySelectorAll('selector')[whole_number].value which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.

For example, document.querySelectorAll('#searchTxt')[0].value; selected by id
document.querySelectorAll('.searchField')[0].value; selected by class
document.querySelectorAll('input')[0].value; selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value; selected by name

Support

Browser          Method1   Method2  Method3  Method4    Method5/6
IE6              Y(Buggy)   N        Y        Y(Buggy)   N
IE7              Y(Buggy)   N        Y        Y(Buggy)   N
IE8              Y          N        Y        Y(Buggy)   Y
IE9              Y          Y        Y        Y(Buggy)   Y
IE10             Y          Y        Y        Y          Y
FF3.0            Y          Y        Y        Y          N    IE=Internet Explorer
FF3.5/FF3.6      Y          Y        Y        Y          Y    FF=Mozilla Firefox
FF4b1            Y          Y        Y        Y          Y    GC=Google Chrome
GC4/GC5          Y          Y        Y        Y          Y    Y=YES,N=NO
Safari4/Safari5  Y          Y        Y        Y          Y
Opera10.10/
Opera10.53/      Y          Y        Y        Y(Buggy)   Y
Opera10.60
Opera 12         Y          Y        Y        Y          Y

Useful links

  1. To see the support of these methods with all the bugs including more details click here
  2. Difference Between Static collections and Live collections click Here
  3. Difference Between NodeList and HTMLCollection click Here

MS Access DB Engine (32-bit) with Office 64-bit

Even tried all suggestions, in my case (Office x64 - Visual Studio 2017), the only way to have both access engines on a Office 64x installation so you can use it on Visual Studio and using a 2016+ version of Office, is to install the 2010 version of the Engine.

First install the x64 from this page

https://www.microsoft.com/en-us/download/details.aspx?id=54920

and then the x86 version from this one

https://www.microsoft.com/en-us/download/details.aspx?id=13255

as from this blog: http://dinesql.blogspot.com/2017/10/microsoft-access-database-engine-2016-Redistributable-Setup-you-cannot-install-the-32-bit-version-You-cannot-install-the-64-bit-version.html

Upper memory limit?

(This is my third answer because I misunderstood what your code was doing in my original, and then made a small but crucial mistake in my second—hopefully three's a charm.

Edits: Since this seems to be a popular answer, I've made a few modifications to improve its implementation over the years—most not too major. This is so if folks use it as template, it will provide an even better basis.

As others have pointed out, your MemoryError problem is most likely because you're attempting to read the entire contents of huge files into memory and then, on top of that, effectively doubling the amount of memory needed by creating a list of lists of the string values from each line.

Python's memory limits are determined by how much physical ram and virtual memory disk space your computer and operating system have available. Even if you don't use it all up and your program "works", using it may be impractical because it takes too long.

Anyway, the most obvious way to avoid that is to process each file a single line at a time, which means you have to do the processing incrementally.

To accomplish this, a list of running totals for each of the fields is kept. When that is finished, the average value of each field can be calculated by dividing the corresponding total value by the count of total lines read. Once that is done, these averages can be printed out and some written to one of the output files. I've also made a conscious effort to use very descriptive variable names to try to make it understandable.

try:
    from itertools import izip_longest
except ImportError:    # Python 3
    from itertools import zip_longest as izip_longest

GROUP_SIZE = 4
input_file_names = ["A1_B1_100000.txt", "A2_B2_100000.txt", "A1_B2_100000.txt",
                    "A2_B1_100000.txt"]
file_write = open("average_generations.txt", 'w')
mutation_average = open("mutation_average", 'w')  # left in, but nothing written

for file_name in input_file_names:
    with open(file_name, 'r') as input_file:
        print('processing file: {}'.format(file_name))

        totals = []
        for count, fields in enumerate((line.split('\t') for line in input_file), 1):
            totals = [sum(values) for values in
                        izip_longest(totals, map(float, fields), fillvalue=0)]
        averages = [total/count for total in totals]

        for print_counter, average in enumerate(averages):
            print('  {:9.4f}'.format(average))
            if print_counter % GROUP_SIZE == 0:
                file_write.write(str(average)+'\n')

file_write.write('\n')
file_write.close()
mutation_average.close()

How do I correct the character encoding of a file?

And then there is the somewhat older recode program.

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Hi I tested below code that worked fine :

    long timeInMillis = System.currentTimeMillis();
    Calendar cal1 = Calendar.getInstance();
    cal1.setTimeInMillis(timeInMillis);
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
    dateFormat.format(cal1.getTime());

Restricting input to textbox: allowing only numbers and decimal point

<input type="text" onkeypress="return isNumberKey(event,this)">

<script>
   function isNumberKey(evt, obj) {

            var charCode = (evt.which) ? evt.which : event.keyCode
            var value = obj.value;
            var dotcontains = value.indexOf(".") != -1;
            if (dotcontains)
                if (charCode == 46) return false;
            if (charCode == 46) return true;
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
            return true;
        }


</script>

How to select specified node within Xpath node sets by index with Selenium?

Here is the solution for index variable

Let's say, you have found 5 elements with same locator and you would like to perform action on each element by providing index number (here, variable is used for index as "i")

for(int i=1; i<=5; i++)
{
    string xPathWithVariable = "(//div[@class='className'])" + "[" + i + "]";
    driver.FindElement(By.XPath(xPathWithVariable)).Click();
}

It takes XPath :

(//div[@class='className'])[1]
(//div[@class='className'])[2]
(//div[@class='className'])[3]
(//div[@class='className'])[4]
(//div[@class='className'])[5]

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME

Android SDK Manager Not Installing Components

Try running Android Studio as an administrator, by right-clicking on the .exe and selecting "Run As Administrator".

Also, some anti-virus programs have been known to interfere with SDK Manager.

Underline text in UIlabel

I have Created for multiline uilabel with underline :

For Font size 8 to 13 set int lineHeight = self.font.pointSize+3;

For font size 14 to 20 set int lineHeight = self.font.pointSize+4;

- (void)drawRect:(CGRect)rect 

{

CGContextRef ctx = UIGraphicsGetCurrentContext();

const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor);

CGContextSetRGBStrokeColor(ctx, colors[0], colors[1], colors[2], 1.0); // RGBA

CGContextSetLineWidth(ctx, 1.0f);
CGSize tmpSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(self.frame.size.width, 9999)];

int height = tmpSize.height;

int lineHeight = self.font.pointSize+4;    

int maxCount = height/lineHeight;

float totalWidth = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(1000, 9999)].width;

for(int i=1;i<=maxCount;i++)

{

    float width=0.0;
    if((i*self.frame.size.width-totalWidth)<=0)
        width = self.frame.size.width;
    else
        width = self.frame.size.width - (i* self.frame.size.width - totalWidth);
    CGContextMoveToPoint(ctx, 0, lineHeight*i-1);
    CGContextAddLineToPoint(ctx, width, lineHeight*i-1);
}

CGContextStrokePath(ctx);

[super drawRect:rect]; 
}

In PHP with PDO, how to check the final SQL parametrized query?

The easiest way it can be done is by reading mysql execution log file and you can do that in runtime.

There is a nice explanation here:

How to show the last queries executed on MySQL?

JavaScript: filter() for Objects

First of all, it's considered bad practice to extend Object.prototype. Instead, provide your feature as utility function on Object, just like there already are Object.keys, Object.assign, Object.is, ...etc.

I provide here several solutions:

  1. Using reduce and Object.keys
  2. As (1), in combination with Object.assign
  3. Using map and spread syntax instead of reduce
  4. Using Object.entries and Object.fromEntries

1. Using reduce and Object.keys

With reduce and Object.keys to implement the desired filter (using ES6 arrow syntax):

_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
    Object.keys(obj)_x000D_
          .filter( key => predicate(obj[key]) )_x000D_
          .reduce( (res, key) => (res[key] = obj[key], res), {} );_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_

Note that in the above code predicate must be an inclusion condition (contrary to the exclusion condition the OP used), so that it is in line with how Array.prototype.filter works.

2. As (1), in combination with Object.assign

In the above solution the comma operator is used in the reduce part to return the mutated res object. This could of course be written as two statements instead of one expression, but the latter is more concise. To do it without the comma operator, you could use Object.assign instead, which does return the mutated object:

_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
    Object.keys(obj)_x000D_
          .filter( key => predicate(obj[key]) )_x000D_
          .reduce( (res, key) => Object.assign(res, { [key]: obj[key] }), {} );_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_

3. Using map and spread syntax instead of reduce

Here we move the Object.assign call out of the loop, so it is only made once, and pass it the individual keys as separate arguments (using the spread syntax):

_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
    Object.assign(...Object.keys(obj)_x000D_
                    .filter( key => predicate(obj[key]) )_x000D_
                    .map( key => ({ [key]: obj[key] }) ) );_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_

4. Using Object.entries and Object.fromEntries

As the solution translates the object to an intermediate array and then converts that back to a plain object, it would be useful to make use of Object.entries (ES2017) and the opposite (i.e. create an object from an array of key/value pairs) with Object.fromEntries (ES2019).

It leads to this "one-liner" method on Object:

_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
                  Object.fromEntries(Object.entries(obj).filter(predicate));_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
_x000D_
var filtered = Object.filter(scores, ([name, score]) => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_

The predicate function gets a key/value pair as argument here, which is a bit different, but allows for more possibilities in the predicate function's logic.

Read properties file outside JAR file

I did it by other way.

Properties prop = new Properties();
    try {

        File jarPath=new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        String propertiesPath=jarPath.getParentFile().getAbsolutePath();
        System.out.println(" propertiesPath-"+propertiesPath);
        prop.load(new FileInputStream(propertiesPath+"/importer.properties"));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
  1. Get Jar file path.
  2. Get Parent folder of that file.
  3. Use that path in InputStreamPath with your properties file name.

When to use which design pattern?

I completely agree with @Peter Rasmussen.

Design patterns provide general solution to commonly occurring design problem.

I would like you to follow below approach.

  1. Understand intent of each pattern
  2. Understand checklist or use case of each pattern
  3. Think of solution to your problem and check if your solution falls into checklist of particular pattern
  4. If not, simply ignore the design-patterns and write your own solution.

Useful links:

sourcemaking : Explains intent, structure and checklist beautifully in multiple languages including C++ and Java

wikipedia : Explains structure, UML diagram and working examples in multiple languages including C# and Java .

Check list and Rules of thumb in each sourcemakding design-pattern provides alram bell you are looking for.

What exactly should be set in PYTHONPATH?

You don't have to set either of them. PYTHONPATH can be set to point to additional directories with private libraries in them. If PYTHONHOME is not set, Python defaults to using the directory where python.exe was found, so that dir should be in PATH.

binning data in python with scipy/numpy

The numpy_indexed package (disclaimer: I am its author) contains functionality to efficiently perform operations of this type:

import numpy_indexed as npi
print(npi.group_by(np.digitize(data, bins)).mean(data))

This is essentially the same solution as the one I posted earlier; but now wrapped in a nice interface, with tests and all :)

What is the difference between const and readonly in C#?

There is notable difference between const and readonly fields in C#.Net

const is by default static and needs to be initialized with constant value, which can not be modified later on. Change of value is not allowed in constructors, too. It can not be used with all datatypes. For ex- DateTime. It can not be used with DateTime datatype.

public const DateTime dt = DateTime.Today;  //throws compilation error
public const string Name = string.Empty;    //throws compilation error
public readonly string Name = string.Empty; //No error, legal

readonly can be declared as static, but not necessary. No need to initialize at the time of declaration. Its value can be assigned or changed using constructor. So, it gives advantage when used as instance class member. Two different instantiation may have different value of readonly field. For ex -

class A
{
    public readonly int Id;

    public A(int i)
    {
        Id = i;
    }
}

Then readonly field can be initialised with instant specific values, as follows:

A objOne = new A(5);
A objTwo = new A(10);

Here, instance objOne will have value of readonly field as 5 and objTwo has 10. Which is not possible using const.

Do I need a content-type header for HTTP GET requests?

GET requests can have "Accept" headers, which say which types of content the client understands. The server can then use that to decide which content type to send back.

They're optional though.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1

Form inside a form, is that alright?

It's not valid XHTML to have to have nested forms. However, you can use multiple submit buttons and use a serverside script to run different codes depending on which button the users has clicked.

How to save a Seaborn plot into a file

Its also possible to just create a matplotlib figure object and then use plt.savefig(...):

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd

df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

Creating pdf files at runtime in c#

iTextSharp http://itextsharp.sourceforge.net/

Complex but comprehensive.

itext7 former iTextSharp

Create pandas Dataframe by appending one row at a time

Instead of a list of dictionaries as in ShikharDua's answer, we can also represent our table as a dictionary of lists, where each list stores one column in row-order, given we know our columns beforehand. At the end we construct our DataFrame once.

For c columns and n rows, this uses 1 dictionary and c lists, versus 1 list and n dictionaries. The list of dictionaries method has each dictionary storing all keys and requires creating a new dictionary for every row. Here we only append to lists, which is constant time and theoretically very fast.

# current data
data = {"Animal":["cow", "horse"], "Color":["blue", "red"]}

# adding a new row (be careful to ensure every column gets another value)
data["Animal"].append("mouse")
data["Color"].append("black")

# at the end, construct our DataFrame
df = pd.DataFrame(data)
#   Animal  Color
# 0    cow   blue
# 1  horse    red
# 2  mouse  black

How do I "select Android SDK" in Android Studio?

The comment from @Nisarg helped: "set latest version in Compile Sdk Version"

I changed from API 8 to API 23 and the error message disappeared.

how to detect search engine bots with php?

 <?php // IPCLOACK HOOK
if (CLOAKING_LEVEL != 4) {
    $lastupdated = date("Ymd", filemtime(FILE_BOTS));
    if ($lastupdated != date("Ymd")) {
        $lists = array(
        'http://labs.getyacg.com/spiders/google.txt',
        'http://labs.getyacg.com/spiders/inktomi.txt',
        'http://labs.getyacg.com/spiders/lycos.txt',
        'http://labs.getyacg.com/spiders/msn.txt',
        'http://labs.getyacg.com/spiders/altavista.txt',
        'http://labs.getyacg.com/spiders/askjeeves.txt',
        'http://labs.getyacg.com/spiders/wisenut.txt',
        );
        foreach($lists as $list) {
            $opt .= fetch($list);
        }
        $opt = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $opt);
        $fp =  fopen(FILE_BOTS,"w");
        fwrite($fp,$opt);
        fclose($fp);
    }
    $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    $ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    $agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    $host = strtolower(gethostbyaddr($ip));
    $file = implode(" ", file(FILE_BOTS));
    $exp = explode(".", $ip);
    $class = $exp[0].'.'.$exp[1].'.'.$exp[2].'.';
    $threshold = CLOAKING_LEVEL;
    $cloak = 0;
    if (stristr($host, "googlebot") && stristr($host, "inktomi") && stristr($host, "msn")) {
        $cloak++;
    }
    if (stristr($file, $class)) {
        $cloak++;
    }
    if (stristr($file, $agent)) {
        $cloak++;
    }
    if (strlen($ref) > 0) {
        $cloak = 0;
    }

    if ($cloak >= $threshold) {
        $cloakdirective = 1;
    } else {
        $cloakdirective = 0;
    }
}
?>

That would be the ideal way to cloak for spiders. It's from an open source script called [YACG] - http://getyacg.com

Needs a bit of work, but definitely the way to go.

Lotus Notes email as an attachment to another email

You can slecet sent item /email and drag to desktop , it will automatic created new file on desktop. Then you can attach and send it in to new emails.

Spring Boot and multiple external configuration files

I have found this to be a useful pattern to follow:

@RunWith(SpringRunner)
@SpringBootTest(classes = [ TestConfiguration, MyApplication ],
        properties = [
                "spring.config.name=application-MyTest_LowerImportance,application-MyTest_MostImportant"
                ,"debug=true", "trace=true"
        ]
)

Here we override the use of "application.yml" to use "application-MyTest_LowerImportance.yml" and also "application-MyTest_MostImportant.yml"
(Spring will also look for .properties files)

Also included as an extra bonus are the debug and trace settings, on a separate line so you can comment them out if required ;]

The debug/trace are incredibly useful as Spring will dump the names of all the files it loads and those it tries to load.
You will see lines like this in the console at runtime:

TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_MostImportant.properties' (file:./config/application-MyTest_MostImportant.properties) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_MostImportant.xml' (file:./config/application-MyTest_MostImportant.xml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_MostImportant.yml' (file:./config/application-MyTest_MostImportant.yml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_MostImportant.yaml' (file:./config/application-MyTest_MostImportant.yaml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_LowerImportance.properties' (file:./config/application-MyTest_LowerImportance.properties) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_LowerImportance.xml' (file:./config/application-MyTest_LowerImportance.xml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_LowerImportance.yml' (file:./config/application-MyTest_LowerImportance.yml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_LowerImportance.yaml' (file:./config/application-MyTest_LowerImportance.yaml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_MostImportant.properties' (file:./application-MyTest_MostImportant.properties) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_MostImportant.xml' (file:./application-MyTest_MostImportant.xml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_MostImportant.yml' (file:./application-MyTest_MostImportant.yml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_MostImportant.yaml' (file:./application-MyTest_MostImportant.yaml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_LowerImportance.properties' (file:./application-MyTest_LowerImportance.properties) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_LowerImportance.xml' (file:./application-MyTest_LowerImportance.xml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_LowerImportance.yml' (file:./application-MyTest_LowerImportance.yml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_LowerImportance.yaml' (file:./application-MyTest_LowerImportance.yaml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_MostImportant.properties' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_MostImportant.xml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_MostImportant.yml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_MostImportant.yaml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.properties' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.xml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.yml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.yaml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_MostImportant.properties' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_MostImportant.xml' resource not found
DEBUG 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Loaded config file 'file:/Users/xxx/dev/myproject/target/test-classes/application-MyTest_MostImportant.yml' (classpath:/application-MyTest_MostImportant.yml)
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_MostImportant.yaml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_LowerImportance.properties' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_LowerImportance.xml' resource not found
DEBUG 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Loaded config file 'file:/Users/xxx/dev/myproject/target/test-classes/application-MyTest_LowerImportance.yml' (classpath:/application-MyTest_LowerImportance.yml)
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_LowerImportance.yaml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_MostImportant-test.properties' (file:./config/application-MyTest_MostImportant-test.properties) resource not found

Python: How to use RegEx in an if statement?

Regex's shouldn't really be used in this fashion - unless you want something more complicated than what you're trying to do - for instance, you could just normalise your content string and comparision string to be:

if 'facebook.com' in content.lower():
    shutil.copy(x, "C:/Users/David/Desktop/Test/MyFiles2")

Access is denied when attaching a database

I moved a database mdf from the default Data folder to my asp.net app_data folder and ran into this problem trying to set the database back online.

I compared the security settings of the other file databases in the original location to the moved files and noticed that MSSQL$SQLEXPRESS was not assigned permissions to the files in their new location. I added Full control for "NT SERVICE\MSSQL$SQLEXPRESS" (must include that NT SERVICE) and it attached just fine.

It appears that the original Data folder has these permissions and the files inherit it. Move the files and the inheritance breaks of course.

I checked another project's mdf file which I created directly into its app_data folder. it does not have MSSQL$SQLEXPRESS permissions. Hmmm. I wonder why SQL Express likes one but not the other?

How to count instances of character in SQL Column

This will return number of occurance of N

select ColumnName, LEN(ColumnName)- LEN(REPLACE(ColumnName, 'N', '')) from Table

Win32Exception (0x80004005): The wait operation timed out

Look into re-indexing tables in your database.

You can first find out the fragmentation level - and if it's above 10% or so you could benefit from re-indexing. If it's very high it's likely this is creating a significant performance bottle neck.

http://blog.sqlauthority.com/2009/01/30/sql-server-2008-2005-rebuild-every-index-of-all-tables-of-database-rebuild-index-with-fillfactor/

This should be done regularly.

What is the significance of #pragma marks? Why do we need #pragma marks?

While searching for doc to point to about how pragma are directives for the compiler, I found this NSHipster article that does the job pretty well.

I hope you'll enjoy the reading

How to negate specific word in regex?

The accepted answer is nice but is really a work-around for the lack of a simple sub-expression negation operator in regexes. This is why grep --invert-match exits. So in *nixes, you can accomplish the desired result using pipes and a second regex.

grep 'something I want' | grep --invert-match 'but not these ones'

Still a workaround, but maybe easier to remember.

Efficient SQL test query or validation query that will work across all (or most) databases

For tests using select count(*), it should be more efficient to use select count(1) because * can cause it to read all the column data.

PHP compare time

$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
  echo "ok";
}

A solution using DateTime (that also regards the timezone).

$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
  echo "OK";
}

http://php.net/datetime.diff

How to loop through an associative array and get the key?

You can do:

foreach ($arr as $key => $value) {
 echo $key;
}

As described in PHP docs.

foreach for JSON array , syntax

Try this:

$.each(result,function(index, value){
    console.log('My array has at position ' + index + ', this value: ' + value);
});

How to change navigation bar color in iOS 7 or 6?

The behavior of tintColor for bars has changed on iOS 7.0. It no longer affects the bar's background and behaves as described for the tintColor property added to UIView. To tint the bar's background, please use -barTintColor.

navController.navigationBar.barTintColor = [UIColor navigationColor];

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

Adding to the popular answer to include this error:

"ERROR 1200 (HY000): The server is not configured as slave; fix in config file or with CHANGE MASTER TO",

Replication from slave in one shot:

In one terminal window:

mysql -h <Master_IP_Address> -uroot -p

After connecting,

RESET MASTER;
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;

The status appears as below: Note that position number varies!

+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      98  | your_DB      |                  |
+------------------+----------+--------------+------------------+

Export the dump similar to how he described "using another terminal"!

Exit and connect to your own DB(which is the slave):

mysql -u root -p

The type the below commands:

STOP SLAVE;

Import the Dump as mentioned (in another terminal, of course!) and type the below commands:

RESET SLAVE;
CHANGE MASTER TO 
  MASTER_HOST = 'Master_IP_Address', 
  MASTER_USER = 'your_Master_user', // usually the "root" user
  MASTER_PASSWORD = 'Your_MasterDB_Password', 
  MASTER_PORT = 3306, 
  MASTER_LOG_FILE = 'mysql-bin.000001', 
  MASTER_LOG_POS = 98; // In this case

Once logged, set the server_id parameter (usually, for new / non-replicated DBs, this is not set by default),

set global server_id=4000;

Now, start the slave.

START SLAVE;
SHOW SLAVE STATUS\G;

The output should be the same as he described.

  Slave_IO_Running: Yes
  Slave_SQL_Running: Yes

Note: Once replicated, the master and slave share the same password!

How to use JavaScript to change the form action

I wanted to use JavaScript to change a form's action, so I could have different submit inputs within the same form linking to different pages.

I also had the added complication of using Apache rewrite to change example.com/page-name into example.com/index.pl?page=page-name. I found that changing the form's action caused example.com/index.pl (with no page parameter) to be rendered, even though the expected URL (example.com/page-name) was displayed in the address bar.

To get around this, I used JavaScript to insert a hidden field to set the page parameter. I still changed the form's action, just so the address bar displayed the correct URL.

function setAction (element, page)
{
  if(checkCondition(page))
  {
    /* Insert a hidden input into the form to set the page as a parameter.
     */
    var input = document.createElement("input");
    input.setAttribute("type","hidden");
    input.setAttribute("name","page");
    input.setAttribute("value",page);
    element.form.appendChild(input);

    /* Change the form's action. This doesn't chage which page is displayed,
     * it just make the URL look right.
     */
    element.form.action = '/' + page;
    element.form.submit();
  }
}

In the form:

<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />

Here are my Apache rewrite rules:

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}

I'd be interested in any explanation as to why just setting the action didn't work.

GROUP BY without aggregate function

The only real use case for GROUP BY without aggregation is when you GROUP BY more columns than are selected, in which case the selected columns might be repeated. Otherwise you might as well use a DISTINCT.

It's worth noting that other RDBMS's do not require that all non-aggregated columns be included in the GROUP BY. For example in PostgreSQL if the primary key columns of a table are included in the GROUP BY then other columns of that table need not be as they are guaranteed to be distinct for every distinct primary key column. I've wished in the past that Oracle did the same as it would have made for more compact SQL in many cases.

Moving Panel in Visual Studio Code to right side

"Wokbench.panel.defaultLocation": "right"

Open settings using CTRL+., search for terminal and you should see this setting at the top. From the drop down below the settings explanation, choose right. See the screenshot below.

enter image description here

Token based authentication in Web API without any user interface

I think there is some confusion about the difference between MVC and Web Api. In short, for MVC you can use a login form and create a session using cookies. For Web Api there is no session. That's why you want to use the token.

You do not need a login form. The Token endpoint is all you need. Like Win described you'll send the credentials to the token endpoint where it is handled.

Here's some client side C# code to get a token:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //string token = GetToken("https://localhost:<port>/", userName, password);

    static string GetToken(string url, string userName, string password) {
        var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ), 
                        new KeyValuePair<string, string>( "username", userName ), 
                        new KeyValuePair<string, string> ( "Password", password )
                    };
        var content = new FormUrlEncodedContent(pairs);
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            var response = client.PostAsync(url + "Token", content).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

In order to use the token add it to the header of the request:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //var result = CallApi("https://localhost:<port>/something", token);

    static string CallApi(string url, string token) {
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            if (!string.IsNullOrWhiteSpace(token)) {
                var t = JsonConvert.DeserializeObject<Token>(token);

                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
            }
            var response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

Where Token is:

//using Newtonsoft.Json;

class Token
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string userName { get; set; }
    [JsonProperty(".issued")]
    public string issued { get; set; }
    [JsonProperty(".expires")]
    public string expires { get; set; }
}

Now for the server side:

In Startup.Auth.cs

        var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider("self"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // https
            AllowInsecureHttp = false
        };
        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(oAuthOptions);

And in ApplicationOAuthProvider.cs the code that actually grants or denies access:

//using Microsoft.AspNet.Identity.Owin;
//using Microsoft.Owin.Security;
//using Microsoft.Owin.Security.OAuth;
//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Threading.Tasks;

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _publicClientId;

    public ApplicationOAuthProvider(string publicClientId)
    {
        if (publicClientId == null)
            throw new ArgumentNullException("publicClientId");

        _publicClientId = publicClientId;
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        var user = await userManager.FindAsync(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
        var propertyDictionary = new Dictionary<string, string> { { "userName", user.UserName } };
        var properties = new AuthenticationProperties(propertyDictionary);

        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        // Token is validated.
        context.Validated(ticket);
    }

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }
        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        // Resource owner password credentials does not provide a client ID.
        if (context.ClientId == null)
            context.Validated();

        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
    {
        if (context.ClientId == _publicClientId)
        {
            var expectedRootUri = new Uri(context.Request.Uri, "/");

            if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                context.Validated();
        }
        return Task.FromResult<object>(null);
    }

}

As you can see there is no controller involved in retrieving the token. In fact, you can remove all MVC references if you want a Web Api only. I have simplified the server side code to make it more readable. You can add code to upgrade the security.

Make sure you use SSL only. Implement the RequireHttpsAttribute to force this.

You can use the Authorize / AllowAnonymous attributes to secure your Web Api. Additionally you can add filters (like RequireHttpsAttribute) to make your Web Api more secure. I hope this helps.

Set and Get Methods in java?

The above answers summarize the role of getters and setters better than I could, however I did want to add that your code should ideally be structured to reduce the use of pure getters and setters, i.e. those without complex constructions, validation, and so forth, as they break encapsulation. This doesn't mean you can't ever use them (stivlo's answer shows an example of a good use of getters and setters), just try to minimize how often you use them.

The problem is that getters and setters can act as a workaround for direct access of private data. Private data is called private because it's not meant to be shared with other objects; it's meant as a representation of the object's state. Allowing other objects to access an object's private fields defeats the entire purpose of setting it private in the first place. Moreover, you introduce coupling for every getter or setter you write. Consider this, for example:

private String foo;

public void setFoo(String bar) {
    this.foo = bar;
}

What happens if, somewhere down the road, you decide you don't need foo anymore, or you want to make it an integer? Every object that uses the setFoo method now needs to be changed along with foo.

How to set-up a favicon?

In my site, I use this:

<!-- for FF, Chrome, Opera -->
<link rel="icon" type="image/png" href="/assets/favicons/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="/assets/favicons/favicon-32x32.png" sizes="32x32">

<!-- for IE -->
<link rel="icon" type="image/x-icon" href="/assets/favicons/favicon.ico" >
<link rel="shortcut icon" type="image/x-icon" href="/assets/favicons/favicon.ico"/>

To simplify your life, use this favicons generator http://realfavicongenerator.net

Twitter Bootstrap Datepicker within modal window

Fwiw. Necro but still.

for <link href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css" rel="stylesheet">

I needed

<style type="text/css">
.ui-timepicker-container {z-index: 1151 !important;}
</style>    

in the HEAD of the doc for it to accept the override

I tried most every other solution on here before resorting to that.

.ssh directory not being created

As a slight improvement over the other answers, you can do the mkdir and chmod as a single operation using mkdir's -m switch.

$ mkdir -m 700 ${HOME}/.ssh

Usage

From a Linux system

$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx - umask
...
...

C# equivalent of the IsNull() function in SQL Server

Use the Equals method:

object value2 = null;
Console.WriteLine(object.Equals(value2,null));

How to add an event after close the modal window?

Few answers that may be useful, especially if you have dynamic content.

$('#dialogueForm').live("dialogclose", function(){
   //your code to run on dialog close
});

Or, when opening the modal, have a callback.

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

Finding the handle to a WPF window

Just use your window with the WindowsInteropHelper class:

// ... Window myWindow = get your Window instance...
IntPtr windowHandle = new WindowInteropHelper(myWindow).Handle;

Right now, you're asking for the Application's main window, of which there will always be one. You can use this same technique on any Window, however, provided it is a System.Windows.Window derived Window class.

How to run python script with elevated privilege on windows

Also if your working directory is different than you can use lpDirectory

    procInfo = ShellExecuteEx(nShow=showCmd,
                          lpVerb=lpVerb,
                          lpFile=cmd,
                          lpDirectory= unicode(direc),
                          lpParameters=params)

Will come handy if changing the path is not a desirable option remove unicode for python 3.X

BOOLEAN or TINYINT confusion

Just a note for php developers (I lack the necessary stackoverflow points to post this as a comment) ... the automagic (and silent) conversion to TINYINT means that php retrieves a value from a "BOOLEAN" column as a "0" or "1", not the expected (by me) true/false.

A developer who is looking at the SQL used to create a table and sees something like: "some_boolean BOOLEAN NOT NULL DEFAULT FALSE," might reasonably expect to see true/false results when a row containing that column is retrieved. Instead (at least in my version of PHP), the result will be "0" or "1" (yes, a string "0" or string "1", not an int 0/1, thank you php).

It's a nit, but enough to cause unit tests to fail.

Binding IIS Express to an IP Address

In order for IIS Express answer on any IP address, just leave the address blank, i.e:

bindingInformation=":8080:"

Don't forget to restart the IIS express before the changes can take place.

Required attribute on multiple checkboxes with the same name?

i had the same problem, my solution was apply the required attribute to all elements

<input type="checkbox" name="checkin_days[]" required="required" value="0" /><span class="w">S</span>
<input type="checkbox" name="checkin_days[]" required="required" value="1" /><span class="w">M</span>
<input type="checkbox" name="checkin_days[]" required="required" value="2" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="3" /><span class="w">W</span>
<input type="checkbox" name="checkin_days[]" required="required" value="4" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="5" /><span class="w">F</span>
<input type="checkbox" name="checkin_days[]" required="required" value="6" /><span class="w">S</span>

when the user check one of the elements i remove the required attribute from all elements:

var $checkedCheckboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]:checked'),
    $checkboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]');

$checkboxes.click(function() {

if($checkedCheckboxes.length) {
        $checkboxes.removeAttr('required');
    } else {
        $checkboxes.attr('required', 'required');
    }

 });

How to get last inserted id?

There are all sorts of ways to get the Last Inserted ID but the easiest way I have found is by simply retrieving it from the TableAdapter in the DataSet like so:

<Your DataTable Class> tblData = new <Your DataTable Class>();
<Your Table Adapter Class> tblAdpt = new <Your Table Adapter Class>();

/*** Initialize and update Table Data Here ***/

/*** Make sure to call the EndEdit() method ***/
/*** of any Binding Sources before update ***/
<YourBindingSource>.EndEdit();

//Update the Dataset
tblAdpt.Update(tblData);

//Get the New ID from the Table Adapter
long newID = tblAdpt.Adapter.InsertCommand.LastInsertedId;

Hope this Helps ...

Detect if string contains any spaces

var inValid = new RegExp('^[_A-z0-9]{1,}$');
var value = "test string";
var k = inValid.test(value);
alert(k);

How to scroll the page when a modal dialog is longer than the screen?

Window Page Scrollbar clickable when Modal is open

This one works for me. Pure CSS.

<style type="text/css">

body.modal-open {
padding-right: 17px !important;
}

.modal-backdrop.in {
margin-right: 16px; 

</style>

Try it and let me know

Should I Dispose() DataSet and DataTable?

Datasets implement IDisposable thorough MarshalByValueComponent, which implements IDisposable. Since datasets are managed there is no real benefit to calling dispose.

Convert an ArrayList to an object array

Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList implements Collection):

TypeA[] array = a.toArray(new TypeA[a.size()]);

On a side note, you should consider defining a to be of type List<TypeA> rather than ArrayList<TypeA>, this avoid some implementation specific definition that may not really be applicable for your application.

Also, please see this question about the use of a.size() instead of 0 as the size of the array passed to a.toArray(TypeA[])

python requests file upload

In Ubuntu you can apply this way,

to save file at some location (temporary) and then open and send it to API

      path = default_storage.save('static/tmp/' + f1.name, ContentFile(f1.read()))
      path12 = os.path.join(os.getcwd(), "static/tmp/" + f1.name)
      data={} #can be anything u want to pass along with File
      file1 = open(path12, 'rb')
      header = {"Content-Disposition": "attachment; filename=" + f1.name, "Authorization": "JWT " + token}
       res= requests.post(url,data,header)

git pull while not in a git directory

As some of my servers are on an old Ubuntu LTS versions, I can't easily upgrade git to the latest version (which supports the -C option as described in some answers).

This trick works well for me, especially because it does not have the side effect of some other answers that leave you in a different directory from where you started.

pushd /X/Y
git pull
popd

Or, doing it as a one-liner:

pushd /X/Y; git pull; popd

Both Linux and Windows have pushd and popd commands.

Add (insert) a column between two columns in a data.frame

df <- data.frame(a=c(1,2), b=c(3,4), c=c(5,6))
df %>%
  mutate(d= a/2) %>%
  select(a, b, d, c)

results

  a b   d c
1 1 3 0.5 5
2 2 4 1.0 6

I suggest to use dplyr::select after dplyr::mutate. It has many helpers to select/de-select subset of columns.

In the context of this question the order by which you select will be reflected in the output data.frame.

Unable to copy a file from obj\Debug to bin\Debug

after day with search and build and rebuild i found that you just need to turn off turn on the visual studio its look like it catch the service in different thread

How do I invoke a Java method when given the method name as a string?

//Step1 - Using string funClass to convert to class
String funClass = "package.myclass";
Class c = Class.forName(funClass);

//Step2 - instantiate an object of the class abov
Object o = c.newInstance();
//Prepare array of the arguments that your function accepts, lets say only one string here
Class[] paramTypes = new Class[1];
paramTypes[0]=String.class;
String methodName = "mymethod";
//Instantiate an object of type method that returns you method name
 Method m = c.getDeclaredMethod(methodName, paramTypes);
//invoke method with actual params
m.invoke(o, "testparam");

Column/Vertical selection with Keyboard in SublimeText 3

For macOS, you don't need install any plugin or mouse. just do like this :- Ctrl+Shift+Down

How to bind to a PasswordBox in MVVM

For anyone who is aware of the risks this implementation imposes, to have the password sync to your ViewModel simply add Mode=OneWayToSource.

XAML

<PasswordBox
    ff:PasswordHelper.Attach="True"
    ff:PasswordHelper.Password="{Binding Path=Password, Mode=OneWayToSource}" />

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

Ran into the same problem and at first defragmenting seemed to work. But it was for just a short while. Turns out the server the customer was using, was running the Express version and that has a licensing limit of about 10gb.

So even though the size was set to "unlimited", it wasn't.

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

How do you run a Python script as a service in Windows?

nssm in python 3+

(I converted my .py file to .exe with pyinstaller)

nssm: as said before

  • run nssm install {ServiceName}
  • On NSSM´s console:

    path: path\to\your\program.exe

    Startup directory: path\to\your\ #same as the path but without your program.exe

    Arguments: empty

If you don't want to convert your project to .exe

  • create a .bat file with python {{your python.py file name}}
  • and set the path to the .bat file

How can I use custom fonts on a website?

CSS lets you use custom fonts, downloadable fonts on your website. You can download the font of your preference, let’s say myfont.ttf, and upload it to your remote server where your blog or website is hosted.

@font-face {
    font-family: myfont;
    src: url('myfont.ttf');
}

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

In the Global.asax I am using the code below. My URI to get JSON is http://www.digantakumar.com/api/values?json=true

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new  QueryStringMapping("json", "true", "application/json"));
}

How can my iphone app detect its own version number?

Read the info.plist file of your app and get the value for key CFBundleShortVersionString. Reading info.plist will give you an NSDictionary object

Margin while printing html page

I also recommend pt versus cm or mm as it's more precise. Also, I cannot get @page to work in Chrome (version 30.0.1599.69 m) It ignores anything I put for the margins, large or small. But, you can get it to work with body margins on the document, weird.

How do I concatenate const/literal strings in C?

Do not forget to initialize the output buffer. The first argument to strcat must be a null terminated string with enough extra space allocated for the resulting string:

char out[1024] = ""; // must be initialized
strcat( out, null_terminated_string ); 
// null_terminated_string has less than 1023 chars

Get first 100 characters from string, respecting full words

## Get first limited character from a string ##

<?php 
  $content= $row->title;
  $result = substr($content, 0, 70);
  echo $result; 
  ?>

Truncate (not round) decimal places in SQL Server

SELECT CAST(Value as Decimal(10,2)) FROM TABLE_NAME;

Would give you 2 values after the decimal point. (MS SQL SERVER)

Show a message box from a class in c#?

System.Windows.MessageBox.Show("Hello world"); //WPF
System.Windows.Forms.MessageBox.Show("Hello world"); //WinForms

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

For me the config file was found "/etc/mysql/mysql.conf.d/mysqld.cnf" commenting out bind address did the trick.

As we can see here: Instead of skip-networking the default is now to listen only on localhost which is more compatible and is not less secure.

Get the decimal part from a double

The simplest variant is possibly with Math.truncate()

double value = 1.761
double decPart = value - Math.truncate(value)

Confirm deletion in modal / dialog using Twitter Bootstrap?

POST Recipe with navigation to target page and reusable Blade file

dfsq's answer is very nice. I modified it a bit to fit my needs: I actually needed a modal for the case that, after clicking, the user would also be navigated to the corresponding page. Executing the query asynchronously is not always what one needs.

Using Blade I created the file resources/views/includes/confirmation_modal.blade.php:

<div class="modal fade" id="confirmation-modal" tabindex="-1" role="dialog" aria-labelledby="confirmation-modal-label" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4>{{ $headerText }}</h4>
            </div>
            <div class="modal-body">
                {{ $bodyText }}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <form action="" method="POST" style="display:inline">
                    {{ method_field($verb) }}
                    {{ csrf_field() }}
                    <input type="submit" class="btn btn-danger btn-ok" value="{{ $confirmButtonText }}" />
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $('#confirmation-modal').on('show.bs.modal', function(e) {
        href = $(e.relatedTarget).data('href');

        // change href of button to corresponding target
        $(this).find('form').attr('action', href);
    });
</script>

Now, using it is straight-forward:

<a data-href="{{ route('data.destroy', ['id' => $data->id]) }}" data-toggle="modal" data-target="#confirmation-modal" class="btn btn-sm btn-danger">Remove</a>

Not much changed here and the modal can be included like this:

@include('includes.confirmation_modal', ['headerText' => 'Delete Data?', 'bodyText' => 'Do you really want to delete these data? This operation is irreversible.',
'confirmButtonText' => 'Remove Data', 'verb' => 'DELETE'])

Just by putting the verb in there, it uses it. This way, CSRF is also utilized.

Helped me, maybe it helps someone else.

How to get difference between two dates in Year/Month/Week/Day?

private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{

        int gyear = dateTimePicker1.Value.Year; 
        int gmonth = dateTimePicker1.Value.Month; 
        int gday = dateTimePicker1.Value.Day; 
        int syear = DateTime.Now.Year; 
        int smonth = DateTime.Now.Month; 
        int sday = DateTime.Now.Day;

        int difday = DateTime.DaysInMonth(syear, gmonth);

        agedisplay = (syear - gyear); 

        lmonth = (smonth - gmonth);
        lday = (sday - gday);


        if (smonth < gmonth)
        {
            agedisplay = agedisplay - 1;
        }
        if (smonth == gmonth)
        {
            if (sday < (gday))
            {
                agedisplay = agedisplay - 1;
            }
        }

        if (smonth < gmonth)
        {
            lmonth = (-(-smonth)+(-gmonth)+12);
        }
        if (lday < 0)
        {
            lday = difday - (-lday);
            lmonth = lmonth - 1;
        }

        if (smonth == gmonth && sday < gday&&gyear!=syear)
        {
            lmonth = 11;
        }

            ageDisplay.Text = Convert.ToString(agedisplay) + " Years,  " + lmonth + " Months,  " + lday + " Days.";

    }

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

SOAP vs REST (differences)

REST vs SOAP is not the right question to ask.

REST, unlike SOAP is not a protocol.

REST is an architectural style and a design for network-based software architectures.

REST concepts are referred to as resources. A representation of a resource must be stateless. It is represented via some media type. Some examples of media types include XML, JSON, and RDF. Resources are manipulated by components. Components request and manipulate resources via a standard uniform interface. In the case of HTTP, this interface consists of standard HTTP ops e.g. GET, PUT, POST, DELETE.

@Abdulaziz's question does illuminate the fact that REST and HTTP are often used in tandem. This is primarily due to the simplicity of HTTP and its very natural mapping to RESTful principles.

Fundamental REST Principles

Client-Server Communication

Client-server architectures have a very distinct separation of concerns. All applications built in the RESTful style must also be client-server in principle.

Stateless

Each client request to the server requires that its state be fully represented. The server must be able to completely understand the client request without using any server context or server session state. It follows that all state must be kept on the client.

Cacheable

Cache constraints may be used, thus enabling response data to be marked as cacheable or not-cacheable. Any data marked as cacheable may be reused as the response to the same subsequent request.

Uniform Interface

All components must interact through a single uniform interface. Because all component interaction occurs via this interface, interaction with different services is very simple. The interface is the same! This also means that implementation changes can be made in isolation. Such changes, will not affect fundamental component interaction because the uniform interface is always unchanged. One disadvantage is that you are stuck with the interface. If an optimization could be provided to a specific service by changing the interface, you are out of luck as REST prohibits this. On the bright side, however, REST is optimized for the web, hence incredible popularity of REST over HTTP!

The above concepts represent defining characteristics of REST and differentiate the REST architecture from other architectures like web services. It is useful to note that a REST service is a web service, but a web service is not necessarily a REST service.

See this blog post on REST Design Principles for more details on REST and the above stated bullets.

EDIT: update content based on comments

Java 8 optional: ifPresent return object orElseThrow exception

I'd prefer mapping after making sure the value is available

private String getStringIfObjectIsPresent(Optional<Object> object) {
   Object ob = object.orElseThrow(MyCustomException::new);
    // do your mapping with ob
   String result = your-map-function(ob);
  return result;
}

or one liner

private String getStringIfObjectIsPresent(Optional<Object> object) {
   return your-map-function(object.orElseThrow(MyCustomException::new));
}

Powershell folder size of folders without listing Subdirectories

Sorry to reanimate a dead thread, but I have just been dealing with this myself, and after finding all sorts of crazy bloated solutions, I managed to come up with this.

[Long]$actualSize = 0
foreach ($item in (Get-ChildItem $path -recurse | Where {-not $_.PSIsContainer} | ForEach-Object {$_.FullName})) {
   $actualSize += (Get-Item $item).length
}

Quickly and in few lines of code gives me a folder size in Bytes, than can easily be converted to any units you want with / 1MB or the like. Am I missing something? Compared to this overwrought mess it seems rather simple and to the point. Not to mention that code doesn't even work since the called function is not the same name as the defined function. And has been wrong for 6 years. ;) So, any reasons NOT to use this stripped down approach?

Spring Boot REST service exception handling

@RestControllerAdvice is a new feature of Spring Framework 4.3 to handle Exception with RestfulApi by a cross-cutting concern solution:

 package com.khan.vaquar.exception;

import javax.servlet.http.HttpServletRequest;

import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.khan.vaquar.domain.ErrorResponse;

/**
 * Handles exceptions raised through requests to spring controllers.
 **/
@RestControllerAdvice
public class RestExceptionHandler {

    private static final String TOKEN_ID = "tokenId";

    private static final Logger log = LoggerFactory.getLogger(RestExceptionHandler.class);

    /**
     * Handles InstructionExceptions from the rest controller.
     * 
     * @param e IntrusionException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IntrusionException.class)
    public ErrorResponse handleIntrusionException(HttpServletRequest request, IntrusionException e) {       
        log.warn(e.getLogMessage(), e);
        return this.handleValidationException(request, new ValidationException(e.getUserMessage(), e.getLogMessage()));
    }

    /**
     * Handles ValidationExceptions from the rest controller.
     * 
     * @param e ValidationException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = ValidationException.class)
    public ErrorResponse handleValidationException(HttpServletRequest request, ValidationException e) {     
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);

        if (e.getUserMessage().contains("Token ID")) {
            tokenId = "<OMITTED>";
        }

        return new ErrorResponse(   tokenId,
                                    HttpStatus.BAD_REQUEST.value(), 
                                    e.getClass().getSimpleName(),
                                    e.getUserMessage());
    }

    /**
     * Handles JsonProcessingExceptions from the rest controller.
     * 
     * @param e JsonProcessingException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = JsonProcessingException.class)
    public ErrorResponse handleJsonProcessingException(HttpServletRequest request, JsonProcessingException e) {     
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.BAD_REQUEST.value(), 
                                    e.getClass().getSimpleName(),
                                    e.getOriginalMessage());
    }

    /**
     * Handles IllegalArgumentExceptions from the rest controller.
     * 
     * @param e IllegalArgumentException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ErrorResponse handleIllegalArgumentException(HttpServletRequest request, IllegalArgumentException e) {
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.BAD_REQUEST.value(), 
                                    e.getClass().getSimpleName(), 
                                    e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = UnsupportedOperationException.class)
    public ErrorResponse handleUnsupportedOperationException(HttpServletRequest request, UnsupportedOperationException e) {
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.BAD_REQUEST.value(), 
                                    e.getClass().getSimpleName(), 
                                    e.getMessage());
    }

    /**
     * Handles MissingServletRequestParameterExceptions from the rest controller.
     * 
     * @param e MissingServletRequestParameterException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public ErrorResponse handleMissingServletRequestParameterException( HttpServletRequest request, 
                                                                        MissingServletRequestParameterException e) {
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.BAD_REQUEST.value(), 
                                    e.getClass().getSimpleName(), 
                                    e.getMessage());
    }

    /**
     * Handles NoHandlerFoundExceptions from the rest controller.
     * 
     * @param e NoHandlerFoundException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ErrorResponse handleNoHandlerFoundException(HttpServletRequest request, NoHandlerFoundException e) {
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.NOT_FOUND.value(), 
                                    e.getClass().getSimpleName(), 
                                    "The resource " + e.getRequestURL() + " is unavailable");
    }

    /**
     * Handles all remaining exceptions from the rest controller.
     * 
     * This acts as a catch-all for any exceptions not handled by previous exception handlers.
     * 
     * @param e Exception
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Exception.class)
    public ErrorResponse handleException(HttpServletRequest request, Exception e) {
        String tokenId = request.getParameter(TOKEN_ID);
        log.error(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.INTERNAL_SERVER_ERROR.value(), 
                                    e.getClass().getSimpleName(), 
                                    "An internal error occurred");
    }   

}

How many bytes in a JavaScript string?

You can try this:

  var b = str.match(/[^\x00-\xff]/g);
  return (str.length + (!b ? 0: b.length)); 

It worked for me.

Check if string ends with one of the strings from a list

Though not widely known, str.endswith also accepts a tuple. You don't need to loop.

>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True

How to POST JSON data with Python Requests?

The better way is:

url = "http://xxx.xxxx.xx"
data = {
    "cardno": "6248889874650987",
    "systemIdentify": "s08",
    "sourceChannel": 12
}
resp = requests.post(url, json=data)

Replace or delete certain characters from filenames of all files in a folder

Use PowerShell to do anything smarter for a DOS prompt. Here, I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _ underscores.

Dir |
Rename-Item -NewName { $_.Name -replace " ","_" }

EDIT :
Optionally, the Where-Object command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:

  • To skip any document files

    Dir |
    Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    
  • To process only directories (pre-3.0 version)

    Dir |
    Where-Object { $_.Mode -match "^d" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

    PowerShell v3.0 introduced new Dir flags. You can also use Dir -Directory there.

  • To skip any files already containing an underscore (or some other character)

    Dir |
    Where-Object { -not $_.Name.Contains("_") } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

Update values from one column in same table to another in SQL Server

UPDATE a
SET a.column1 = b.column2
FROM myTable a 
INNER JOIN myTable b
on a.myID = b.myID

in order for both "a" and "b" to work, both aliases must be defined

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: sdetail in mydt, Duplicate key: string: , Duplicate value:

I faced this error because i had written wrong database name in my php api part......

So this error may also occurs when you are fetching the data from database base, whose name is written incorrect by you.

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Looping through a DataTable

foreach (DataColumn col in rightsTable.Columns)
{
     foreach (DataRow row in rightsTable.Rows)
     {
          Console.WriteLine(row[col.ColumnName].ToString());           
     }
} 

How to remove files and directories quickly via terminal (bash shell)

rm -rf some_dir

-r "recursive" -f "force" (suppress confirmation messages)

Be careful!

CSS:Defining Styles for input elements inside a div

You can define style rules which only apply to specific elements inside your div with id divContainer like this:

#divContainer input { ... }
#divContainer input[type="radio"] { ... }
#divContainer input[type="text"] { ... }
/* etc */

How do I create a crontab through a script

Well /etc/crontab just an ascii file so the simplest is to just

 echo "*/15 * * * *   root     date" >> /etc/crontab

which will add a job which will email you every 15 mins. Adjust to taste, and test via grep or other means whether the line was already added to make your script idempotent.

On Ubuntu et al, you can also drop files in /etc/cron.* which is easier to do and test for---plus you don't mess with (system) config files such as /etc/crontab.

HashMap: One Key, multiple Values

Thinking about a Map with 2 keys immediately compelled me to use a user-defined key, and that would probably be a Class. Following is the key Class:

public class MapKey {
    private Object key1;
    private Object key2;

    public Object getKey1() {
        return key1;
    }

    public void setKey1(Object key1) {
        this.key1 = key1;
    }

    public Object getKey2() {
        return key2;
    }

    public void setKey2(Object key2) {
        this.key2 = key2;
    }
}


// Create first map entry with key <A,B>.
        MapKey mapKey1 = new MapKey();
        mapKey1.setKey1("A");
        mapKey1.setKey2("B");

How to convert interface{} to string?

You don't need to use a type assertion, instead just use the %v format specifier with Sprintf:

hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])

Could not resolve all dependencies for configuration ':classpath'

I had this issue and it was because I hadn't added an exception for gradle in my firewall (TinyWall).

Type safety: Unchecked cast

Well, first of all, you're wasting memory with the new HashMap creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:

private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");

Secondly, the compiler is complaining that you cast the object to a HashMap without checking if it is a HashMap. But, even if you were to do:

if(getApplicationContext().getBean("someMap") instanceof HashMap) {
    private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
}

You would probably still get this warning. The problem is, getBean returns Object, so it is unknown what the type is. Converting it to HashMap directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a HashMap<String, String>.

HashMaps are really maps that take an object as a key and have an object as a value, HashMap<Object, Object> if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a HashMap<String, String> because you could have HashMap<Date, Calendar> because the non-generic representation that is returned can have any objects.

If the code compiles, and you can execute String value = map.get("thisString"); without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a ClassCastException at runtime, because the generics cannot block this from happening in this case.

ElasticSearch: Unassigned Shards, how to fix?

In my case, the hard disk space upper bound was reached.

Look at this article: https://www.elastic.co/guide/en/elasticsearch/reference/current/disk-allocator.html

Basically, I ran:

PUT /_cluster/settings
{
  "transient": {
    "cluster.routing.allocation.disk.watermark.low": "90%",
    "cluster.routing.allocation.disk.watermark.high": "95%",
    "cluster.info.update.interval": "1m"
  }
}

So that it will allocate if <90% hard disk space used, and move a shard to another machine in the cluster if >95% hard disk space used; and it checks every 1 minute.

Maven Modules + Building a Single Specific Module

If you have previously run mvn install on project B it will have been installed to your local repository, so when you build package A Maven can resolve the dependency. So as long as you install project B each time you change it your builds for project A will be up to date.

You can define a multi-module project with an aggregator pom to build a set of projects.

It's also worthwhile mentioning m2eclipse, it integrates Maven into Eclipse and allows you to (optionally) resolve dependencies from the workspace. So if you are hacking away on multiple projects, the workspace content will be used for compilation. Once you are happy with your changes, run mvn install (on each project in turn, or using an aggregator) to put them in your local repository.

Specifying maxlength for multiline textbox

$('#txtInput').attr('maxLength', 100);

Custom exception type

//create error object
var error = new Object();
error.reason="some reason!";

//business function
function exception(){
    try{
        throw error;
    }catch(err){
        err.reason;
    }
}

Now we set add the reason or whatever properties we want to the error object and retrieve it. By making the error more reasonable.

Convert DataSet to List

Use the code below:

using Newtonsoft.Json;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(ds.Tables[0]);

Getting command-line password input in Python

This code will print an asterisk instead of every letter.

import sys
import msvcrt

passwor = ''
while True:
    x = msvcrt.getch()
    if x == '\r':
        break
    sys.stdout.write('*')
    passwor +=x

print '\n'+passwor

Creating a .p12 file

I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.

I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!

  1. Generate 2048-bit RSA private key:

    openssl genrsa -out key.pem 2048

  2. Generate a Certificate Signing Request:

    openssl req -new -sha256 -key key.pem -out csr.csr

  3. Generate a self-signed x509 certificate suitable for use on web servers.

    openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem

  4. Create SSL identity file in PKCS12 as mentioned here

    openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem

Create Directory When Writing To File In Node.js

My advise is: try not to rely on dependencies when you can easily do it with few lines of codes

Here's what you're trying to achieve in 14 lines of code:

fs.isDir = function(dpath) {
    try {
        return fs.lstatSync(dpath).isDirectory();
    } catch(e) {
        return false;
    }
};
fs.mkdirp = function(dirname) {
    dirname = path.normalize(dirname).split(path.sep);
    dirname.forEach((sdir,index)=>{
        var pathInQuestion = dirname.slice(0,index+1).join(path.sep);
        if((!fs.isDir(pathInQuestion)) && pathInQuestion) fs.mkdirSync(pathInQuestion);
    });
};

How do you add an action to a button programmatically in xcode

UIButton *btnNotification=[UIButton buttonWithType:UIButtonTypeCustom];
btnNotification.frame=CGRectMake(130,80,120,40);
btnNotification.backgroundColor=[UIColor greenColor];
[btnNotification setTitle:@"create Notification" forState:UIControlStateNormal];
[btnNotification addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnNotification];


}

-(void)btnClicked
{
    // Here You can write functionality 

}

How to hash a password

  1. Create a salt,
  2. Create a hash password with salt
  3. Save both hash and salt
  4. decrypt with password and salt... so developers cant decrypt password
public class CryptographyProcessor
{
    public string CreateSalt(int size)
    {
        //Generate a cryptographic random number.
          RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
         byte[] buff = new byte[size];
         rng.GetBytes(buff);
         return Convert.ToBase64String(buff);
    }


      public string GenerateHash(string input, string salt)
      { 
         byte[] bytes = Encoding.UTF8.GetBytes(input + salt);
         SHA256Managed sHA256ManagedString = new SHA256Managed();
         byte[] hash = sHA256ManagedString.ComputeHash(bytes);
         return Convert.ToBase64String(hash);
      }

      public bool AreEqual(string plainTextInput, string hashedInput, string salt)
      {
           string newHashedPin = GenerateHash(plainTextInput, salt);
           return newHashedPin.Equals(hashedInput); 
      }
 }

C#: Looping through lines of multiline string

Try using String.Split Method:

string text = @"First line
second line
third line";

foreach (string line in text.Split('\n'))
{
    // do something
}

Get encoding of a file in Windows

EncodingChecker

File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify.

File Encoding Checker requires .NET 4 or above to run.

How can I regenerate ios folder in React Native project?

As @Alok mentioned in the comments, you can do react-native eject to generate the ios and android folders. But you will need an app.json in your project first.

{"name": "example", "displayName": "Example"}

What is the format specifier for unsigned short int?

Try using the "%h" modifier:

scanf("%hu", &length);
        ^

ISO/IEC 9899:201x - 7.21.6.1-7

Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to short or unsigned short.

What's wrong with nullable columns in composite primary keys?

Fundamentally speaking nothing is wrong with a NULL in a multi-column primary key. But having one has implications the designer likely did not intend, which is why many systems throw an error when you try this.

Consider the case of module/package versions stored as a series of fields:

CREATE TABLE module
  (name        varchar(20) PRIMARY KEY,
   description text DEFAULT '' NOT NULL);

CREATE TABLE version
  (module      varchar(20) REFERENCES module,
   major       integer NOT NULL,
   minor       integer DEFAULT 0 NOT NULL,
   patch       integer DEFAULT 0 NOT NULL,
   release     integer DEFAULT 1 NOT NULL,
   ext         varchar(20),
   notes       text DEFAULT '' NOT NULL,
   PRIMARY KEY (module, major, minor, patch, release, ext));

The first 5 elements of the primary key are regularly defined parts of a release version, but some packages have a customized extension that is usually not an integer (like "rc-foo" or "vanilla" or "beta" or whatever else someone for whom four fields is insufficient might dream up). If a package does not have an extension, then it is NULL in the above model, and no harm would be done by leaving things that way.

But what is a NULL? It is supposed to represent a lack of information, an unknown. That said, perhaps this makes more sense:

CREATE TABLE version
  (module      varchar(20) REFERENCES module,
   major       integer NOT NULL,
   minor       integer DEFAULT 0 NOT NULL,
   patch       integer DEFAULT 0 NOT NULL,
   release     integer DEFAULT 1 NOT NULL,
   ext         varchar(20) DEFAULT '' NOT NULL,
   notes       text DEFAULT '' NOT NULL,
   PRIMARY KEY (module, major, minor, patch, release, ext));

In this version the "ext" part of the tuple is NOT NULL but defaults to an empty string -- which is semantically (and practically) different from a NULL. A NULL is an unknown, whereas an empty string is a deliberate record of "something not being present". In other words, "empty" and "null" are different things. Its the difference between "I don't have a value here" and "I don't know what the value here is."

When you register a package that lacks a version extension you know it lacks an extension, so an empty string is actually the correct value. A NULL would only be correct if you didn't know whether it had an extension or not, or you knew that it did but didn't know what it was. This situation is easier to deal with in systems where string values are the norm, because there is no way to represent an "empty integer" other than inserting 0 or 1, which will wind up being rolled up in any comparisons made later (which has its own implications)*.

Incidentally, both ways are valid in Postgres (since we're discussing "enterprise" RDMBSs), but comparison results can vary quite a bit when you throw a NULL into the mix -- because NULL == "don't know" so all results of a comparison involving a NULL wind up being NULL since you can't know something that is unknown. DANGER! Think carefully about that: this means that NULL comparison results propagate through a series of comparisons. This can be a source of subtle bugs when sorting, comparing, etc.

Postgres assumes you're an adult and can make this decision for yourself. Oracle and DB2 assume you didn't realize you were doing something silly and throw an error. This is usually the right thing, but not always -- you might actually not know and have a NULL in some cases and therefore leaving a row with an unknown element against which meaningful comparisons are impossible is correct behavior.

In any case you should strive to eliminate the number of NULL fields you permit across the entire schema and doubly so when it comes to fields that are part of a primary key. In the vast majority of cases the presence of NULL columns is an indication of un-normalized (as opposed to deliberately de-normalized) schema design and should be thought very hard about before being accepted.

[* NOTE: It is possible to create a custom type that is the union of integers and a "bottom" type that would semantically mean "empty" as opposed to "unknown". Unfortunately this introduces a bit of complexity in comparison operations and usually being truly type correct isn't worth the effort in practice as you shouldn't be permitted many NULL values at all in the first place. That said, it would be wonderful if RDBMSs would include a default BOTTOM type in addition to NULL to prevent the habit of casually conflating the semantics of "no value" with "unknown value".]

How to commit changes to a new branch

git checkout -b your-new-branch

git add <files>

git commit -m <message>

First, checkout your new branch. Then add all the files you want to commit to staging. Lastly, commit all the files you just added. You might want to do a git push origin your-new-branch afterward so your changes show up on the remote.

How to read multiple text files into a single RDD?

You can use a single textFile call to read multiple files. Scala:

sc.textFile(','.join(files)) 

Get element type with jQuery

As Distdev alluded to, you still need to differentiate the input type. That is to say,

$(this).prev().prop('tagName');

will tell you input, but that doesn't differentiate between checkbox/text/radio. If it's an input, you can then use

$('#elementId').attr('type');

to tell you checkbox/text/radio, so you know what kind of control it is.

How to delete a specific line in a file?

If you use Linux, you can try the following approach.
Suppose you have a text file named animal.txt:

$ cat animal.txt  
dog
pig
cat 
monkey         
elephant  

Delete the first line:

>>> import subprocess
>>> subprocess.call(['sed','-i','/.*dog.*/d','animal.txt']) 

then

$ cat animal.txt
pig
cat
monkey
elephant

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Had this issue after a reinstall today. Make sure the Application Experience service is started and not set to disabled. If its set to manual, I believe VS will start it.

How to implement private method in ES6 class with Traceur

Have you considered using factory functions? They usually are a much better alternative to classes or constructor functions in Javascript. Here is an example of how it works:

function car () {

    var privateVariable = 4

    function privateFunction () {}

    return {

        color: 'red',

        drive: function (miles) {},

        stop: function() {}

        ....

    }

}

Thanks to closures you have access to all private functions and variabels inside the returned object, but you can not access them from outside.

Unable to cast object of type 'System.DBNull' to type 'System.String`

A shorter form can be used:

return (accountNumber == DBNull.Value) ? string.Empty : accountNumber.ToString()

EDIT: Haven't paid attention to ExecuteScalar. It does really return null if the field is absent in the return result. So use instead:

return (accountNumber == null) ? string.Empty : accountNumber.ToString() 

Convert character to Date in R

You may be overcomplicating things, is there any reason you need the stringr package?

 df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
 as.Date(df$Date, "%m/%d/%Y %H:%M:%S")

[1] "2009-10-09" "2009-10-15"

More generally and if you need the time component as well, use strptime:

strptime(df$Date, "%m/%d/%Y %H:%M:%S")

I'm guessing at what your actual data might look at from the partial results you give.

long long int vs. long int vs. int64_t in C++

So my question is: Is there a way to tell the compiler that a long long int is the also a int64_t, just like long int is?

This is a good question or problem, but I suspect the answer is NO.

Also, a long int may not be a long long int.


# if __WORDSIZE == 64
typedef long int  int64_t;
# else
__extension__
typedef long long int  int64_t;
# endif

I believe this is libc. I suspect you want to go deeper.

In both 32-bit compile with GCC (and with 32- and 64-bit MSVC), the output of the program will be:

int:           0
int64_t:       1
long int:      0
long long int: 1

32-bit Linux uses the ILP32 data model. Integers, longs and pointers are 32-bit. The 64-bit type is a long long.

Microsoft documents the ranges at Data Type Ranges. The say the long long is equivalent to __int64.

However, the program resulting from a 64-bit GCC compile will output:

int:           0
int64_t:       1
long int:      1
long long int: 0

64-bit Linux uses the LP64 data model. Longs are 64-bit and long long are 64-bit. As with 32-bit, Microsoft documents the ranges at Data Type Ranges and long long is still __int64.

There's a ILP64 data model where everything is 64-bit. You have to do some extra work to get a definition for your word32 type. Also see papers like 64-Bit Programming Models: Why LP64?


But this is horribly hackish and does not scale well (actual functions of substance, uint64_t, etc)...

Yeah, it gets even better. GCC mixes and matches declarations that are supposed to take 64 bit types, so its easy to get into trouble even though you follow a particular data model. For example, the following causes a compile error and tells you to use -fpermissive:

#if __LP64__
typedef unsigned long word64;
#else
typedef unsigned long long word64;
#endif

// intel definition of rdrand64_step (http://software.intel.com/en-us/node/523864)
// extern int _rdrand64_step(unsigned __int64 *random_val);

// Try it:
word64 val;
int res = rdrand64_step(&val);

It results in:

error: invalid conversion from `word64* {aka long unsigned int*}' to `long long unsigned int*'

So, ignore LP64 and change it to:

typedef unsigned long long word64;

Then, wander over to a 64-bit ARM IoT gadget that defines LP64 and use NEON:

error: invalid conversion from `word64* {aka long long unsigned int*}' to `uint64_t*'

Truncate all tables in a MySQL database in one command?

if using sql server 2005, there is a hidden stored procedure that allows you to execute a command or a set of commands against all tables inside a database. Here is how you would call TRUNCATE TABLE with this stored procedure:

EXEC [sp_MSforeachtable] @command1="TRUNCATE TABLE ?"

Here is a good article that elaborates further.

For MySql, however, you could use mysqldump and specify the --add-drop-tables and --no-data options to drop and create all tables ignoring the data. like this:

mysqldump -u[USERNAME] -p[PASSWORD] --add-drop-table --no-data [DATABASE]

mysqldump usage guide from dev.mysql

Write a formula in an Excel Cell using VBA

You can try using FormulaLocal property instead of Formula. Then the semicolon should work.

merge two object arrays with Angular 2 and TypeScript?

try this

 data => {
                this.results = [...this.results, ...data.results];
                this._next = data.next;
            }

Get environment value in controller

To simplify: Only configuration files can access environment variables - and then pass them on.

Step 1.) Add your variable to your .env file, for example,

EXAMPLE_URL="http://google.com"

Step 2.) Create a new file inside of the config folder, with any name, for example,

config/example.php

Step 3.) Inside of this new file, I add an array being returned, containing that environment variable.

<?php
return [
  'url' => env('EXAMPLE_URL')
];

Step 4.) Because I named it "example", my configuration 'namespace' is now example. So now, in my controller I can access this variable with:

$url = \config('example.url');

Tip - if you add use Config; at the top of your controller, you don't need the backslash (which designates the root namespace). For example,

namespace App\Http\Controllers;
use Config; // Added this line

class ExampleController extends Controller
{
    public function url() {
        return config('example.url');
    }
}

Finally, commit the changes:

php artisan config:cache

--- IMPORTANT --- Remember to enter php artisan config:cache into the console once you have created your example.php file. Configuration files and variables are cached, so if you make changes you need to flush that cache - the same applies to the .env file being changed / added to.

What's the difference between `raw_input()` and `input()` in Python 3?

I'd like to add a little more detail to the explanation provided by everyone for the python 2 users. raw_input(), which, by now, you know that evaluates what ever data the user enters as a string. This means that python doesn't try to even understand the entered data again. All it will consider is that the entered data will be string, whether or not it is an actual string or int or anything.

While input() on the other hand tries to understand the data entered by the user. So the input like helloworld would even show the error as 'helloworld is undefined'.

In conclusion, for python 2, to enter a string too you need to enter it like 'helloworld' which is the common structure used in python to use strings.

How to change the docker image installation directory?

For Those looking in 2020. The following is for Windows 10 Machine:

  1. In the global Actions pane of Hyper-V Manager click Hyper-V Settings…
  2. Under Virtual Hard Disks change the location from the default to your desired location.
  3. Under Virtual Machines change the location from the default to your desired location, and click apply.

enter image description here

  1. Click OK to close the Hyper-V Settings page.

Using Server.MapPath in external C# Classes in ASP.NET

Can't you just add a reference to System.Web and then you can use Server.MapPath ?

Edit: Nowadays I'd recommend using the HostingEnvironment.MapPath Method:

It's a static method in System.Web assembly that Maps a virtual path to a physical path on the server. It doesn't require a reference to HttpContext.

Array vs ArrayList in performance

When deciding to use Array or ArrayList, your first instinct really shouldn't be worrying about performance, though they do perform differently. You first concern should be whether or not you know the size of the Array before hand. If you don't, naturally you would go with an array list, just for functionality.

How to embed a video into GitHub README.md?

just to extend @GabLeRoux's answer:

[<img src="https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg" width="50%">](https://youtu.be/<VIDEO ID>)

this way you will be able to adjust the size of the thumbnail image in the README.md file on you Github repo.

Angular 4 img src is not found

You have to mention the width for the image as default

 <img width="300" src="assets/company_logo.png">

its working for me based on all other alternate way.

Numpy: Creating a complex array from 2 real ones?

If your real and imaginary parts are the slices along the last dimension and your array is contiguous along the last dimension, you can just do

A.view(dtype=np.complex128)

If you are using single precision floats, this would be

A.view(dtype=np.complex64)

Here is a fuller example

import numpy as np
from numpy.random import rand
# Randomly choose real and imaginary parts.
# Treat last axis as the real and imaginary parts.
A = rand(100, 2)
# Cast the array as a complex array
# Note that this will now be a 100x1 array
A_comp = A.view(dtype=np.complex128)
# To get the original array A back from the complex version
A = A.view(dtype=np.float64)

If you want to get rid of the extra dimension that stays around from the casting, you could do something like

A_comp = A.view(dtype=np.complex128)[...,0]

This works because, in memory, a complex number is really just two floating point numbers. The first represents the real part, and the second represents the imaginary part. The view method of the array changes the dtype of the array to reflect that you want to treat two adjacent floating point values as a single complex number and updates the dimension accordingly.

This method does not copy any values in the array or perform any new computations, all it does is create a new array object that views the same block of memory differently. That makes it so that this operation can be performed much faster than anything that involves copying values. It also means that any changes made in the complex-valued array will be reflected in the array with the real and imaginary parts.

It may also be a little trickier to recover the original array if you remove the extra axis that is there immediately after the type cast. Things like A_comp[...,np.newaxis].view(np.float64) do not currently work because, as of this writing, NumPy doesn't detect that the array is still C-contiguous when the new axis is added. See this issue. A_comp.view(np.float64).reshape(A.shape) seems to work in most cases though.

How to Sort Date in descending order From Arraylist Date in android?

Date is Comparable so just create list of List<Date> and sort it using Collections.sort(). And use Collections.reverseOrder() to get comparator in reverse ordering.

From Java Doc

Returns a comparator that imposes the reverse ordering of the specified comparator. If the specified comparator is null, this method is equivalent to reverseOrder() (in other words, it returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface).

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

handleChange({target}) {
    const files = target.files
    target.value = ''
}

Storing files in SQL Server

There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.

There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)

The article is definitely worth a read.

How do I execute a bash script in Terminal?

$prompt: /path/to/script and hit enter. Note you need to make sure the script has execute permissions.

Php header location redirect not working

Make Sure that you don't leave a space before <?php when you start <?php tag at the top of the page.

Determine whether a Access checkbox is checked or not

Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.

In Access, there are two types:

  1. 2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.

  2. 3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.

Minor quibble with the answers:

There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:

  ?Me!MyCheckBox.Value
  ?Me!MyCheckBox

The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:

  If Me!MyCheckBox Then

...write one of these options:

  If (Me!MyCheckBox) Then  ' forces evaluation of the control

  If Me!MyCheckBox = True Then

  If (Me!MyCheckBox = True) Then

  If (Me!MyCheckBox = Not False) Then

Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.

Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

I know this answer is too late considering the question is dated 2010 but I came across this question as I was facing a similar problem myself. As already stated in the answer, normed=True means that the total area under the histogram is equal to 1 but the sum of heights is not equal to 1. However, I wanted to, for convenience of physical interpretation of a histogram, make one with sum of heights equal to 1.

I found a hint in the following question - Python: Histogram with area normalized to something other than 1

But I was not able to find a way of making bars mimic the histtype="step" feature hist(). This diverted me to : Matplotlib - Stepped histogram with already binned data

If the community finds it acceptable I should like to put forth a solution which synthesises ideas from both the above posts.

import matplotlib.pyplot as plt

# Let X be the array whose histogram needs to be plotted.
nx, xbins, ptchs = plt.hist(X, bins=20)
plt.clf() # Get rid of this histogram since not the one we want.

nx_frac = nx/float(len(nx)) # Each bin divided by total number of objects.
width = xbins[1] - xbins[0] # Width of each bin.
x = np.ravel(zip(xbins[:-1], xbins[:-1]+width))
y = np.ravel(zip(nx_frac,nx_frac))

plt.plot(x,y,linestyle="dashed",label="MyLabel")
#... Further formatting.

This has worked wonderfully for me though in some cases I have noticed that the left most "bar" or the right most "bar" of the histogram does not close down by touching the lowest point of the Y-axis. In such a case adding an element 0 at the begging or the end of y achieved the necessary result.

Just thought I'd share my experience. Thank you.

MATLAB, Filling in the area between two sets of data, lines in one figure

Building off of @gnovice's answer, you can actually create filled plots with shading only in the area between the two curves. Just use fill in conjunction with fliplr.

Example:

x=0:0.01:2*pi;                  %#initialize x array
y1=sin(x);                      %#create first curve
y2=sin(x)+.5;                   %#create second curve
X=[x,fliplr(x)];                %#create continuous x value array for plotting
Y=[y1,fliplr(y2)];              %#create y values for out and then back
fill(X,Y,'b');                  %#plot filled area

enter image description here

By flipping the x array and concatenating it with the original, you're going out, down, back, and then up to close both arrays in a complete, many-many-many-sided polygon.

How to test if a string contains one of the substrings in a list, in pandas?

One option is just to use the regex | character to try to match each of the substrings in the words in your Series s (still using str.contains).

You can construct the regex by joining the words in searchfor with |:

>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0    cat
1    hat
2    dog
3    fog
dtype: object

As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $ and ^ which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.

You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape:

>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']

The strings with in this new list will match each character literally when used with str.contains.

Getting all names in an enum as a String[]

You can put enum values to list of strings and convert to array:

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

            for (State state: State.values()) {
                stateList.add(state.toString());
            }

    String[] stateArray = new String[stateList.size()];
    stateArray = stateList.toArray(stateArray);

Send values from one form to another form

Constructors are the best ways to pass data between forms or Gui Objects you can do this. In the form1 click button you should have:

Form1.Enable = false;
Form2 f = new Form2();
f.ShowDialog();

In form 2, when the user clicks the button it should have a code like this or similar:

this.Close();
Form1 form = new Form1(textBox1.Text)
form.Show();

Once inside the form load of form 1 you can add code to do anything as you get the values from constructor.

how to import csv data into django models

For django 1.8 that im using,

I made a command that you can create objects dynamically in the future, so you can just put the file path of the csv, the model name and the app name of the relevant django application, and it will populate the relevant model without specified the field names. so if we take for example the next csv:

field1,field2,field3
value1,value2,value3
value11,value22,value33

it will create the objects [{field1:value1,field2:value2,field3:value3}, {field1:value11,field2:value22,field3:value33}] for the model name you will enter to the command.

the command code:

from django.core.management.base import BaseCommand
from django.db.models.loading import get_model
import csv


class Command(BaseCommand):
    help = 'Creating model objects according the file path specified'

    def add_arguments(self, parser):
        parser.add_argument('--path', type=str, help="file path")
        parser.add_argument('--model_name', type=str, help="model name")
        parser.add_argument('--app_name', type=str, help="django app name that the model is connected to")

    def handle(self, *args, **options):
        file_path = options['path']
        _model = get_model(options['app_name'], options['model_name'])
        with open(file_path, 'rb') as csv_file:
            reader = csv.reader(csv_file, delimiter=',', quotechar='|')
            header = reader.next()
            for row in reader:
                _object_dict = {key: value for key, value in zip(header, row)}
                _model.objects.create(**_object_dict)

note that maybe in later versions

from django.db.models.loading import get_model

is deprecated and need to be change to

from django.apps.apps import get_model

What is better, adjacency lists or adjacency matrices for graph problems in C++?

I am just going to touch on overcoming the trade-off of regular adjacency list representation, since other answers have covered other aspects.

It is possible to represent a graph in adjacency list with EdgeExists query in amortized constant time, by taking advantage of Dictionary and HashSet data structures. The idea is to keep vertices in a dictionary, and for each vertex, we keep a hash set referencing to other vertices it has edges with.

One minor trade-off in this implementation is that it will have space complexity O(V + 2E) instead of O(V + E) as in regular adjacency list, since edges are represented twice here (because each vertex have its own hash set of edges). But operations such as AddVertex, AddEdge, RemoveEdge can be done in amortized time O(1) with this implementation, except for RemoveVertex which takes O(V) like adjacency matrix. This would mean that other than implementation simplicity, adjacency matrix don't have any specific advantage. We can save space on sparse graph with almost the same performance in this adjacency list implementation.

Take a look at implementations below in Github C# repository for details. Note that for weighted graph it uses a nested dictionary instead of dictionary-hash set combination so as to accommodate weight value. Similarly for directed graph there is separate hash sets for in & out edges.

Advanced-Algorithms

Note: I believe using lazy deletion we can further optimize RemoveVertex operation to O(1) amortized, even though I haven't tested that idea. For example, upon deletion just mark the vertex as deleted in dictionary, and then lazily clear orphaned edges during other operations.

Removing carriage return and new-line from the end of a string in c#

string k = "This is my\r\nugly string. I want\r\nto change this. Please \r\n help!";
k = System.Text.RegularExpressions.Regex.Replace(k, @"\r\n+", " ");

HttpClient.GetAsync(...) never returns when using await/async

I'm going to put this in here more for completeness than direct relevance to the OP. I spent nearly a day debugging an HttpClient request, wondering why I was never getting back a response.

Finally found that I had forgotten to await the async call further down the call stack.

Feels about as good as missing a semicolon.

Should I use Python 32bit or Python 64bit

I had trouble running python app (running large dataframes) in 32 - got MemoryError message, while on 64 it worked fine.

Django: multiple models in one template using forms

I very recently had the some problem and just figured out how to do this. Assuming you have three classes, Primary, B, C and that B,C have a foreign key to primary

    class PrimaryForm(ModelForm):
        class Meta:
            model = Primary

    class BForm(ModelForm):
        class Meta:
            model = B
            exclude = ('primary',)

    class CForm(ModelForm):
         class Meta:
            model = C
            exclude = ('primary',)

    def generateView(request):
        if request.method == 'POST': # If the form has been submitted...
            primary_form = PrimaryForm(request.POST, prefix = "primary")
            b_form = BForm(request.POST, prefix = "b")
            c_form = CForm(request.POST, prefix = "c")
            if primary_form.is_valid() and b_form.is_valid() and c_form.is_valid(): # All validation rules pass
                    print "all validation passed"
                    primary = primary_form.save()
                    b_form.cleaned_data["primary"] = primary
                    b = b_form.save()
                    c_form.cleaned_data["primary"] = primary
                    c = c_form.save()
                    return HttpResponseRedirect("/viewer/%s/" % (primary.name))
            else:
                    print "failed"

        else:
            primary_form = PrimaryForm(prefix = "primary")
            b_form = BForm(prefix = "b")
            c_form = Form(prefix = "c")
     return render_to_response('multi_model.html', {
     'primary_form': primary_form,
     'b_form': b_form,
     'c_form': c_form,
      })

This method should allow you to do whatever validation you require, as well as generating all three objects on the same page. I have also used javascript and hidden fields to allow the generation of multiple B,C objects on the same page.

Creating an IFRAME using JavaScript

It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.

<div id="placeholder"></div>

<script id="iframeTemplate" type="text/html">
    <iframe src="...">
        <!-- replace this line with alternate content -->
    </iframe>
</script>

<script type="text/javascript">
var element,
    html,
    template;

element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;

element.innerHTML = html;
</script>

Concatenating elements in an array to a string

Use StringBuilder instead of StringBuffer, because it is faster than StringBuffer.

Sample code

String[] strArr = {"1", "2", "3"};
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < strArr.length; i++) {
   strBuilder.append(strArr[i]);
}
String newString = strBuilder.toString();

Here's why this is a better solution to using string concatenation: When you concatenate 2 strings, a new string object is created and character by character copy is performed.
Effectively meaning that the code complexity would be the order of the squared of the size of your array!

(1+2+3+ ... n which is the number of characters copied per iteration). StringBuilder would do the 'copying to a string' only once in this case reducing the complexity to O(n).

How to add an element at the end of an array?

To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).

What you can do is create a new array one element larger and fill in the new element in the last slot:

public static int[] append(int[] array, int value) {
     int[] result = Arrays.copyOf(array, array.length + 1);
     result[result.length - 1] = value;
     return result;
}

This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.

One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.

And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.

What is Express.js?

Express.js created by TJ Holowaychuk and now managed by the community. It is one of the most popular frameworks in the node.js. Express can also be used to develop various products such as web applications or RESTful API.For more information please read on the expressjs.com official site.

Correct set of dependencies for using Jackson mapper

The package names in Jackson 2.x got changed to com.fasterxml1 from org.codehaus2. So if you just need ObjectMapper, I think Jackson 1.X can satisfy with your needs.