Programs & Examples On #Cp1251

Windows-1251 (a.k.a. code page CP1251) is a popular 8-bit character encoding, designed to cover languages that use the Cyrillic script such as Russian, Bulgarian, Serbian Cyrillic and other languages. It is the most widely used for encoding the Bulgarian, Serbian and Macedonian languages. In modern applications, Unicode is a preferred character set.

xcode-select active developer directory error

There are only two steps required, and the full XCode.app is not required at all:

sudo rm -rf /Library/Developer/CommandLineTools
xcode-select --install

At this point the "Installing Softwre" dialog pops up:

enter image description here

That's it!

.NET Core vs Mono

In the .NET world there are two types of CLRs, "full" CLRs and Core CLRs, and these are quite different things.

There are two "full" CLR implementations, the Microsoft native .NET CLR (for Windows) and the Mono CLR (which itself has implementations for Windows, linux and unix (Mac OS X and FreeBSD)). A full CLR is exactly that - everything, pretty much, that you need. As such, "full" CLRs tend to be large in size.

Core CLRs are on the other hand are cut down, and much smaller. Because they are only a core implementation, they are unlikely to have everything you need in them, so with Core CLRs you add feature sets to the CLR that your specific software product uses, using NuGet. There are Core CLR implementations for Windows, linux (various) and unix (Mac OS X and FreeBSD) in the mix. Microsoft have or are refactoring the .NET framework libraries for Core CLR too, to make them more portable for the core context. Given mono's presence on *nix OSs it would be a surprise if the Core CLRs for *nix did not include some mono code base, but only the Mono community and Microsoft could tell us that for sure.

Also, I'd concur with Nico in that Core CLRs are new -- it's at RC2 at the moment I think. I wouldn't depend on it for production code yet.

To answer your question you could delivery your site on linux using Core CLR or Mono, and these are two different ways of doing it. If you want a safe bet right now I'd go with mono on linux, then port if you want to later, to Core.

What is the maximum length of data I can put in a BLOB column in MySQL?

May or may not be accurate, but according to this site: http://www.htmlite.com/mysql003.php.

BLOB A string with a maximum length of 65535 characters.

The MySQL manual says:

The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers

I think the first site gets their answers from interpreting the MySQL manual, per http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html

Setting selected option in laravel form

            @foreach ($categories as $category)
             <option value="{{$category->id}}" 
               @foreach ($posts->postRelateToCategory as $Postcategory)
                 @if ($Postcategory->id == $category->id)
                 {{'selected="selected"'}}
                 @endif 
               @endforeach >
              {{ $category->category_name }} </option>               
            @endforeach    

Cocoa: What's the difference between the frame and the bounds?

try to run the code below

- (void)viewDidLoad {
    [super viewDidLoad];
    UIWindow *w = [[UIApplication sharedApplication] keyWindow];
    UIView *v = [w.subviews objectAtIndex:0];

    NSLog(@"%@", NSStringFromCGRect(v.frame));
    NSLog(@"%@", NSStringFromCGRect(v.bounds));
}

the output of this code is:

case device orientation is Portrait

{{0, 0}, {768, 1024}}
{{0, 0}, {768, 1024}}

case device orientation is Landscape

{{0, 0}, {768, 1024}}
{{0, 0}, {1024, 768}}

obviously, you can see the difference between frame and bounds

How can I use optional parameters in a T-SQL stored procedure?

Extend your WHERE condition:

WHERE
    (FirstName = ISNULL(@FirstName, FirstName)
    OR COALESCE(@FirstName, FirstName, '') = '')
AND (LastName = ISNULL(@LastName, LastName)
    OR COALESCE(@LastName, LastName, '') = '')
AND (Title = ISNULL(@Title, Title)
    OR COALESCE(@Title, Title, '') = '')

i. e. combine different cases with boolean conditions.

Iterating over Numpy matrix rows to apply a function each?

Use numpy.apply_along_axis(). Assuming your matrix is 2D, you can use like:

import numpy as np
mymatrix = np.matrix([[11,12,13],
                      [21,22,23],
                      [31,32,33]])
def myfunction( x ):
    return sum(x)

print np.apply_along_axis( myfunction, axis=1, arr=mymatrix )
#[36 66 96]

Javascript to convert UTC to local time

var offset = new Date().getTimezoneOffset();

offset will be the interval in minutes from Local time to UTC. To get Local time from a UTC date, you would then subtract the minutes from your date.

utc_date.setMinutes(utc_date.getMinutes() - offset);

What is the difference between DAO and Repository patterns?

DAO provides abstraction on database/data files or any other persistence mechanism so that, persistence layer could be manipulated without knowing its implementation details.

Whereas in Repository classes, multiple DAO classes can be used inside a single Repository method to get an operation done from "app perspective". So, instead of using multiple DAO at Domain layer, use repository to get it done. Repository is a layer which may contain some application logic like: If data is available in in-memory cache then fetch it from cache otherwise, fetch data from network and store it in in-memory cache for next time retrieval.

UILabel - Wordwrap text

UILabel has a property lineBreakMode that you can set as per your requirement.

How can I scroll to a specific location on the page using jquery?

There is no need to use any plugin, you can do it like this:

var divPosition = $('#divId').offset();

then use this to scroll document to specific DOM:

$('html, body').animate({scrollTop: divPosition.top}, "slow");

Print ArrayList

Put houseAddress.get(i) inside the brackets and call .toString() function: i.e Please see below

for(int i = 0; i < houseAddress.size(); i++) {
    System.out.print((houseAddress.get(i)).toString());
}

How to change a package name in Eclipse?

Right Click your Project
Android Tools>>Rename Application Package Just Change Package in there... enter image description here

converting epoch time with milliseconds to datetime

those are miliseconds, just divide them by 1000, since gmtime expects seconds ...

time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))

Picasso v/s Imageloader v/s Fresco vs Glide

These answers are totally my opinion

Answers

  1. Picasso is an easy to use image loader, same goes for Imageloader. Fresco uses a different approach to image loading, i haven't used it yet but it looks too me more like a solution for getting image from network and caching them then showing the images. then the other way around like Picasso/Imageloader/Glide which to me are more Showing image on screen that also does getting images from network and caching them.

  2. Glide tries to be somewhat interchangeable with Picasso.I think when they were created Picasso's mind set was follow HTTP spec's and let the server decide the caching policies and cache full sized and resize on demand. Glide is the same with following the HTTP spec but tries to have a smaller memory footprint by making some different assumptions like cache the resized images instead of the fullsized images, and show images with RGB_565 instead of RGB_8888. Both libraries offer full customization of the default settings.

  3. As to which library is the best to use is really hard to say. Picasso, Glide and Imageloader are well respected and well tested libraries which all are easy to use with the default settings. Both Picasso and Glide require only 1 line of code to load an image and have a placeholder and error image. Customizing the behaviour also doesn't require that much work. Same goes for Imageloader which is also an older library then Picasso and Glide, however I haven't used it so can't say much about performance/memory usage/customizations but looking at the readme on github gives me the impression that it is also relatively easy to use and setup. So in choosing any of these 3 libraries you can't make the wrong decision, its more a matter of personal taste. For fresco my opinion is that its another facebook library so we have to see how that is going to work out for them, so far there track record isn't that good. Like the facebook SDK is still isn't officially released on mavenCentral I have not used to facebook sdk since sept 2014 and it seems they have put the first version online on mavenCentral in oct 2014. So it will take some time before we can get any good opinion about it.

  4. between the 3 big name libraries I think there are no significant differences. The only one that stand out is fresco but that is because it has a different approach and is new and not battle tested.

Adding an image to a project in Visual Studio

You need to turn on Show All Files option on solution pane toolbar and include this file manually.

finding the type of an element using jQuery

It is worth noting that @Marius's second answer could be used as pure Javascript solution.

document.getElementById('elementId').tagName

How to check if a socket is connected/disconnected in C#?

As zendar wrote, it is nice to use the Socket.Poll and Socket.Available, but you need to take into consideration that the socket might not have been initialized in the first place. This is the last (I believe) piece of information and it is supplied by the Socket.Connected property. The revised version of the method would looks something like this:

 static bool IsSocketConnected(Socket s)
    {
        return !((s.Poll(1000, SelectMode.SelectRead) && (s.Available == 0)) || !s.Connected);

/* The long, but simpler-to-understand version:

        bool part1 = s.Poll(1000, SelectMode.SelectRead);
        bool part2 = (s.Available == 0);
        if ((part1 && part2 ) || !s.Connected)
            return false;
        else
            return true;

*/
    }

How can I use threading in Python?

Since this question was asked in 2010, there has been real simplification in how to do simple multithreading with Python with map and pool.

The code below comes from an article/blog post that you should definitely check out (no affiliation) - Parallelism in one line: A Better Model for Day to Day Threading Tasks. I'll summarize below - it ends up being just a few lines of code:

from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
results = pool.map(my_function, my_array)

Which is the multithreaded version of:

results = []
for item in my_array:
    results.append(my_function(item))

Description

Map is a cool little function, and the key to easily injecting parallelism into your Python code. For those unfamiliar, map is something lifted from functional languages like Lisp. It is a function which maps another function over a sequence.

Map handles the iteration over the sequence for us, applies the function, and stores all of the results in a handy list at the end.

Enter image description here


Implementation

Parallel versions of the map function are provided by two libraries:multiprocessing, and also its little known, but equally fantastic step child:multiprocessing.dummy.

multiprocessing.dummy is exactly the same as multiprocessing module, but uses threads instead (an important distinction - use multiple processes for CPU-intensive tasks; threads for (and during) I/O):

multiprocessing.dummy replicates the API of multiprocessing, but is no more than a wrapper around the threading module.

import urllib2
from multiprocessing.dummy import Pool as ThreadPool

urls = [
  'http://www.python.org',
  'http://www.python.org/about/',
  'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
  'http://www.python.org/doc/',
  'http://www.python.org/download/',
  'http://www.python.org/getit/',
  'http://www.python.org/community/',
  'https://wiki.python.org/moin/',
]

# Make the Pool of workers
pool = ThreadPool(4)

# Open the URLs in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)

# Close the pool and wait for the work to finish
pool.close()
pool.join()

And the timing results:

Single thread:   14.4 seconds
       4 Pool:   3.1 seconds
       8 Pool:   1.4 seconds
      13 Pool:   1.3 seconds

Passing multiple arguments (works like this only in Python 3.3 and later):

To pass multiple arrays:

results = pool.starmap(function, zip(list_a, list_b))

Or to pass a constant and an array:

results = pool.starmap(function, zip(itertools.repeat(constant), list_a))

If you are using an earlier version of Python, you can pass multiple arguments via this workaround).

(Thanks to user136036 for the helpful comment.)

"git rebase origin" vs."git rebase origin/master"

Here's a better option:

git remote set-head -a origin

From the documentation:

With -a, the remote is queried to determine its HEAD, then $GIT_DIR/remotes//HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set $GIT_DIR/refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first.

This has actually been around quite a while (since v1.6.3); not sure how I missed it!

Mongoimport of json file

console:

mongoimport -d dbName -c collectionName dataFile.js 

How do I import an SQL file using the command line in MySQL?

You do not need to specify the name of the database on the command line if the .sql file contains CREATE DATABASE IF NOT EXISTS db_name and USE db_name statements.

Just make sure you are connecting with a user that has the permissions to create the database, if the database mentioned in the .sql file does not exist.

Handling the null value from a resultset in JAVA

The code should be like given below

