Programs & Examples On #Rsyslog

Rsyslog is enhanced syslogd with lot of enhanced features

Understanding the Linux oom-killer's logs

Sum of total_vm is 847170 and sum of rss is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.

Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.

rss for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss and file-rss.

[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB

what is the use of xsi:schemaLocation?

If you go into any of those locations, then you will find what is defined in those schema. For example, it tells you what is the data type of the ini-method key words value.

When to use: Java 8+ interface default method, vs. abstract method

Whenever we have a choice between abstract class and interface we should always (almost) prefer default (also known as defender or virtual extensions) methods.

  1. Default methods have put an end to classic pattern of interface and a companion class that implements most or all of the methods in that interface. An example is Collection and AbstractCollection. Now we should implement the methods in the interface itself to provide default functionality. The classes which implement the interface has choice to override the methods or inherit the default implementation.

  2. Another important use of default methods is interface evolution. Suppose I had a class Ball as:

    public class Ball implements Collection { ... }

Now in Java 8 a new feature streams in introduced. We can get a stream by using stream method added to the interface. If stream were not a default method all the implementations for Collection interface would have broken as they would not be implementing this new method. Adding a non-default method to an interface is not source-compatible.

But suppose we do not recompile the class and use an old jar file which contains this class Ball. The class will load fine without this missing method, instances can be created and it seems everything is working fine. BUT if program invokes stream method on instance of Ball we will get AbstractMethodError. So making method default solved both the problems.

Java 9 has got even private methods in interface which can be used to encapsulate the common code logic that was used in the interface methods that provided a default implementation.

Incrementing a date in JavaScript

Two methods:

1:

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)

2: Similar to the previous method

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)

Calculate distance between 2 GPS coordinates

This is very easy to do with geography type in SQL Server 2008.

SELECT geography::Point(lat1, lon1, 4326).STDistance(geography::Point(lat2, lon2, 4326))
-- computes distance in meters using eliptical model, accurate to the mm

4326 is SRID for WGS84 elipsoidal Earth model

Symbol for any number of any characters in regex?

Yes, there is one, it's the asterisk: *

a* // looks for 0 or more instances of "a"

This should be covered in any Java regex tutorial or documentation that you look up.

How to parse XML using jQuery?

I assume you are loading the XML from an external file. With $.ajax(), it's quite simple actually:

$.ajax({
    url: 'xmlfile.xml',
    dataType: 'xml',
    success: function(data){
        // Extract relevant data from XML
        var xml_node = $('Pages',data);
        console.log( xml_node.find('Page[Name="test"] > controls > test').text() );
    },
    error: function(data){
        console.log('Error loading XML data');
    }
});

Also, you should be consistent about the XML node naming. You have both lowercase and capitalized node names (<Page> versus <page>) which can be confusing when you try to use XML tree selectors.

How to remove from a map while iterating it?

The C++20 draft contains the convenience function std::erase_if.

So you can use that function to do it as a one-liner.

std::map<K, V> map_obj;
//calls needs_removing for each element and erases it, if true was reuturned
std::erase_if(map_obj,needs_removing);
//if you need to pass only part of the key/value pair
std::erase_if(map_obj,[](auto& kv){return needs_removing(kv.first);});

C++ auto keyword. Why is it magic?

It's Magic is it's ability to reduce having to write code for every Variable Type passed into specific functions. Consider a Python similar print() function in it's C base.

#include <iostream>
#include <string>
#include <array>

using namespace std;

void print(auto arg) {
     cout<<arg<<" ";
}

int main()
{
  string f = "String";//tok assigned
  int x = 998;
  double a = 4.785;
  string b = "C++ Auto !";
//In an opt-code ASCII token stream would be iterated from tok's as:
  print(a);
  print(b);
  print(x);
  print(f);
}

Append a single character to a string or char array in java?

new StringBuilder().append(str.charAt(0))
                   .append(str.charAt(10))
                   .append(str.charAt(20))
                   .append(str.charAt(30))
                   .toString();

This way you can get the new string with whatever characters you want.

What is the reason for the error message "System cannot find the path specified"?

The following worked for me:

  1. Open the Registry Editor (press windows key, type regedit and hit Enter) .
  2. Navigate to HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun and clear the values.
  3. Also check HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun.

How to write hello world in assembler under Windows?

Flat Assembler does not need an extra linker. This makes assembler programming quite easy. It is also available for Linux.

This is hello.asm from the Fasm examples:

include 'win32ax.inc'

.code

  start:
    invoke  MessageBox,HWND_DESKTOP,"Hi! I'm the example program!",invoke GetCommandLine,MB_OK
    invoke  ExitProcess,0

.end start

Fasm creates an executable:

>fasm hello.asm
flat assembler  version 1.70.03  (1048575 kilobytes memory)
4 passes, 1536 bytes.

And this is the program in IDA:

enter image description here

You can see the three calls: GetCommandLine, MessageBox and ExitProcess.

long long in C/C++

It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).

The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.

jQuery to loop through elements with the same class

In JavaScript ES6 .forEach() over an array-like NodeList collection given by Element.querySelectorAll()

_x000D_
_x000D_
document.querySelectorAll('.testimonial').forEach( el => {_x000D_
  el.style.color = 'red';_x000D_
  console.log( `Element ${el.tagName} with ID #${el.id} says: ${el.textContent}` );_x000D_
});
_x000D_
<p class="testimonial" id="1">This is some text</p>_x000D_
<div class="testimonial" id="2">Lorem ipsum</div>
_x000D_
_x000D_
_x000D_

Select multiple images from android gallery

Hi below code is working fine.

 Cursor imagecursor1 = managedQuery(
    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
    null, orderBy + " DESC");

   this.imageUrls = new ArrayList<String>();
  imageUrls.size();

   for (int i = 0; i < imagecursor1.getCount(); i++) {
   imagecursor1.moveToPosition(i);
   int dataColumnIndex = imagecursor1
     .getColumnIndex(MediaStore.Images.Media.DATA);
   imageUrls.add(imagecursor1.getString(dataColumnIndex));
  }

   options = new DisplayImageOptions.Builder()
  .showStubImage(R.drawable.stub_image)
  .showImageForEmptyUri(R.drawable.image_for_empty_url)
  .cacheInMemory().cacheOnDisc().build();

   imageAdapter = new ImageAdapter(this, imageUrls);

   gridView = (GridView) findViewById(R.id.PhoneImageGrid);
  gridView.setAdapter(imageAdapter);

You want to more clarifications. http://mylearnandroid.blogspot.in/2014/02/multiple-choose-custom-gallery.html

How to add a new line of text to an existing file in Java?

On line 2 change new FileWriter(my_file_name) to new FileWriter(my_file_name, true) so you're appending to the file rather than overwriting.

File f = new File("/path/of/the/file");
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
            bw.append(line);
            bw.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

How do I redirect to another webpage?

First write properly. You want to navigate within an application for another link from your application for another link. Here is the code:

window.location.href = "http://www.google.com";

And if you want to navigate pages within your application then I also have code, if you want.

Rotate camera in Three.js with mouse

Take a look at THREE.PointerLockControls

How can I get a list of Git branches, ordered by most recent commit?

I pipe the output from the accepted answer into dialog, to give me an interactive list:

#!/bin/bash

TMP_FILE=/tmp/selected-git-branch

eval `resize`
dialog --title "Recent Git Branches" --menu "Choose a branch" $LINES $COLUMNS $(( $LINES - 8 )) $(git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short) %(committerdate:short)') 2> $TMP_FILE

if [ $? -eq 0 ]
then
    git checkout $(< $TMP_FILE)
fi

rm -f $TMP_FILE

clear

Save as (e.g.) ~/bin/git_recent_branches.sh and chmod +x it. Then git config --global alias.rb '!git_recent_branches.sh' to give me a new git rb command.

How to unload a package without restarting R

When you are going back and forth between scripts it may only sometimes be necessary to unload a package. Here's a simple IF statement that will prevent warnings that would appear if you tried to unload a package that was not currently loaded.

if("package:vegan" %in% search()) detach("package:vegan", unload=TRUE) 

Including this at the top of a script might be helpful.

I hope that makes your day!

Limit file format when using <input type="file">?

You could actually do it with javascript but remember js is client side, so you would actually be "warning users" what type of files they can upload, if you want to AVOID (restrict or limit as you said) certain type of files you MUST do it server side.

Look at this basic tut if you would like to get started with server side validation. For the whole tutorial visit this page.

Good luck!

Base64 String throwing invalid character error

string stringToDecrypt = HttpContext.Current.Request.QueryString.ToString()

//change to string stringToDecrypt = HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString.ToString())

Save file Javascript with file name

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

Here a compatibility table for downloadattribute: http://caniuse.com/download

Getting results between two dates in PostgreSQL

just had the same question, and answered this way, if this could help.

select * 
from table
where start_date between '2012-01-01' and '2012-04-13'
or    end_date   between '2012-01-01' and '2012-04-13'

Connect different Windows User in SQL Server Management Studio (2005 or later)

One other way that I discovered is to go to "Start" > "Control Panel" > "Stored Usernames and passwords" (Administrative Tools > Credential Manager in Windows 7) and add the domain account that you would use with the "runas" command.

Then, in SQL Management Studio 2005, just select the "Windows Authentication" and input the server you wanna connect to (even though the user that you can see greyed out is still the local user)... and it works!

Don't ask me why ! :)

Edit: Make sure to include ":1433" after the server name in Credential Manager or it may not connect due to not trusting the domain.

How to efficiently use try...catch blocks in PHP

Important note

The following discussion assumes that we are talking about code structured as in the example above: no matter which alternative is chosen, an exception will cause the method to logically stop doing whatever it was in the middle of.


As long as you intend to do the same thing no matter which statement in the try block throws an exception, then it's certainly better to use a single try/catch. For example:

function createCar()
{
    try {
      install_engine();
      install_brakes();
    } catch (Exception $e) {
        die("I could not create a car");
    }
}

Multiple try/catch blocks are useful if you can and intend to handle the failure in a manner specific to what exactly caused it.

function makeCocktail()
{
    try {
        pour_ingredients();
        stir();
    } catch (Exception $e) {
        die("I could not make you a cocktail");
    }

    try {
        put_decorative_umbrella();
    } catch (Exception $e) {
        echo "We 're out of umbrellas, but the drink itself is fine"
    }
}

How to reset db in Django? I get a command 'reset' not found error

python manage.py flush

deleted old db contents,

Don't forget to create new superuser:

python manage.py createsuperuser

Getting Django admin url for an object

Here's another option, using models:

Create a base model (or just add the admin_link method to a particular model)

class CommonModel(models.Model):
    def admin_link(self):
        if self.pk:
            return mark_safe(u'<a target="_blank" href="../../../%s/%s/%s/">%s</a>' % (self._meta.app_label,
                    self._meta.object_name.lower(), self.pk, self))
        else:
            return mark_safe(u'')
    class Meta:
        abstract = True

Inherit from that base model

   class User(CommonModel):
        username = models.CharField(max_length=765)
        password = models.CharField(max_length=192)

Use it in a template

{{ user.admin_link }}

Or view

user.admin_link()

CSS background-image - What is the correct usage?

Have a look at the respective sitepoint reference pages for background-image and URIs

  1. It does not have to be in quotes but can use them if you like. (I think IE5/Mac does not support single quotes).
  2. Both relative and absolute is possible; a relative path is relative to the path of the css file.

How to replace four spaces with a tab in Sublime Text 2?

Do a regex "Search" for \t (backslash-t, a tab), and replace with four spaces.