String selectSQL = "SELECT IFNULL(tbl.column, \"\") AS column FROM MySQL_table AS tbl";
Statement st = ...;
Result set rs = st.executeQuery(selectSQL);

How to JSON serialize sets?

JSON notation has only a handful of native datatypes (objects, arrays, strings, numbers, booleans, and null), so anything serialized in JSON needs to be expressed as one of these types.

As shown in the json module docs, this conversion can be done automatically by a JSONEncoder and JSONDecoder, but then you would be giving up some other structure you might need (if you convert sets to a list, then you lose the ability to recover regular lists; if you convert sets to a dictionary using dict.fromkeys(s) then you lose the ability to recover dictionaries).

A more sophisticated solution is to build-out a custom type that can coexist with other native JSON types. This lets you store nested structures that include lists, sets, dicts, decimals, datetime objects, etc.:

from json import dumps, loads, JSONEncoder, JSONDecoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))):
            return JSONEncoder.default(self, obj)
        return {'_python_object': pickle.dumps(obj)}

def as_python_object(dct):
    if '_python_object' in dct:
        return pickle.loads(str(dct['_python_object']))
    return dct

Here is a sample session showing that it can handle lists, dicts, and sets:

>>> data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]

>>> j = dumps(data, cls=PythonObjectEncoder)

>>> loads(j, object_hook=as_python_object)
[1, 2, 3, set(['knights', 'say', 'who', 'ni']), {u'key': u'value'}, Decimal('3.14')]

Alternatively, it may be useful to use a more general purpose serialization technique such as YAML, Twisted Jelly, or Python's pickle module. These each support a much greater range of datatypes.

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

How to change the default background color white to something else in twitter bootstrap

The colors changed due to the order of CSS files.

Place the custom CSS under the bootstrap CSS.

Access denied for user 'test'@'localhost' (using password: YES) except root user

connect your server from mysqlworkbench and run this command-> ALTER USER 'root'@'localhost' IDENTIFIED BY 'yourpassword';

ArrayList of int array in java

The setup:

    List<int[]> intArrays=new ArrayList<>();
    int anExample[]={1,2,3};
    intArrays.add(anExample);

To retrieve a single int[] array in the ArrayList by index:

    int[] anIntArray = intArrays.get(0); //'0' is the index
    //iterate the retrieved array an print the individual elements
    for (int aNumber : anIntArray ) { 
        System.out.println("Arraylist contains:" + aNumber );
    }

To retrieve all int[] arrays in the ArrayList:

    //iterate the ArrayList, get and print the elements of each int[] array  
    for(int[] anIntArray:intArrays) {
       //iterate the retrieved array an print the individual elements
       for (int aNumber : anIntArray) {
           System.out.println("Arraylist contains:" + aNumber);
       }
}

Output formatting can be performed based on this logic. Goodluck!!

Under which circumstances textAlign property works in Flutter?

You can use the container, It will help you to set the alignment.

Widget _buildListWidget({Map reminder}) {
return Container(
  color: Colors.amber,
  alignment: Alignment.centerLeft,
  padding: EdgeInsets.all(20),
  height: 80,
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Container(
        alignment: Alignment.centerLeft,
        child: Text(
          reminder['title'],
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16,
            color: Colors.black,
            backgroundColor: Colors.blue,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
      Container(
        alignment: Alignment.centerRight,
        child: Text(
          reminder['Date'],
          textAlign: TextAlign.right,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey,
            backgroundColor: Colors.blue,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
    ],
  ),
);
}

Why is the parent div height zero when it has floated children

Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).

Setting overflow: hidden on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

You could use jQuery to add an event listener on the document DOM.

_x000D_
_x000D_
    $(document).on("click", function () {_x000D_
        console.log('clicked');_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

querying WHERE condition to character length?

I think you want this:

select *
from dbo.table
where DATALENGTH(column_name) = 3

Allow only numbers to be typed in a textbox

With HTML5 you can do

<input type="number">

You can also use a regex pattern to limit the input text.

<input type="text" pattern="^[0-9]*$" />

android - setting LayoutParams programmatically

int dp1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
            context.getResources().getDisplayMetrics());

tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
dp1 * 100)); // if you want to set layout height to 100dp

llview.addView(tv);

Google Map API v3 ~ Simply Close an infowindow?

We can use infowindow.close(map); to close all info windows if you already initialize the info window using infowindow = new google.maps.InfoWindow();

What exactly does a jar file contain?

While learning about JAR, I came across this thread, but couldn't get enough information for people like me, who have .NET background, so I'm gonna add few points which can help persons like myself with .NET background.

First we need to define similar concept to JAR in .NET which is Assembly and assembly shares a lot in common with Java JAR files.

So, an assembly is the fundamental unit of code packaging in the .NET environment. Assemblies are self contained and typically contain the intermediate code from compiling classes, metadata about the classes, and any other files needed by the packaged code to perform its task. Since assemblies are the fundamental unit of code packaging, several actions related to interacting with types must be done at the assembly level. For instance, granting of security permissions, code deployment, and versioning are done at the assembly level.

Java JAR files perform a similar task in Java with most differences being in the implementation. Assemblies are usually stored as EXEs or DLLs while JAR files are stored in the ZIP file format.

Source of Information -> 5- Assemblies

How to drop columns using Rails migration

rails g migration RemoveXColumnFromY column_name:data_type

X = column name
Y = table name

EDIT

Changed RemoveXColumnToY to RemoveXColumnFromY as per comments - provides more clarity for what the migration is actually doing.

jQuery remove options from select

It works on either option tag or text field:

$("#idname option[value='option1']").remove();

Find all storage devices attached to a Linux machine

Modern linux systems will normally only have entries in /dev for devices that exist, so going through hda* and sda* as you suggest would work fairly well.

Otherwise, there may be something in /proc you can use. From a quick look in there, I'd have said /proc/partitions looks like it could do what you need.

eloquent laravel: How to get a row count from a ->get()

Direct get a count of row

Using Eloquent

 //Useing Eloquent
 $count = Model::count();    

 //example            
 $count1 = Wordlist::count();

Using query builder

 //Using query builder
 $count = \DB::table('table_name')->count();

 //example
 $count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();

How to remove and clear all localStorage data

If you want to remove/clean all the values from local storage than use

localStorage.clear();

And if you want to remove the specific item from local storage than use the following code

localStorage.removeItem(key);

SQL Server 2008 can't login with newly created user

SQL Server was not configured to allow mixed authentication.

Here are steps to fix:

  1. Right-click on SQL Server instance at root of Object Explorer, click on Properties
  2. Select Security from the left pane.
  3. Select the SQL Server and Windows Authentication mode radio button, and click OK.

    enter image description here

  4. Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).

This is also incredibly helpful for IBM Connections users, my wizards were not able to connect until I fxed this setting.

How to ftp with a batch file?

You need to write the ftp commands in a text file and give it as a parameter for the ftp command like this:

ftp -s:filename

More info here: http://www.nsftools.com/tips/MSFTP.htm

I am not sure though if it would work with username and password prompt.

Get client IP address via third party web service

This pulls back client info as well.

var get = function(u){
    var x = new XMLHttpRequest;
    x.open('GET', u, false);
    x.send();
    return x.responseText;
}

JSON.parse(get('http://ifconfig.me/all.json'))

Run bash script from Windows PowerShell

There is now a "native" solution on Windows 10, after enabling Bash on Windows, you can enter Bash shell by typing bash: Bash on Windows

You can run Bash script like bash ./script.sh, but keep in mind that C drive is located at /mnt/c, and external hard drives are not mountable. So you might need to change your script a bit so it is compatible to Windows.

Also, even as root, you can still get permission denied when moving files around in /mnt, but you have your full root power in the / file system.

Also make sure your shell script is formatted with Unix style, or there can be errors. Example script

If statements for Checkboxes

I suggest

if (checkbox.IsChecked == true)
{
    //do something
}

Hope it's helpful ^^

Placing a textview on top of imageview in android

you can try this too. I use just framelayout.

 <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/cover"
                android:gravity="bottom">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:text="Hello !"
                    android:id="@+id/welcomeTV"
                    android:textColor="@color/textColor"
                    android:layout_gravity="left|bottom" />
            </FrameLayout>

React "after render" code?

componentDidMount()

This method is called once after your component is rendered. So your code would look like so.

var AppBase = React.createClass({
  componentDidMount: function() {
    var $this = $(ReactDOM.findDOMNode(this));
    // set el height and width etc.
  },

  render: function () {
    return (
      <div className="wrapper">
        <Sidebar />
          <div className="inner-wrapper">
            <ActionBar title="Title Here" />
            <BalanceBar balance={balance} />
            <div className="app-content">
              <List items={items} />
          </div>
        </div>
      </div>
    );
  }
});

How to convert SQL Query result to PANDAS Data Structure?

resoverall is a sqlalchemy ResultProxy object. You can read more about it in the sqlalchemy docs, the latter explains basic usage of working with Engines and Connections. Important here is that resoverall is dict like.

Pandas likes dict like objects to create its data structures, see the online docs

Good luck with sqlalchemy and pandas.

How can I use jQuery to make an input readonly?

<html xmlns="http://www.w3.org/1999/xhtml">
<head >
    <title></title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

</head>
<body>
    <div>
        <input id="fieldName" name="fieldName" type="text" class="text_box" value="Firstname" />
    </div>
</body>

<script type="text/javascript">
    $(function()
    {
        $('#fieldName').attr('disabled', 'disabled');

    });
</script>
</html>

The property 'value' does not exist on value of type 'HTMLElement'

The problem is here:

document.getElementById(elementId).value

You know that HTMLElement returned from getElementById() is actually an instance of HTMLInputElement inheriting from it because you are passing an ID of input element. Similarly in statically typed Java this won't compile:

public Object foo() {
  return 42;
}

foo().signum();

signum() is a method of Integer, but the compiler only knows the static type of foo(), which is Object. And Object doesn't have a signum() method.

But the compiler can't know that, it can only base on static types, not dynamic behaviour of your code. And as far as the compiler knows, the type of document.getElementById(elementId) expression does not have value property. Only input elements have value.

For a reference check HTMLElement and HTMLInputElement in MDN. I guess Typescript is more or less consistent with these.

How to change the size of the font of a JLabel to take the maximum size

 JLabel textLabel = new JLabel("<html><span style='font-size:20px'>"+Text+"</span></html>");

hibernate: LazyInitializationException: could not initialize proxy

Okay, finally figured out where I was remiss. I was under the mistaken notion that I should wrap each DAO method in a transaction. Terribly wrong! I've learned my lesson. I've hauled all the transaction code from all the DAO methods and have set up transactions strictly at the application/manager layer. This has totally solved all my problems. Data is properly lazy loaded as I need it, wrapped up and closed down once I do the commit.

Life is goodly... :)

Reference an Element in a List of Tuples

You also can use itemgetter operator:

from operator import itemgetter
my_tuples = [('c','r'), (2, 3), ('e'), (True, False),('text','sample')]
map(itemgetter(0), my_tuples)

When is it appropriate to use UDP instead of TCP?

I'm a bit reluctant to suggest UDP when TCP could possibly work. The problem is that if TCP isn't working for some reason, because the connection is too laggy or congested, changing the application to use UDP is unlikely to help. A bad connection is bad for UDP too. TCP already does a very good job of minimizing congestion.

The only case I can think of where UDP is required is for broadcast protocols. In cases where an application involves two, known hosts, UDP will likely only offer marginal performance benefits for substantially increased costs of code complexity.

PHP fwrite new line

fwrite($handle, "<br>"."\r\n");

Add this under

$password = $_POST['password'].PHP_EOL;

this. .

Facebook OAuth "The domain of this URL isn't included in the app's domain"

in my case, i solved this issue by adding the full URL and not only the domain as facebook ask. i hope that they will rename it for more clarification. so the Valid OAuth Redirect URIs should be like so:
Before: https://www.mobile-battles.com
After: https://www.mobile-battles.com/register

Convert .class to .java

I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."

INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there

Wait until ActiveWorkbook.RefreshAll finishes - VBA

Though @Wayne G. Dunn has given in code. Here is the place when you don't want to code. And uncheck to disable the background refresh.

enter image description here

Search an Oracle database for tables with specific column names?

The data you want is in the "cols" meta-data table:

SELECT * FROM COLS WHERE COLUMN_NAME = 'id'

This one will give you a list of tables that have all of the columns you want:

select distinct
  C1.TABLE_NAME
from
  cols c1
  inner join
  cols c2
  on C1.TABLE_NAME = C2.TABLE_NAME
  inner join
  cols c3
  on C2.TABLE_NAME = C3.TABLE_NAME
  inner join
  cols c4
  on C3.TABLE_NAME = C4.TABLE_NAME  
  inner join
  tab t
  on T.TNAME = C1.TABLE_NAME
where T.TABTYPE = 'TABLE' --could be 'VIEW' if you wanted
  and upper(C1.COLUMN_NAME) like upper('%id%')
  and upper(C2.COLUMN_NAME) like upper('%fname%')
  and upper(C3.COLUMN_NAME) like upper('%lname%')
  and upper(C4.COLUMN_NAME) like upper('%address%')  

To do this in a different schema, just specify the schema in front of the table, as in

SELECT * FROM SCHEMA1.COLS WHERE COLUMN_NAME LIKE '%ID%';

If you want to combine the searches of many schemas into one output result, then you could do this:

SELECT DISTINCT
  'SCHEMA1' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA1.COLS
WHERE COLUMN_NAME LIKE '%ID%'
UNION
SELECT DISTINCT
  'SCHEMA2' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA2.COLS
WHERE COLUMN_NAME LIKE '%ID%'

Truncate number to two decimal places without rounding

Update (Jan 2021)

Depending on its range, a number in javascript may be shown in scientific notation. For example, if you type 0.0000001 in the console, you may see it as 1e-7, whereas 0.000001 appears unchanged (0.000001). If your application works on a range of numbers for which scientific notation is not involved, you can just ignore this update and use the original answer below.

This update is about adding a function that checks if the number is in scientific format and, if so, converts it into decimal format. Here I'm proposing this one, but you can use any other function that achieves the same goal, according to your application's needs:

function toFixed(x) {
  if (Math.abs(x) < 1.0) {
    var e = parseInt(x.toString().split('e-')[1]);
    if (e) {
        x *= Math.pow(10,e-1);
        x = '0.' + (new Array(e)).join('0') + x.toString().substring(2);
    }
  } else {
    var e = parseInt(x.toString().split('+')[1]);
    if (e > 20) {
        e -= 20;
        x /= Math.pow(10,e);
        x += (new Array(e+1)).join('0');
    }
  }
  return x;
}

Now just apply that function to the parameter (that's the only change with respect to the original answer):

function toFixedTrunc(x, n) {
      x = toFixed(x) 

      // From here on the code is the same than the original answer
      const v = (typeof x === 'string' ? x : x.toString()).split('.');
      if (n <= 0) return v[0];
      let f = v[1] || '';
      if (f.length > n) return `${v[0]}.${f.substr(0,n)}`;
      while (f.length < n) f += '0';
      return `${v[0]}.${f}`
    }

This updated version addresses also a case mentioned in a comment:

toFixedTrunc(0.000000199, 2) => "0.00" 

Again, choose what fits your application needs at best.

Original answer (October 2017)

General solution to truncate (no rounding) a number to the n-th decimal digit and convert it to a string with exactly n decimal digits, for any n=0.
function toFixedTrunc(x, n) {
  const v = (typeof x === 'string' ? x : x.toString()).split('.');
  if (n <= 0) return v[0];
  let f = v[1] || '';
  if (f.length > n) return `${v[0]}.${f.substr(0,n)}`;
  while (f.length < n) f += '0';
  return `${v[0]}.${f}`
}

where x can be either a number (which gets converted into a string) or a string.

Here are some tests for n=2 (including the one requested by OP):

0           => 0.00
0.01        => 0.01
0.5839      => 0.58
0.999       => 0.99
1.01        => 1.01
2           => 2.00
2.551       => 2.55
2.99999     => 2.99
4.27        => 4.27
15.7784514  => 15.77
123.5999    => 123.59

And for some other values of n:

15.001097   => 15.0010 (n=4)
0.000003298 => 0.0000032 (n=7)
0.000003298257899 => 0.000003298257 (n=12)

Disable validation of HTML5 form elements

I found a solution for Chrome with CSS this following selector without bypassing the native verification form which could be very useful.

form input::-webkit-validation-bubble-message, 
form select::-webkit-validation-bubble-message,
form textarea::-webkit-validation-bubble-message {
    display:none;
} 

By this way, you can also customise your message...

I got the solution on this page : http://trac.webkit.org/wiki/Styling%20Form%20Controls

jQuery add required to input fields

Should not enclose true with double quote " " it should be like

$(document).ready(function() {            
   $('input').attr('required', true);   
});

Also you can use prop

jQuery(document).ready(function() {            
   $('input').prop('required', true);   
}); 

Instead of true you can try required. Such as

$('input').prop('required', 'required');

Fixed width buttons with Bootstrap

btn-group-justified and btn-group only work for static content but not on dynamically created buttons, and fixed with of button in css is not practical as it stay on the same width even all content are short.

My solution: put the same class to group of buttons then loop to all of them, get the width of the longest button and apply it to all

var bwidth=0
$("button.btnGroup").each(function(i,v){
    if($(v).width()>bwidth) bwidth=$(v).width();
});
$("button.btnGroup").width(bwidth);

Sample output here

How to make Bootstrap 4 cards the same height in card-columns?

If anyone is interested, there is a jquery plugin called: jquery.matchHeight.js

https://github.com/liabru/jquery-match-height

matchHeight makes the height of all selected elements exactly equal. It handles many edge cases that cause similar plugins to fail.

For a row of cards, I use:

<div class="row match-height">

Then enable site-wide:

$('.row.match-height').each(function() {
   $(this).find('.card').not('.card .card').matchHeight(); // Not .card .card prevents collapsible cards from taking height
});

MySQL WHERE IN ()

you must have record in table or array record in database.

example:

SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);

How to Diff between local uncommitted changes and origin

To see non-staged (non-added) changes to existing files

git diff

Note that this does not track new files. To see staged, non-commited changes

git diff --cached

Hidden property of a button in HTML

It also works without jQuery if you do the following changes:

  1. Add type="button" to the edit button in order not to trigger submission of the form.

  2. Change the name of your function from change() to anything else.

  3. Don't use hidden="hidden", use CSS instead: style="display: none;".

The following code works for me:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">

<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
    <img src="dba_images/textfield_key.png" alt=""/>
    Edit
</button>

<button type="submit" class="positive" name="save" id="save" style="display:none;">
    <img src="dba_images/apply2.png" alt=""/>
    Save
</button>

<button class="regular" name="change" id="change" style="display:none;">
    <img src="dba_images/textfield_key.png" alt=""/>
    change
</button>

    <button class="negative" name="cancel" id="cancel" style="display:none;">
        <img src="dba_images/cross.png" alt=""/>
        Cancel
    </button>
</div>
</form>
</body>
</html>

Select second last element with css

In CSS3 you have:

:nth-last-child(2)

See: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child

nth-last-child Browser Support:

  • Chrome 2
  • Firefox 3.5
  • Opera 9.5, 10
  • Safari 3.1, 4
  • Internet Explorer 9

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

I think you should indeed be using the Control overload of the RegisterStartupScript.

I've tried the following code in a server control:

[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]
public class AlertControl : Control{
    protected override void OnInit(EventArgs e){
        base.OnInit(e);
        string script = "alert(\"Hello!\");";
        ScriptManager.RegisterStartupScript(this, GetType(), 
                      "ServerControlScript", script, true);
    }
}

Then in my page I have:

protected override void OnInit(EventArgs e){
    base.OnInit(e);
    Placeholder1.Controls.Add(new AlertControl());
}

Where Placeholder1 is a placeholder in an update panel. The placeholder has a couple of other controls on in it, including buttons.

This behaved exactly as you would expect, I got an alert saying "Hello" every time I loaded the page or caused the update panel to update.

The other thing you could look at is to hook into some of the page lifecycle events that are fired during an update panel request:

Sys.WebForms.PageRequestManager.getInstance()
   .add_endRequest(EndRequestHandler);

The PageRequestManager endRequestHandler event fires every time an update panel completes its update - this would allow you to call a method to set up your control.

My only other questions are:

  • What is your script actually doing?
  • Presumably you can see the script in the HTML at the bottom of the page (just before the closing </form> tag)?
  • Have you tried putting a few "alert("Here");" calls in your startup script to see if it's being called correctly?
  • Have you tried Firefox and Firebug - is that reporting any script errors?

Can you pass parameters to an AngularJS controller on creation?

If ng-init is not for passing objects into $scope, you can always write your own directive. So here is what I got:

http://jsfiddle.net/goliney/89bLj/

Javasript:

var app = angular.module('myApp', []);
app.directive('initData', function($parse) {
    return function(scope, element, attrs) {
        //modify scope
        var model = $parse(attrs.initData);
        model(scope);
    };
});

function Ctrl1($scope) {
    //should be defined
    $scope.inputdata = {foo:"east", bar:"west"};
}

Html:

<div ng-controller="Ctrl1">
    <div init-data="inputdata.foo=123; inputdata.bar=321"></div>
</div>

But my approach can only modify objects, which are already defined at controller.

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

Why not to use separate func?

def func(*args, **kwargs):
    return inst.method(args, kwargs)

print pool.map(func, arr)

Uncaught TypeError: Cannot set property 'value' of null

It seems to be this function

h_url=document.getElementById("u").value;

You can help yourself using some 'console.log' to see what object is Null.

Center an element in Bootstrap 4 Navbar

In Bootstrap 4, there is a new utility known as .mx-auto. You just need to specify the width of the centered element.

Ref: http://v4-alpha.getbootstrap.com/utilities/spacing/#horizontal-centering

Diffferent from Bass Jobsen's answer, which is a relative center to the elements on both ends, the following example is absolute centered.

Here's the HTML:

<nav class="navbar bg-faded">
  <div class="container">
    <ul class="nav navbar-nav pull-sm-left">
      <li class="nav-item">
        <a class="nav-link" href="#">Link 1</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 2</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 3</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 4</a>
      </li>
    </ul>
    <ul class="nav navbar-nav navbar-logo mx-auto">
      <li class="nav-item">
        <a class="nav-link" href="#">Brand</a>
      </li>
    </ul>
    <ul class="nav navbar-nav pull-sm-right">
      <li class="nav-item">
        <a class="nav-link" href="#">Link 5</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 6</a>
      </li>
    </ul>
  </div>
</nav>

And CSS:

.navbar-logo {
  width: 90px;
}

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

Merging two images with PHP

Merger two image png and jpg/png [Image Masking]

//URL or Local path
$src_url = '1.png';
$dest_url = '2.jpg';
$src = imagecreatefrompng($src_url);
$dest1 = imagecreatefromjpeg($dest_url);