Either the main menu, or lower-right status-bar spacing menu does the same thing, with less work.

How to sort by Date with DataTables jquery plugin?

I realize this is a two year old question, but I still found it useful. I ended up using the sample code provided by Fudgey but with a minor mod. Saved me some time, thanks!

jQuery.fn.dataTableExt.oSort['us_date-asc']  = function(a,b) { 
  var x = new Date($(a).text()),
  y = new Date($(b).text());
  return ((x < y) ? -1 : ((x > y) ?  1 : 0)); 
}; 

jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) { 
  var x = new Date($(a).text()),
  y = new Date($(b).text());
  return ((x < y) ? 1 : ((x > y) ?  -1 : 0)); 
}; 

Mixing C# & VB In The Same Project

Why don't you just compile your VB code into a library(.dll).Reference it later from your code and that's it. Managed dlls contain MSIL to which both c# and vb are compiled.

Getting the array length of a 2D array in Java

There's not a cleaner way at the language level because not all multidimensional arrays are rectangular. Sometimes jagged (differing column lengths) arrays are necessary.

You could easy create your own class to abstract the functionality you need.

If you aren't limited to arrays, then perhaps some of the various collection classes would work as well, like a Multimap.

What is the difference between functional and non-functional requirements?

Functional requirements

  1. Functional requirements specifies a function that a system or system component must be able to perform. It can be documented in various ways. The most common ones are written descriptions in documents, and use cases.

  2. Use cases can be textual enumeration lists as well as diagrams, describing user actions. Each use case illustrates behavioural scenarios through one or more functional requirements. Often, though, an analyst will begin by eliciting a set of use cases, from which the analyst can derive the functional requirements that must be implemented to allow a user to perform each use case.

  3. Functional requirements is what a system is supposed to accomplish. It may be

    • Calculations
    • Technical details
    • Data manipulation
    • Data processing
    • Other specific functionality
  4. A typical functional requirement will contain a unique name and number, a brief summary, and a rationale. This information is used to help the reader understand why the requirement is needed, and to track the requirement through the development of the system.

Non-functional requirements

LBushkin have already explained more about Non-functional requirements. I will add more.

  1. Non-functional requirements are any other requirement than functional requirements. This are the requirements that specifies criteria that can be used to judge the operation of a system, rather than specific behaviours.

  2. Non-functional requirements are in the form of "system shall be ", an overall property of the system as a whole or of a particular aspect and not a specific function. The system's overall properties commonly mark the difference between whether the development project has succeeded or failed.

  3. Non-functional requirements - can be divided into two main categories:

    • Execution qualities, such as security and usability, which are observable at run time.
    • Evolution qualities, such as testability, maintainability, extensibility and scalability, which are embodied in the static structure of the software system.
  4. Non-functional requirements place restrictions on the product being developed, the development process, and specify external constraints that the product must meet.
  5. The IEEE-Std 830 - 1993 lists 13 non-functional requirements to be included in a Software Requirements Document.
  1. Performance requirements
  2. Interface requirements
  3. Operational requirements
  4. Resource requirements
  5. Verification requirements
  6. Acceptance requirements
  7. Documentation requirements
  8. Security requirements
  9. Portability requirements
  10. Quality requirements
  11. Reliability requirements
  12. Maintainability requirements
  13. Safety requirements

Whether or not a requirement is expressed as a functional or a non-functional requirement may depend:

  • on the level of detail to be included in the requirements document
  • the degree of trust which exists between a system customer and a system developer.

Ex. A system may be required to present the user with a display of the number of records in a database. This is a functional requirement. How up-to-date [update] this number needs to be, is a non-functional requirement. If the number needs to be updated in real time, the system architects must ensure that the system is capable of updating the [displayed] record count within an acceptably short interval of the number of records changing.

References:

  1. Functional requirement
  2. Non-functional requirement
  3. Quantification and Traceability of Requirements

Difference between exit() and sys.exit() in Python

If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing. See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.

psycopg2: insert multiple rows with one query

Finally in SQLalchemy1.2 version, this new implementation is added to use psycopg2.extras.execute_batch() instead of executemany when you initialize your engine with use_batch_mode=True like:

engine = create_engine(
    "postgresql+psycopg2://scott:tiger@host/dbname",
    use_batch_mode=True)

http://docs.sqlalchemy.org/en/latest/changelog/migration_12.html#change-4109

Then someone would have to use SQLalchmey won't bother to try different combinations of sqla and psycopg2 and direct SQL together..

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

My app has a fragment to loading in 3 secs, but when the fist screen is preparing to show, I press home button and resume run it, it show the same error, so It edit my code and it ran very smooth:

new Handler().post(new Runnable() {
        public void run() {
            if (saveIns == null) {
                mFragment = new Fragment_S1_loading();
                getFragmentManager().beginTransaction()
                        .replace(R.id.container, mFragment).commit();
            }
            getActionBar().hide();
            // Loading screen in 3 secs:
            mCountDownTimerLoading = new CountDownTimer(3000, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    if (saveIns == null) {// TODO bug when start app and press home
                                            // button
                        getFragmentManager()
                                .beginTransaction()
                                .replace(R.id.container,
                                        new Fragment_S2_sesstion1()).commitAllowingStateLoss();
                    }
                    getActionBar().show();
                }
            }.start();
        }
    });

NOTE: add commitAllowingStateLoss() instead of commit()

Reusing output from last command in Bash

The answer is no. Bash doesn't allocate any output to any parameter or any block on its memory. Also, you are only allowed to access Bash by its allowed interface operations. Bash's private data is not accessible unless you hack it.

filter items in a python dictionary where keys contain a specific string

You can use the built-in filter function to filter dictionaries, lists, etc. based on specific conditions.

filtered_dict = dict(filter(lambda item: filter_str in item[0], d.items()))

The advantage is that you can use it for different data structures.

How do I use namespaces with TypeScript external modules?

Try to organize by folder:

baseTypes.ts

export class Animal {
    move() { /* ... */ }
}

export class Plant {
    photosynthesize() { /* ... */ }
}

dog.ts

import b = require('./baseTypes');

export class Dog extends b.Animal {
    woof() { }
}   

tree.ts

import b = require('./baseTypes');

class Tree extends b.Plant {
}

LivingThings.ts

import dog = require('./dog')
import tree = require('./tree')

export = {
    dog: dog,
    tree: tree
}

main.ts

import LivingThings = require('./LivingThings');
console.log(LivingThings.Tree)
console.log(LivingThings.Dog)

The idea is that your module themselves shouldn't care / know they are participating in a namespace, but this exposes your API to the consumer in a compact, sensible way which is agnostic to which type of module system you are using for the project.

How eliminate the tab space in the column in SQL Server 2008

Try this code

SELECT REPLACE([Column], char(9), '') From [dbo.Table] 

char(9) is the TAB character

Force IE9 to emulate IE8. Possible?

You can use the document compatibility mode to do this, which is what you were trying.. However, thing to note is: It must appear in the Web page's header (the HEAD section) before all other elements, except for the title element and other meta elements Hope that was the issue.. Also, The X-UA-compatible header is not case sensitive Refer: http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#SetMode

Edit: in case something happens to kill the msdn link, here is the content:

Specifying Document Compatibility Modes

You can use document modes to control the way Internet Explorer interprets and displays your webpage. To specify a specific document mode for your webpage, use the meta element to include an X-UA-Compatible header in your webpage, as shown in the following example.

<html>
<head>
  <!-- Enable IE9 Standards mode -->
  <meta http-equiv="X-UA-Compatible" content="IE=9" >
  <title>My webpage</title>
</head>
<body>
  <p>Content goes here.</p>
</body>
</html> 

If you view this webpage in Internet Explorer 9, it will be displayed in IE9 mode.

The following example specifies EmulateIE7 mode.

<html>
<head>
  <!-- Mimic Internet Explorer 7 -->
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
  <title>My webpage</title>
</head>
<body>
  <p>Content goes here.</p>
</body>
</html> 

In this example, the X-UA-Compatible header directs Internet Explorer to mimic the behavior of Internet Explorer 7 when determining how to display the webpage. This means that Internet Explorer will use the directive (or lack thereof) to choose the appropriate document type. Because this page does not contain a directive, the example would be displayed in IE5 (Quirks) mode.

Show or hide element in React

Here is my approach.

import React, { useState } from 'react';

function ToggleBox({ title, children }) {
  const [isOpened, setIsOpened] = useState(false);

  function toggle() {
    setIsOpened(wasOpened => !wasOpened);
  }

  return (
    <div className="box">
      <div className="boxTitle" onClick={toggle}>
        {title}
      </div>
      {isOpened && (
        <div className="boxContent">
          {children}
        </div>
      )}
    </div>
  );
}

In code above, to achieve this, I'm using code like:

{opened && <SomeElement />}

That will render SomeElement only if opened is true. It works because of the way how JavaScript resolve logical conditions:

true && true && 2; // will output 2
true && false && 2; // will output false
true && 'some string'; // will output 'some string'
opened && <SomeElement />; // will output SomeElement if `opened` is true, will output false otherwise (and false will be ignored by react during rendering)
// be careful with 'falsy' values eg
const someValue = 0;
someValue && <SomeElement /> // will output 0, which will be rednered by react
// it'll be better to:
!!someValue && <SomeElement /> // will render nothing as we cast the value to boolean

Reasons for using this approach instead of CSS 'display: none';

  • While it might be 'cheaper' to hide an element with CSS - in such case 'hidden' element is still 'alive' in react world (which might make it actually way more expensive)
    • it means that if props of the parent element (eg. <TabView>) will change - even if you see only one tab, all 5 tabs will get re-rendered
    • the hidden element might still have some lifecycle methods running - eg. it might fetch some data from the server after every update even tho it's not visible
    • the hidden element might crash the app if it'll receive incorrect data. It might happen as you can 'forget' about invisible nodes when updating the state
    • you might by mistake set wrong 'display' style when making element visible - eg. some div is 'display: flex' by default, but you'll set 'display: block' by mistake with display: invisible ? 'block' : 'none' which might break the layout
    • using someBoolean && <SomeNode /> is very simple to understand and reason about, especially if your logic related to displaying something or not gets complex
    • in many cases, you want to 'reset' element state when it re-appears. eg. you might have a slider that you want to set to initial position every time it's shown. (if that's desired behavior to keep previous element state, even if it's hidden, which IMO is rare - I'd indeed consider using CSS if remembering this state in a different way would be complicated)

How to convert int to NSString?

Primitives can be converted to objects with @() expression. So the shortest way is to transform int to NSNumber and pick up string representation with stringValue method:

NSString *strValue = [@(myInt) stringValue];

or

NSString *strValue = @(myInt).stringValue;

How to Retrieve value from JTextField in Java Swing?

testField.getText()

See the java doc for JTextField

Sample code can be:

button.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent ae){
      String textFieldValue = testField.getText();
      // .... do some operation on value ...
   }
})

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

I agree with the above comments about overriding toString() on your own classes (and about automating that process as much as possible).

For classes you didn't define, you could write a ToStringHelper class with an overloaded method for each library class you want to have handled to your own tastes:

public class ToStringHelper {
    //... instance configuration here (e.g. punctuation, etc.)
    public toString(List m) {
        // presentation of List content to your liking
    }
    public toString(Map m) {
        // presentation of Map content to your liking
    }
    public toString(Set m) {
        // presentation of Set content to your liking
    }
    //... etc.
}

EDIT: Responding to the comment by xukxpvfzflbbld, here's a possible implementation for the cases mentioned previously.