//if you want to make same size
list($width, $height) = getimagesize($dest_url);
list($newWidth, $newHeight) = getimagesize($src_url);
$dest = imagecreatetruecolor($newWidth, $newHeight);

imagecopyresampled($dest, $dest1, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

list($src_w, $src_h) = getimagesize($src_url);

//merger with same size
$this->imagecopymerge_alpha($dest, $src, 0, 0, 0, 0, $src_w, $src_h, 100);

//show output on browser
header('Content-Type: image/png');
imagejpeg($dest);

imagecopymerge_alpha

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct)
    {
        $cut = imagecreatetruecolor($src_w, $src_h);
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
    }

Objective-C ARC: strong vs retain and weak vs assign

As far as I know, strong and retain are synonyms, so they do exactly the same.

Then the weak is almost like assign, but automatically set to nil after the object, it is pointing to, is deallocated.

That means, you can simply replace them.

However, there is one special case I've encountered, where I had to use assign, rather than weak. Let's say we have two properties delegateAssign and delegateWeak. In both is stored our delegate, that is owning us by having the only strong reference. The delegate is deallocating, so our -dealloc method is called too.

// Our delegate is deallocating and there is no other strong ref.
- (void)dealloc {
    [delegateWeak doSomething];
    [delegateAssign doSomething];
}

The delegate is already in deallocation process, but still not fully deallocated. The problem is that weak references to him are already nullified! Property delegateWeak contains nil, but delegateAssign contains valid object (with all properties already released and nullified, but still valid).

// Our delegate is deallocating and there is no other strong ref.
- (void)dealloc {
    [delegateWeak doSomething]; // Does nothing, already nil.
    [delegateAssign doSomething]; // Successful call.
}

It is quite special case, but it reveal us how those weak variables work and when they are nullified.

UITableView load more when scrolling to bottom like Facebook application

For Xcode 10.1, Swift 4.2

This video seems like a great tutorial!

Starter/Complete project: https://github.com/RobCanton/Swift-Infinite-Scrolling-Example

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var tableView:UITableView!

    var fetchingMore = false
    var items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        initTableView()
    }

    func initTableView() {
        tableView = UITableView(frame: view.bounds, style: .plain)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "tableCell")
        tableView.delegate = self
        tableView.dataSource = self

        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false

        let layoutGuide = view.safeAreaLayoutGuide
        tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

        tableView.reloadData()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
            cell.textLabel?.text = "Item \(items[indexPath.row])"
            return cell
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y
        let contentHeight = scrollView.contentSize.height

        if offsetY > contentHeight - scrollView.frame.height * 4 {
            if !fetchingMore {
                beginBatchFetch()
            }
        }
    }

    func beginBatchFetch() {
        fetchingMore = true
        print("Call API here..")
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.50, execute: {
            print("Consider this as API response.")
            let newItems = (self.items.count...self.items.count + 12).map { index in index }
            self.items.append(contentsOf: newItems)
            self.fetchingMore = false
            self.tableView.reloadData()
        })
    }
}

What is object slicing?

Most answers here fail to explain what the actual problem with slicing is. They only explain the benign cases of slicing, not the treacherous ones. Assume, like the other answers, that you're dealing with two classes A and B, where B derives (publicly) from A.

In this situation, C++ lets you pass an instance of B to A's assignment operator (and also to the copy constructor). This works because an instance of B can be converted to a const A&, which is what assignment operators and copy-constructors expect their arguments to be.

The benign case

B b;
A a = b;

Nothing bad happens there - you asked for an instance of A which is a copy of B, and that's exactly what you get. Sure, a won't contain some of b's members, but how should it? It's an A, after all, not a B, so it hasn't even heard about these members, let alone would be able to store them.

The treacherous case

B b1;
B b2;
A& a_ref = b2;
a_ref = b1;
//b2 now contains a mixture of b1 and b2!

You might think that b2 will be a copy of b1 afterward. But, alas, it's not! If you inspect it, you'll discover that b2 is a Frankensteinian creature, made from some chunks of b1 (the chunks that B inherits from A), and some chunks of b2 (the chunks that only B contains). Ouch!

What happened? Well, C++ by default doesn't treat assignment operators as virtual. Thus, the line a_ref = b1 will call the assignment operator of A, not that of B. This is because, for non-virtual functions, the declared (formally: static) type (which is A&) determines which function is called, as opposed to the actual (formally: dynamic) type (which would be B, since a_ref references an instance of B). Now, A's assignment operator obviously knows only about the members declared in A, so it will copy only those, leaving the members added in B unchanged.

A solution

Assigning only to parts of an object usually makes little sense, yet C++, unfortunately, provides no built-in way to forbid this. You can, however, roll your own. The first step is making the assignment operator virtual. This will guarantee that it's always the actual type's assignment operator which is called, not the declared type's. The second step is to use dynamic_cast to verify that the assigned object has a compatible type. The third step is to do the actual assignment in a (protected!) member assign(), since B's assign() will probably want to use A's assign() to copy A's, members.

class A {
public:
  virtual A& operator= (const A& a) {
    assign(a);
    return *this;
  }

protected:
  void assign(const A& a) {
    // copy members of A from a to this
  }
};

class B : public A {
public:
  virtual B& operator= (const A& a) {
    if (const B* b = dynamic_cast<const B*>(&a))
      assign(*b);
    else
      throw bad_assignment();
    return *this;
  }

protected:
  void assign(const B& b) {
    A::assign(b); // Let A's assign() copy members of A from b to this
    // copy members of B from b to this
  }
};

Note that, for pure convenience, B's operator= covariantly overrides the return type, since it knows that it's returning an instance of B.

Get top first record from duplicate records having no unique identity

Find all products that has been ordered 1 or more times... (kind of duplicate records)

SELECT DISTINCT * from [order_items] where productid in 
(SELECT productid 
  FROM [order_items]
  group by productid 
  having COUNT(*)>0)
order by productid 

To select the last inserted of those...

SELECT DISTINCT productid, MAX(id) OVER (PARTITION BY productid) AS LastRowId from [order_items] where productid in 
(SELECT productid 
  FROM [order_items]
  group by productid 
  having COUNT(*)>0)
order by productid 

Using a custom typeface in Android

It may be useful to know that starting from Android 8.0 (API level 26) you can use a custom font in XML.

Simply put, you can do it in the following way.

  1. Put the font in the folder res/font.

  2. Either use it in the attribute of a widget

<Button android:fontFamily="@font/myfont"/>

or put it in res/values/styles.xml

<style name="MyButton" parent="android:Widget.Button">
    <item name="android:fontFamily">@font/myfont</item>
</style>

and use it as a style

<Button style="@style/MyButton"/>

Check whether specific radio button is checked

Just found a proper working solution for other guys,

_x000D_
_x000D_
// Returns true or false based on the radio button checked_x000D_
$('#test1').prop('checked')_x000D_
_x000D_
_x000D_
$('body').on('change','input[type="radio"]',function () {_x000D_
alert('Test1 checked = ' + $('#test1').prop('checked') + '. Test2 checked = ' + $('#test2').prop('checked') + '. Test3 checked = ' + $('#test3').prop('checked'));_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="radio" runat="server" name="testGroup" id="test1" /><label for="<%=test1.ClientID %>" style="cursor:hand" runat="server">Test1</label>_x000D_
_x000D_
<input type="radio" runat="server" name="testGroup" id="test2" /><label for="<%=test2.ClientID %>" style="cursor:hand" runat="server">Test2</label>_x000D_
_x000D_
<input type="radio" runat="server" name="testGroup" id="test3" /> <label for="<%=test3.ClientID %>" style="cursor:hand">Test3</label>
_x000D_
_x000D_
_x000D_

and in your method you can use like

return $('#test2').prop('checked');

Correctly ignore all files recursively under a specific folder except for a specific file type

Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.

I have actually found the proper solution and posted it under almost the same question here. For more details head there.

Solution:

# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo

scale fit mobile web content using viewport meta tag

I had same problem as yours, but my concern was list view. When i try to scroll list view fixed header also scroll little bit. Problem was list view height smaller than viewport (browser) height. You just need to reduce your viewport height lower than content tag (list view within content tag) height. Here is my meta tag;

<meta name="viewport" content="width=device-width,height=90%,  user-scalable = no"> 

Hope this will help.Thnks.

ImportError: No module named pandas

It might be too late to answer this but I just had the problem and I kept installing and uninstalling, it turns out the the problem happens when you're installing pandas to a version of python and trying to run the program using another python version

So to start off, run:

which python
python --version
which pip

make sure both are aligned, most probably, python is 2.7 and pip is working on 3.x or pip is coming from anaconda's python version which is highly likely to be 3.x as well

Incase of python redirects to 2.7, and pip redirects to pip3, install pandas using pip install pandas and use python3 file_name.py to run the program.

How to correctly use the ASP.NET FileUpload control

Instead of instantiating the FileUpload in your code behind file, just declare it in your markup file (.aspx file):

<asp:FileUpload ID="fileUpload" runat="server" />

Then you will be able to access all of the properties of the control, such as HasFile.

Calling a rest api with username and password - how to

If the API says to use HTTP Basic authentication, then you need to add an Authorization header to your request. I'd alter your code to look like this:

    WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value&param2=value");
    req.Method = "GET";
    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
    //req.Credentials = new NetworkCredential("username", "password");
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

Replacing "username" and "password" with the correct values, of course.

Text not wrapping in p tag

EASY

p{
    word-wrap: break-word;
}

How to get a variable from a file to another file in Node.js

You need module.exports:

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

Or you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

If all you want out of the file is variableName then

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):

Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.

  • For Node v13.9.0 and beyond, experimental modules are enabled by default
  • For versions of Node less than version 13.9.0, use --experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Once you have it setup, you can use import and export.

Using the example above, there are two approaches you can take

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

Linux bash script to extract IP address

awk '/inet addr:/{gsub(/^.{5}/,"",$2); print $2}' file
192.168.1.103

What is the 'open' keyword in Swift?

open is a new access level in Swift 3, introduced with the implementation of

It is available with the Swift 3 snapshot from August 7, 2016, and with Xcode 8 beta 6.

In short:

  • An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
  • A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.

So open is what public used to be in previous Swift releases and the access of public has been restricted. Or, as Chris Lattner puts it in SE-0177: Allow distinguishing between public access and public overridability:

“open” is now simply “more public than public”, providing a very simple and clean model.

In your example, open var hashValue is a property which is accessible and can be overridden in NSObject subclasses.

For more examples and details, have a look at SE-0117.

How to pass argument to Makefile from command line?

Here is a generic working solution based on @Beta's

I'm using GNU Make 4.1 with SHELL=/bin/bash atop my Makefile, so YMMV!

This allows us to accept extra arguments (by doing nothing when we get a job that doesn't match, rather than throwing an error).

%:
    @:

And this is a macro which gets the args for us:

args = `arg="$(filter-out $@,$(MAKECMDGOALS))" && echo $${arg:-${1}}`

Here is a job which might call this one:

test:
    @echo $(call args,defaultstring)

The result would be:

$ make test
defaultstring
$ make test hi
hi

Note! You might be better off using a "Taskfile", which is a bash pattern that works similarly to make, only without the nuances of Maketools. See https://github.com/adriancooney/Taskfile

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

iptalbes tool relies on a kernel module interacting with netfilter to control network traffic.

This error happens while iptalbes cannot found that module in kernel, so iptables suggest you to upgrade it :)

Perhaps iptables or your kernel needs to be upgraded.

However in most cases it's just the module not added to kernel or being banned, try this command to check whether be banned:

cd /etc/modprobe.d/ && grep -nr iptable_nat

if the command shows any rule matched, such as blacklist iptable_nat or install iptable_nat /bin/true, delete it. Since iptalbes will cost some performance, it's not strange to ban it while not necessary.

If nothing found in blacklist, try add iptable-nat to the kernal manual:

modprobe iptable-nat

If all of above not works, you can consider really upgrade your kernal...

React: how to update state.item[1] in state using setState?

As none of the above options was ideal to me I ended up using map:

this.setState({items: this.state.items.map((item,idx)=> idx!==1 ?item :{...item,name:'new_name'}) })

How do I print the percent sign(%) in c

there's no explanation in this topic why to print a percentage sign one must type %% and not for example escape character with percentage - \%.

from comp.lang.c FAQ list · Question 12.6 :

The reason it's tricky to print % signs with printf is that % is essentially printf's escape character. Whenever printf sees a %, it expects it to be followed by a character telling it what to do next. The two-character sequence %% is defined to print a single %.

To understand why \% can't work, remember that the backslash \ is the compiler's escape character, and controls how the compiler interprets source code characters at compile time. In this case, however, we want to control how printf interprets its format string at run-time. As far as the compiler is concerned, the escape sequence \% is undefined, and probably results in a single % character. It would be unlikely for both the \ and the % to make it through to printf, even if printf were prepared to treat the \ specially.

so the reason why one must type printf("%%"); to print single % is that's what is defined in printf function. % is an escape character of printf's, and \ of compiler.

How to set DialogFragment's width and height?

I fixed it setting the root element layout parameters.

int width = activity.getResources().getDisplayMetrics().widthPixels;
int height = activity.getResources().getDisplayMetrics().heightPixels;
content.setLayoutParams(new LinearLayout.LayoutParams(width, height));

Android ListView with different layouts for each row

ListView was intended for simple use cases like the same static view for all row items.
Since you have to create ViewHolders and make significant use of getItemViewType(), and dynamically show different row item layout xml's, you should try doing that using the RecyclerView, which is available in Android API 22. It offers better support and structure for multiple view types.

Check out this tutorial on how to use the RecyclerView to do what you are looking for.

Android Studio Stuck at Gradle Download on create new project

Quick Fix: Just turn off your firewall, it seems that android studio wants to download something and because our firewall prevents it from downloading the file that it wants it becomes stuck.

Note: Turning your firewall off can lower your security, if you have time you can just allow android studio in your firewall. By doing this you can turn on your firewall while allowing android studio to download anything that it wants.

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

Is there a foreach loop in Go?

I have jus implement this library:https://github.com/jose78/go-collection. This is an example about how to use the Foreach loop:

package main

import (
    "fmt"

    col "github.com/jose78/go-collection/collections"
)

type user struct {
    name string
    age  int
    id   int
}

func main() {
    newList := col.ListType{user{"Alvaro", 6, 1}, user{"Sofia", 3, 2}}
    newList = append(newList, user{"Mon", 0, 3})

    newList.Foreach(simpleLoop)
    
    if err := newList.Foreach(simpleLoopWithError); err != nil{
        fmt.Printf("This error >>> %v <<< was produced", err )  
    }
}

var simpleLoop col.FnForeachList = func(mapper interface{}, index int) {
    fmt.Printf("%d.- item:%v\n", index, mapper)
}


var simpleLoopWithError col.FnForeachList = func(mapper interface{}, index int) {
    if index > 1{
        panic(fmt.Sprintf("Error produced with index == %d\n", index))
    }
    fmt.Printf("%d.- item:%v\n", index, mapper)
}

The result of this execution should be:

0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
2.- item:{Mon 0 3}
0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
Recovered in f Error produced with index == 2

ERROR: Error produced with index == 2
This error >>> Error produced with index == 2
 <<< was produced

Try this code in playGrounD

\r\n, \r and \n what is the difference between them?

  • \r = CR (Carriage Return) → Used as a new line character in Mac OS before X
  • \n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X
  • \r\n = CR + LF → Used as a new line character in Windows

git reset --hard HEAD leaves untracked files behind

The command you are looking for is git clean

How to hide .php extension in .htaccess

The other option for using PHP scripts sans extension is

Options +MultiViews

Or even just following in the directories .htaccess:

DefaultType application/x-httpd-php

The latter allows having all filenames without extension script being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).

Google map V3 Set Center to specific Marker

Once you have markers on the map, you can retrieve the Lat/Long coordinates through the API and use this to set the map's center. You'll first just need to determine which marker you wish to center on - I'll leave that up to you.

// "marker" refers to the Marker object you wish to center on

var latLng = marker.getPosition(); // returns LatLng object
map.setCenter(latLng); // setCenter takes a LatLng object

Info windows are separate objects which are typically bound to a marker, so to open the info window you might do something like this (however it will depend on your code):

var infoWindow = marker.infoWindow; // retrieve the InfoWindow object
infoWindow.open(map); // Trigger the "open()" method

Hope this helps.

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

Put in other words, this error is telling you that SQL Server does not know which B to select from the group.

Either you want to select one specific value (e.g. the MIN, SUM, or AVG) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B in the GROUP BY field list).


Consider the following data:

ID  A   B
1   1  13
1   1  79
1   2  13
1   2  13
1   2  42

The query

SELECT A, COUNT(B) AS T1 
FROM T2 
GROUP BY A

would return:

A  T1
1  2
2  3

which is all well and good.

However consider the following (illegal) query, which would produce this error:

SELECT A, COUNT(B) AS T1, B 
FROM T2 
GROUP BY A

And its returned data set illustrating the problem:

A  T1  B
1  2   13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...?
2  3   13? 42? ...?

However, the following two queries make this clear, and will not cause the error:

  1. Using an aggregate

    SELECT A, COUNT(B) AS T1, SUM(B) AS B
    FROM T2
    GROUP BY A
    

    would return:

    A  T1  B
    1  2   92
    2  3   68
    
  2. Adding the column to the GROUP BY list

    SELECT A, COUNT(B) AS T1, B
    FROM T2
    GROUP BY A, B
    

    would return:

    A  T1  B
    1  1   13
    1  1   79
    2  2   13
    2  1   42
    

In C#, what's the difference between \n and \r\n?

\n is Unix, \r is Mac, \r\n is Windows.

Sometimes it's giving trouble especially when running code cross platform. You can bypass this by using Environment.NewLine.

Please refer to What is the difference between \r, \n and \r\n ?! for more information. Happy reading

C++ Array of pointers: delete or delete []?

The second one is correct under the circumstances (well, the least wrong, anyway).

Edit: "least wrong", as in the original code shows no good reason to be using new or delete in the first place, so you should probably just use:

std::vector<Monster> monsters;

The result will be simpler code and cleaner separation of responsibilities.

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I tried above answers and they didn't help in my case.

I solved it with this link help: http://vjscrazzy.blogspot.co.il/2016/02/failed-to-sync-gradle-project.html

step 1) file>Setttings>appearance and behaviour> system setttings>HTTP proxy> set No Proxy

step 2) build,execution and deployment> Build tools > gradle> now under project level settings > select local gradle distribution> gradle home = F:/Program Files/Android/Android Studio/gradle/gradle-2.4

After that, I did these changes(because it still wrote me some other errors)

Android Studio asked me:

  1. Android Studio asked me to update my Gradle version (which he didn't before)

  2. Enable - Tools> Android> Enable ADB integration.

Also, if your working in a team with repositories, it's important to check that the version of the Andorid Studio is the same.

File Upload ASP.NET MVC 3.0

Html:

@using (Html.BeginForm("StoreMyCompany", "MyCompany", FormMethod.Post, new { id = "formMyCompany", enctype = "multipart/form-data" }))
{
   <div class="form-group">
      @Html.LabelFor(model => model.modelMyCompany.Logo, htmlAttributes: new { @class = "control-label col-md-3" })
      <div class="col-md-6">
        <input type="file" name="Logo" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" />
      </div>
    </div>

    <br />
    <div class="form-group">
          <div class="col-md-offset-3 col-md-6">
              <input type="submit" value="Save" class="btn btn-success" />
          </div>
     </div>
}  

Code Behind:

public ActionResult StoreMyCompany([Bind(Exclude = "Logo")]MyCompanyVM model)
{
    try
    {        
        byte[] imageData = null;
        if (Request.Files.Count > 0)
        {
            HttpPostedFileBase objFiles = Request.Files["Logo"];

            using (var binaryReader = new BinaryReader(objFiles.InputStream))
            {
                imageData = binaryReader.ReadBytes(objFiles.ContentLength);
            }
        }

        if (imageData != null && imageData.Length > 0)
        {
           //Your code
        }

        dbo.SaveChanges();

        return RedirectToAction("MyCompany", "Home");

    }
    catch (Exception ex)
    {
        Utility.LogError(ex);
    }

    return View();
}

Custom events in jQuery?

I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):

 $("p").bind("myCustomEvent", function(e, myName, myValue){
      $(this).text(myName + ", hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent", [ "John" ]);
    });

How to set a value of a variable inside a template code?

Perhaps the default template filter wasn't an option back in 2009...

<html>
<div>Hello {{name|default:"World"}}!</div>
</html>

When to use throws in a Java method declaration?

In the example you gave, the method will never throw an IOException, therefore the declaration is wrong (but valid). My guess is that the original method threw the IOException, but it was then updated to handle the exception within but the declaration was not changed.

Better way to find last used row

I use the following function extensively. As pointed out above, using other methods can sometimes give inaccurate results due to used range updates, gaps in the data, or different columns having different row counts.

Example of use:

lastRow=FindRange("Sheet1","A1:A1000")

would return the last occupied row number of the entire range. You can specify any range you want from single columns to random rows, eg FindRange("Sheet1","A100:A150")

Public Function FindRange(inSheet As String, inRange As String) As Long
    Set fr = ThisWorkbook.Sheets(inSheet).Range(inRange).find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
    If Not fr Is Nothing Then FindRange = fr.row Else FindRange = 0
End Function

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

The regex you're looking for is ^[A-Za-z.\s_-]+$

  • ^ asserts that the regular expression must match at the beginning of the subject
  • [] is a character class - any character that matches inside this expression is allowed
  • A-Z allows a range of uppercase characters
  • a-z allows a range of lowercase characters
  • . matches a period rather than a range of characters
  • \s matches whitespace (spaces and tabs)
  • _ matches an underscore
  • - matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-) instead and put it anywhere in the character class, but that's less clear
  • + asserts that the preceding expression (in our case, the character class) must match one or more times
  • $ Finally, this asserts that we're now at the end of the subject

When you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.

Use CSS to automatically add 'required field' asterisk to form inputs

What you need is :required selector - it will select all fields with 'required' attribute (so no need to add any additional classes). Then - style inputs according to your needs. You can use ':after' selector and add asterisk in the way suggested among other answers

proper way to sudo over ssh

I was able to fully automate it with the following command:

echo pass | ssh -tt user@server "sudo script"

Advantages:

  • no password prompt
  • won't show password in remote machine bash history

Regarding security: as Kurt said, running this command will show your password on your local bash history, and it's better to save the password in a different file or save the all command in a .sh file and execute it. NOTE: The file need to have the correct permissions so that only the allowed users can access it.

C# - insert values from file into two arrays

string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>();  foreach (var line in lines) {     string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);     list1.Add(values[0]);     list2.Add(values[1]);  } 

Can a java file have more than one class?