package com.so.demos;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class ToStringHelper {

    private String separator;
    private String arrow;

    public ToStringHelper(String separator, String arrow) {
        this.separator = separator;
        this.arrow = arrow;
    }

   public String toString(List<?> l) {
        StringBuilder sb = new StringBuilder("(");
        String sep = "";
        for (Object object : l) {
            sb.append(sep).append(object.toString());
            sep = separator;
        }
        return sb.append(")").toString();
    }

    public String toString(Map<?,?> m) {
        StringBuilder sb = new StringBuilder("[");
        String sep = "";
        for (Object object : m.keySet()) {
            sb.append(sep)
              .append(object.toString())
              .append(arrow)
              .append(m.get(object).toString());
            sep = separator;
        }
        return sb.append("]").toString();
    }

    public String toString(Set<?> s) {
        StringBuilder sb = new StringBuilder("{");
        String sep = "";
        for (Object object : s) {
            sb.append(sep).append(object.toString());
            sep = separator;
        }
        return sb.append("}").toString();
    }

}

This isn't a full-blown implementation, but just a starter.

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

Here is a pretty simple stored procedure that does the trick as well...

    CREATE PROCEDURE GetBCPTable
    @table_name varchar(200)
AS
BEGIN
    DECLARE @raw_sql nvarchar(3000)

    DECLARE @columnHeader VARCHAR(8000)
    SELECT @columnHeader = COALESCE(@columnHeader+',' ,'')+ ''''+column_name +'''' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name

    DECLARE @ColumnList VARCHAR(8000)
    SELECT @ColumnList = COALESCE(@ColumnList+',' ,'')+ 'CAST('+column_name +' AS VARCHAR)' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name

    SELECT @raw_sql = 'SELECT '+ @columnHeader +' UNION ALL SELECT ' + @ColumnList + ' FROM ' + @table_name
    --PRINT @raw_SQL
    EXECUTE sp_executesql  @raw_sql
END
GO

How to add time to DateTime in SQL

DECLARE @DDate      date        -- To store the current date
DECLARE @DTime      time        -- To store the current time
DECLARE @DateTime   datetime    -- To store the result of the concatenation
;
SET @DDate      =   GETDATE()   -- Getting the current date
SET @DTime      =   GETDATE()   -- Getting the current time



SET @DateTime   =   CONVERT(datetime, CONVERT(varchar(19), LTRIM(@DDate) + ' ' + LTRIM(@DTime) ));
;
/*
    1. LTRIM the date and time do an automatic conversion of both types to string.
    2. The inside CONVERT to varchar(19) is needed, because you cannot do a direct conversion to datetime
    3. Once the inside conversion is done, the second do the final conversion to datetime.
*/  

-- The following select shows the initial variables and the result of the concatenation
SELECT @DDate, @DTime, @DateTime

Set up Python 3 build system with Sublime Text 3

The reason you're getting the error is that you have a Unix-style path to the python executable, when you're running Windows. Change /usr/bin/python3 to C:/Python32/python.exe (make sure you use the forward slashes / and not Windows-style back slashes \). Once you make this change, you should be all set.

Also, you need to change the single quotes ' to double quotes " like so:

{
    "cmd": ["c:/Python32/python.exe", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

The .sublime-build file needs to be valid JSON, which requires strings be wrapped in double quotes, not single.

Javascript Audio Play on click

While several answers are similar, I still had an issue - the user would click the button several times, playing the audio over itself (either it was clicked by accident or they were just 'playing'....)

An easy fix:

var music = new Audio();
function playMusic(file) {
    music.pause();
    music = new Audio(file);
    music.play();
}

Setting up the audio on load allowed 'music' to be paused every time the function is called - effectively stopping the 'noise' even if they user clicks the button several times (and there is also no need to turn off the button, though for user experience it may be something you want to do).

Hibernate show real SQL

select this_.code from true.employee this_ where this_.code=? is what will be sent to your database.

this_ is an alias for that instance of the employee table.

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

Angular JS break ForEach

This example works. Try it.

var array = [0,1,2];
for( var i = 0, ii = array.length; i < ii; i++){
  if(i === 1){
   break;
  }
}

Is there a way to get colored text in GitHubflavored Markdown?

In case this may be helpful for someone who just needs to show colors rather than output, as a hackish workaround (and FYI), since GitHub supports Unicode (as Unicode, numeric character references or HTML entities), you could try colored Unicode symbols, though it depends on the font rendering them in color (as it happens to be appearing for me on Windows 10 and Mac 10.12.5, at least, though on the Mac at least, the up/down-pointing small red triangles don't show in red):

  • RED APPLE (&#x1F34E;):
  • GREEN APPLE (&#x1F34F;):
  • BLUE HEART (&#x1F499;):
  • GREEN HEART (&#x1F49A;):
  • YELLOW HEART (&#x1F49B;):
  • PURPLE HEART (&#x1F49C;):
  • GREEN BOOK (&#x1F4D7;):
  • BLUE BOOK (&#x1F4D8;):
  • ORANGE BOOK (&#x1F4D9;):
  • LARGE RED CIRCLE (&#x1F534;):
  • LARGE BLUE CIRCLE (&#x1F535;):
  • LARGE ORANGE DIAMOND (&#x1F536;):
  • LARGE BLUE DIAMOND (&#x1F537;):
  • SMALL ORANGE DIAMOND (&#x1F538;):
  • SMALL BLUE DIAMOND (&#x1F539;):
  • UP-POINTING RED TRIANGLE (&#x1F53A;):
  • DOWN-POINTING RED TRIANGLE (&#x1F53B;):
  • UP-POINTING SMALL RED TRIANGLE (&#x1F53C;):
  • DOWN-POINTING SMALL RED TRIANGLE (&#x1F53D;):

JQuery How to extract value from href tag?

if ($('a').on('Clicked').text().search('1') == -1)
{
    //Page == 1
}
else
{
    //Page != 1
}

Prevent jQuery UI dialog from setting focus to first textbox

Simple workaround:

Just create a invisible element with tabindex=1 ... This will not focus the datepicker ...

eg.:

<a href="" tabindex="1"></a>
...
Here comes the input element

Difference between a script and a program?

For me, the main difference is that a script is interpreted, while a program is executed (i.e. the source is first compiled, and the result of that compilation is expected).


Wikipedia seems to agree with me on this :

Script :

"Scripts" are distinct from the core code of the application, which is usually written in a different language, and are often created or at least modified by the end-user.
Scripts are often interpreted from source code or bytecode, whereas the applications they control are traditionally compiled to native machine code.

Program :

The program has an executable form that the computer can use directly to execute the instructions.
The same program in its human-readable source code form, from which executable programs are derived (e.g., compiled)

Is there a library function for Root mean square error (RMSE) in python?

You can't find RMSE function directly in SKLearn. But , instead of manually doing sqrt , there is another standard way using sklearn. Apparently, Sklearn's mean_squared_error itself contains a parameter called as "squared" with default value as true .If we set it to false ,the same function will return RMSE instead of MSE.

# code changes implemented by Esha Prakash
from sklearn.metrics import mean_squared_error
rmse = mean_squared_error(y_true, y_pred , squared=False)

Does MS SQL Server's "between" include the range boundaries?

Yes, but be careful when using between for dates.

BETWEEN '20090101' AND '20090131'

is really interpreted as 12am, or

BETWEEN '20090101 00:00:00' AND '20090131 00:00:00'

so will miss anything that occurred during the day of Jan 31st. In this case, you will have to use:

myDate >= '20090101 00:00:00' AND myDate < '20090201 00:00:00'  --CORRECT!

or

BETWEEN '20090101 00:00:00' AND '20090131 23:59:59' --WRONG! (see update!)

UPDATE: It is entirely possible to have records created within that last second of the day, with a datetime as late as 20090101 23:59:59.997!!

For this reason, the BETWEEN (firstday) AND (lastday 23:59:59) approach is not recommended.

Use the myDate >= (firstday) AND myDate < (Lastday+1) approach instead.

Good article on this issue here.

Symbolicating iPhone App Crash Reports

I like to use Textwrangler to pinpoint errors in an original app upload binary rejection. (The crash data will be found in your itunesConnect account.) Using Sachin's method above I copy the original.crash to TextWrangler, then copy the symbolicatecrash file I've created to another TextWrangler file. Comparing the two files pinpoints differences. The symbolicatecrash file will have differences which point out the file and line number of problems.

How to split a string between letters and digits (or between digits and letters)?

You could try to split on (?<=\D)(?=\d)|(?<=\d)(?=\D), like:

str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

It matches positions between a number and not-a-number (in any order).

  • (?<=\D)(?=\d) - matches a position between a non-digit (\D) and a digit (\d)
  • (?<=\d)(?=\D) - matches a position between a digit and a non-digit.

Extracting Nupkg files using command line

NuPKG files are just zip files, so anything that can process a zip file should be able to process a nupkg file, i.e, 7zip.

What is the difference between tree depth and height?

height and depth of a tree is equal...

but height and depth of a node is not equal because...

the height is calculated by traversing from the given node to the deepest possible leaf.

depth is calculated from traversal from root to the given node.....

Where am I? - Get country

This will get the country code set for the phone (phones language, NOT user location):

 String locale = context.getResources().getConfiguration().locale.getCountry(); 

can also replace getCountry() with getISO3Country() to get a 3 letter ISO code for the country. This will get the country name:

 String locale = context.getResources().getConfiguration().locale.getDisplayCountry();

This seems easier than the other methods and rely upon the localisation settings on the phone, so if a US user is abroad they probably still want Fahrenheit and this will work :)

Editors note: This solution has nothing to do with the location of the phone. It is constant. When you travel to Germany locale will NOT change. In short: locale != location.

TypeError: can't pickle _thread.lock objects

I had the same problem with Pool() in Python 3.6.3.

Error received: TypeError: can't pickle _thread.RLock objects

Let's say we want to add some number num_to_add to each element of some list num_list in parallel. The code is schematically like this:

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1 

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list)) 
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

    def run_parallel(self, num, shared_new_num_list):
        new_num = num + self.num_to_add # uses class parameter
        shared_new_num_list.append(new_num)

The problem here is that self in function run_parallel() can't be pickled as it is a class instance. Moving this parallelized function run_parallel() out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add and then you have to pass it as an argument.

Solution:

def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
    new_num = num + to_add
    shared_new_num_list.append(new_num)

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

Other suggestions above didn't help me.

Getting next element while cycling through a list

        li = [0, 1, 2, 3]
        for elem in li:
            if (li.index(elem))+1 != len(li):
                thiselem = elem
                nextelem = li[li.index(elem)+1]
                print 'thiselem',thiselem
                print 'nextel',nextelem
            else:
                print 'thiselem',li[li.index(elem)]
                print 'nextel',li[li.index(elem)]

jQuery click function doesn't work after ajax call?

Here's the FIDDLE

Same code as yours but it will work on dynamically created elements.

$(document).on('click', '.deletelanguage', function () {
    alert("success");
    $('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>');
});

Working with INTERVAL and CURDATE in MySQL

As suggested by A Star, I always use something along the lines of:

DATE(NOW()) - INTERVAL 1 MONTH

Similarly you can do:

NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY

and so on. Much easier than typing DATE_ADD or DATE_SUB all the time :)!

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Vertical Menu in Bootstrap

With a few CSS overrides, I find the accordion / collapse plugin works well as a sidebar vertical menu. Here's a small sample of some overrides I use for a menu on a white background. The accordion is placed within a section container:

.accordion-group
{
    margin-bottom: 1px;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    border-radius: 0px;
    border-bottom: 1px solid #E5E5E5;
    border-top: none;
    border-left: none;
    border-right: none;
}

.accordion-heading:hover
{
    background-color: #FFFAD9;
}

How can I use JavaScript in Java?

Rhino is what you are looking for.

Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.

Update: Now Nashorn, which is more performant JavaScript Engine for Java, is available with jdk8.

Convert row names into first column

dplyr::as_data_frame(df, rownames = "your_row_name") will give you even simpler result.

Visual Studio Code - Convert spaces to tabs

There are 3 options in .vscode/settings.json:

// The number of spaces a tab is equal to.
"editor.tabSize": 4,

// Insert spaces when pressing Tab.
"editor.insertSpaces": true,

// When opening a file, `editor.tabSize` and `editor.insertSpaces` will be detected based on the file contents.
"editor.detectIndentation": true

editor.detectIndentation detects it from your file, you have to disable it. If it didn't help, check that you have no settings with higher priority. For example when you save it to User settings it could be overwritten by Workspace settings which are in your project folder.

Update:

You may just open File » Preferences » Settings or use shortcut:

CTRL+, (Windows, Linux)

?+, (Mac)

Update:

Now you have alternative to editing those options manually.
Click on selector Spaces:4 at the bottom-right of the editor:
 Ln44, Col .  [Spaces:4] . UTF-8 with BOM . CTRLF . HTML . :)

When you want to convert existing ws to tab, install extension from Marketplace
EDIT:
To convert existing indentation from spaces to tabs hit Ctrl+Shift+P and type:

>Convert indentation to Tabs

This will change the indentation for your document based on the defined settings to Tabs.

How to auto generate migrations with Sequelize CLI from Sequelize models?

It's 2020 and many of these answers no longer apply to the Sequelize v4/v5/v6 ecosystem.

The one good answer says to use sequelize-auto-migrations, but probably is not prescriptive enough to use in your project. So here's a bit more color...

Setup

My team uses a fork of sequelize-auto-migrations because the original repo is has not been merged a few critical PRs. #56 #57 #58 #59

$ yarn add github:scimonster/sequelize-auto-migrations#a063aa6535a3f580623581bf866cef2d609531ba

Edit package.json:

"scripts": {
  ...
  "db:makemigrations": "./node_modules/sequelize-auto-migrations/bin/makemigration.js",
  ...
}

Process

Note: Make sure you’re using git (or some source control) and database backups so that you can undo these changes if something goes really bad.

  1. Delete all old migrations if any exist.
  2. Turn off .sync()
  3. Create a mega-migration that migrates everything in your current models (yarn db:makemigrations --name "mega-migration").
  4. Commit your 01-mega-migration.js and the _current.json that is generated.
  5. if you've previously run .sync() or hand-written migrations, you need to “Fake” that mega-migration by inserting the name of it into your SequelizeMeta table. INSERT INTO SequelizeMeta Values ('01-mega-migration.js').
  6. Now you should be able to use this as normal…
  7. Make changes to your models (add/remove columns, change constraints)
  8. Run $ yarn db:makemigrations --name whatever
  9. Commit your 02-whatever.js migration and the changes to _current.json, and _current.bak.json.
  10. Run your migration through the normal sequelize-cli: $ yarn sequelize db:migrate.
  11. Repeat 7-10 as necessary

Known Gotchas

  1. Renaming a column will turn into a pair of removeColumn and addColumn. This will lose data in production. You will need to modify the up and down actions to use renameColumn instead.

For those who confused how to use renameColumn, the snippet would look like this. (switch "column_name_before" and "column_name_after" for the rollbackCommands)

{
    fn: "renameColumn",
    params: [
        "table_name",
        "column_name_before",
        "column_name_after",
        {
            transaction: transaction
        }
    ]
}
  1. If you have a lot of migrations, the down action may not perfectly remove items in an order consistent way.

  2. The maintainer of this library does not actively check it. So if it doesn't work for you out of the box, you will need to find a different community fork or another solution.

Email & Phone Validation in Swift

another solution for variety sake..

public extension String {
    public var validPhoneNumber:Bool {
        let types:NSTextCheckingType = [.PhoneNumber]
        guard let detector = try? NSDataDetector(types: types.rawValue) else { return false }

        if let match = detector.matchesInString(self, options: [], range: NSMakeRange(0, characters.count)).first?.phoneNumber {
            return match == self
        }else{
            return false
        }
    }
}

//and use like so:
if "16465551212".validPhoneNumber {
    print("valid phone number")
}

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

Python Selenium accessing HTML source

To answer your question about getting the URL to use for urllib, just execute this JavaScript code:

url = browser.execute_script("return window.location;")

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

Slightly unrelated to your problem, so here's one for Google.

If you didn't mysqldump the SQL, it might be that your SQL is broken.

I just got this error by accidentally having an unclosed string literal in my code. Sloppy fingers happen.

That's a fantastic error message to get for a runaway string, thanks for that MySQL!

SQL update query using joins

You can use the following query:

UPDATE im
SET mf_item_number = (some value) 
FROM item_master im
JOIN group_master gm
    ON im.sku = gm.sku 
JOIN Manufacturer_Master mm
    ON gm.ManufacturerID = mm.ManufacturerID
WHERE im.mf_item_number like 'STA%' AND
      gm.manufacturerID = 34    `sql`

Facebook Architecture

Well Facebook has undergone MANY many changes and it wasn't originally designed to be efficient. It was designed to do it's job. I have absolutely no idea what the code looks like and you probably won't find much info about it (for obvious security and copyright reasons), but just take a look at the API. Look at how often it changes and how much of it doesn't work properly, anymore, or at all.

I think the biggest ace up their sleeve is the Hiphop. http://developers.facebook.com/blog/post/358 You can use HipHop yourself: https://github.com/facebook/hiphop-php/wiki

But if you ask me it's a very ambitious and probably time wasting task. Hiphop only supports so much, it can't simply convert everything to C++. So what does this tell us? Well, it tells us that Facebook is NOT fully taking advantage of the PHP language. It's not using the latest 5.3 and I'm willing to bet there's still a lot that is PHP 4 compatible. Otherwise, they couldn't use HipHop. HipHop IS A GOOD IDEA and needs to grow and expand, but in it's current state it's not really useful for that many people who are building NEW PHP apps.

There's also PHP to JAVA via things like Resin/Quercus. Again, it doesn't support everything...

Another thing to note is that if you use any non-standard PHP module, you aren't going to be able to convert that code to C++ or Java either. However...Let's take a look at PHP modules. They are ARE compiled in C++. So if you can build PHP modules that do things (like parse XML, etc.) then you are basically (minus some interaction) working at the same speed. Of course you can't just make a PHP module for every possible need and your entire app because you would have to recompile and it would be much more difficult to code, etc.

However...There are some handy PHP modules that can help with speed concerns. Though at the end of the day, we have this awesome thing known as "the cloud" and with it, we can scale our applications (PHP included) so it doesn't matter as much anymore. Hardware is becoming cheaper and cheaper. Amazon just lowered it's prices (again) speaking of.

So as long as you code your PHP app around the idea that it will need to one day scale...Then I think you're fine and I'm not really sure I'd even look at Facebook and what they did because when they did it, it was a completely different world and now trying to hold up that infrastructure and maintain it...Well, you get things like HipHop.

Now how is HipHop going to help you? It won't. It can't. You're starting fresh, you can use PHP 5.3. I'd highly recommend looking into PHP 5.3 frameworks and all the new benefits that PHP 5.3 brings to the table along with the SPL libraries and also think about your database too. You're most likely serving up content from a database, so check out MongoDB and other types of databases that are schema-less and document-oriented. They are much much faster and better for the most "common" type of web site/app.

Look at NEW companies like Foursquare and Smugmug and some other companies that are utilizing NEW technology and HOW they are using it. For as successful as Facebook is, I honestly would not look at them for "how" to build an efficient web site/app. I'm not saying they don't have very (very) talented people that work there that are solving (their) problems creatively...I'm also not saying that Facebook isn't a great idea in general and that it's not successful and that you shouldn't get ideas from it....I'm just saying that if you could view their entire source code, you probably wouldn't benefit from it.

How to transform numpy.matrix or array to scipy sparse matrix

There are several sparse matrix classes in scipy.

bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix

Any of them can do the conversion.

import numpy as np
from scipy import sparse
a=np.array([[1,0,1],[0,0,1]])
b=sparse.csr_matrix(a)
print(b)

(0, 0)  1
(0, 2)  1
(1, 2)  1

See http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information .

Check to see if python script is running

The other answers are great for things like cron jobs, but if you're running a daemon you should monitor it with something like daemontools.

Find object by its property in array of objects with AngularJS way

The solucion that work for me is the following

$filter('filter')(data, {'id':10}) 

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

Cancel split window in Vim

Okay I just detached and reattach to the screen session and I am back to normal screen I wanted

How to split a delimited string into an array in awk?

Actually awk has a feature called 'Input Field Separator Variable' link. This is how to use it. It's not really an array, but it uses the internal $ variables. For splitting a simple string it is easier.

echo "12|23|11" | awk 'BEGIN {FS="|";} { print $1, $2, $3 }'

how to access the command line for xampp on windows

Run PHP file from command Promp.

Please set Environment Variable as per below mention steps.

  1. Right Click on MY Computer Icon and Click on Properties or Go to "Control Panel\System and Security\System".
  2. Select "Advanced System Settings" and select "Advance" Tab
  3. Now Select "Environment Variable" option and select "Path" from "System Variables" and click on "Edit" button
  4. Now set path where php.exe file is available - For example if XAMPP install in to C: drive then Path is "C:\xampp\php"
  5. After set path Click Ok and Apply.

Now open Command prompt where your source file are available and run command "php test.php"

Manually highlight selected text in Notepad++

To highlight a block of code in Notepad++, please do the following steps

  1. Select the required text.
  2. Right click to display the context menu
  3. Choose Style token and select any of the five choices available ( styles from Using 1st style to using 5th style). Each is of different colors.If you want yellow color choose using 3rd style.

If you want to create your own style you can use Style Configurator under Settings menu.

Recover sa password

The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).

If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:

Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.

You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).

As an aside, the login properties for sa would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.

I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):

And some other resources:

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

What is the difference between parseInt() and Number()?

I found two links of performance compare among several ways of converting string to int.

parseInt(str,10)    
parseFloat(str)
str << 0
+str
str*1 
str-0
Number(str)

http://jsben.ch/#/zGJHM

http://phrogz.net/js/string_to_number.html

SQLException: No suitable driver found for jdbc:derby://localhost:1527

For me

DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());

helped. In this way, the DriveManager does know the derby EmbeddedDriver. Maybe allocating a new EmbeddedDriver is to heavy but on the other side, Class.forName needs try/catch/doSomethingIntelligentWithException that I dont like very much.

recyclerview No adapter attached; skipping layout

In Kotlin we had this weird illogical issue.

This didn't work:

 mBinding.serviceProviderCertificates.apply {
            adapter = adapter
            layoutManager =  LinearLayoutManager(activity)
        }

While this worked:

mBinding.serviceProviderCertificates.adapter = adapter
mBinding.serviceProviderCertificates.layoutManager = LinearLayoutManager(activity)

Once I get more after work hours, I will share more insights.

Warn user before leaving web page with unsaved changes

var unsaved = false;
$(":input").change(function () {         
    unsaved = true;
});

function unloadPage() {         
    if (unsaved) {             
        alert("You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?");
    }
} 
window.onbeforeunload = unloadPage;

Batch file to copy directories recursively

After reading the accepted answer's comments, I tried the robocopy command, which worked for me (using the standard command prompt from Windows 7 64 bits SP 1):

robocopy source_dir dest_dir /s /e

How to compare Boolean?

From your comments, it seems like you're looking for "best practices" for the use of the Boolean wrapper class. But there really aren't any best practices, because it's a bad idea to use this class to begin with. The only reason to use the object wrapper is in cases where you absolutely must (such as when using Generics, i.e., storing a boolean in a HashMap<String, Boolean> or the like). Using the object wrapper has no upsides and a lot of downsides, most notably that it opens you up to NullPointerExceptions.

Does it matter if '!' is used instead of .equals() for Boolean?

Both techniques will be susceptible to a NullPointerException, so it doesn't matter in that regard. In the first scenario, the Boolean will be unboxed into its respective boolean value and compared as normal. In the second scenario, you are invoking a method from the Boolean class, which is the following:

public boolean equals(Object obj) {
    if (obj instanceof Boolean) {
        return value == ((Boolean)obj).booleanValue();
    }
    return false;
}

Either way, the results are the same.

Would it matter if .equals(false) was used to check for the value of the Boolean checker?

Per above, no.

Secondary question: Should Boolean be dealt differently than boolean?

If you absolutely must use the Boolean class, always check for null before performing any comparisons. e.g.,

Map<String, Boolean> map = new HashMap<String, Boolean>();
//...stuff to populate the Map
Boolean value = map.get("someKey");
if(value != null && value) {
    //do stuff
}

This will work because Java short-circuits conditional evaluations. You can also use the ternary operator.

boolean easyToUseValue = value != null ? value : false;

But seriously... just use the primitive type, unless you're forced not to.

How to Get a Specific Column Value from a DataTable?

Datatables have a .Select method, which returns a rows array according to the criteria you specify. Something like this:

Dim oRows() As DataRow

oRows = dtCountries.Select("CountryName = '" & userinput & "'")

If oRows.Count = 0 Then
   ' No rows found
Else
   ' At least one row found. Could be more than one
End If

Of course, if userinput contains ' character, it would raise an exception (like if you query the database). You should escape the ' characters (I use a function to do that).

Datatables - Setting column width

you should use "bAutoWidth" property of datatable and give width to each td/column in %

 $(".table").dataTable({"bAutoWidth": false , 
aoColumns : [
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "10%"},
    ]
});

Hope this will help.

Custom li list-style with font-awesome icon

I wanted to add to JOPLOmacedo's answer. His solution is my favourite, but I always had problem with indentation when the li had more than one line. It was fiddly to find the correct indentation with margins etc. But this might concern only me.

For me absolute positioning of the :before pseudo-element works best. I set padding-left on ul, negative position left on the :before element, same as ul's padding-left. To get the distance of the content from the :before element right I just set the padding-left on the li. Of course the li has to have position relative. For example

ul {
  margin: 0 0 1em 0;
  padding: 0 0 0 1em;
  /* make space for li's :before */
  list-style: none;
}

li {
  position: relative;
  padding-left: 0.4em;
  /* text distance to icon */
}

li:before {
  font-family: 'my-icon-font';
  content: 'character-code-here';
  position: absolute;
  left: -1em;
  /* same as ul padding-left */
  top: 0.65em;
  /* depends on character, maybe use padding-top instead */
  /*  .... more styling, maybe set width etc ... */
}

Hopefully this is clear and has some value for someone else than me.

Get free disk space

I was looking for the size in GB, so I just improved the code from Superman above with the following changes:

public double GetTotalHDDSize(string driveName)
{
    foreach (DriveInfo drive in DriveInfo.GetDrives())
    {
        if (drive.IsReady && drive.Name == driveName)
        {
            return drive.TotalSize / (1024 * 1024 * 1024);
        }
    }
    return -1;
}

Anaconda vs. miniconda

Both Anaconda and miniconda use the conda package manager. The chief differece between between Anaconda and miniconda,however,is that

The Anaconda distribution comes pre-loaded with all the packages while the miniconda distribution is just the management system without any pre-loaded packages. If one uses miniconda, one has to download individual packages and libraries separately.

I personally use Anaconda distribution as I dont really have to worry much about individual package installations.

A disadvantage of miniconda is that installing each individual package can take a long amount of time. Compared to that installing and using Anaconda takes a lot less time.

However, there are some packages in anaconda (QtConsole, Glueviz,Orange3) that I have never had to use. I dont even know their purpose. So a disadvantage of anaconda is that it occupies more space than needed.

How to check if a scope variable is undefined in AngularJS template?

As @impulsgraw wrote. You need to check for undefined after the pipes:

<div ng-show="foo || undefined">
    Show this if foo is defined!
</div>
<div ng-show="boo || !undefined">
    Show this if boo is undefined!
</div>

https://jsfiddle.net/mjfz2q9h/11/

For loop in Objective-C

The traditional for loop in Objective-C is inherited from standard C and takes the following form:

for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
    // Do something.
}

For example, to print the numbers from 1 to 10, you could use the for loop:

for (int i = 1; i <= 10; i++)
{
    NSLog(@"%d", i);
}

On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.

for (NSString* currentString in myArrayOfStrings)
{
    NSLog(@"%@", currentString);
}

This is logically equivilant to the following traditional for loop:

for (int i = 0; i < [myArrayOfStrings count]; i++)
{
    NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}

The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.

Hope this helps.

Removing address bar from browser (to view on Android)

I found that if you add the command to unload, he keeps down the page, ie the page that move! Hope it works with you too!

window.addEventListener("load", function() { window.scrollTo(0, 1); });
window.addEventListener("unload", function() { window.scrollTo(0, 1); });

Using a 7-inch tablet with android, www.kupsoft.com visit my website and check how it behaves page, I use this command in my portal.

"Error: Main method not found in class MyClass, please define the main method as..."

The problem is that you do not have a public void main(String[] args) method in the class you attempt to invoke.

It

  • must be static
  • must have exactly one String array argument (which may be named anything)
  • must be spelled m-a-i-n in lowercase.

Note, that you HAVE actually specified an existing class (otherwise the error would have been different), but that class lacks the main method.

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

How to install JDK 11 under Ubuntu?

I came here looking for the answer and since no one put the command for the oracle Java 11 but only openjava 11 I figured out how to do it on Ubuntu, the syntax is as following:

sudo add-apt-repository ppa:linuxuprising/java
sudo apt update
sudo apt install oracle-java11-installer

How to read a PEM RSA private key from .NET

The stuff between the

-----BEGIN RSA PRIVATE KEY---- 

and

-----END RSA PRIVATE KEY----- 

is the base64 encoding of a PKCS#8 PrivateKeyInfo (unless it says RSA ENCRYPTED PRIVATE KEY in which case it is a EncryptedPrivateKeyInfo).

It is not that hard to decode manually, but otherwise your best bet is to P/Invoke to CryptImportPKCS8.


Update: The CryptImportPKCS8 function is no longer available for use as of Windows Server 2008 and Windows Vista. Instead, use the PFXImportCertStore function.

Unique on a dataframe with only selected columns

Here are a couple dplyr options that keep non-duplicate rows based on columns id and id2:

library(dplyr)                                        
df %>% distinct(id, id2, .keep_all = TRUE)
df %>% group_by(id, id2) %>% filter(row_number() == 1)
df %>% group_by(id, id2) %>% slice(1)

Compare object instances for equality by their attributes

You override the rich comparison operators in your object.

class MyClass:
 def __lt__(self, other):
      # return comparison
 def __le__(self, other):
      # return comparison
 def __eq__(self, other):
      # return comparison
 def __ne__(self, other):
      # return comparison
 def __gt__(self, other):
      # return comparison
 def __ge__(self, other):
      # return comparison

Like this:

    def __eq__(self, other):
        return self._id == other._id

CentOS: Enabling GD Support in PHP Installation

For PHP7 on CentOS or EC2 Linux AMI:

sudo yum install php70-gd

Proper MIME type for OTF fonts

Ignore the chrome warning. There is no standard MIME type for OTF fonts.

font/opentype may silence the warning, but that doesn't make it the "right" thing to do.

Arguably, you're better off making one up, e.g. with "application/x-opentype" because at least "application" is a registered content type, while "font" is not.

Update: OTF remains a problem, but WOFF grew an IANA MIME type of application/font-woff in January 2013.

Update 2: OTF has grown a MIME type: application/font-sfnt In March 2013. This type also applies to .ttf

Are global variables bad?

I'd answer this question with another question: Do you use singeltons/ Are singeltons bad?

Because (almost all) singelton usage is a glorified global variable.

Find and replace with sed in directory and sub directories

I think we can do this with one line simple command

for i in `grep -rl eth0 . 2> /dev/null`; do sed -i ‘s/eth0/eth1/’ $i; done

Refer to this page.

Pass a String from one Activity to another Activity in Android

You need to pass it as an extra:

String easyPuzzle  = "630208010200050089109060030"+
                     "008006050000187000060500900"+
                     "09007010681002000502003097";

Intent i = new Intent(this, ToClass.class);
i.putExtra("epuzzle", easyPuzzle);
startActivity(i); 

Then extract it from your new activity like this:

Intent intent = getIntent();
String easyPuzzle = intent.getExtras().getString("epuzzle");

Proper way to wait for one function to finish before continuing?

One way to deal with asynchronous work like this is to use a callback function, eg:

function firstFunction(_callback){
    // do some asynchronous work
    // and when the asynchronous stuff is complete
    _callback();    
}

function secondFunction(){
    // call first function and pass in a callback function which
    // first function runs when it has completed
    firstFunction(function() {
        console.log('huzzah, I\'m done!');
    });    
}

As per @Janaka Pushpakumara's suggestion, you can now use arrow functions to achieve the same thing. For example:

firstFunction(() => console.log('huzzah, I\'m done!'))


Update: I answered this quite some time ago, and really want to update it. While callbacks are absolutely fine, in my experience they tend to result in code that is more difficult to read and maintain. There are situations where I still use them though, such as to pass in progress events and the like as parameters. This update is just to emphasise alternatives.

Also the original question doesn't specificallty mention async, so in case anyone is confused, if your function is synchronous, it will block when called. For example:

doSomething()
// the function below will wait until doSomething completes if it is synchronous
doSomethingElse()

If though as implied the function is asynchronous, the way I tend to deal with all my asynchronous work today is with async/await. For example:

const secondFunction = async () => {
  const result = await firstFunction()
  // do something else here after firstFunction completes
}

IMO, async/await makes your code much more readable than using promises directly (most of the time). If you need to handle catching errors then use it with try/catch. Read about it more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function .

How to generate random number in Bash?

Generate random 3-digit number

This is great for creating sample data. Example: put all testing data in a directory called "test-create-volume-123", then after your test is done, zap the entire directory. By generating exactly three digits, you don't have weird sorting issues.

printf '%02d\n' $((1 + RANDOM % 100))

This scales down, e.g. to one digit:

printf '%01d\n' $((1 + RANDOM % 10))

It scales up, but only to four digits. See above as to why :)

Change the location of the ~ directory in a Windows install of Git Bash

I know this is an old question, but it is the top google result for "gitbash homedir windows" so figured I'd add my findings.

No matter what I tried I couldn't get git-bash to start in anywhere but my network drive,(U:) in my case making every operation take 15-20 seconds to respond. (Remote employee on VPN, network drive hosted on the other side of the country)

I tried setting HOME and HOMEDIR variables in windows.

I tried setting HOME and HOMEDIR variables in the git installation'setc/profile file.

I tried editing the "Start in" on the git-bash shortcut to be C:/user/myusername.

"env" command inside the git-bash shell would show correct c:/user/myusername. But git-bash would still start in U:

What ultimately fixed it for me was editing the git-bash shortcut and removing the "--cd-to-home" from the Target line.

I'm on Windows 10 running latest version of Git-for-windows 2.22.0.

Assign multiple values to array in C

If you really to assign values (as opposed to initialize), you can do it like this:

 GLfloat coordinates[8]; 
 static const GLfloat coordinates_defaults[8] = {1.0f, 0.0f, 1.0f ....};
 ... 
 memcpy(coordinates, coordinates_defaults, sizeof(coordinates_defaults));

 return coordinates; 

How do I create a list of random numbers without duplicates?

import random

sourcelist=[]
resultlist=[]

for x in range(100):
    sourcelist.append(x)

for y in sourcelist:
    resultlist.insert(random.randint(0,len(resultlist)),y)

print (resultlist)

How to calculate a Mod b in Casio fx-991ES calculator

mod formula Note: Math error means a mod m = 0

How do you tell if a checkbox is selected in Selenium for Java?

public boolean getcheckboxvalue(String element)
    {   
        WebElement webElement=driver.findElement(By.xpath(element));
        return webElement.isSelected();
    }

Pass Additional ViewData to a Strongly-Typed Partial View

Create another class which contains your strongly typed class.

Add your new stuff to the class and return it in the view.

Then in the view, ensure you inherit your new class and change the bits of code that will now be in error. namely the references to your fields.

Hope this helps. If not then let me know and I'll post specific code.

How to increase the distance between table columns in HTML?

If you need to give a distance between two rows use this tag

margin-top: 10px !important;

What is setContentView(R.layout.main)?

In Android the visual design is stored in XML files and each Activity is associated to a design.

setContentView(R.layout.main)

R means Resource

layout means design

main is the xml you have created under res->layout->main.xml

Whenever you want to change the current look of an Activity or when you move from one Activity to another, the new Activity must have a design to show. We call setContentView in onCreate with the desired design as argument.

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I had similar problem. I r?n npm cache clear, closed android SDK manager(which was open before) and re-ran npm install -g cordova and that was enough to solve the problem.

How can I stop the browser back button using JavaScript?

Try this to prevent the backspace button in Internet Explorer which by default acts as "Back":

<script language="JavaScript">
    $(document).ready(function() {
    $(document).unbind('keydown').bind('keydown', function (event) {
        var doPrevent = false;

        if (event.keyCode === 8 ) {
            var d = event.srcElement || event.target;
            if ((d.tagName.toUpperCase() === 'INPUT' &&
                 (
                     d.type.toUpperCase() === 'TEXT'     ||
                     d.type.toUpperCase() === 'PASSWORD' ||
                     d.type.toUpperCase() === 'FILE'     ||
                     d.type.toUpperCase() === 'EMAIL'    ||
                     d.type.toUpperCase() === 'SEARCH'   ||
                     d.type.toUpperCase() === 'DATE' )
                ) ||
                d.tagName.toUpperCase() === 'TEXTAREA') {

                     doPrevent = d.readOnly || d.disabled;
                }
                else {
                    doPrevent = true;
                }
            }

            if (doPrevent) {
                event.preventDefault();
            }

            try {
                document.addEventListener('keydown', function (e) {
                    if ((e.keyCode === 13)) {
                        //alert('Enter keydown');
                        e.stopPropagation();
                        e.preventDefault();
                    }
                }, true);
            }
            catch (err) {
            }
        });
    });
</script>

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

How to draw a checkmark / tick using CSS?

I've used something similar to BM2ilabs's answer in the past to style the tick in checkboxes. This technique uses only a single pseudo element so it preserves the semantic HTML and there is no reason for additional HTML elements.

_x000D_
_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
input[type="checkbox"] {_x000D_
  position: relative;_x000D_
  top: 2px;_x000D_
  box-sizing: content-box;_x000D_
  width: 14px;_x000D_
  height: 14px;_x000D_
  margin: 0 5px 0 0;_x000D_
  cursor: pointer;_x000D_
  -webkit-appearance: none;_x000D_
  border-radius: 2px;_x000D_
  background-color: #fff;_x000D_
  border: 1px solid #b7b7b7;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:before {_x000D_
  content: '';_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked:before {_x000D_
  width: 4px;_x000D_
  height: 9px;_x000D_
  margin: 0px 4px;_x000D_
  border-bottom: 2px solid #115c80;_x000D_
  border-right: 2px solid #115c80;_x000D_
  transform: rotate(45deg);_x000D_
}
_x000D_
<label>_x000D_
  <input type="checkbox" name="check-1" value="Label">Label_x000D_
</label>
_x000D_
_x000D_
_x000D_

Count lines in large files

Try: sed -n '$=' filename

Also cat is unnecessary: wc -l filename is enough in your present way.

How to browse localhost on Android device?

If your localhost is not running on the default HTTP port(which is port 80), you need to specify the port in your url to something that corresponds to the port on which your localhost is running. E.g. If your localhost is running on, say port 85, Your url should be

http://10.0.2.2:85

git is not installed or not in the PATH

Install git and tortoise git for windows and make sure it is on your path, (the installer for Tortoise Git includes options for the command line tools and ensuring that it is on the path - select them).

You will need to close and re-open any existing command line sessions for the changes to take effect.

Then you should be able to run npm install successfully or move on to the next problem!

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

Creating a site wrapper div inside the body and applying the overflow->x:hidden to the wrapper INSTEAD of the body or html fixed the issue.

This worked for me after also adding position: relative to the wrapper.

How to use npm with ASP.NET Core

Instead of trying to serve the node modules folder, you can also use Gulp to copy what you need to wwwroot.

https://docs.asp.net/en/latest/client-side/using-gulp.html

This might help too

Visual Studio 2015 ASP.NET 5, Gulp task not copying files from node_modules

Disable browser 'Save Password' functionality

autocomplete="off" does not work for disabling the password manager in Firefox 31 and most likely not in some earlier versions, too.

Checkout the discussion at mozilla about this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=956906

We wanted to use a second password field to enter a one-time password generated by a token. Now we are using a text input instead of a password input. :-(

How to upload files in asp.net core?

Fileservice.cs:

public class FileService : IFileService
{
    private readonly IWebHostEnvironment env;

    public FileService(IWebHostEnvironment env)
    {
        this.env = env;
    }

    public string Upload(IFormFile file)
    {
        var uploadDirecotroy = "uploads/";
        var uploadPath = Path.Combine(env.WebRootPath, uploadDirecotroy);

        if (!Directory.Exists(uploadPath))
            Directory.CreateDirectory(uploadPath);

        var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
        var filePath = Path.Combine(uploadPath, fileName);

        using (var strem = File.Create(filePath))
        {
            file.CopyTo(strem);
        }
        return fileName;
    }
}

IFileService:

namespace studentapps.Services
{
    public interface IFileService
    {
        string Upload(IFormFile file);
    }
}

StudentController:

[HttpGet]
public IActionResult Create()
{
    var student = new StudentCreateVM();
    student.Colleges = dbContext.Colleges.ToList();
    return View(student);
}

[HttpPost]
public IActionResult Create([FromForm] StudentCreateVM vm)
{
    Student student = new Student()
    {
        DisplayImage = vm.DisplayImage.FileName,
        Name = vm.Name,
        Roll_no = vm.Roll_no,
        CollegeId = vm.SelectedCollegeId,
    };


    if (ModelState.IsValid)
    {
        var fileName = fileService.Upload(vm.DisplayImage);
        student.DisplayImage = fileName;
        getpath = fileName;

        dbContext.Add(student);
        dbContext.SaveChanges();
        TempData["message"] = "Successfully Added";
    }
    return RedirectToAction("Index");
}

javascript: pause setTimeout();

If you have several divs to hide, you could use an setInterval and a number of cycles to do like in:

<div id="div1">1</div><div id="div2">2</div>
<div id="div3">3</div><div id="div4">4</div>
<script>
    function hideDiv(elm){
        var interval,
            unit = 1000,
            cycle = 5,
            hide = function(){
                interval = setInterval(function(){
                    if(--cycle === 0){
                        elm.style.display = 'none';
                        clearInterval(interval);
                    }
                    elm.setAttribute('data-cycle', cycle);
                    elm.innerHTML += '*';
                }, unit);
            };
        elm.onmouseover = function(){
            clearInterval(interval);
        };
        elm.onmouseout = function(){
            hide();
        };
        hide();
    }
    function hideDivs(ids){
        var id;
        while(id = ids.pop()){
            hideDiv(document.getElementById(id));
        }
    }
    hideDivs(['div1','div2','div3','div4']);
</script>

send/post xml file using curl command line

Here's how you can POST XML on Windows using curl command line on Windows. Better use batch/.cmd file for that:

curl -i -X POST -H "Content-Type: text/xml" -d             ^
"^<?xml version=\"1.0\" encoding=\"UTF-8\" ?^>                ^
    ^<Transaction^>                                           ^
        ^<SomeParam1^>Some-Param-01^</SomeParam1^>            ^
        ^<Password^>SomePassW0rd^</Password^>                 ^
        ^<Transaction_Type^>00^</Transaction_Type^>           ^
        ^<CardHoldersName^>John Smith^</CardHoldersName^>     ^
        ^<DollarAmount^>9.97^</DollarAmount^>                 ^
        ^<Card_Number^>4111111111111111^</Card_Number^>       ^
        ^<Expiry_Date^>1118^</Expiry_Date^>                   ^
        ^<VerificationStr2^>123^</VerificationStr2^>          ^
        ^<CVD_Presence_Ind^>1^</CVD_Presence_Ind^>            ^
        ^<Reference_No^>Some Reference Text^</Reference_No^>  ^
        ^<Client_Email^>[email protected]^</Client_Email^>       ^
        ^<Client_IP^>123.4.56.7^</Client_IP^>                 ^
        ^<Tax1Amount^>^</Tax1Amount^>                         ^
        ^<Tax2Amount^>^</Tax2Amount^>                         ^
    ^</Transaction^>                                          ^
" "http://localhost:8080"

Creating composite primary key in SQL Server

it simple, select columns want to insert primary key and click on Key icon on header and save tablesql composite key

happy coding..,

Does hosts file exist on the iPhone? How to change it?

Another option here is to have your iPhone connect via a proxy. Here's an example of how to do it with Fiddler (it's very easy):

http://conceptdev.blogspot.com/2009/01/monitoring-iphone-web-traffic-with.html

In that case any dns lookups your iPhone does will use the hosts file of the machine Fiddler is running on. Note, though, that you must use a name that will be resolved via DNS. example.local, for instance, will not work. example.xyz or example.dev will.

Set Text property of asp:label in Javascript PROPER way

The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.

I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:

You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.

How do I find the MySQL my.cnf location

Found mine using

mysqld --help --verbose | grep my.cnf

Twitter Bootstrap dropdown menu

You must include jQuery in the project.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

I didn't find any doc about this so I just opened a random code example from tutorialrepublic.com http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-dropdowns.php

Hope this helps someone else.

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

When you typed in the mongod command, did you also give it a path? This is usually the issue. You don't have to bother with the conf file. simply type

mongod --dbpath="put your path to where you want it to save the working area for your database here!! without these silly quotations marks I may also add!"

example: mongod --dbpath=C:/Users/kyles2/Desktop/DEV/mongodb/data

That is my path and don't forget if on windows to flip the slashes forward if you copied it from the or it won't work!

.NET Format a string with fixed spaces

/// <summary>
/// Returns a string With count chars Left or Right value
/// </summary>
/// <param name="val"></param>
/// <param name="count"></param>
/// <param name="space"></param>
/// <param name="right"></param>
/// <returns></returns>
 public static string Formating(object val, int count, char space = ' ', bool right = false)
{
    var value = val.ToString();
    for (int i = 0; i < count - value.Length; i++) value = right ? value + space : space + value;
    return value;
}

Java Serializable Object to Byte Array

I also recommend to use SerializationUtils tool. I want to make a ajust on a wrong comment by @Abilash. The SerializationUtils.serialize() method is not restricted to 1024 bytes, contrary to another answer here.

public static byte[] serialize(Object object) {
    if (object == null) {
        return null;
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    try {
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        oos.flush();
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
    }
    return baos.toByteArray();
}

At first sight, you may think that new ByteArrayOutputStream(1024) will only allow a fixed size. But if you take a close look at the ByteArrayOutputStream, you will figure out the the stream will grow if necessary:

This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString().

How do I drop table variables in SQL-Server? Should I even do this?

But you all forgot to mention, that if a variable table is used within a loop it will need emptying (delete @table) prior to loading with data again within a loop.

Nested Recycler view height doesn't wrap its content

The code up above doesn't work well when you need to make your items "wrap_content", because it measures both items height and width with MeasureSpec.UNSPECIFIED. After some troubles I've modified that solution so now items can expand. The only difference is that it provides parents height or width MeasureSpec depends on layout orientation.

public class MyLinearLayoutManager extends LinearLayoutManager {

public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                      int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {


        if (getOrientation() == HORIZONTAL) {

            measureScrapChild(recycler, i,
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    heightSpec,
                    mMeasuredDimension);

            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            measureScrapChild(recycler, i,
                    widthSpec,
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);
            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }
    switch (widthMode) {
        case View.MeasureSpec.EXACTLY:
            width = widthSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    switch (heightMode) {
        case View.MeasureSpec.EXACTLY:
            height = heightSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    setMeasuredDimension(width, height);
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                               int heightSpec, int[] measuredDimension) {
    View view = recycler.getViewForPosition(position);
    recycler.bindViewToPosition(view, position);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                getPaddingLeft() + getPaddingRight(), p.width);
        int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                getPaddingTop() + getPaddingBottom(), p.height);
        view.measure(childWidthSpec, childHeightSpec);
        measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
        measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
        recycler.recycleView(view);
    }
}
}

How to change title of Activity in Android?

If you want to set title in Java file, then write in your activity onCreate

setTitle("Your Title");

if you want to in Manifest then write

    <activity
        android:name=".MainActivity"
        android:label="Your Title" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

See Windows Batch File (.bat) to get current date in MMDDYYYY format:

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%

If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:

For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

C:> .\date.bat
2008-10-14_0642

If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:

@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]

C:>test.cmd
Local date is [2012-06-19 10:23:47.048]

What JSON library to use in Scala?

Let me also give you the SON of JSON version:

import nl.typeset.sonofjson._

arr(
  obj(id = 1, name = "John)
  obj(id = 2, name = "Dani)
)

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

_x000D_
_x000D_
function formatto24(date) {_x000D_
  let ampm = date.split(" ")[1];_x000D_
  let time = date.split(" ")[0];_x000D_
  if (ampm == "PM") {_x000D_
    let hours = time.split(":")[0];_x000D_
    let minutes = time.split(":")[1];_x000D_
    let seconds = time.split(":")[2];_x000D_
    let hours24 = JSON.parse(hours) + 12;_x000D_
    return hours24 + ":" + minutes + ":" + seconds;_x000D_
  } else {_x000D_
    return time;_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Most efficient way to concatenate strings?

From Chinh Do - StringBuilder is not always faster:

Rules of Thumb

  • When concatenating three dynamic string values or less, use traditional string concatenation.

  • When concatenating more than three dynamic string values, use StringBuilder.

  • When building a big string from several string literals, use either the @ string literal or the inline + operator.

Most of the time StringBuilder is your best bet, but there are cases as shown in that post that you should at least think about each situation.

How to set a dropdownlist item as selected in ASP.NET?

You can use the FindByValue method to search the DropDownList for an Item with a Value matching the parameter.

dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;

Alternatively you can use the FindByText method to search the DropDownList for an Item with Text matching the parameter.

Before using the FindByValue method, don't forget to reset the DropDownList so that no items are selected by using the ClearSelection() method. It clears out the list selection and sets the Selected property of all items to false. Otherwise you will get the following exception.

"Cannot have multiple items selected in a DropDownList"

Rails find_or_create_by more than one attribute?

Multiple attributes can be connected with an and:

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

(use find_or_initialize_by if you don't want to save the record right away)

Edit: The above method is deprecated in Rails 4. The new way to do it will be:

GroupMember.where(:member_id => 4, :group_id => 7).first_or_create

and

GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize

Edit 2: Not all of these were factored out of rails just the attribute specific ones.

https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md

Example

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

became

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

What is the use of a cursor in SQL Server?

Cursor might used for retrieving data row by row basis.its act like a looping statement(ie while or for loop). To use cursors in SQL procedures, you need to do the following: 1.Declare a cursor that defines a result set. 2.Open the cursor to establish the result set. 3.Fetch the data into local variables as needed from the cursor, one row at a time. 4.Close the cursor when done.

for ex:

declare @tab table
(
Game varchar(15),
Rollno varchar(15)
)
insert into @tab values('Cricket','R11')
insert into @tab values('VollyBall','R12')

declare @game  varchar(20)
declare @Rollno varchar(20)

declare cur2 cursor for select game,rollno from @tab 

open cur2

fetch next from cur2 into @game,@rollno

WHILE   @@FETCH_STATUS = 0   
begin

print @game

print @rollno

FETCH NEXT FROM cur2 into @game,@rollno

end

close cur2

deallocate cur2

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

To make it a bit more user-friendly: After you've unpacked it, go into the directory, and run bin/pycharm.sh. Once it opens, it either offers you to create a desktop entry, or if it doesn't, you can ask it to do so by going to the Tools menu and selecting Create Desktop Entry...

Then close PyCharm, and in the future you can just click on the created menu entry. (or copy it onto your Desktop)

To answer the specifics between Run and Run in Terminal: It's essentially the same, but "Run in Terminal" actually opens a terminal window first and shows you console output of the program. Chances are you don't want that :)

(Unless you are trying to debug an application, you usually do not need to see the output of it.)

C - reading command line parameters

There's also a C standard built-in library to get command line arguments: getopt

You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.

How does DateTime.Now.Ticks exactly work?

Not really an answer to your question as asked, but thought I'd chip in about your general objective.

There already is a method to generate random file names in .NET.

See System.Path.GetTempFileName and GetRandomFileName.

Alternatively, it is a common practice to use a GUID to name random files.

Make page to tell browser not to cache/preserve input values

Are you explicitly setting the values as blank? For example:

<input type="text" name="textfield" value="">

That should stop browsers putting data in where it shouldn't. Alternatively, you can add the autocomplete attribute to the form tag:

<form autocomplete="off" ...></form>

no match for ‘operator<<’ in ‘std::operator

There's only one error:

cout.cpp:26:29: error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = std::char_traits]((* & std::cout), ((const char*)"my structure ")) << m’

This means that the compiler couldn't find a matching overload for operator<<. The rest of the output is the compiler listing operator<< overloads that didn't match. The third line actually says this:

cout.cpp:26:29: note: candidates are:

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

If you see an out of memory, consider if that is plausible: Do you really need that much memory? If not (i.e. when you don't have huge objects and if you don't need to create millions of objects for some reason), chances are that you have a memory leak.

In Java, this means that you're keeping a reference to an object somewhere even though you don't need it anymore. Common causes for this is forgetting to call close() on resources (files, DB connections, statements and result sets, etc.).

If you suspect a memory leak, use a profiler to find which object occupies all the available memory.

Getting DOM node from React child element

I found an easy way using the new callback refs. You can just pass a callback as a prop to the child component. Like this:

class Container extends React.Component {
  constructor(props) {
    super(props)
    this.setRef = this.setRef.bind(this)
  }

  setRef(node) {
    this.childRef = node
  }

  render() {
    return <Child setRef={ this.setRef }/>
  }
}

const Child = ({ setRef }) => (
    <div ref={ setRef }>
    </div>
)

Here's an example of doing this with a modal:

class Container extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      modalOpen: false
    }
    this.open = this.open.bind(this)
    this.close = this.close.bind(this)
    this.setModal = this.setModal.bind(this)
  }

  open() {
    this.setState({ open: true })
  }

  close(event) {
    if (!this.modal.contains(event.target)) {
      this.setState({ open: false })
    }
  }

  setModal(node) {
    this.modal = node
  }

  render() {
    let { modalOpen } = this.state
    return (
      <div>
        <button onClick={ this.open }>Open</button>
        {
          modalOpen ? <Modal close={ this.close } setModal={ this.setModal }/> : null
        }
      </div>
    )
  }
}

const Modal = ({ close, setModal }) => (
  <div className='modal' onClick={ close }>
    <div className='modal-window' ref={ setModal }>
    </div>
  </div>
)

Return string Input with parse.string

You don't need to parse the string, it's defined as a string already.

Just do:

    private static String getStringInput (String prompt) {
     String input = EZJ.getUserInput(prompt);
     return input;
    }

select2 - hiding the search box

For multiselect you have to write js code, there is no settings property.

$('#js-example-basic-hide-search-multi').select2();

$('#js-example-basic-hide-search-multi').on('select2:opening select2:closing', function( event ) {
    var $searchfield = $(this).parent().find('.select2-search__field');
    $searchfield.prop('disabled', true);
});

This mentioned on their page: https://select2.org/searching#multi-select

base64 encode in MySQL

Functions from http://wi-fizzle.com/downloads/base64.sql contain some error when in encoded string are 32-byte (space), ex BASE64_ENCODE(CONCAT(CHAR(15), CHAR(32))). Here is corrected function

DELIMITER $$

USE `YOUR DATABASE`$$

DROP TABLE IF EXISTS core_base64_data$$
CREATE TABLE core_base64_data (c CHAR(1) BINARY, val TINYINT)$$
INSERT INTO core_base64_data VALUES 
('A',0), ('B',1), ('C',2), ('D',3), ('E',4), ('F',5), ('G',6), ('H',7), ('I',8), ('J',9),
('K',10), ('L',11), ('M',12), ('N',13), ('O',14), ('P',15), ('Q',16), ('R',17), ('S',18), ('T',19),
('U',20), ('V',21), ('W',22), ('X',23), ('Y',24), ('Z',25), ('a',26), ('b',27), ('c',28), ('d',29),
('e',30), ('f',31), ('g',32), ('h',33), ('i',34), ('j',35), ('k',36), ('l',37), ('m',38), ('n',39),
('o',40), ('p',41), ('q',42), ('r',43), ('s',44), ('t',45), ('u',46), ('v',47), ('w',48), ('x',49),
('y',50), ('z',51), ('0',52), ('1',53), ('2',54), ('3',55), ('4',56), ('5',57), ('6',58), ('7',59),
('8',60), ('9',61), ('+',62), ('/',63), ('=',0) $$

DROP FUNCTION IF EXISTS `BASE64_ENCODE`$$

CREATE DEFINER=`YOUR DATABASE`@`%` FUNCTION `BASE64_ENCODE`(input BLOB) RETURNS BLOB
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE ret BLOB DEFAULT '';
    DECLARE done TINYINT DEFAULT 0;
    IF input IS NULL THEN
        RETURN NULL;
    END IF;
each_block:
    WHILE NOT done DO BEGIN
        DECLARE accum_value BIGINT UNSIGNED DEFAULT 0;
        DECLARE in_count TINYINT DEFAULT 0;
        DECLARE out_count TINYINT;
each_input_char:
        WHILE in_count < 3 DO BEGIN
            DECLARE first_char BLOB(1);

            IF LENGTH(input) = 0 THEN
                SET done = 1;
                SET accum_value = accum_value << (8 * (3 - in_count));
                LEAVE each_input_char;
            END IF;

            SET first_char = SUBSTRING(input,1,1);
            SET input = SUBSTRING(input,2);

            SET accum_value = (accum_value << 8) + ASCII(first_char);
            SET in_count = in_count + 1;
        END; END WHILE;

        -- We've now accumulated 24 bits; deaccumulate into base64 characters
        -- We have to work from the left, so use the third byte position and shift left
        CASE
            WHEN in_count = 3 THEN SET out_count = 4;
            WHEN in_count = 2 THEN SET out_count = 3;
            WHEN in_count = 1 THEN SET out_count = 2;
            ELSE RETURN ret;
        END CASE;

        WHILE out_count > 0 DO BEGIN
            BEGIN
                DECLARE out_char CHAR(1);
                DECLARE base64_getval CURSOR FOR SELECT c FROM core_base64_data WHERE val = (accum_value >> 18);
                OPEN base64_getval;
                FETCH base64_getval INTO out_char;
                CLOSE base64_getval;
                SET ret = CONCAT(ret,out_char);
                SET out_count = out_count - 1;
                SET accum_value = accum_value << 6 & 0xffffff;
            END;
        END; END WHILE;
        CASE
            WHEN in_count = 2 THEN SET ret = CONCAT(ret,'=');
            WHEN in_count = 1 THEN SET ret = CONCAT(ret,'==');
            ELSE BEGIN END;
        END CASE;

    END; END WHILE;
    RETURN ret;
END$$

DELIMITER ;

Route [login] not defined

I ran into this error recently after using Laravel's built-in authentication routing using php artisan make:auth. When you run that command, these new routes are added to your web.php file:

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

I must have accidentally deleted these routes. Running php artisan make:auth again restored the routes and solved the problem. I'm running Laravel 5.5.28.

Copy files from one directory into an existing directory

If you want to copy something from one directory into the current directory, do this:

cp dir1/* .

This assumes you're not trying to copy hidden files.

What is the equivalent of bigint in C#?

I think the equivalent is Int64

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

We could do without any xxxFactory, xxxManager or xxxRepository classes if we modeled the real world correctly:

Universe.Instance.Galaxies["Milky Way"].SolarSystems["Sol"]
        .Planets["Earth"].Inhabitants.OfType<Human>().WorkingFor["Initech, USA"]
        .OfType<User>().CreateNew("John Doe");

;-)

How do I serialize an object and save it to a file in Android?

Saving (w/o exception handling code):

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();

Loading (w/o exception handling code):

FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();

Send array with Ajax to PHP script

Encode your data string into JSON.

dataString = ??? ; // array?
var jsonString = JSON.stringify(dataString);
   $.ajax({
        type: "POST",
        url: "script.php",
        data: {data : jsonString}, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

In your PHP

$data = json_decode(stripslashes($_POST['data']));

  // here i would like use foreach:

  foreach($data as $d){
     echo $d;
  }

Note

When you send data via POST, it needs to be as a keyvalue pair.

Thus

data: dataString

is wrong. Instead do:

data: {data:dataString}

Is there a command to undo git init?

In windows, type rmdir .git or rmdir /s .git if the .git folder has subfolders.

If your git shell isn't setup with proper administrative rights (i.e. it denies you when you try to rmdir), you can open a command prompt (possibly as administrator--hit the windows key, type 'cmd', right click 'command prompt' and select 'run as administrator) and try the same commands.

rd is an alternative form of the rmdir command. http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/rmdir.mspx?mfr=true

Origin is not allowed by Access-Control-Allow-Origin

This was the first question/answer that popped up for me when trying to solve the same problem using ASP.NET MVC as the source of my data. I realize this doesn't solve the PHP question, but it is related enough to be valuable.

I am using ASP.NET MVC. The blog post from Greg Brant worked for me. Ultimately, you create an attribute, [HttpHeaderAttribute("Access-Control-Allow-Origin", "*")], that you are able to add to controller actions.

For example:

public class HttpHeaderAttribute : ActionFilterAttribute
{
    public string Name { get; set; }
    public string Value { get; set; }
    public HttpHeaderAttribute(string name, string value)
    {
        Name = name;
        Value = value;
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.AppendHeader(Name, Value);
        base.OnResultExecuted(filterContext);
    }
}

And then using it with:

[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")]
public ActionResult MyVeryAvailableAction(string id)
{
    return Json( "Some public result" );
}

Change input value onclick button - pure javascript or jQuery

Another simple solution for this case using jQuery. Keep in mind it's not a good practice to use inline javascript.

JsFiddle

I've added IDs to html on the total price and on the buttons. Here is the jQuery.

$('#two').click(function(){
    $('#count').val('2');
    $('#total').text('Product price: $1000');
});

$('#four').click(function(){
    $('#count').val('4');
    $('#total').text('Product price: $2000');
});

JSON date to Java date?

Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).

So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX") produces a format that can parse both "2013-03-11T01:38:18.309Z" and "2013-03-11T01:38:18.309+0000" and will give you the same result.

Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.

I actually have more trouble on the JavaScript side to deal with both formats.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

Adding the why this occurs and more possible cause. A lot of interfaces still do not understand ES6 Javascript syntax/features, hence there is need for Es6 to be compiled to ES5 whenever it is used in any file or project. The possible reasons for the SyntaxError: Cannot use import statement outside a module error is you are trying to run the file independently, you are yet to install and set up an Es6 compiler such as Babel or the path of the file in your runscript is wrong/not the compiled file. If you will want to continue without a compiler the best possible solution is to use ES5 syntax which in your case would be var ms = require(./ms.js); this can later be updated as appropriate or better still setup your compiler and ensure your file/project is compiled before running and also ensure your run script is running the compiled file usually named dist, build or whatever you named it and the path to the compiled file in your runscript is correct.

ORA-28001: The password has expired

you are in wrong cdb/pdb so connect to right pdb

How to compare two files in Notepad++ v6.6.8

There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.

Alternatively you can install a specialized file compare software like WinMerge.

getDate with Jquery Datepicker

try

$('#page_output').html(str_output);

How to align an image dead center with bootstrap

You could use the following. It supports Bootstrap 3.x above.

<img src="..." alt="..." class="img-responsive center-block" />

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Happy coding..

What is the difference between Jupyter Notebook and JupyterLab?

If you are looking for features that notebooks in JupyterLab have that traditional Jupyter Notebooks do not, check out the JupyterLab notebooks documentation. There is a simple video showing how to use each of the features in the documentation link.

JupyterLab notebooks have the following features and more:

  • Drag and drop cells to rearrange your notebook
  • Drag cells between notebooks to quickly copy content (since you can
    have more than one open at a time)
  • Create multiple synchronized views of a single notebook
  • Themes and customizations: Dark theme and increase code font size

Correct format specifier to print pointer or address?

Use %p, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u expects an unsigned int, but what if void* has a different size or alignment requirement than unsigned int?)

*) [See Jonathan's fine answer!] Alternatively to %p, you can use pointer-specific macros from <inttypes.h>, added in C99.

All object pointers are implicitly convertible to void* in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):

printf("x lives at %p.\n", (void*)&x);

How to check user is "logged in"?

if (User.Identity.IsAuthenticated)
{
    Page.Title = "Home page for " + User.Identity.Name;
}
else
{
    Page.Title = "Home page for guest user.";
}

Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

Simply quote your variable:

[ -e "$VAR" ]

This evaluates to [ -e "" ] if $VAR is empty.

Your version does not work because it evaluates to [ -e ]. Now in this case, bash simply checks if the single argument (-e) is a non-empty string.

From the manpage:

test and [ evaluate conditional expressions using a set of rules based on the number of arguments. ...

1 argument

The expression is true if and only if the argument is not null.

(Also, this solution has the additional benefit of working with filenames containing spaces)

How to clear radio button in Javascript?

An ES6 approach to clearing a group of radio buttons:

    Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );

How to make a script wait for a pressed key?

If you are ok with depending on system commands you can use the following:

Linux and Mac OS X:

import os
os.system('read -s -n 1 -p "Press any key to continue..."')
print()

Windows:

import os
os.system("pause")

Renaming Columns in an SQL SELECT Statement

you have to rename each column

SELECT col1 as MyCol1,
       col2 as MyCol2,
 .......
 FROM `foobar`

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

Simple logical operators in Bash

very close

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

should work.

breaking it down

[[ $varA -eq 1 ]] 

is an integer comparison where as

$varB == 't1'

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

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

How to pass object from one component to another in Angular 2?

you could also store your data in an service with an setter and get it over a getter

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

@Injectable()
export class StorageService {

    public scope: Array<any> | boolean = false;

    constructor() {
    }

    public getScope(): Array<any> | boolean {
        return this.scope;
    }

    public setScope(scope: any): void {
        this.scope = scope;
    }
}

Copy file from source directory to binary directory using CMake

If you want to put the content of example into install folder after build:

code/
  src/
  example/
  CMakeLists.txt

try add the following to your CMakeLists.txt:

install(DIRECTORY example/ DESTINATION example)

python numpy machine epsilon

An easier way to get the machine epsilon for a given float type is to use np.finfo():

print(np.finfo(float).eps)
# 2.22044604925e-16

print(np.finfo(np.float32).eps)
# 1.19209e-07

Sending data through POST request from a node.js server to a node.js server

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for executing a POST request:

var requestify = require('requestify');

requestify.post('http://example.com', {
    hello: 'world'
})
.then(function(response) {
    // Get the response body (JSON parsed or jQuery object for XMLs)
    response.getBody();
});

What and where are the stack and heap?

Simply, the stack is where local variables get created. Also, every time you call a subroutine the program counter (pointer to the next machine instruction) and any important registers, and sometimes the parameters get pushed on the stack. Then any local variables inside the subroutine are pushed onto the stack (and used from there). When the subroutine finishes, that stuff all gets popped back off the stack. The PC and register data gets and put back where it was as it is popped, so your program can go on its merry way.

The heap is the area of memory dynamic memory allocations are made out of (explicit "new" or "allocate" calls). It is a special data structure that can keep track of blocks of memory of varying sizes and their allocation status.

In "classic" systems RAM was laid out such that the stack pointer started out at the bottom of memory, the heap pointer started out at the top, and they grew towards each other. If they overlap, you are out of RAM. That doesn't work with modern multi-threaded OSes though. Every thread has to have its own stack, and those can get created dynamicly.

Excel VBA - read cell value from code

I think you need this ..

Dim n as Integer   

For n = 5 to 17
  msgbox cells(n,3) '--> sched waste
  msgbox cells(n,4) '--> type of treatm
  msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
  msgbox cells(n,6) '--> email col
Next

Add a column to a table, if it does not already exist

IF NOT EXISTS (SELECT * FROM syscolumns
  WHERE ID=OBJECT_ID('[db].[Employee]') AND NAME='EmpName')
  ALTER TABLE [db].[Employee]
  ADD [EmpName] VARCHAR(10)
GO

I Hope this would help. More info