Yes You can have more than one Class in one .Java file . But You have make one of them Public . and save .java file with same name as name of public class. when you will compile that .java file than you will get Separate .class files for each class defined in .java file .

Apart from this there are too many method for defining more than one class in one .java file .

  1. use concept of Inner Classes.
  2. Use Concept of Anonymous Classes .

Jquery - animate height toggle

Worked for me:

$(".filter-mobile").click(function() {
   if ($("#menuProdutos").height() > 0) {
      $("#menuProdutos").animate({
         height: 0
      }, 200);
   } else {
      $("#menuProdutos").animate({
         height: 500
      }, 200);
   }
});

How to convert a negative number to positive?

simply multiplying by -1 works in both ways ...

>>> -10 * -1
10
>>> 10 * -1
-10

Getting list of items inside div using Selenium Webdriver

I'm not sure if your findElements statement gets you all the divs. I would try the following:

List<WebElement> elementsRoot = driver.findElements(By.xpath("//div[@class=\"facetContainerDiv\"]/div));

for(int i = 0; i < elementsRoot.size(); ++i) {
     WebElement checkbox = elementsRoot.get(i).findElement(By.xpath("./label/input"));
     checkbox.click();
     blah blah blah
}

The idea here is that you get the root element then use another a 'sub' xpath or any selector you like to find the node element. Of course the xpath or selector may need to be adjusted to properly find the element you want.

How to group dataframe rows into list in pandas groupby

As you were saying the groupby method of a pd.DataFrame object can do the job.

Example

 L = ['A','A','B','B','B','C']
 N = [1,2,5,5,4,6]

 import pandas as pd
 df = pd.DataFrame(zip(L,N),columns = list('LN'))


 groups = df.groupby(df.L)

 groups.groups
      {'A': [0, 1], 'B': [2, 3, 4], 'C': [5]}

which gives and index-wise description of the groups.

To get elements of single groups, you can do, for instance

 groups.get_group('A')

     L  N
  0  A  1
  1  A  2

  groups.get_group('B')

     L  N
  2  B  5
  3  B  5
  4  B  4

clear javascript console in Google Chrome

On the Mac you can also use ?+K just like in Terminal.

Where does git config --global get written to?

I am using SmartGit with msysgit on Windows 8.1 and noticed that there can be three different locations for the gitconfig file:

%USERPROFILE%\.gitconfig
C:\Program Files (x86)\Git\etc\gitconfig
C:\Program Files (x86)\SmartGitHg\git\etc\gitconfig

But the one that is used is the one from %USERPROFILE%\.gitconfig.

Combine or merge JSON on node.js without jQuery

Let object1 and object2 be two JSON object.

var object1 = [{"name": "John"}];
var object2 = [{"location": "San Jose"}];

object1.push(object2);

This will simply append object2 in object1:

[{"name":"John"},{"location":"San Jose"}]

How To: Execute command line in C#, get STD OUT results

In case you also need to execute some command in the cmd.exe, you can do the following:

// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C vol";
p.Start();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);

This returns just the output of the command itself:

enter image description here

You can also use StandardInput instead of StartInfo.Arguments:

// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.Start();
// Read the output stream first and then wait.
p.StandardInput.WriteLine("vol");
p.StandardInput.WriteLine("exit");
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);

The result looks like this:

enter image description here

How to copy a file to a remote server in Python using SCP or SSH?

You can call the scp bash command (it copies files over SSH) with subprocess.run:

import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "[email protected]:/path/to/foo.bar"])

If you're creating the file that you want to send in the same Python program, you'll want to call subprocess.run command outside the with block you're using to open the file (or call .close() on the file first if you're not using a with block), so you know it's flushed to disk from Python.

You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password).

How to fix error Base table or view not found: 1146 Table laravel relationship table?

You should change/add in your PostController: (and change PostsController to PostController)

public function create()
{
    $categories = Category::all();
    return view('create',compact('categories'));
}

public function store(Request $request)
{
    $post = new Posts;
    $post->title = $request->get('title'); // CHANGE THIS
    $post->body = $request->get('body'); // CHANGE THIS
    $post->save(); // ADD THIS
    $post->categories()->attach($request->get('categories_id')); // CHANGE THIS

    return redirect()->route('posts.index'); // PS ON THIS ONE
}

PS: using route() means you have named your route as such

Route::get('example', 'ExampleController@getExample')->name('getExample');

UPDATE

The comments above are also right, change your 'Posts' Model to 'Post'

Python/Json:Expecting property name enclosed in double quotes

I have run into this problem multiple times when the JSON has been edited by hand. If someone was to delete something from the file without noticing it can throw the same error.

For instance, If your JSON last "}" is missing it will throw the same error.

So If you edit you file by hand make sure you format it like it is expected by the JSON decoder, otherwise you will run into the same problem.

Hope this helps!

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

Typical mainframe flow...

Input Disk/Tape/User (runtime) --> Job Control Language (JCL) --> Output Disk/Tape/Screen/Printer
                                   |                          ^
                                   v                          |
                                   `--> COBOL Program --------' 

Typical Linux flow...

Input Disk/SSD/User (runtime) --> sh/bash/ksh/zsh/... ----------> Output Disk/SSD/Screen/Printer
                                   |                          ^
                                   v                          |
                                   `--> Python script --------'
                                   |                          ^
                                   v                          |
                                   `--> awk script -----------'
                                   |                          ^
                                   v                          |
                                   `--> sed script -----------'
                                   |                          ^
                                   v                          |
                                   `--> C/C++ program --------'
                                   |                          ^
                                   v                          |
                                   `--- Java program ---------'
                                   |                          ^
                                   v                          |
                                   :                          :

Shells are the glue of Linux

Linux shells like sh/ksh/bash/... provide input/output/flow-control designation facilities much like the old mainframe Job Control Language... but on steroids! They are Turing complete languages in their own right while being optimized to efficiently pass data and control to and from other executing processes written in any language the O/S supports.

Most Linux applications, regardless what language the bulk of the program is written in, depend on shell scripts and Bash has become the most common. Clicking an icon on the desktop usually runs a short Bash script. That script, either directly or indirectly, knows where all the files needed are and sets variables and command line parameters, finally calling the program. That's a shell's simplest use.

Linux as we know it however would hardly be Linux without the thousands of shell scripts that startup the system, respond to events, control execution priorities and compile, configure and run programs. Many of these are quite large and complex.

Shells provide an infrastructure that lets us use pre-built components that are linked together at run time rather than compile time. Those components are free-standing programs in their own right that can be used alone or in other combinations without recompiling. The syntax for calling them is indistinguishable from that of a Bash builtin command, and there are in fact numerous builtin commands for which there is also a stand-alone executable on the system, often having additional options.

There is no language-wide difference between Python and Bash in performance. It entirely depends on how each is coded and which external tools are called.

Any of the well known tools like awk, sed, grep, bc, dc, tr, etc. will leave doing those operations in either language in the dust. Bash then is preferred for anything without a graphical user interface since it is easier and more efficient to call and pass data back from a tool like those with Bash than Python.

Performance

It depends on which programs the Bash shell script calls and their suitability for the subtask they are given whether the overall throughput and/or responsiveness will be better or worse than the equivalent Python. To complicate matters Python, like most languages, can also call other executables, though it is more cumbersome and thus not as often used.

User Interface

One area where Python is the clear winner is user interface. That makes it an excellent language for building local or client-server applications as it natively supports GTK graphics and is far more intuitive than Bash.

Bash only understands text. Other tools must be called for a GUI and data passed back from them. A Python script is one option. Faster but less flexible options are the binaries like YAD, Zenity, and GTKDialog.

While shells like Bash work well with GUIs like Yad, GtkDialog (embedded XML-like interface to GTK+ functions), dialog, and xmessage, Python is much more capable and so better for complex GUI windows.

Summary

Building with shell scripts is like assembling a computer with off-the-shelf components the way desktop PCs are.

Building with Python, C++ or most any other language is more like building a computer by soldering the chips (libraries) and other electronic parts together the way smartphones are.

The best results are usually obtained by using a combination of languages where each can do what they do best. One developer calls this "polyglot programming".

How to sum all values in a column in Jaspersoft iReport Designer?

It is quite easy to solve your task. You should create and use a new variable for summing values of the "Doctor Payment" column.

In your case the variable can be declared like this:

<variable name="total" class="java.lang.Integer" calculation="Sum">
    <variableExpression><![CDATA[$F{payment}]]></variableExpression>
</variable>
  • the Calculation type is Sum;
  • the Reset type is Report;
  • the Variable expression is $F{payment}, where $F{payment} is the name of a field contains sum (Doctor Payment).

The working example.

CSV datasource:

doctor_id,payment
A1,123
B1,223
C2,234
D3,678
D1,343

The template:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport ...>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="doctor_id" class="java.lang.String"/>
    <field name="payment" class="java.lang.Integer"/>
    <variable name="total" class="java.lang.Integer" calculation="Sum">
        <variableExpression><![CDATA[$F{payment}]]></variableExpression>
    </variable>
    <columnHeader>
        <band height="20" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="10" isBold="true" isItalic="true"/>
                </textElement>
                <text><![CDATA[Doctor ID]]></text>
            </staticText>
            <staticText>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="10" isBold="true" isItalic="true"/>
                </textElement>
                <text><![CDATA[Doctor Payment]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{doctor_id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{payment}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <summary>
        <band height="20">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement>
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Total]]></text>
            </staticText>
            <textField>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement>
                    <font isBold="true" isItalic="true"/>
                </textElement>
                <textFieldExpression><![CDATA[$V{total}]]></textFieldExpression>
            </textField>
        </band>
    </summary>
</jasperReport>

The result will be:

Generated report via iReport's preview


You can find a lot of info in the JasperReports Ultimate Guide.

How are POST and GET variables handled in Python?

I know this is an old question. Yet it's surprising that no good answer was given.

First of all the question is completely valid without mentioning the framework. The CONTEXT is a PHP language equivalence. Although there are many ways to get the query string parameters in Python, the framework variables are just conveniently populated. In PHP, $_GET and $_POST are also convenience variables. They are parsed from QUERY_URI and php://input respectively.

In Python, these functions would be os.getenv('QUERY_STRING') and sys.stdin.read(). Remember to import os and sys modules.

We have to be careful with the word "CGI" here, especially when talking about two languages and their commonalities when interfacing with a web server. 1. CGI, as a protocol, defines the data transport mechanism in the HTTP protocol. 2. Python can be configured to run as a CGI-script in Apache. 3. The CGI module in Python offers some convenience functions.

Since the HTTP protocol is language-independent, and that Apache's CGI extension is also language-independent, getting the GET and POST parameters should bear only syntax differences across languages.

Here's the Python routine to populate a GET dictionary:

GET={}
args=os.getenv("QUERY_STRING").split('&')

for arg in args: 
    t=arg.split('=')
    if len(t)>1: k,v=arg.split('='); GET[k]=v

and for POST:

POST={}
args=sys.stdin.read().split('&')

for arg in args: 
    t=arg.split('=')
    if len(t)>1: k, v=arg.split('='); POST[k]=v

You can now access the fields as following:

print GET.get('user_id')
print POST.get('user_name')

I must also point out that the CGI module doesn't work well. Consider this HTTP request:

POST / test.py?user_id=6

user_name=Bob&age=30

Using CGI.FieldStorage().getvalue('user_id') will cause a null pointer exception because the module blindly checks the POST data, ignoring the fact that a POST request can carry GET parameters too.

Generating PDF files with JavaScript

I've just written a library called jsPDF which generates PDFs using Javascript alone. It's still very young, and I'll be adding features and bug fixes soon. Also got a few ideas for workarounds in browsers that do not support Data URIs. It's licensed under a liberal MIT license.

I came across this question before I started writing it and thought I'd come back and let you know :)

Generate PDFs in Javascript

Example create a "Hello World" PDF file.

_x000D_
_x000D_
// Default export is a4 paper, portrait, using milimeters for units_x000D_
var doc = new jsPDF()_x000D_
_x000D_
doc.text('Hello world!', 10, 10)_x000D_
doc.save('a4.pdf')
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>
_x000D_
_x000D_
_x000D_

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

Where it is documented:

From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

Class Dog
   has_many :tags
   belongs_to :person
end

Class Person
  has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

or even

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

substring of an entire column in pandas dataframe

case the column isn't string, use astype to convert:

df['col'] = df['col'].astype(str).str[:9]

Recursively list files in Java

I would go with something like:

public void list(File file) {
    System.out.println(file.getName());
    File[] children = file.listFiles();
    for (File child : children) {
        list(child);
    }
}

The System.out.println is just there to indicate to do something with the file. there is no need to differentiate between files and directories, since a normal file will simply have zero children.

Creating and Naming Worksheet in Excel VBA

Are you using an error handler? If you're ignoring errors and try to name a sheet the same as an existing sheet or a name with invalid characters, it could be just skipping over that line. See the CleanSheetName function here

http://www.dailydoseofexcel.com/archives/2005/01/04/naming-a-sheet-based-on-a-cell/

for a list of invalid characters that you may want to check for.

Update

Other things to try: Fully qualified references, throwing in a Doevents, code cleaning. This code qualifies your Sheets reference to ThisWorkbook (you can change it to ActiveWorkbook if that suits). It also adds a thousand DoEvents (stupid overkill, but if something's taking a while to get done, this will allow it to - you may only need one DoEvents if this actually fixes anything).

Dim WS As Worksheet
Dim i As Long

With ThisWorkbook
    Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With

For i = 1 To 1000
    DoEvents
Next i

WS.Name = txtSheetName.Value

Finally, whenever I have a goofy VBA problem that just doesn't make sense, I use Rob Bovey's CodeCleaner. It's an add-in that exports all of your modules to text files then re-imports them. You can do it manually too. This process cleans out any corrupted p-code that's hanging around.

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

PHP mPDF save file as PDF

The mPDF docs state that the first argument of Output() is the file path, second is the saving mode - you need to set it to 'F'.

$mpdf->Output('filename.pdf','F');

Can I target all <H> tags with a single selector?

You can also use PostCSS and the custom selectors plugin

@custom-selector :--headings h1, h2, h3, h4, h5, h6;

article :--headings {
  margin-top: 0;
}

Output:

article h1,
article h2,
article h3,
article h4,
article h5,
article h6 {
  margin-top: 0;
}

Typescript: difference between String and string

TypeScript: String vs string

Argument of type 'String' is not assignable to parameter of type 'string'.

'string' is a primitive, but 'String' is a wrapper object.

Prefer using 'string' when possible.

demo

String Object

// error
class SVGStorageUtils {
  store: object;
  constructor(store: object) {
    this.store = store;
  }
  setData(key: String = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  getData(key: String = ``) {
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
}

string primitive

// ok
class SVGStorageUtils {
  store: object;
  constructor(store: object) {
    this.store = store;
  }
  setData(key: string = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  getData(key: string = ``) {
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
}

enter image description here

Binding ng-model inside ng-repeat loop in AngularJS

<h4>Order List</h4>
<ul>
    <li ng-repeat="val in filter_option.order">
        <span>
            <input title="{{filter_option.order_name[$index]}}" type="radio" ng-model="filter_param.order_option" ng-value="'{{val}}'" />
            &nbsp;{{filter_option.order_name[$index]}}
        </span>
        <select title="" ng-model="filter_param[val]">
            <option value="asc">Asc</option>
            <option value="desc">Desc</option>
        </select>
    </li>
</ul>

How can I remove space (margin) above HTML header?

Try:

h1 {
    margin-top: 0;
}

You're seeing the effects of margin collapsing.

How can I run Tensorboard on a remote server?

--bind_all option is useful.

$ tensorboard --logdir runs --bind_all

The port will be automatically selected from 6006 incrementally.(6006, 6007, 6008... )

Ping with timestamp on Windows CLI

WindowsPowershell:

option 1

ping.exe -t COMPUTERNAME|Foreach{"{0} - {1}" -f (Get-Date),$_}

option 2

Test-Connection -Count 9999 -ComputerName COMPUTERNAME | Format-Table @{Name='TimeStamp';Expression={Get-Date}},Address,ProtocolAddress,ResponseTime

HTML: how to force links to open in a new tab, not new window

You can set IE to open links in new tab, just go to the settings menu.

Delete duplicate elements from an array

It's easier using Array.filter:

var unique = arr.filter(function(elem, index, self) {
    return index === self.indexOf(elem);
})

What characters are forbidden in Windows and Linux directory names?

Though the only illegal Unix chars might be / and NULL, although some consideration for command line interpretation should be included.

For example, while it might be legal to name a file 1>&2 or 2>&1 in Unix, file names such as this might be misinterpreted when used on a command line.

Similarly it might be possible to name a file $PATH, but when trying to access it from the command line, the shell will translate $PATH to its variable value.

Converting integer to string in Python

For someone who wants to convert int to string in specific digits, the below method is recommended.

month = "{0:04d}".format(localtime[1])

For more details, you can refer to Stack Overflow question Display number with leading zeros.

How to enable authentication on MongoDB through Docker?

@jbochniak: Thanks, although at first read I thought I've already discovered all of this, it turned out that your example (esp. the version of the Mongo Docker image) helped me out!

That version (v3.4.2) and the v3.4 (currently corresponding to v3.4.3) still support 'MONGO_INITDB_ROOT' specified through those variables, as of v3.5 (at least tags '3' and 'latest') DON'T work as described in your answer and in the docs.

I quickly had a look at the code on GitHub, but saw similar usage of these variables and couldn't find the bug immediately, should do so before filing this as a bug...

Webdriver findElements By xpath

Instead of

css=#container

use

css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)

Something better than .NET Reflector?

9Rays used to have a decompiler, but I haven't checked in a while. It was not free, I remember...

There is also a new one (at least for me) named Dis#.

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

Make sure you are sending the proper parameters too. This happened to me after switching to UI-Router.

To fix it, I changed $routeParams to use $stateParams in my controller. The main issue was that $stateParams was no longer sending a proper parameter to the resource.

Insert line break inside placeholder attribute of a textarea?

very simple

  var position = your break position;
    var breakLine = "&#13;&#10;";//in html 
    var output = [value.slice(0, position), breakLine, value.slice(position)].join('');
    return output;

value represent the original string

How to Implement DOM Data Binding in JavaScript

I have gone through some basic javascript example using onkeypress and onchange event handlers for making binding view to our js and js to view

Here example plunker http://plnkr.co/edit/7hSOIFRTvqLAvdZT4Bcc?p=preview

<!DOCTYPE html>
<html>
<body>

    <p>Two way binding data.</p>

    <p>Binding data from  view to JS</p>

    <input type="text" onkeypress="myFunction()" id="myinput">
    <p id="myid"></p>
    <p>Binding data from  js to view</p>
    <input type="text" id="myid2" onkeypress="myFunction1()" oninput="myFunction1()">
    <p id="myid3" onkeypress="myFunction1()" id="myinput" oninput="myFunction1()"></p>

    <script>

        document.getElementById('myid2').value="myvalue from script";
        document.getElementById('myid3').innerHTML="myvalue from script";
        function myFunction() {
            document.getElementById('myid').innerHTML=document.getElementById('myinput').value;
        }
        document.getElementById("myinput").onchange=function(){

            myFunction();

        }
        document.getElementById("myinput").oninput=function(){

            myFunction();

        }

        function myFunction1() {

            document.getElementById('myid3').innerHTML=document.getElementById('myid2').value;
        }
    </script>

</body>
</html>

Import and insert sql.gz file into database with putty

If the mysql dump was a .gz file, you need to gunzip to uncompress the file by typing $ gunzip mysqldump.sql.gz

This will uncompress the .gz file and will just store mysqldump.sql in the same location.

Type the following command to import sql data file:

$ mysql -u username -p -h localhost test-database < mysqldump.sql password: _

How to write to a file, using the logging Python module?

here's a simpler way to go about it. this solution doesn't use a config dictionary and uses a rotation file handler, like so:

import logging
from logging.handlers import RotatingFileHandler

logging.basicConfig(handlers=[RotatingFileHandler(filename=logpath+filename,
                     mode='w', maxBytes=512000, backupCount=4)], level=debug_level,
                     format='%(levelname)s %(asctime)s %(message)s', 
                    datefmt='%m/%d/%Y%I:%M:%S %p')

logger = logging.getLogger('my_logger')

or like so:

import logging
from logging.handlers import RotatingFileHandler

handlers = [
            RotatingFileHandler(filename=logpath+filename, mode='w', maxBytes=512000, 
                                backupCount=4)
           ]
logging.basicConfig(handlers=handlers, level=debug_level, 
                    format='%(levelname)s %(asctime)s %(message)s', 
                    datefmt='%m/%d/%Y%I:%M:%S %p')

logger = logging.getLogger('my_logger')

the handlers variable needs to be an iterable. logpath+filename and debug_level are just variables holding the respective info. of course, the values for the function params are up to you.

the first time i was using the logging module i made the mistake of writing the following, which generates an OS file lock error (the above is the solution to that):

import logging
from logging.handlers import RotatingFileHandler

logging.basicConfig(filename=logpath+filename, level=debug_level, format='%(levelname)s %(asctime)s %(message)s', datefmt='%m/%d/%Y
 %I:%M:%S %p')

logger = logging.getLogger('my_logger')
logger.addHandler(RotatingFileHandler(filename=logpath+filename, mode='w', 
                  maxBytes=512000, backupCount=4))

and Bob's your uncle!

How to generate a random number in C++?

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    srand(time(NULL));
    int random_number = std::rand(); // rand() return a number between ?0? and RAND_MAX
    std::cout << random_number;
    return 0;
}

http://en.cppreference.com/w/cpp/numeric/random/rand

Splitting on last delimiter in Python string?

I just did this for fun

    >>> s = 'a,b,c,d'
    >>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
    ['a,b,c', 'd']

Caution: Refer to the first comment in below where this answer can go wrong.

Hide axis and gridlines Highcharts

Just add

xAxis: {
   ...  
   lineWidth: 0,
   minorGridLineWidth: 0,
   lineColor: 'transparent',
   ...          
   labels: {
       enabled: false
   },
   minorTickLength: 0,
   tickLength: 0
}

to the xAxis definition.

Since Version 4.1.9 you can simply use the axis attribute visible:

xAxis: {
    visible: false,
}

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

Convert Python ElementTree to string

How do I convert ElementTree.Element to a String?

For Python 3:

xml_str = ElementTree.tostring(xml, encoding='unicode')

For Python 2:

xml_str = ElementTree.tostring(xml, encoding='utf-8')

The following is compatible with both Python 2 & 3, but only works for Latin characters:

xml_str = ElementTree.tostring(xml).decode()

Example usage

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
xml_str = ElementTree.tostring(xml).decode()
print(xml_str)

Output:

<Person Name="John" />

Explanation

Despite what the name implies, ElementTree.tostring() returns a bytestring by default in Python 2 & 3. This is an issue in Python 3, which uses Unicode for strings.

In Python 2 you could use the str type for both text and binary data. Unfortunately this confluence of two different concepts could lead to brittle code which sometimes worked for either kind of data, sometimes not. [...]

To make the distinction between text and binary data clearer and more pronounced, [Python 3] made text and binary data distinct types that cannot blindly be mixed together.

Source: Porting Python 2 Code to Python 3

If we know what version of Python is being used, we can specify the encoding as unicode or utf-8. Otherwise, if we need compatibility with both Python 2 & 3, we can use decode() to convert into the correct type.

For reference, I've included a comparison of .tostring() results between Python 2 and Python 3.

ElementTree.tostring(xml)
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml, encoding='unicode')
# Python 3: <Person Name="John" />
# Python 2: LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3: <Person Name="John" />
# Python 2: <Person Name="John" />

Thanks to Martijn Peters for pointing out that the str datatype changed between Python 2 and 3.


Why not use str()?

In most scenarios, using str() would be the "cannonical" way to convert an object to a string. Unfortunately, using this with Element returns the object's location in memory as a hexstring, rather than a string representation of the object's data.

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
print(str(xml))  # <Element 'Person' at 0x00497A80>

Convert JSON String To C# Object

As tripletdad99 said

var result = JsonConvert.DeserializeObject<T>(json);

but if you don't want to create an extra object you can make it with Dictionary instead

var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(json_serializer);

Git stash pop- needs merge, unable to refresh index

You need to add app.coffee to staging.

Do git add app.coffee and then you will be able to apply your stash (after that commit and push).

Windows Application has stopped working :: Event Name CLR20r3

Download and install SAP Crystal Reports Runtime engine for .net (32 bit or 64 bit) depending on your os version. Should work there after

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

You should install the graphviz package in your system (not just the python package). On Ubuntu you should try:

sudo apt-get install graphviz

Exclude Blank and NA in R

Don't know exactly what kind of dataset you have, so I provide general answer.

x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
   x  y
1  1  1
2  2  2
3 NA  3
4  3 NA
5  4  6
6  5  8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
  x y
1 1 1
2 2 2
5 4 6
6 5 8

Adding Http Headers to HttpClient

Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri("http://www.someURI.com"),
    Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

Convert a Python list with strings all to lowercase or uppercase

Python3.6.8

In [1]: a = 'which option is the fastest'                                                                                                                                           

In [2]: %%timeit 
   ...: ''.join(a).upper() 
762 ns ± 11.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [3]: %%timeit  
   ...: map(lambda x:x.upper(), a) 
209 ns ± 5.73 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [4]: %%timeit  
   ...: map(str.upper, [i for i in a]) 
1.18 µs ± 11.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [5]: %%timeit 
   ...: [i.upper() for i in a] 
3.2 µs ± 64.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

If you need a string or list as the output and not an iterator (this is for Python3), compare ''.join(string).upper() option to this:

In [10]: %%timeit  
    ...: [i for i in map(lambda x:x.upper(), a)] 
4.32 µs ± 112 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Create a new workspace in Eclipse

You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.

You can then import project to your workspace, copy paste project to your new workspace folder, then

File?Import?Existing project in to workspace?select project.

Assign output of a program to a variable using a MS batch file

As an addition to this previous answer, pipes can be used inside a for statement, escaped by a caret symbol:

    for /f "tokens=*" %%i in ('tasklist ^| grep "explorer"') do set VAR=%%i

Is having an 'OR' in an INNER JOIN condition a bad idea?

You can use UNION ALL instead.

SELECT mt.ID, mt.ParentID, ot.MasterID FROM dbo.MainTable AS mt Union ALL SELECT mt.ID, mt.ParentID, ot.MasterID FROM dbo.OtherTable AS ot

C/C++ line number

Use __LINE__ (that's double-underscore LINE double-underscore), the preprocessor will replace it with the line number on which it is encountered.

How to remove gaps between subplots in matplotlib?

The problem is the use of aspect='equal', which prevents the subplots from stretching to an arbitrary aspect ratio and filling up all the empty space.

Normally, this would work:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])

plt.subplots_adjust(wspace=0, hspace=0)

The result is this:

However, with aspect='equal', as in the following code:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])
    a.set_aspect('equal')

plt.subplots_adjust(wspace=0, hspace=0)

This is what we get:

The difference in this second case is that you've forced the x- and y-axes to have the same number of units/pixel. Since the axes go from 0 to 1 by default (i.e., before you plot anything), using aspect='equal' forces each axis to be a square. Since the figure is not a square, pyplot adds in extra spacing between the axes horizontally.

To get around this problem, you can set your figure to have the correct aspect ratio. We're going to use the object-oriented pyplot interface here, which I consider to be superior in general:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,8)) # Notice the equal aspect ratio
ax = [fig.add_subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])
    a.set_aspect('equal')

fig.subplots_adjust(wspace=0, hspace=0)

Here's the result:

select unique rows based on single distinct column

I'm assuming you mean that you don't care which row is used to obtain the title, id, and commentname values (you have "rob" for all of the rows, but I don't know if that is actually something that would be enforced or not in your data model). If so, then you can use windowing functions to return the first row for a given email address:

select
    id,
    title,
    email,
    commentname

from
(
select 
    *, 
    row_number() over (partition by email order by id) as RowNbr 

from YourTable
) source

where RowNbr = 1

Javascript Click on Element by Class

If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).

var divs = document.querySelectorAll('.love-button.love-button--loved'); 

for (i = 0; i < divs.length; ++i) {
  divs[i].click();
};

With ES6 and Babel (cannot be run in the browser console directly)

[...document.querySelectorAll('.love-button.love-button--loved')]
   .forEach(div => { div.click(); })

How to revert a "git rm -r ."?

If you end up with none of the above working, you might be able to retrieve data using the suggestion from here: http://www.spinics.net/lists/git/msg62499.html

git prune -n
git cat-file -p <blob #>

Android selector & text color

Here is the example of selector. If you use eclipse , it does not suggest something when you click ctrl and space both :/ you must type it.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_default_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/btn_default_selected"
    android:state_focused="true"
    android:state_enabled="true"
    android:state_window_focused="true"  />
<item android:drawable="@drawable/btn_default_normal" />

You can look at for reference;

http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

What is the default maximum heap size for Sun's JVM from Java SE 6?

one way is if you have a jdk installed , in bin folder there is a utility called jconsole(even visualvm can be used). Launch it and connect to the relevant java process and you can see what are the heap size settings set and many other details

When running headless or cli only, jConsole can be used over lan, if you specify a port to connect on when starting the service in question.

How to define custom sort function in javascript?

For Objects try this:

function sortBy(field) {
  return function(a, b) {
    if (a[field] > b[field]) {
      return -1;
    } else if (a[field] < b[field]) {
      return 1;
    }
    return 0;
  };
}

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

building on these answers - i also had to modify an X86 reference under Librarian -> Command Line -> Additional Options (for the x64 Platform)

How do I check if a string is a number (float)?

In a most general case for a float, one would like to take care of integers and decimals. Let's take the string "1.1" as an example.

I would try one of the following:

1.> isnumeric()

word = "1.1"

"".join(word.split(".")).isnumeric()
>>> True

2.> isdigit()

word = "1.1"

"".join(word.split(".")).isdigit()
>>> True

3.> isdecimal()

word = "1.1"

"".join(word.split(".")).isdecimal()
>>> True

Speed:

? All the aforementioned methods have similar speeds.

%timeit "".join(word.split(".")).isnumeric()
>>> 257 ns ± 12 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit "".join(word.split(".")).isdigit()
>>> 252 ns ± 11 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit "".join(word.split(".")).isdecimal()
>>> 244 ns ± 7.17 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

How can I wait for 10 second without locking application UI in android

do this on a new thread (seperate it from main thread)

 new Thread(new Runnable() {
     @Override
     public void run() {
        // TODO Auto-generated method stub
     }
}).run();

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

std::string length() and size() member functions

As per the documentation, these are just synonyms. size() is there to be consistent with other STL containers (like vector, map, etc.) and length() is to be consistent with most peoples' intuitive notion of character strings. People usually talk about a word, sentence or paragraph's length, not its size, so length() is there to make things more readable.

Having trouble setting working directory

This may help... use the following code and browse the folder you want to set as the working folder

setwd(choose.dir())

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

I ran into this issue when I use djangocms and added a plugin (in my case: djangocms-cascade). Of course I had to add the plugin to the INSTALLED_APPS. But the order is here important.

To place 'cmsplugin_cascade' before 'cms' solved the issue.

Remove non-numeric characters (except periods and commas) from a string

You could use filter_var to remove all illegal characters except digits, dot and the comma.

  • The FILTER_SANITIZE_NUMBER_FLOAT filter is used to remove all non-numeric character from the string.
  • FILTER_FLAG_ALLOW_FRACTION is allowing fraction separator " . "
  • The purpose of FILTER_FLAG_ALLOW_THOUSAND to get comma from the string.

Code

$var1 = '12.322,11T';

echo filter_var($var1, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);

Output

12.322,11

To read more about filter_var() and Sanitize filters

How to find all trigger associated with a table with SQL Server?

You Can View All trigger related to your database by below query

select * from sys.triggers

And for open trigger you can use below syntax

sp_helptext 'dbo.trg_InsertIntoUserTable'

How to programmatically set drawableLeft on Android button?

Following is the way to change the color of the left icon in edit text and set it in left side.

 Drawable img = getResources().getDrawable( R.drawable.user );
img.setBounds( 0, 0, 60, 60 );
mNameEditText.setCompoundDrawables(img,null, null, null);

int color = ContextCompat.getColor(this, R.color.blackColor);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    DrawableCompat.setTint(img, color);

} else {
    img.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

You can simply add an inspect() method to your object which will override the representation of object in console.log messages

eg:

var myObject = {
   "a":"a",
   "b":{
      "c":"c",
      "d":{
         "e":"e",
         "f":{
            "g":"g",
            "h":{
               "i":"i"
            }
         }
      }
   }
};
myObject.inspect = function(){ return JSON.stringify( this, null, ' ' ); }

then, your object will be represented as required in both console.log and node shell


Update:

object.inspect has been deprecated ( https://github.com/nodejs/node/issues/15549). Use myObject[util.inspect.custom] instead:

const util = require('util')

var myObject = {
  /* nested properties not shown */
}

myObject[util.inspect.custom] = function(){ return JSON.stringify( this, null, 4 ); }


console.log(util.inspect(myObject))

Generate MD5 hash string with T-SQL

You didn't explicitly say you wanted the string to be hex; if you are open to the more space efficient base 64 string encoding, and you are using SQL Server 2016 or later, here's an alternative:

select SubString(h, 1, 32) from OpenJson(
    (select HashBytes('MD5', '[email protected]') h for json path)
) with (h nvarchar(max));

This produces:

9TvQiSDl0lgJ3yVj75xStg==

What is a Data Transfer Object (DTO)?

  1. To me the best answer to the question what is a DTO is that DTO's are simple objects that should not contain any business logic or methods implementation that would require testing.
  2. Normally your model (using the MVC pattern) are intelligent models, and they can contain a lot of/some methods that do some different operations for that model specifically (not business logic, this should be at the controllers). However, when you transfer data (eg. calling a REST (GET/POST/whatever) endpoint from somewhere, or consuming a webservice using SOA, etc...) you do not want to transmit the big sized object with code that is not necessary for the endpoint, will consume data, and slow down the transfer.