Programs & Examples On #Django ajax selects

django-ajax-selects is a module for Django which enables editing of ForeignKey, ManyToMany and CharField using jQuery UI Autocomplete.

How to display raw JSON data on a HTML page

I think all you need to display the data on an HTML page is JSON.stringify.

For example, if your JSON is stored like this:

var jsonVar = {
        text: "example",
        number: 1
    };

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

Of course you will probably want to replace body with some other element via getElementById.

As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.

var jsonVar = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonStr = JSON.stringify(jsonVar),  // THE OBJECT STRINGIFIED
    regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
    f = {
            brace: 0
        }; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
           // IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)

regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
        return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    rtnStr = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        rtnStr = rtnFn();
        f['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         f['brace'] -= 1;
        rtnStr = rtnFn();
    } else {
        rtnStr = rtnFn();
    }
    return rtnStr;
});

document.body.innerHTML += regeStr; // appends the result to the body of the HTML document

This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

How do I update a Mongo document after inserting it?

I will use collection.save(the_changed_dict) this way. I've just tested this, and it still works for me. The following is quoted directly from pymongo doc.:

save(to_save[, manipulate=True[, safe=False[, **kwargs]]])

Save a document in this collection.

If to_save already has an "_id" then an update() (upsert) operation is performed and any existing document with that "_id" is overwritten. Otherwise an insert() operation is performed. In this case if manipulate is True an "_id" will be added to to_save and this method returns the "_id" of the saved document. If manipulate is False the "_id" will be added by the server but this method will return None.

Rewrite left outer join involving multiple tables from Informix to Oracle

Write one table per join, like this:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
  left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk

Note that while my query contains actual left join, your query apparently doesn't. Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).

The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.

In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.

So look what happens when you move conditions to the where clause:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx
  left join table4 tab4 on tab4.xya = tab3.xya
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
  tab3.desc = "XYZ" and
  tab4.ss = tab3.ss

Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.

PS: left join and left outer join are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join to make not the left, but the right table the leading table. And there is and even full [outer] join to return a row if there is data in either table.

What is the correct way to declare a boolean variable in Java?

First of all, you should use none of them. You are using wrapper type, which should rarely be used in case you have a primitive type. So, you should use boolean rather.

Further, we initialize the boolean variable to false to hold an initial default value which is false. In case you have declared it as instance variable, it will automatically be initialized to false.

But, its completely upto you, whether you assign a default value or not. I rather prefer to initialize them at the time of declaration.

But if you are immediately assigning to your variable, then you can directly assign a value to it, without having to define a default value.

So, in your case I would use it like this: -

boolean isMatch = email1.equals (email2);

How to sparsely checkout only one single file from a git repository?

Originally, I mentioned in 2012 git archive (see Jared Forsyth's answer and Robert Knight's answer), since git1.7.9.5 (March 2012), Paul Brannan's answer:

git archive --format=tar --remote=origin HEAD:path/to/directory -- filename | tar -O -xf -

But: in 2013, that was no longer possible for remote https://github.com URLs.
See the old page "Can I archive a repository?"

The current (2018) page "About archiving content and data on GitHub" recommends using third-party services like GHTorrent or GH Archive.


So you can also deal with local copies/clone:

You could alternatively do the following if you have a local copy of the bare repository as mentioned in this answer,

git --no-pager --git-dir /path/to/bar/repo.git show branch:path/to/file >file

Or you must clone first the repo, meaning you get the full history: - in the .git repo - in the working tree.

  • But then you can do a sparse checkout (if you are using Git1.7+),:
    • enable the sparse checkout option (git config core.sparsecheckout true)
    • adding what you want to see in the .git/info/sparse-checkout file
    • re-reading the working tree to only display what you need

To re-read the working tree:

$ git read-tree -m -u HEAD

That way, you end up with a working tree including precisely what you want (even if it is only one file)


Richard Gomes points (in the comments) to "How do I clone, fetch or sparse checkout a single directory or a list of directories from git repository?"

A bash function which avoids downloading the history, which retrieves a single branch and which retrieves a list of files or directories you need.

How to convert a char array back to a string?

Try this

Arrays.toString(array)

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

While this question has been answered already (it's a bug that causes bottomLeftRadius and bottomRightRadius to be reversed), the bug has been fixed in android 3.1 (api level 12 - tested on the emulator).

So to make sure your drawables look correct on all platforms, you should put "corrected" versions of the drawables (i.e. where bottom left/right radii are actually correct in the xml) in the res/drawable-v12 folder of your app. This way all devices using an android version >= 12 will use the correct drawable files, while devices using older versions of android will use the "workaround" drawables that are located in the res/drawables folder.

Why functional languages?

Functional Programming will likely be a tool that is used by Engineers, Scientists to solve the problems that they are facing. It isn't going to take the world like earlier langages. However, the hard product to beat is Excel, if I am an engineer and need to do calculations, Excel is awesome.

However, F# is going to be another source and will likely fill design needs by the non-Computer Scientists. Let's face it, Computer Scientists have done a great job of creating a WHOLE new way of doing things. Object Oriented Programming is GREAT. But sometimes you just need a way to solve an equation, get a solution and graph it. That's it. Then a language like F# fills the bill. Or maybe you want to build a finite state machine, F# again could be one of the solutions, but then C could be a solution as well.

But when it comes to parallel processing, Excel shines and in time F# will be there as well. In a friendly manner though, F#= friendly.

Beginner question: returning a boolean value from a function in Python

Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

def rps():
    # Code to determine if player wins
    if player_wins:
        return True

    return False

Then, just assign a value to the variable outside this function like so:

player_wins = rps()

It will be assigned the return value (either True or False) of the function you just called.


After the comments, I decided to add that idiomatically, this would be better expressed thus:

 def rps(): 
     # Code to determine if player wins, assigning a boolean value (True or False)
     # to the variable player_wins.

     return player_wins

 pw = rps()

This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

How to pass a callback as a parameter into another function

Also, could be simple as:

if( typeof foo == "function" )
    foo();

Counting array elements in Python

The method len() returns the number of elements in the list.

Syntax:

len(myArray)

Eg:

myArray = [1, 2, 3]
len(myArray)

Output:

3

Error message Strict standards: Non-static method should not be called statically in php

Instead of using the instance with the scope resolution operator :: because it wasn't defined like static function.

$r=Page::getInstanceByName($page);

change it to :

$r=Page->getInstanceByName($page);

And it will work like a charm.

How can I do SELECT UNIQUE with LINQ?

Using query comprehension syntax you could achieve the orderby as follows:

var uniqueColors = (from dbo in database.MainTable
                    where dbo.Property
                    orderby dbo.Color.Name ascending
                    select dbo.Color.Name).Distinct();

Mime type for WOFF fonts?

WOFF:

  1. Web Open Font Format
  2. It can be compiled with either TrueType or PostScript (CFF) outlines
  3. It is currently supported by FireFox 3.6+

Try to add that:

AddType application/vnd.ms-fontobject .eot
AddType application/octet-stream .otf .ttf

How to compile multiple java source files in command line

Here is another example, for compiling a java file in a nested directory.

I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.

Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'

% mkdir -p temp/classes
% curl --get \
    http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
        --output commons-collections-3.2.2.jar

% javac -g -classpath commons-collections-3.2.2.jar \
     -sourcepath src/main/java -d temp/classes \
      src/main/java/org/gradle/Person.java 

% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
   0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
  69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class

Get text of label with jquery

Try:

<%=this.Label1.Text%>

How to extract year and month from date in PostgreSQL without using to_char() function?

date_part(text, timestamp)

e.g.

date_part('month', timestamp '2001-02-16 20:38:40'),
date_part('year', timestamp '2001-02-16 20:38:40') 

http://www.postgresql.org/docs/8.0/interactive/functions-datetime.html

"Failed to install the following Android SDK packages as some licences have not been accepted" error

in Windows OS go to your sdkmanager path directory in cmd

You can find your sdkmanager in C:\Users\USER\AppData\Local\Android\Sdk\tools\bin

then execute the followwing command:

sdkmanager --licenses

after that it will ask to accept license agreement several times then accept all by just typing y on cmd

Invalid syntax when using "print"?

You need parentheses:

print(2**100)

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

Getting a count of objects in a queryset in django

Use related name to count votes for a specific contest

class Item(models.Model):
    name = models.CharField()

class Contest(models.Model);
    name = models.CharField()

class Votes(models.Model):
    user = models.ForeignKey(User)
    item = models.ForeignKey(Item)
    contest = models.ForeignKey(Contest, related_name="contest_votes")
    comment = models.TextField()

>>> comments = Contest.objects.get(id=contest_id).contest_votes.count()

How can I export tables to Excel from a webpage

A long time ago, I discovered that Excel would open an HTML file with a table if we send it with Excel content type. Consider the document above:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Java Friends</title>
</head>
<body>
  <table style="font-weight: bold">
    <tr style="background-color:red"><td>a</td><td>b</td></tr>
    <tr><td>1</td><td>2</td></tr>
  </table>    
</body>
</html>

I ran the following bookmarklet on it:

javascript:window.open('data:application/vnd.ms-excel,'+document.documentElement.innerHTML);

and in fact I got it downloadable as a Excel file. However, I did not get the expected result - the file was open in OpenOffice.org Writer. That is my problem: I do not have Excel in this machine so I cannot try it better. Also, this trick worked more or less six years ago with older browsers and an antique version of MS Office, so I really cannot say if it will work today.

Anyway, in the document above I added a button which would download the entire document as an Excel file, in theory:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Java Friends</title>
</head>
<body>
  <table style="font-weight: bold">
    <tr style="background-color:red"><td>a</td><td>b</td></tr>
    <tr><td>1</td><td>2</td></tr>
    <tr>
      <td colspan="2">
        <button onclick="window.open('data:application/vnd.ms-excel,'+document.documentElement.innerHTML);">
            Get as Excel spreadsheet
        </button>
      </td>
    </tr>
  </table>    
</body>
</html>

Save it in a file and click on the button. I'd love to know if it worked or not, so I ask you to comment even for saying that it did not work.

How does the "final" keyword in Java work? (I can still modify an object.)

Worth to mention some straightforward definitions:

Classes/Methods

You can declare some or all of a class methods as final, in order to indicate that the method cannot be overridden by subclasses.

Variables

Once a final variable has been initialized, it always contains the same value.

final basically avoid overwrite/superscribe by anything (subclasses, variable "reassign"), depending on the case.

Simple calculations for working with lat/lon and km distance?

Interesting that I didn't see a mention of UTM coordinates.

https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system.

At least if you want to add km to the same zone, it should be straightforward (in Python : https://pypi.org/project/utm/ )

utm.from_latlon and utm.to_latlon.

Elegant way to report missing values in a data.frame

Just use sapply

> sapply(airquality, function(x) sum(is.na(x)))
  Ozone Solar.R    Wind    Temp   Month     Day 
     37       7       0       0       0       0

You could also use apply or colSums on the matrix created by is.na()

> apply(is.na(airquality),2,sum)
  Ozone Solar.R    Wind    Temp   Month     Day 
     37       7       0       0       0       0
> colSums(is.na(airquality))
  Ozone Solar.R    Wind    Temp   Month     Day 
     37       7       0       0       0       0 

HTML Display Current date

var currentDate  = new Date(),
    currentDay   = currentDate.getDate() < 10 
                 ? '0' + currentDate.getDate() 
                 : currentDate.getDate(),
    currentMonth = currentDate.getMonth() < 9 
                 ? '0' + (currentDate.getMonth() + 1) 
                 : (currentDate.getMonth() + 1);

document.getElementById("date").innerHTML = currentDay + '/' + currentMonth + '/' +  currentDate.getFullYear();

You can read more about Date object

PHP Notice: Undefined offset: 1 with array when reading data

In your code: $parts = array_map('trim', explode(':', $line_of_text, 2)); You have ":" as separator. If you use another separator in file, then you will get an "Undefined offset: 1" but not "Undefined offset: 0" All information will be in $parts[0] but no information in $parts[1] or [2] etc. Try to echo $part[0]; echo $part[1]; you will see the information.

count number of lines in terminal output

"abcd4yyyy" | grep 4 -c gives the count as 1

Delete files or folder recursively on Windows CMD

If you want to delete a specific extension recursively, use this:

For /R "C:\Users\Desktop\saleh" %G IN (*.ppt) do del "%G"

Postgresql 9.2 pg_dump version mismatch

If you're using Heroku's Postgres.app the pg_dump (along with all the other binaries) is in /Applications/Postgres.app/Contents/MacOS/bin/

so in that case it's

ln -s /Applications/Postgres.app/Contents/MacOS/bin/pg_dump /usr/local/bin/pg_dump

or

ln -s /Applications/Postgres.app/Contents/MacOS/bin/* /usr/local/bin/.

to just grab them all

Get Last Part of URL PHP

1-liner

$end = preg_replace( '%^(.+)/%', '', $url );

// if( ! $end ) no match.

This simply removes everything before the last slash, including it.

How to print the value of a Tensor object in TensorFlow?

You can use Keras, one-line answer will be to use eval method like so:

import keras.backend as K
print(K.eval(your_tensor))

What is "origin" in Git?

origin is not the remote repository name. It is rather a local alias set as a key in place of the remote repository URL.

It avoids the user having to type the whole remote URL when prompting a push.

This name is set by default and for convention by Git when cloning from a remote for the first time.

This alias name is not hard coded and could be changed using following command prompt:

git remote rename origin mynewalias

Take a look at http://git-scm.com/docs/git-remote for further clarifications.

Javascript : array.length returns undefined

try this

Object.keys(data).length

If IE < 9, you can loop through the object yourself with a for loop

var len = 0;
var i;

for (i in data) {
    if (data.hasOwnProperty(i)) {
        len++;
    }
}

Can't find @Nullable inside javax.annotation.*

JSR-305 is a "Java Specification Request" to extend the specification. @Nullable etc. were part of it; however it appears to be "dormant" (or frozen) ever since (See this SO question). So to use these annotations, you have to add the library yourself.

FindBugs was renamed to SpotBugs and is being developed under that name.

For maven this is the current annotation-only dependency (other integrations here):

<dependency>
  <groupId>com.github.spotbugs</groupId>
  <artifactId>spotbugs-annotations</artifactId>
  <version>4.2.0</version>
</dependency>

If you wish to use the full plugin, refer to the documentation of SpotBugs.

Using Thymeleaf when the value is null

The shortest way! it's working for me, Where NA is my default value.

<td th:text="${ins.eValue!=null}? ${ins.eValue}:'NA'" />

Create an empty list in python with certain size

Try this instead:

lst = [None] * 10

The above will create a list of size 10, where each position is initialized to None. After that, you can add elements to it:

lst = [None] * 10
for i in range(10):
    lst[i] = i

Admittedly, that's not the Pythonic way to do things. Better do this:

lst = []
for i in range(10):
    lst.append(i)

Or even simpler, in Python 2.x you can do this to initialize a list with values from 0 to 9:

lst = range(10)

And in Python 3.x:

lst = list(range(10))

Access 2013 - Cannot open a database created with a previous version of your application

You can do all these things but the underlying problem will be incompatibility with Windows updates of library files. Eventually you will have problems again. .ocx and .dll files will be clobbered and replaced: your database will not be able to cope with the new versions and it will not build or it will malfunction unexpectedly.

Get webpage contents with Python?

Because you're using Python 3.1, you need to use the new Python 3.1 APIs.

Try:

urllib.request.urlopen('http://www.python.org/')

Alternately, it looks like you're working from Python 2 examples. Write it in Python 2, then use the 2to3 tool to convert it. On Windows, 2to3.py is in \python31\tools\scripts. Can someone else point out where to find 2to3.py on other platforms?

Edit

These days, I write Python 2 and 3 compatible code by using six.

from six.moves import urllib
urllib.request.urlopen('http://www.python.org')

Assuming you have six installed, that runs on both Python 2 and Python 3.

How to POST JSON Data With PHP cURL?

First,

  1. always define certificates with CURLOPT_CAPATH option,

  2. decide how your POSTed data will be transfered.

1 Certificates

By default:

  • CURLOPT_SSL_VERIFYHOST == 2 which "checks the existence of a common name and also verify that it matches the hostname provided" and

  • CURLOPT_VERIFYPEER == true which "verifies the peer's certificate".

So, all you have to do is:

const CAINFO = SERVER_ROOT . '/registry/cacert.pem';
...
\curl_setopt($ch, CURLOPT_CAINFO, self::CAINFO);

taken from a working class where SERVER_ROOT is a constant defined during application bootstraping like in a custom classloader, another class etc.

Forget things like \curl_setopt($handler, CURLOPT_SSL_VERIFYHOST, 0); or \curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, 0);.

Find cacert.pem there as seen in this question.

2 POST modes

There are actually 2 modes when posting data:

  • the data is transfered with Content-Type header set to multipart/form-data or,

  • the data is a urlencoded string with application/x-www-form-urlencoded encoding.

In the first case you pass an array while in the second you pass a urlencoded string.

multipart/form-data ex.:

$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

application/x-www-form-urlencoded ex.:

$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, \http_build_query($fields));

http_build_query:

Test it at your command line as

user@group:$ php -a
php > $fields = array('a' => 'sth', 'b' => 'else');
php > echo \http_build_query($fields);
a=sth&b=else

The other end of the POST request will define the appropriate mode of connection.

Change fill color on vector asset in Android Studio

As said in other answers, don't edit the vector drawable directly, instead you can tint in java code, like that:

    mWrappedDrawable = mDrawable.mutate();
    mWrappedDrawable = DrawableCompat.wrap(mWrappedDrawable);
    DrawableCompat.setTint(mWrappedDrawable, mColor);
    DrawableCompat.setTintMode(mWrappedDrawable, PorterDuff.Mode.SRC_IN);

And for the sake of simplicity, I have created a helper class:

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

/**
 * {@link Drawable} helper class.
 *
 * @author Filipe Bezerra
 * @version 18/01/2016
 * @since 18/01/2016
 */
public class DrawableHelper {
    @NonNull Context mContext;
    @ColorRes private int mColor;
    private Drawable mDrawable;
    private Drawable mWrappedDrawable;

    public DrawableHelper(@NonNull Context context) {
        mContext = context;
    }

    public static DrawableHelper withContext(@NonNull Context context) {
        return new DrawableHelper(context);
    }

    public DrawableHelper withDrawable(@DrawableRes int drawableRes) {
        mDrawable = ContextCompat.getDrawable(mContext, drawableRes);
        return this;
    }

    public DrawableHelper withDrawable(@NonNull Drawable drawable) {
        mDrawable = drawable;
        return this;
    }

    public DrawableHelper withColor(@ColorRes int colorRes) {
        mColor = ContextCompat.getColor(mContext, colorRes);
        return this;
    }

    public DrawableHelper tint() {
        if (mDrawable == null) {
            throw new NullPointerException("É preciso informar o recurso drawable pelo método withDrawable()");
        }

        if (mColor == 0) {
            throw new IllegalStateException("É necessário informar a cor a ser definida pelo método withColor()");
        }

        mWrappedDrawable = mDrawable.mutate();
        mWrappedDrawable = DrawableCompat.wrap(mWrappedDrawable);
        DrawableCompat.setTint(mWrappedDrawable, mColor);
        DrawableCompat.setTintMode(mWrappedDrawable, PorterDuff.Mode.SRC_IN);

        return this;
    }

    @SuppressWarnings("deprecation")
    public void applyToBackground(@NonNull View view) {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackground(mWrappedDrawable);
        } else {
            view.setBackgroundDrawable(mWrappedDrawable);
        }
    }

    public void applyTo(@NonNull ImageView imageView) {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        imageView.setImageDrawable(mWrappedDrawable);
    }

    public void applyTo(@NonNull MenuItem menuItem) {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        menuItem.setIcon(mWrappedDrawable);
    }

    public Drawable get() {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        return mWrappedDrawable;
    }
}

To use just do the following:

    DrawableHelper
            .withContext(this)
            .withColor(R.color.white)
            .withDrawable(R.drawable.ic_search_24dp)
            .tint()
            .applyTo(mSearchItem);

Or:

    final Drawable drawable = DrawableHelper
            .withContext(this)
            .withColor(R.color.white)
            .withDrawable(R.drawable.ic_search_24dp)
            .tint()
            .get();

    actionBar.setHomeAsUpIndicator(drawable);

SQL Query to concatenate column values from multiple rows in Oracle

There's also an XMLAGG function, which works on versions prior to 11.2. Because WM_CONCAT is undocumented and unsupported by Oracle, it's recommended not to use it in production system.

With XMLAGG you can do the following:

SELECT XMLAGG(XMLELEMENT(E,ename||',')).EXTRACT('//text()') "Result" 
FROM employee_names

What this does is

  • put the values of the ename column (concatenated with a comma) from the employee_names table in an xml element (with tag E)
  • extract the text of this
  • aggregate the xml (concatenate it)
  • call the resulting column "Result"

Using Razor within JavaScript

You're trying to jam a square peg in a round hole.

Razor was intended as an HTML-generating template language. You may very well get it to generate JavaScript code, but it wasn't designed for that.

For instance: What if Model.Title contains an apostrophe? That would break your JavaScript code, and Razor won't escape it correctly by default.

It would probably be more appropriate to use a String generator in a helper function. There will likely be fewer unintended consequences of that approach.

Change project name on Android Studio

Here's what I did in Android Studio Beta (0.8.14)

  1. Changed the package name manually in the manifest file
  2. Navigated to build -> source -> r -> release and drilled down until I found R.java
  3. Selected the file and pressed F6 to rename
  4. Then from the Build menu selected Make Project
  5. Clicked the first error and pressed Shift+F6 on the package name and renamed which updated all my source files
  6. Selected my project name in Android Studio, right clicked -> Refactor -> Rename and changed the name there too.
  7. Next went to app -> build.gradle and updated my applicationId
  8. Navigate to .idea -> .name file and rename your Android Studio project in there too
  9. Just to clean up I deleted the old package folder inside build -> source -> r -> release

And vola, my package name has now changed and builds successfully.

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

Font is not available to the JVM with Jasper Reports

can make your custom fonts via iReport and converting like jars files

C/C++ macro string concatenation

You don't need that sort of solution for string literals, since they are concatenated at the language level, and it wouldn't work anyway because "s""1" isn't a valid preprocessor token.

[Edit: In response to the incorrect "Just for the record" comment below that unfortunately received several upvotes, I will reiterate the statement above and observe that the program fragment

#define PPCAT_NX(A, B) A ## B
PPCAT_NX("s", "1")

produces this error message from the preprocessing phase of gcc: error: pasting ""s"" and ""1"" does not give a valid preprocessing token

]

However, for general token pasting, try this:

/*
 * Concatenate preprocessor tokens A and B without expanding macro definitions
 * (however, if invoked from a macro, macro arguments are expanded).
 */
#define PPCAT_NX(A, B) A ## B

/*
 * Concatenate preprocessor tokens A and B after macro-expanding them.
 */
#define PPCAT(A, B) PPCAT_NX(A, B)

Then, e.g., both PPCAT_NX(s, 1) and PPCAT(s, 1) produce the identifier s1, unless s is defined as a macro, in which case PPCAT(s, 1) produces <macro value of s>1.

Continuing on the theme are these macros:

/*
 * Turn A into a string literal without expanding macro definitions
 * (however, if invoked from a macro, macro arguments are expanded).
 */
#define STRINGIZE_NX(A) #A

/*
 * Turn A into a string literal after macro-expanding it.
 */
#define STRINGIZE(A) STRINGIZE_NX(A)

Then,

#define T1 s
#define T2 1
STRINGIZE(PPCAT(T1, T2)) // produces "s1"

By contrast,

STRINGIZE(PPCAT_NX(T1, T2)) // produces "T1T2"
STRINGIZE_NX(PPCAT_NX(T1, T2)) // produces "PPCAT_NX(T1, T2)"

#define T1T2 visit the zoo
STRINGIZE(PPCAT_NX(T1, T2)) // produces "visit the zoo"
STRINGIZE_NX(PPCAT(T1, T2)) // produces "PPCAT(T1, T2)"

How to shut down the computer from C#

You can launch the shutdown process:

  • shutdown -s -t 0 - Shutdown
  • shutdown -r -t 0 - Restart

Dynamic creation of table with DOM

It is because you're only creating two td elements and 2 text nodes.


Creating all nodes in a loop

Recreate the nodes inside your loop:

var tablearea = document.getElementById('tablearea'),
    table = document.createElement('table');

for (var i = 1; i < 4; i++) {
    var tr = document.createElement('tr');

    tr.appendChild( document.createElement('td') );
    tr.appendChild( document.createElement('td') );

    tr.cells[0].appendChild( document.createTextNode('Text1') )
    tr.cells[1].appendChild( document.createTextNode('Text2') );

    table.appendChild(tr);
}

tablearea.appendChild(table);

Creating then cloning in a loop

Create them beforehand, and clone them inside the loop:

var tablearea = document.getElementById('tablearea'),
    table = document.createElement('table'),
    tr = document.createElement('tr');

tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );

tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );

for (var i = 1; i < 4; i++) {
    table.appendChild(tr.cloneNode( true ));
}

tablearea.appendChild(table);

Table factory with text string

Make a table factory:

function populateTable(table, rows, cells, content) {
    if (!table) table = document.createElement('table');
    for (var i = 0; i < rows; ++i) {
        var row = document.createElement('tr');
        for (var j = 0; j < cells; ++j) {
            row.appendChild(document.createElement('td'));
            row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
        }
        table.appendChild(row);
    }
    return table;
}

And use it like this:

document.getElementById('tablearea')
        .appendChild( populateTable(null, 3, 2, "Text") );

Table factory with text string or callback

The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.

function populateTable(table, rows, cells, content) {
    var is_func = (typeof content === 'function');
    if (!table) table = document.createElement('table');
    for (var i = 0; i < rows; ++i) {
        var row = document.createElement('tr');
        for (var j = 0; j < cells; ++j) {
            row.appendChild(document.createElement('td'));
            var text = !is_func ? (content + '') : content(table, i, j);
            row.cells[j].appendChild(document.createTextNode(text));
        }
        table.appendChild(row);
    }
    return table;
}

Used like this:

document.getElementById('tablearea')
        .appendChild(populateTable(null, 3, 2, function(t, r, c) {
                        return ' row: ' + r + ', cell: ' + c;
                     })
        );

java- reset list iterator to first element of the list

You can call listIterator method again to get an instance of iterator pointing at beginning of list:

iter = list.listIterator();

Current date without time

it should be as simple as

DateTime.Today

Efficient way to remove keys with empty strings from a dict

An alternative way you can do this, is using dictionary comprehension. This should be compatible with 2.7+

result = {
    key: value for key, value in
    {"foo": "bar", "lorem": None}.items()
    if value
}

From milliseconds to hour, minutes, seconds and milliseconds

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class MyTest {

    public static void main(String[] args) {
        long seconds = 360000;

        long days = TimeUnit.SECONDS.toDays(seconds);
        long hours = TimeUnit.SECONDS.toHours(seconds - TimeUnit.DAYS.toSeconds(days));

        System.out.println("days: " + days);
        System.out.println("hours: " + hours);
    }
}

How can I reload .emacs after changing it?

You can use the command load-file (M-x load-file, then press return twice to accept the default filename, which is the current file being edited).

You can also just move the point to the end of any sexp and press C-xC-e to execute just that sexp. Usually it's not necessary to reload the whole file if you're just changing a line or two.

How to return multiple values?

You can do something like this:

public class Example
{
    public String name;
    public String location;

    public String[] getExample()
    {
        String ar[] = new String[2];
        ar[0]= name;
        ar[1] =  location;
        return ar; //returning two values at once
    }
}

How to pass multiple parameters in a querystring

Query String: ?strID=XXXX&strName=yyyy&strDate=zzzzz

before you redirect:

string queryString = Request.QueryString.ToString();

Response.Redirect("page.aspx?"+queryString);

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

python NameError: global name '__file__' is not defined

Are you using the interactive interpreter? You can use

sys.argv[0]

You should read: How do I get the path of the current executed file in Python?

phantomjs not waiting for "full" page load

This is an old question, but since I was looking for full page load but for Spookyjs (that uses casperjs and phantomjs) and didn't find my solution, I made my own script for that, with the same approach as the user deemstone . What this approach does is, for a given quantity of time, if the page did not receive or started any request it will end the execution.

On casper.js file (if you installed it globally, the path would be something like /usr/local/lib/node_modules/casperjs/modules/casper.js) add the following lines:

At the top of the file with all the global vars:

var waitResponseInterval = 500
var reqResInterval = null
var reqResFinished = false
var resetTimeout = function() {}

Then inside function "createPage(casper)" just after "var page = require('webpage').create();" add the following code:

 resetTimeout = function() {
     if(reqResInterval)
         clearTimeout(reqResInterval)

     reqResInterval = setTimeout(function(){
         reqResFinished = true
         page.onLoadFinished("success")
     },waitResponseInterval)
 }
 resetTimeout()

Then inside "page.onResourceReceived = function onResourceReceived(resource) {" on the first line add:

 resetTimeout()

Do the same for "page.onResourceRequested = function onResourceRequested(requestData, request) {"

Finally, on "page.onLoadFinished = function onLoadFinished(status) {" on the first line add:

 if(!reqResFinished)
 {
      return
 }
 reqResFinished = false

And that's it, hope this one helps someone in trouble like I was. This solution is for casperjs but works directly for Spooky.

Good luck !

Ruby: Calling class method from instance

Using self.class.blah is NOT the same as using ClassName.blah when it comes to inheritance.

class Truck
  def self.default_make
    "mac"
  end

  def make1
    self.class.default_make
  end

  def make2
    Truck.default_make
  end
end


class BigTruck < Truck
  def self.default_make
    "bigmac"
  end
end

ruby-1.9.3-p0 :021 > b=BigTruck.new
 => #<BigTruck:0x0000000307f348> 
ruby-1.9.3-p0 :022 > b.make1
 => "bigmac" 
ruby-1.9.3-p0 :023 > b.make2
 => "mac" 

Importing JSON into an Eclipse project

Download the json jar from here. This will solve your problem.

How to skip over an element in .map()?

Here is a updated version of the code provided by @theprtk. It is a cleaned up a little to show the generalized version whilst having an example.

Note: I'd add this as a comment to his post but I don't have enough reputation yet

/**
 * @see http://clojure.com/blog/2012/05/15/anatomy-of-reducer.html
 * @description functions that transform reducing functions
 */
const transduce = {
  /** a generic map() that can take a reducing() & return another reducing() */
  map: changeInput => reducing => (acc, input) =>
    reducing(acc, changeInput(input)),
  /** a generic filter() that can take a reducing() & return */
  filter: predicate => reducing => (acc, input) =>
    predicate(input) ? reducing(acc, input) : acc,
  /**
   * a composing() that can take an infinite # transducers to operate on
   *  reducing functions to compose a computed accumulator without ever creating
   *  that intermediate array
   */
  compose: (...args) => x => {
    const fns = args;
    var i = fns.length;
    while (i--) x = fns[i].call(this, x);
    return x;
  },
};

const example = {
  data: [{ src: 'file.html' }, { src: 'file.txt' }, { src: 'file.json' }],
  /** note: `[1,2,3].reduce(concat, [])` -> `[1,2,3]` */
  concat: (acc, input) => acc.concat([input]),
  getSrc: x => x.src,
  filterJson: x => x.src.split('.').pop() !== 'json',
};

/** step 1: create a reducing() that can be passed into `reduce` */
const reduceFn = example.concat;
/** step 2: transforming your reducing function by mapping */
const mapFn = transduce.map(example.getSrc);
/** step 3: create your filter() that operates on an input */
const filterFn = transduce.filter(example.filterJson);
/** step 4: aggregate your transformations */
const composeFn = transduce.compose(
  filterFn,
  mapFn,
  transduce.map(x => x.toUpperCase() + '!'), // new mapping()
);

/**
 * Expected example output
 *  Note: each is wrapped in `example.data.reduce(x, [])`
 *  1: ['file.html', 'file.txt', 'file.json']
 *  2:  ['file.html', 'file.txt']
 *  3: ['FILE.HTML!', 'FILE.TXT!']
 */
const exampleFns = {
  transducers: [
    mapFn(reduceFn),
    filterFn(mapFn(reduceFn)),
    composeFn(reduceFn),
  ],
  raw: [
    (acc, x) => acc.concat([x.src]),
    (acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src] : []),
    (acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src.toUpperCase() + '!'] : []),
  ],
};
const execExample = (currentValue, index) =>
  console.log('Example ' + index, example.data.reduce(currentValue, []));

exampleFns.raw.forEach(execExample);
exampleFns.transducers.forEach(execExample);

Vertical Alignment of text in a table cell

Try

_x000D_
_x000D_
td.description {_x000D_
  line-height: 15px_x000D_
}
_x000D_
<td class="description">Description</td>
_x000D_
_x000D_
_x000D_

Set the line-height value to the desired value.

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

Preventing an image from being draggable or selectable without using JS

You could probably just resort to

<img src="..." style="pointer-events: none;">

Solving a "communications link failure" with JDBC and MySQL

I have had the same problem in two of my programs. My error was this:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

I spent several days to solve this problem. I have tested many approaches that have been mentioned in different web sites, but non of them worked. Finally I changed my code and found out what was the problem. I'll try to tell you about different approaches and sum them up here.

While I was seeking the internet to find the solution for this error, I figured out that there are many solutions that worked for at least one person, but others say that it doesn't work for them! why there are many approaches to this error? It seems this error can occur generally when there is a problem in connecting to the server. Maybe the problem is because of the wrong query string or too many connections to the database.

So I suggest you to try all the solutions one by one and don't give up!

Here are the solutions that I found on the internet and for each of them, there is at least on person who his problem has been solved with that solution.

Tip: For the solutions that you need to change the MySQL settings, you can refer to the following files:

  • Linux: /etc/mysql/my.cnf or /etc/my.cnf (depending on the Linux distribution and MySQL package used)

  • Windows: C:**ProgramData**\MySQL\MySQL Server 5.6\my.ini (Notice it's ProgramData, not Program Files)

Here are the solutions:

  • changing "bind-address" attribute

Uncomment "bind-address" attribute or change it to one of the following IPs:

bind-address="127.0.0.1"

or

bind-address="0.0.0.0"

  • commenting out "skip-networking"

If there is a "skip-networking" line in your MySQL config file, make it comment by adding "#" sign at the beginning of that line.

  • change "wait_timeout" and "interactive_timeout"

Add these lines to the MySQL config file:

wait_timeout = number

interactive_timeout = number

connect_timeout = number

  • Make sure Java isn't translating 'localhost' to [:::1] instead of [127.0.0.1]

Since MySQL recognizes 127.0.0.1 (IPv4) but not :::1 (IPv6)

This could be avoided by using one of two approaches:

Option #1: In the connection string use 127.0.0.1 instead of localhost to avoid localhost being translated to :::1

Option #2: Run java with the option -Djava.net.preferIPv4Stack=true to force java to use IPv4 instead of IPv6. On Linux, this could also be achieved by running (or placing it inside /etc/profile:

export _JAVA_OPTIONS="-Djava.net.preferIPv4Stack=true"
  • check Operating System proxy settings, firewalls and anti-virus programs

Make sure the Firewall, or Anti-virus software isn't blocking MySQL service.

Stop iptables temporarily on linux. If iptables are misconfigured they may allow tcp packets to be sent to mysql port, but block tcp packets from coming back on the same connection.

# Redhat enterprise and CentOS
systemctl stop iptables.service
# Other linux distros
service iptables stop

Stop anti-virus software on Windows.

  • change connection string

Check your query string. your connection string should be some thing like this:

dbName = "my_database";
dbUserName = "root";
dbPassword = "";
String connectionString = "jdbc:mysql://localhost/" + dbName + "?user=" + dbUserName + "&password=" + dbPassword + "&useUnicode=true&characterEncoding=UTF-8";

Make sure you don't have spaces in your string. All the connection string should be continues without any space characters.

Try to replace "localhost" with the loopback address 127.0.0.1. Also try to add port number to your connection string, like:

String connectionString = "jdbc:mysql://localhost:3306/my_database?user=root&password=Pass&useUnicode=true&characterEncoding=UTF-8";

Usually default port for MySQL is 3306.

Don't forget to change username and password to the username and password of your MySQL server.

  • update your JDK driver library file
  • test different JDK and JREs (like JDK 6 and 7)
  • don't change max_allowed_packet

"max_allowed_packet" is a variable in MySQL config file that indicates the maximum packet size, not the maximum number of packets. So it will not help to solve this error.

  • change tomcat security

change TOMCAT6_SECURITY=yes to TOMCAT6_SECURITY=no

  • use validationQuery property

use validationQuery="select now()" to make sure each query has responses

  • AutoReconnect

Add this code to your connection string:

&autoReconnect=true&failOverReadOnly=false&maxReconnects=10

Although non of these solutions worked for me, I suggest you to try them. Because there are some people who solved their problem with following these steps.

But what solved my problem?

My problem was that I had many SELECTs on database. Each time I was creating a connection and then closing it. Although I was closing the connection every time, but the system faced with many connections and gave me that error. What I did was that I defined my connection variable as a public (or private) variable for whole class and initialized it in the constructor. Then every time I just used that connection. It solved my problem and also increased my speed dramatically.

Conclusion

There is no simple and unique way to solve this problem. I suggest you to think about your own situation and choose above solutions. If you take this error at the beginning of the program and you are not able to connect to the database at all, you might have problem in your connection string. But If you take this error after several successful interaction to the database, the problem might be with number of connections and you may think about changing "wait_timeout" and other MySQL settings or rewrite your code how that reduce number of connections.

error running apache after xampp install

I think killing the process which is uses that port is more easy to handle than changing the ports in config files. Here is how to do it in Windows. You can follow same procedure to Linux but different commands. Run command prompt as Administrator. Then type below command to find out all of processes using the port.

netstat -ano

There will be plenty of processes using various ports. So to get only port we need use findstr like below (here I use port 80)

netstat -ano | findstr 80

this will gave you result like this

TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       7964

Last number is the process ID of the process. so what we have to do is kill the process using PID we can use taskkill command for that.

taskkill /PID 7964 /F

Run your server again. This time it will be able to run. This can uses for Mysql server too.

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

Function Pointers in Java

There is no such thing in Java. You will need to wrap your function into some object and pass the reference to that object in order to pass the reference to the method on that object.

Syntactically, this can be eased to a certain extent by using anonymous classes defined in-place or anonymous classes defined as member variables of the class.

Example:

class MyComponent extends JPanel {
    private JButton button;
    public MyComponent() {
        button = new JButton("click me");
        button.addActionListener(buttonAction);
        add(button);
    }

    private ActionListener buttonAction = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // handle the event...
            // note how the handler instance can access 
            // members of the surrounding class
            button.setText("you clicked me");
        }
    }
}

Query to display all tablespaces in a database and datafiles

If you want to get a list of all tablespaces used in the current database instance, you can use the DBA_TABLESPACES view as shown in the following SQL script example:

SQL> connect SYSTEM/fyicenter
Connected.

SQL> SELECT TABLESPACE_NAME, STATUS, CONTENTS
  2  FROM USER_TABLESPACES;
TABLESPACE_NAME                STATUS    CONTENTS
------------------------------ --------- ---------
SYSTEM                         ONLINE    PERMANENT
UNDO                           ONLINE    UNDO
SYSAUX                         ONLINE    PERMANENT
TEMP                           ONLINE    TEMPORARY
USERS                          ONLINE    PERMANENT

http://dba.fyicenter.com/faq/oracle/Show-All-Tablespaces-in-Current-Database.html

jQuery addClass onClick

Try to make your css more specific so that the new (green) style is more specific than the previous one, so that it worked for me!

For example, you might use in css:

button:active {/*your style here*/}

Instead of (probably not working):

.active {/*style*/} (.active is not a pseudo-class)

Hope it helps!

How can I temporarily disable a foreign key constraint in MySQL?

I normally only disable foreign key constraints when I want to truncate a table, and since I keep coming back to this answer this is for future me:

SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE table;
SET FOREIGN_KEY_CHECKS=1;

Find a row in dataGridView based on column and value

Or you can use like this. This may be faster.

int iFindNo = 14;
int j = dataGridView1.Rows.Count-1;
int iRowIndex = -1;
for (int i = 0; i < Convert.ToInt32(dataGridView1.Rows.Count/2) +1; i++)
{
    if (Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value) == iFindNo)
    {
        iRowIndex = i;
        break;
    }
    if (Convert.ToInt32(dataGridView1.Rows[j].Cells[0].Value) == iFindNo)
    {
        iRowIndex = j;
        break;
    }
    j--;
}
if (iRowIndex != -1)
    MessageBox.Show("Index is " + iRowIndex.ToString());
else
    MessageBox.Show("Index not found." );

jQuery replace one class with another

you could have both of them use a "corpo_button" class, or something like that, and then in $(".corpo_button").click(...) just call $(this).toggleClass("corpo_buttons_asia corpo_buttons_global");

Remove columns from DataTable in C#

Aside from limiting the columns selected to reduce bandwidth and memory:

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);

Transposing a 2D-array in JavaScript

Neat and pure:

[[0, 1], [2, 3], [4, 5]].reduce((prev, next) => next.map((item, i) =>
    (prev[i] || []).concat(next[i])
), []); // [[0, 2, 4], [1, 3, 5]]

Previous solutions may lead to failure in case an empty array is provided.

Here it is as a function:

function transpose(array) {
    return array.reduce((prev, next) => next.map((item, i) =>
        (prev[i] || []).concat(next[i])
    ), []);
}

console.log(transpose([[0, 1], [2, 3], [4, 5]]));

Update. It can be written even better with spread operator:

const transpose = matrix => matrix.reduce(
    ($, row) => row.map((_, i) => [...($[i] || []), row[i]]), 
    []
)

What is 'Currying'?

Currying is one of the higher-order functions of Java Script.

Currying is a function of many arguments which is rewritten such that it takes the first argument and return a function which in turns uses the remaining arguments and returns the value.

Confused?

Let see an example,

function add(a,b)
    {
        return a+b;
    }
add(5,6);

This is similar to the following currying function,

function add(a)
    {
        return function(b){
            return a+b;
        }
    }
var curryAdd = add(5);
curryAdd(6);

So what does this code means?

Now read the definition again,

Currying is a function of many arguments which is rewritten such that it takes first argument and return a function which in turns uses the remaining arguments and returns the value.

Still, Confused? Let me explain in deep!

When you call this function,

var curryAdd = add(5);

It will return you a function like this,

curryAdd=function(y){return 5+y;}

So, this is called higher-order functions. Meaning, Invoking one function in turns returns another function is an exact definition for higher-order function. This is the greatest advantage for the legend, Java Script. So come back to the currying,

This line will pass the second argument to the curryAdd function.

curryAdd(6);

which in turns results,

curryAdd=function(6){return 5+6;}
// Which results in 11

Hope you understand the usage of currying here. So, Coming to the advantages,

Why Currying?

It makes use of code reusability. Less code, Less Error. You may ask how it is less code?

I can prove it with ECMA script 6 new feature arrow functions.

Yes! ECMA 6, provide us with the wonderful feature called arrow functions,

function add(a)
    {
        return function(b){
            return a+b;
        }
    }

With the help of the arrow function, we can write the above function as follows,

x=>y=>x+y

Cool right?

So, Less Code and Fewer bugs!!

With the help of these higher-order function one can easily develop a bug-free code.

I challenge you!

Hope, you understood what is currying. Please feel free to comment over here if you need any clarifications.

Thanks, Have a nice day!

How to clear radio button in Javascript?

In my case this got the job done:

const chbx = document.getElementsByName("input_name");

for(let i=0; i < chbx.length; i++) {
    chbx[i].checked = false;
}

Setting up maven dependency for SQL Server

Even after installing the sqlserver jar, my maven was trying to fetch the dependecy from maven repository. I then, provided my pom the repository of my local machine and it works fine after that...might be of help for someone.

    <repository>
        <id>local</id>
        <name>local</name>
        <url>file://C:/Users/mywindows/.m2/repository</url>
    </repository>

How to show uncommitted changes in Git and some Git diffs in detail

I had a situation of git status showing changes, but git diff printing nothing, although there were changes in several lines. However:

$ git diff data.txt > myfile
$ cat myfile
<prints diff>

Git 2.20.1 on raspbian. Other commands like git checkout, git pull are printing to stdout without problems.

How to time Java program execution speed

Be aware that there are some issues where System#nanoTime() cannot be reliably used on multi-core CPU's to record elapsed time ... each core has maintains its own TSC (Time Stamp Counter): this counter is used to obtain the nano time (really it is the number of ticks since the CPU booted).

Hence, unless the OS does some TSC time warping to keep the cores in sync, then if a thread gets scheduled on one core when the initial time reading is taken, then switched to a different core, the relative time can sporadically appear to jump backwards and forwards.

I observed this some time ago on AMD/Solaris where elapsed times between two timing points were sometimes coming back as either negative values or unexpectedly large positive numbers. There was a Solaris kernel patch and a BIOS setting required to force the AMD PowerNow! off, which appeared to solved it.

Also, there is (AFAIK) a so-far unfixed bug when using java System#nanoTime() in a VirtualBox environment; causing all sorts of bizarre intermittent threading problems for us as much of the java.util.concurrency package relies on nano time.

See also:

Is System.nanoTime() completely useless? http://vbox.innotek.de/pipermail/vbox-trac/2010-January/135631.html

Create Windows service from executable

Probably all your answers are better, but - just to be complete on the choice of options - I wanted to remind about old, similar method used for years:

SrvAny (installed by InstSrv)

as described here: https://docs.microsoft.com/en-us/troubleshoot/windows-client/deployment/create-user-defined-service

Body of Http.DELETE request in Angular2

Definition in http.js from the @angular/http:

delete(url, options)

The request doesn't accept a body so it seem your only option is to but your data in the URI.

I found another topic with references to correspond RFC, among other things: How to pass data in the ajax DELETE request other than headers

What does the Java assert keyword do, and when should it be used?

A real world example, from a Stack-class (from Assertion in Java Articles)

public int pop() {
   // precondition
   assert !isEmpty() : "Stack is empty";
   return stack[--num];
}

Tool to compare directories (Windows 7)

I use WinMerge. It is free and works pretty well (works for files and directories).

Why is HttpContext.Current null?

In IIS7 with integrated mode, Current is not available in Application_Start. There is a similar thread here.

Android: How to set password property in an edit text?

My search for a similar solution for Visual Studio 2015/Xamarin lead me to this thread. While setting the EditText.InputType to Android.Text.InputTypes.TextVariationVisiblePassword properly hid the password during user entry, it did not 'hide' the password if it was visible before the EditText Layout was rendered (before the user submitted their password entry). In order to hide a visible password after the user submits their password and the EditText Layout is rendered, I used EditText.TransformationMethod = PasswordTransformationMethod.Instance as suggested by LuxuryMode.

AngularJS - ng-if check string empty value

If by "empty" you mean undefined, it is the way ng-expressions are interpreted. Then, you could use :

<a ng-if="!item.photo" href="#/details/{{item.id}}"><img src="/img.jpg" class="img-responsive"></a>

Change label text using JavaScript

Because a label element is not loaded when a script is executed. Swap the label and script elements, and it will work:

<label id="lbltipAddedComment"></label>
<script>
    document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>

How do I solve this "Cannot read property 'appendChild' of null" error?

Just reorder or make sure, the (DOM or HTML) is loaded before the JavaScript.

Accessing an SQLite Database in Swift

This is by far the best SQLite library that I've used in Swift: https://github.com/stephencelis/SQLite.swift

Look at the code examples. So much cleaner than the C API:

import SQLite

let db = try Connection("path/to/db.sqlite3")

let users = Table("users")
let id = Expression<Int64>("id")
let name = Expression<String?>("name")
let email = Expression<String>("email")

try db.run(users.create { t in
    t.column(id, primaryKey: true)
    t.column(name)
    t.column(email, unique: true)
})
// CREATE TABLE "users" (
//     "id" INTEGER PRIMARY KEY NOT NULL,
//     "name" TEXT,
//     "email" TEXT NOT NULL UNIQUE
// )

let insert = users.insert(name <- "Alice", email <- "[email protected]")
let rowid = try db.run(insert)
// INSERT INTO "users" ("name", "email") VALUES ('Alice', '[email protected]')

for user in try db.prepare(users) {
    print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
    // id: 1, name: Optional("Alice"), email: [email protected]
}
// SELECT * FROM "users"

let alice = users.filter(id == rowid)

try db.run(alice.update(email <- email.replace("mac.com", with: "me.com")))
// UPDATE "users" SET "email" = replace("email", 'mac.com', 'me.com')
// WHERE ("id" = 1)

try db.run(alice.delete())
// DELETE FROM "users" WHERE ("id" = 1)

try db.scalar(users.count) // 0
// SELECT count(*) FROM "users"

The documentation also says that "SQLite.swift also works as a lightweight, Swift-friendly wrapper over the C API," and follows with some examples of that.

Uncaught TypeError: undefined is not a function while using jQuery UI

Usually when you get this problem, it happens because a script is trying to reference an element that doesn't exist yet while the page is loading.

As richie mentioned: "The HTML parser will parse the HTML content from top to bottom..."

So you can add your JavaScript references to the bottom of the HTML file. This will not only improve performance; it will also ensure that all elements referenced in your script files have already been loaded by the HTML parser.

So you could have something like this:

<html>
    <head>
        <!--  Style sheet references and CSS definitions -->
    </head>
    <body>
        <!-- HTML markup and other page content -->

        <!-- JavaScript references. You could include jQuery here as well and do all your scripting here. -->
    </body>
</html>

Create a date time with month and day only, no year

Well, you can create your own type - but a DateTime always has a full date and time. You can't even have "just a date" using DateTime - the closest you can come is to have a DateTime at midnight.

You could always ignore the year though - or take the current year:

// Consider whether you want DateTime.UtcNow.Year instead
DateTime value = new DateTime(DateTime.Now.Year, month, day);

To create your own type, you could always just embed a DateTime within a struct, and proxy on calls like AddDays etc:

public struct MonthDay : IEquatable<MonthDay>
{
    private readonly DateTime dateTime;

    public MonthDay(int month, int day)
    {
        dateTime = new DateTime(2000, month, day);
    }

    public MonthDay AddDays(int days)
    {
        DateTime added = dateTime.AddDays(days);
        return new MonthDay(added.Month, added.Day);
    }

    // TODO: Implement interfaces, equality etc
}

Note that the year you choose affects the behaviour of the type - should Feb 29th be a valid month/day value or not? It depends on the year...

Personally I don't think I would create a type for this - instead I'd have a method to return "the next time the program should be run".

Force browser to refresh css, javascript, etc

Try this:

link href="styles/style.css?=time()" rel="stylesheet" type="text/css"

If you need something after the '?' that is different every time the page is accessed then the time() will do it. Leaving this in your code permanently is not really a good idea since it will only slow down page loading and probably isn't necessary.

I've found that forcing a style sheet refresh is helpful if you've made extensive changes to a page's layout and accessing the new style sheet is vital to having something sensible appear on the screen.

How exactly do you configure httpOnlyCookies in ASP.NET?

If you want to do it in code, use the System.Web.HttpCookie.HttpOnly property.

This is directly from the MSDN docs:

// Create a new HttpCookie.
HttpCookie myHttpCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// By default, the HttpOnly property is set to false 
// unless specified otherwise in configuration.
myHttpCookie.Name = "MyHttpCookie";
Response.AppendCookie(myHttpCookie);
// Show the name of the cookie.
Response.Write(myHttpCookie.Name);
// Create an HttpOnly cookie.
HttpCookie myHttpOnlyCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// Setting the HttpOnly value to true, makes
// this cookie accessible only to ASP.NET.
myHttpOnlyCookie.HttpOnly = true;
myHttpOnlyCookie.Name = "MyHttpOnlyCookie";
Response.AppendCookie(myHttpOnlyCookie);
// Show the name of the HttpOnly cookie.
Response.Write(myHttpOnlyCookie.Name);

Doing it in code allows you to selectively choose which cookies are HttpOnly and which are not.

jQuery How to Get Element's Margin and Padding?

If the element you're analyzing does not have any margin, border or whatsoever defined you won't be able to return it. At tops you'll be able to get 'auto' which is normally the default.

From your example I can see that you have margT as variable. Not sure if're trying to get margin-top. If that's the case you should be using .css('margin-top').

You're also trying to get the stylization from 'img' which will result (if you have more than one) in an array.

What you should do is use the .each() jquery method.

For example:

jQuery('img').each(function() {
    // get margin top
    var margT = jQuery(this).css('margin-top');

    // Do something with margT
});

Convert String to Date in MS Access Query

In Access, click Create > Module and paste in the following code

Public Function ConvertMyStringToDateTime(strIn As String) As Date
ConvertMyStringToDateTime = CDate( _
        Mid(strIn, 1, 4) & "-" & Mid(strIn, 5, 2) & "-" & Mid(strIn, 7, 2) & " " & _
        Mid(strIn, 9, 2) & ":" & Mid(strIn, 11, 2) & ":" & Mid(strIn, 13, 2))
End Function

Hit Ctrl+S and save the module as modDateConversion.

Now try using a query like

Select * from Events
Where Events.[Date] > ConvertMyStringToDateTime("20130423014854")

--- Edit ---

Alternative solution avoiding user-defined VBA function:

SELECT * FROM Events
WHERE Format(Events.[Date],'yyyyMMddHhNnSs') > '20130423014854'

Deciding between HttpClient and WebClient

HttpClientFactory

It's important to evaluate the different ways you can create an HttpClient, and part of that is understanding HttpClientFactory.

https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

This is not a direct answer I know - but you're better off starting here than ending up with new HttpClient(...) everywhere.

Using an attribute of the current class instance as a default value for method's parameter

There are multiple false assumptions you're making here - First, function belong to a class and not to an instance, meaning the actual function involved is the same for any two instances of a class. Second, default parameters are evaluated at compile time and are constant (as in, a constant object reference - if the parameter is a mutable object you can change it). Thus you cannot access self in a default parameter and will never be able to.

Convert a string to int using sql query

Try this one, it worked for me in Athena:

cast(MyVarcharCol as integer)

Determine when a ViewPager changes pages

You can also use ViewPager.SimpleOnPageChangeListener instead of ViewPager.OnPageChangeListener and override only those methods you want to use.

viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

    // optional 
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

    // optional 
    @Override
    public void onPageSelected(int position) { }

    // optional 
    @Override
    public void onPageScrollStateChanged(int state) { }
});

Hope this help :)

Edit: As per android APIs, setOnPageChangeListener (ViewPager.OnPageChangeListener listener) is deprecated. Please check this url:- Android ViewPager API

How do I start/stop IIS Express Server?

Closing IIS Express

By default Visual Studio places the IISExpress icon in your system tray at the lower right hand side of your screen, by the clock. You can right click it and choose exit. If you don't see the icon, try clicking the small arrow to view the full list of icons in the system tray.

IIS Express icon

then right click and choose Exit:

enter image description here


Changing the Port

Another option is to change the port by modifying the project properties. You'll need to do this for each web project in your solution.

  1. Visual Studio > Solution Explorer
  2. Right click the web project and choose Properties
  3. Go to the Web tab
  4. In the 'Servers' section, change the port in the Project URL box
  5. Repeat for each web project in the solution

Changing the IIS Express port


If All Else Fails

If that doesn't work, you can try to bring up Task Manager and close the IIS Express System Tray (32 bit) process and IIS Express Worker Process (32 bit).

Terminating the IIS Express Worker Thread process

If it still doesn't work, as ni5ni6 pointed out, there is a 'Web Deployment Agent Service' running on the port 80. Use this article to track down which process uses it, and turn it off:

https://sites.google.com/site/anashkb/port-80-in-use

How do I clear all variables in the middle of a Python script?

The globals() function returns a dictionary, where keys are names of objects you can name (and values, by the way, are ids of these objects) The exec() function takes a string and executes it as if you just type it in a python console. So, the code is

for i in list(globals().keys()):
    if(i[0] != '_'):
        exec('del {}'.format(i))

How do I share a global variable between c files?

Use extern keyword in another .c file.

How can I add a space in between two outputs?

Add a literal space, or a tab:

public void displayCustomerInfo() {
    System.out.println(Name + " " + Income);

    // or a tab
    System.out.println(Name + "\t" + Income);
}

Get last record of a table in Postgres

In Oracle SQL,

select * from (select row_number() over (order by rowid desc) rn, emp.* from emp) where rn=1;

How to check if the request is an AJAX request with PHP

Here is the tutorial of achieving the result.

Example:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{    
  exit;    
}
continue;

This checks if the HTTP_X_REQUESTED_WITH parameter is not empty and if it's equal to xmlhttprequest, then it will exit from the script.

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

Had this issue when migrated spring boot 1.5.2 to 2.0.4. Instead of creating bean I've used @EnableAutoConfiguration in the main class and it solved my problem.

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

Looks like you are using pandas dataframe (from the name df2).

You could also do the following:

regr = LinearRegression()
regr.fit(df2.iloc[1:1000, 5].to_frame(), df2.iloc[1:1000, 2].to_frame())

NOTE: I have removed "values" as that converts the pandas Series to numpy.ndarray and numpy.ndarray does not have attribute to_frame().

Java random numbers using a seed

That's the principle of a Pseudo-RNG. The numbers are not really random. They are generated using a deterministic algorithm, but depending on the seed, the sequence of generated numbers vary. Since you always use the same seed, you always get the same sequence.

Select statement to find duplicates on certain fields

To get the list of fields for which there are multiple records, you can use..

select field1,field2,field3, count(*)
  from table_name
  group by field1,field2,field3
  having count(*) > 1

Check this link for more information on how to delete the rows.

http://support.microsoft.com/kb/139444

There should be a criterion for deciding how you define "first rows" before you use the approach in the link above. Based on that you'll need to use an order by clause and a sub query if needed. If you can post some sample data, it would really help.

Python loop to run for certain amount of seconds

Simply You can do it

import time
delay=60*15    ###for 15 minutes delay 
close_time=time.time()+delay
while True:
      ##bla bla
      ###bla bla
     if time.time()>close_time
         break

How to check all checkboxes using jQuery?

html :

    <div class="col-md-3 general-sidebar" id="CategoryGrid">
                                                    <h5>Category &amp; Sub Category <span style="color: red;">* </span></h5>
                                                    <div class="checkbox">
                                                        <label>
                                                            <input onclick="checkUncheckAll(this)" type="checkbox">
                                                            All
                                                        </label>
                                                    </div>
                                                <div class="checkbox"><label><input class="cat" type="checkbox" value="Quality">Quality</label></div>
<div class="checkbox"><label><input class="subcat" type="checkbox" value="Planning process and execution">Planning process and execution</label></div>

javascript:

function checkUncheckAll(ele) {
    if (ele.checked) {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
    else {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
}

Visual Studio Code Tab Key does not insert a tab

I had accidentally enabled a different mode for the tab key. Fixed it by pressing Ctrl+Shift(for Mac only)+M.

From the Visual Studio Code Keybinding docs:

| Key      | Command                                 | Command id                       |
| Ctrl + M | Toggle Use of Tab Key for Setting Focus | editor.action.toggleTabFocusMode |

The current tab control mode should also show up in the status bar:

enter image description here

How to add a new audio (not mixing) into a video using ffmpeg?

Nothing quite worked for me (I think it was because my input .mp4 video didn't had any audio) so I found this worked for me:

ffmpeg -i input_video.mp4 -i balipraiavid.wav -map 0:v:0 -map 1:a:0 output.mp4

How to resume Fragment from BackStack if exists

I think this method my solve your problem:

public static void attachFragment ( int fragmentHolderLayoutId, Fragment fragment, Context context, String tag ) {


    FragmentManager manager = ( (AppCompatActivity) context ).getSupportFragmentManager ();
    FragmentTransaction ft = manager.beginTransaction ();

    if (manager.findFragmentByTag ( tag ) == null) { // No fragment in backStack with same tag..
        ft.add ( fragmentHolderLayoutId, fragment, tag );
        ft.addToBackStack ( tag );
        ft.commit ();
    }
    else {
        ft.show ( manager.findFragmentByTag ( tag ) ).commit ();
    }
}

which was originally posted in This Question

mongodb service is not starting up

I had issue that starting the service mongodb failed, without logs. what i did to fix the error is to give write access to the directory /var/log/mongodb for user mongodb

How to update /etc/hosts file in Docker image during "docker build"

You can not modify the host file in the image using echo in RUN step because docker daemon will maintain the file(/etc/hosts) and its content(hosts entry) when you start a container from the image.

However following can be used to achieve the same:

ENTRYPOINT ["/bin/sh", "-c" , "echo 192.168.254.10   database-server >> /etc/hosts && echo 192.168.239.62   redis-ms-server >> /etc/hosts && exec java -jar ./botblocker.jar " ]

Key to notice here is the use of exec command as docker documentation suggests. Use of exec will make the java command as PID 1 for the container. Docker interrupts will only respond to that.

See https://docs.docker.com/engine/reference/builder/#entrypoint

How do I find which program is using port 80 in Windows?

If you want to be really fancy, download TCPView from Sysinternals:

TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, and XP, TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows.

Check if two lists are equal

Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement), 
                         SecondList.OrderBy(sElement => sElement))

Insert an item into sorted list in Python

# function to insert a number in an sorted list


def pstatement(value_returned):
    return print('new sorted list =', value_returned)


def insert(input, n):
    print('input list = ', input)
    print('number to insert = ', n)
    print('range to iterate is =', len(input))

    first = input[0]
    print('first element =', first)
    last = input[-1]
    print('last element =', last)

    if first > n:
        list = [n] + input[:]
        return pstatement(list)
    elif last < n:
        list = input[:] + [n]
        return pstatement(list)
    else:
        for i in range(len(input)):
            if input[i] > n:
                break
    list = input[:i] + [n] + input[i:]
    return pstatement(list)

# Input values
listq = [2, 4, 5]
n = 1

insert(listq, n)

Where in memory are my variables stored in C?

You got some of these right, but whoever wrote the questions tricked you on at least one question:

  • global variables -------> data (correct)
  • static variables -------> data (correct)
  • constant data types -----> code and/or data. Consider string literals for a situation when a constant itself would be stored in the data segment, and references to it would be embedded in the code
  • local variables(declared and defined in functions) --------> stack (correct)
  • variables declared and defined in main function -----> heap also stack (the teacher was trying to trick you)
  • pointers(ex: char *arr, int *arr) -------> heap data or stack, depending on the context. C lets you declare a global or a static pointer, in which case the pointer itself would end up in the data segment.
  • dynamically allocated space(using malloc, calloc, realloc) --------> stack heap

It is worth mentioning that "stack" is officially called "automatic storage class".

How to add a new line in textarea element?

After lots of tests, following code works for me in Typescreipt

 export function ReplaceNewline(input: string) {
    var newline = String.fromCharCode(13, 10);
    return ReplaceAll(input, "<br>", newline.toString());
}
export function ReplaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}

Why does GitHub recommend HTTPS over SSH?

It's possible to argue that using SSHs key to authenticate is less secure because we tend to change our password more periodically than we generate new SSH keys.

Servers that limit the lifespan for which they'll honor given SSH keys can help force users toward the practice of refreshing SSH-keys periodically.

Cache an HTTP 'Get' service response in AngularJS?

Check out the library angular-cache if you like $http's built-in caching but want more control. You can use it to seamlessly augment $http cache with time-to-live, periodic purges, and the option of persisting the cache to localStorage so that it's available across sessions.

FWIW, it also provides tools and patterns for making your cache into a more dynamic sort of data-store that you can interact with as POJO's, rather than just the default JSON strings. Can't comment on the utility of that option as yet.

(Then, on top of that, related library angular-data is sort of a replacement for $resource and/or Restangular, and is dependent upon angular-cache.)

Preferred way of getting the selected item of a JComboBox

If you have only put (non-null) String references in the JComboBox, then either way is fine.

However, the first solution would also allow for future modifications in which you insert Integers, Doubless, LinkedLists etc. as items in the combo box.

To be robust against null values (still without casting) you may consider a third option:

String x = String.valueOf(JComboBox.getSelectedItem());

Find and replace with a newline in Visual Studio Code

Also note, after hitting the regex icon, to actually replace \n text with a newline, I had to use \\n as search and \n as replace.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data,response,error in
        if error != nil{
            print(error!.localizedDescription)
            return
        }
        if let responseJSON = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [String:AnyObject]{
            if let response_token:String = responseJSON["token"] as? String {
                print("Singleton Firebase Token : \(response_token)")
                completion(response_token)
            }
        }
    })
    task.resume()

How to use Git and Dropbox together?

I use Mercurial (or Git) + TrueCrypt + Dropbox for encrypted remote backups.

The coolest thing is that Dropbox does NOT sync the entire TrueCrypt container if you modify a small portion of your code. The sync time is roughly proportional to the amount of changes. Even though it's encrypted, the combination of TrueCrypt + Dropbox makes excellent usage of block cipher + block level sync.

Secondly, a monolithic encrypted container not just adds security, it also reduces chances of repository corruption .

Caution: However you have to be very careful about not having the container mounted while Dropbox is running. It can also be a pain to resolve conflicts if 2 different clients check-in different versions to the container. So, it's practical only for a single person using it for backups, not for a team.

Setup:

  • Create a Truecrypt container (multiple Gigabyte is fine)
  • Under Truecrypt preferences, uncheck preserve modification timestamp*.
  • Create a repo as mentioned above by Dan ( https://stackoverflow.com/a/1961515/781695 )

Usage:

  • Quit Dropbox
  • Mount the container, push your changes, unmount
  • Run dropbox

P.S. Unchecking the preserve modification timestamp tells dropbox that the file has been modified and it should be sync'd. Note that mounting the container modifies the timestamp even if you don't change any file in it. If you don't want that to happen, simply mount the volume as read-only

Could not find a part of the path ... bin\roslyn\csc.exe

Open the project file and remove all references with Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0....

Open web.config and remove all system.codedom compilers attributes

getActionBar() returns null

In my case, I had this in my code which did not work:

@Override
protected void onCreate(Bundle savedInstanceState) {
    context = getApplicationContext();

    requestWindowFeature(Window.FEATURE_ACTION_BAR);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
}

Then I played with the order of the code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_ACTION_BAR);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    context = getApplicationContext();
}

And it worked!

Conclusion: requestWindowFeature should be the first thing you call in the onCreate method.

Eclipse does not start when I run the exe?

I tried everything except this. After rigorous trials,Uninstalling java 8 update 25 helped me.

Has anyone ever got a remote JMX JConsole to work?

When testing/debugging/diagnosing remote JMX problems, first always try to connect on the same host that contains the MBeanServer (i.e. localhost), to rule out network and other non-JMX specific problems.

How to put multiple statements in one line?

Yes this post is 8 years old, but incase someone comes on here also looking for an answer: you can now just use semicolons. However, you cannot use if/elif/else staments, for/while loops, and you can't define functions. The main use of this would be when using imported modules where you don't have to define any functions or use any if/elif/else/for/while statements/loops.

Here's an example that takes the artist of a song, the song name, and searches genius for the lyrics:

import bs4, requests; song = input('Input artist then song name\n'); print(bs4.BeautifulSoup(requests.get(f'https://genius.com/{song.replace(" ", "-")}-lyrics').text,'html.parser').select('.lyrics')[0].text.strip())

<button> background image

You absolutely need a button tag element? because you can use instead an input type="button" element.

Then just link this CSS:

_x000D_
_x000D_
  input[type="button"]{
  width:150px;
  height:150px;
  /*just this*/ background-image: url(https://images.freeimages.com/images/large-previews/48d/marguerite-1372118.jpg);
  background-position: center;
  background-repeat: no-repeat;
  background-size: 150px 150px;
}
_x000D_
<input type="button"/>
_x000D_
_x000D_
_x000D_

How copy data from Excel to a table using Oracle SQL Developer

None of these options show up for me. The way to paste data from Excel is as follows:

  • Add an extra column to the left of your spreadsheet data (if you don't have row numbers showing in PL/SQL Developer you may not have to have an extra empty column to the left).

  • Copy the rows of data from your spreadsheet including the empty column.

  • In PL/SQL Developer, open your table in edit mode. You can right-click the table name in the object browser and select Edit Data or write your own select statement that includes the rowid and click the lock icon. Be sure your columns are ordered the same as in your spreadsheet.

  • Here's the part that took me forever to figure out: click on the left side of the first empty row to highlight it. It will not work if you don't have the first empty row highlighted.

  • Paste as usual using Ctrl+V or right-click Paste.

I couldn't find this info anywhere when I needed it, so I wanted to be sure to post it.

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

You may try the following if your database does not have any data OR you have another away to restore that data. You will need to know the Ubuntu server root password but not the mysql root password.

It is highly probably that many of us have installed "mysql_secure_installation" as this is a best practice. Navigate to bin directory where mysql_secure_installation exist. It can be found in the /bin directory on Ubuntu systems. By rerunning the installer, you will be prompted about whether to change root database password.

SHA-1 fingerprint of keystore certificate

This solution is for android studio 3.5 version:

  1. Open your project into Android studio.
  2. Click on Gradle tab on right side.
  3. Will see two things one is our project(root) and just app.
  4. Select our project in your case it might be your app.
  5. Right click on the project and refresh it.
  6. Then click on the the project drop don button.
  7. Click on the Tasks where will see android folder.
  8. Double Click on signingReport and will see the details in Run console.

Meaning of Open hashing and Closed hashing

The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).

In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.

This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)

How do you join tables from two different SQL Server instances in one SQL query

The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:

SELECT *
FROM server1table
    INNER JOIN server2.database.dbo.server2table ON .....

Material Design not styling alert dialogs

You could use

Material Design Library

Material Design Library made for pretty alert dialogs, buttons, and other things like snack bars. Currently it's heavily developed.

Guide, code, example - https://github.com/navasmdc/MaterialDesignLibrary

Guide how to add library to Android Studio 1.0 - How do I import material design library to Android Studio?

.

Happy coding ;)

Should each and every table have a primary key?

I am in the role of maintaining application created by offshore development team. Now I am having all kinds of issues in the application because original database schema did not contain PRIMARY KEYS on some tables. So please dont let other people suffer because of your poor design. It is always good idea to have primary keys on tables.

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

Warning: push.default is unset; its implicit value is changing in Git 2.0

I was wondering why I was getting that big warning message on Ubuntu 16.04 (which comes with Git 2.7.4), but not on Arch Linux. The reason is that the warning was removed in Git 2.8 (March 2016):

Across the transition at around Git version 2.0, the user used to get a pretty loud warning when running "git push" without setting push.default configuration variable. We no longer warn because the transition was completed a long time ago.

So you won't see the warning if you have Git 2.8 and later and don't need to set push.default unless you want to change the default 'simple' behavior.

CSS Selector "(A or B) and C"?

is there a better syntax?

No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c.

java - iterating a linked list

Linked list does guarantee sequential order.

Don't use linkedList.get(i), especially inside a sequential loop since it defeats the purpose of having a linked list and will be inefficient code.

Use ListIterator

    ListIterator<Object> iterator = myLinkedList.listIterator();
    while( iterator.hasNext()) {
        System.out.println(iterator.next());
    }

install cx_oracle for python

The following worked for me, both on mac and Linux. This one command should download needed additional files, without need need to set environment variables.

python -m pip install cx_Oracle --pre

Note, the --pre option is for development and pre-release of the Oracle driver. As of this posting, it was grabbing cx_Oracle-6.0rc1.tar.gz, which was needed. (I'm using python 3.6)

Shortest way to check for null and assign another value if not

Use the C# coalesce operator: ??

// if Value is not null, newValue = Value else if Value is null newValue is YournullValue
var newValue = Value ?? YourNullReplacement;

Is it possible to use a div as content for Twitter's Popover

here is an another example

<a   data-container = "body" data-toggle = "popover" data-placement = "left" 
    data-content = "&lt;img src='<?php echo baseImgUrl . $row1[2] ?>' width='250' height='100' &gt;&lt;div&gt;&lt;h3&gt; <?php echo $row1['1'] ?>&lt/h3&gt; &lt;p&gt; &lt;span&gt;<?php echo $countsss ?>videos &lt;/span&gt;
&lt;span&gt;<?php echo $countsss1 ?> followers&lt;/span&gt;
&lt;/p&gt;&lt;/div&gt;
<?php echo $row1['4'] ?>   &lt;hr&gt;&lt;div&gt;
&lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt;Follow  &lt;/button&gt;  &lt;/span&gt; &lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt; Go to channel page&lt;/button&gt;   &lt;/span&gt;&lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt;Close  &lt;/button&gt;  &lt;/span&gt;

 &lt;/div&gt;">

<?php echo $row1['1'] ?>
  </a>

ffmpeg usage to encode a video to H264 codec format

I believe you have libx264 installed and configured with ffmpeg to convert video to h264... Then you can try with -vcodec libx264... The -format option is for showing available formats, this is not a conversion option I think...

How to restart remote MySQL server running on Ubuntu linux?

  • To restart mysql use this command

sudo service mysql restart

Or

sudo restart mysql

Reference

How do implement a breadth first traversal?

Breadth first search

Queue<TreeNode> queue = new LinkedList<BinaryTree.TreeNode>() ;
public void breadth(TreeNode root) {
    if (root == null)
        return;
    queue.clear();
    queue.add(root);
    while(!queue.isEmpty()){
        TreeNode node = queue.remove();
        System.out.print(node.element + " ");
        if(node.left != null) queue.add(node.left);
        if(node.right != null) queue.add(node.right);
    }

}

How to print out all the elements of a List in Java?

System.out.println(list); works for me.

Here is a full example:

import java.util.List;    
import java.util.ArrayList;

public class HelloWorld {
     public static void main(String[] args) {
        final List<String> list = new ArrayList<>();
        list.add("Hello");
        list.add("World");
        System.out.println(list);
     }
}

It will print [Hello, World].

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

I checked the line 35 of xampp/apache/conf/httpd.conf and it was:

ServerRoot "/xampp/apache"

Which doesn't exist. ...

Create the directory, or change the path to the directory that contains your hypertext documents.

Use String.split() with multiple delimiters

Using Guava you could do this:

Iterable<String> tokens = Splitter.on(CharMatcher.anyOf("-.")).split(pdfName);

How to declare empty list and then add string in scala?

Per default collections in scala are immutable, so you have a + method which returns a new list with the element added to it. If you really need something like an add method you need a mutable collection, e.g. http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.html which has a += method.

How to read from a text file using VBScript?

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")

' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close

' Write file
outFile.write (strRetVal)
outFile.Close

PHP parse/syntax errors; and how to solve them

Unexpected '.'

This can occur if you are trying to use the splat operator(...) in an unsupported version of PHP.

... first became available in PHP 5.6 to capture a variable number of arguments to a function:

function concatenate($transform, ...$strings) {
    $string = '';
    foreach($strings as $piece) {
        $string .= $piece;
    }
    return($transform($string));
}

echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
// This would print:
// I'D LIKE 6 APPLES

In PHP 7.4, you could use it for Array expressions.

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];

Trigger change event of dropdown

If you are trying to have linked drop downs, the best way to do it is to have a script that returns the a prebuilt select box and an AJAX call that requests it.

Here is the documentation for jQuery's Ajax method if you need it.

$(document).ready(function(){

    $('#countrylist').change(function(e){
        $this = $(e.target);
        $.ajax({
            type: "POST",
            url: "scriptname.asp", // Don't know asp/asp.net at all so you will have to do this bit
            data: { country: $this.val() },
            success:function(data){
                $('#stateBoxHook').html(data);
            }
        });
    });

});

Then have a span around your state select box with the id of "stateBoxHook"

Peak detection in a 2D array

a rough outline...

you'd probably want to use a connected components algorithm to isolate each paw region. wiki has a decent description of this (with some code) here: http://en.wikipedia.org/wiki/Connected_Component_Labeling

you'll have to make a decision about whether to use 4 or 8 connectedness. personally, for most problems i prefer 6-connectedness. anyway, once you've separated out each "paw print" as a connected region, it should be easy enough to iterate through the region and find the maxima. once you've found the maxima, you could iteratively enlarge the region until you reach a predetermined threshold in order to identify it as a given "toe".

one subtle problem here is that as soon as you start using computer vision techniques to identify something as a right/left/front/rear paw and you start looking at individual toes, you have to start taking rotations, skews, and translations into account. this is accomplished through the analysis of so-called "moments". there are a few different moments to consider in vision applications:

central moments: translation invariant normalized moments: scaling and translation invariant hu moments: translation, scale, and rotation invariant

more information about moments can be found by searching "image moments" on wiki.

Recursive sub folder search and return files in a list python

If you don't mind installing an additional light library, you can do this:

pip install plazy

Usage:

import plazy

txt_filter = lambda x : True if x.endswith('.txt') else False
files = plazy.list_files(root='data', filter_func=txt_filter, is_include_root=True)

The result should look something like this:

['data/a.txt', 'data/b.txt', 'data/sub_dir/c.txt']

It works on both Python 2.7 and Python 3.

Github: https://github.com/kyzas/plazy#list-files

Disclaimer: I'm an author of plazy.

ASP.NET MVC Razor render without encoding

Since ASP.NET MVC 3, you can use:

@Html.Raw(myString)

How to truncate milliseconds off of a .NET DateTime

DateTime d = DateTime.Now;
d = d.AddMilliseconds(-d.Millisecond);

Nested ifelse statement

With data.table, the solutions is:

DT[, idnat2 := ifelse(idbp %in% "foreign", "foreign", 
        ifelse(idbp %in% c("colony", "overseas"), "overseas", "mainland" ))]

The ifelse is vectorized. The if-else is not. Here, DT is:

    idnat     idbp
1  french mainland
2  french   colony
3  french overseas
4 foreign  foreign

This gives:

   idnat     idbp   idnat2
1:  french mainland mainland
2:  french   colony overseas
3:  french overseas overseas
4: foreign  foreign  foreign

Click a button programmatically

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Button2_Click(Sender, e)
End Sub

This Code call button click event programmatically

How do I get sed to read from standard input?

If you are trying to do an in-place update of text within a file, this is much easier to reason about in my mind.

grep -Rl text_to_find directory_to_search 2>/dev/null | while read line; do  sed -i 's/text_to_find/replacement_text/g' $line; done

contenteditable change events

Non JQuery answer...

function makeEditable(elem){
    elem.setAttribute('contenteditable', 'true');
    elem.addEventListener('blur', function (evt) {
        elem.removeAttribute('contenteditable');
        elem.removeEventListener('blur', evt.target);
    });
    elem.focus();
}

To use it, call on (say) a header element with id="myHeader"

makeEditable(document.getElementById('myHeader'))

That element will now be editable by the user until it loses focus.

How to encode a string in JavaScript for displaying in HTML?

You need to escape < and &. Escaping > too doesn't hurt:

function magic(input) {
    input = input.replace(/&/g, '&amp;');
    input = input.replace(/</g, '&lt;');
    input = input.replace(/>/g, '&gt;');
    return input;
}

Or you let the DOM engine do the dirty work for you (using jQuery because I'm lazy):

function magic(input) {
    return $('<span>').text(input).html();
}

What this does is creating a dummy element, assigning your string as its textContent (i.e. no HTML-specific characters have side effects since it's just text) and then you retrieve the HTML content of that element - which is the text but with special characters converted to HTML entities in cases where it's necessary.

Add element to a list In Scala

You are using an immutable list. The operations on the List return a new List. The old List remains unchanged. This can be very useful if another class / method holds a reference to the original collection and is relying on it remaining unchanged. You can either use different named vals as in

val myList1 = 1.0 :: 5.5 :: Nil 
val myList2 = 2.2 :: 3.7 :: mylist1

or use a var as in

var myList = 1.0 :: 5.5 :: Nil 
myList :::= List(2.2, 3.7)

This is equivalent syntax for:

myList = myList.:::(List(2.2, 3.7))

Or you could use one of the mutable collections such as

val myList = scala.collection.mutable.MutableList(1.0, 5.5)
myList.++=(List(2.2, 3.7))

Not to be confused with the following that does not modify the original mutable List, but returns a new value:

myList.++:(List(2.2, 3.7))

However you should only use mutable collections in performance critical code. Immutable collections are much easier to reason about and use. One big advantage is that immutable List and scala.collection.immutable.Vector are Covariant. Don't worry if that doesn't mean anything to you yet. The advantage of it is you can use it without fully understanding it. Hence the collection you were using by default is actually scala.collection.immutable.List its just imported for you automatically.

I tend to use List as my default collection. From 2.12.6 Seq defaults to immutable Seq prior to this it defaulted to immutable.

Getting new Twitter API consumer and secret keys

  1. Log into the Twitter Developers section.

    • If you don't already have an account, you can login with your normal Twitter credentials
  2. Go to "Create an app"

  3. Fill in the details of the application you'll be using to connect with the API

    • Your application name must be unique. If someone else is already using it, you won't be able to register your application until you can think of something that isn't being used.
  4. Click on Create your Twitter application

  5. Details of your new app will be shown along with your consumer key and consumer secret.

  6. If you need access tokens, scroll down and click Create my access token

    • The page will then refresh on the "Details" tab with your new access tokens. You can recreate these at any time if you need to.

By default your apps will be granted for read-only access. To change this, go to the Settings tab and change the access level required in the "Application Type" section.

Existing apps

To get the consumer and access tokens for an existing application, go to My applications (which is available from the menu in the upper-right).

Print line numbers starting at zero using awk

If Perl is an option, you can try this:

perl -ne 'printf "%s,$_" , $.-1' file

$_ is the line
$. is the line number

Vue.js redirection to another page

According to the docs, router.push seems like the preferred method:

To navigate to a different URL, use router.push. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.

source: https://router.vuejs.org/en/essentials/navigation.html

FYI : Webpack & component setup, single page app (where you import the router through Main.js), I had to call the router functions by saying:

this.$router

Example: if you wanted to redirect to a route called "Home" after a condition is met:

this.$router.push('Home') 

How do I REALLY reset the Visual Studio window layout?

Note: if you have vs2010 and vs2008 and you want to reset the 2008, you will need to specify in command line the whole path. like this:

"C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe" /resetsettings

If you don't specify the path (like devenv.exe /resetsettings), it will reset the latest version of Visual studio installed on your computer.

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

By changing proxy settings to "no proxy" in netbeans the tomcat prbolem got solved.Try this it's seriously working.

JavaScript null check

The simple way to do your test is :

function (data) {
    if (data) { // check if null, undefined, empty ...
        // some code here
    }
}

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

How do you use "git --bare init" repository?

The --bare flag creates a repository that doesn’t have a working directory. The bare repository is the central repository and you can't edit(store) codes here for avoiding the merging error.

For example, when you add a file in your local repository (machine 1) and push it to the bare repository, you can't see the file in the bare repository for it is always 'empty'. However, you really push something to the repository and you can see it inexplicitly by cloning another repository in your server(machine 2).

Both the local repository in machine 1 and the 'copy' repository in machine 2 are non-bare. relationship between bare and non-bare repositories

The blog will help you understand it. https://www.atlassian.com/git/tutorials/setting-up-a-repository

How may I align text to the left and text to the right in the same line?

If you just want to change alignment of text just make a classes

.left {
text-align: left;
}

and span that class through the text

<span class='left'>aligned left</span>

JavaScript: location.href to open in new window/tab?

window.open(
  'https://support.wwf.org.uk/earth_hour/index.php?type=individual',
  '_blank' // <- This is what makes it open in a new window.
);

How to auto-remove trailing whitespace in Eclipse?

You don't need any plugin to do so. For instance, if you code JAVA, you can erase trailing whitespaces configuring save actions:

Eclipse 3.6

Preferences -> Java -> Editors -> Save Actions -> Check Perform the selected actions on save -> Check Additional actions -> Click the Configure.. button.

In the Code organizing tab, check Remove trailing whitespace

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Tapestry pages and components are simple POJO's(Plain Old Java Object) consisting of getters and setters for easy access to Java language features.

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Difference in months between two dates

Use Noda Time:

LocalDate start = new LocalDate(2013, 1, 5);
LocalDate end = new LocalDate(2014, 6, 1);
Period period = Period.Between(start, end, PeriodUnits.Months);
Console.WriteLine(period.Months); // 16

(example source)

C# Convert a Base64 -> byte[]

Try

byte[] incomingByteArray = receive...; // This is your Base64-encoded bute[]

byte[] decodedByteArray =Convert.FromBase64String (Encoding.ASCII.GetString (incomingByteArray)); 
// This work because all Base64-encoding is done with pure ASCII characters

How to encode the plus (+) symbol in a URL

The + character has a special meaning in a URL => it means whitespace - . If you want to use the literal + sign, you need to URL encode it to %2b:

body=Hi+there%2bHello+there

Here's an example of how you could properly generate URLs in .NET:

var uriBuilder = new UriBuilder("https://mail.google.com/mail");

var values = HttpUtility.ParseQueryString(string.Empty);
values["view"] = "cm";
values["tf"] = "0";
values["to"] = "[email protected]";
values["su"] = "some subject";
values["body"] = "Hi there+Hello there";

uriBuilder.Query = values.ToString();

Console.WriteLine(uriBuilder.ToString());

The result

https://mail.google.com:443/mail?view=cm&tf=0&to=someemail%40somedomain.com&su=some+subject&body=Hi+there%2bHello+there

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

I was having the same problems with the JVM that App Inventor for Android Blocks Editor uses. It sets the heap at 925m max. This is not enough but I couldn't set it more than about 1200m, depending on various random factors on my machine.

I downloaded Nightly, the beta 64-bit browser from Firefox, and also JAVA 7 64 bit version.

I haven't yet found my new heap limit, but I just opened a JVM with a heap size of 5900m. No problem!

I am running Win 7 64 bit Ultimate on a machine with 24gb RAM.

How to find the path of Flutter SDK

If you've installed flutter from the snap store on Ubuntu, you'll find the SDK at /home/(username)/snap/flutter/common/flutter

FYI - I installed Flutter on Ubuntu 20.04 LTS using snap install and am using Android Studio 4.0.1 installed via JetBrains toolbox app

sudo snap install flutter --classic
sudo snap install flutter-gallery
flutter channel dev
flutter upgrade
flutter config --enable-linux-desktop

It was not necessary to install the SDK separately, the snap steps above will place the SDK at /home/(username)/snap/flutter/common/flutter

Here's the Android Studio Pop-up for a new Flutter app accepting this location for the Flutter SDK:

Flutter SDK Path

How to print GETDATE() in SQL Server with milliseconds in time?

these 2 are the same:

Print CAST(GETDATE() as Datetime2 (3) )
PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))

enter image description here

Find intersection of two nested lists?

If you want:

c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [[13, 32], [7, 13, 28], [1,6]]

Then here is your solution for Python 2:

c3 = [filter(lambda x: x in c1, sublist) for sublist in c2]

In Python 3 filter returns an iterable instead of list, so you need to wrap filter calls with list():

c3 = [list(filter(lambda x: x in c1, sublist)) for sublist in c2]

Explanation:

The filter part takes each sublist's item and checks to see if it is in the source list c1. The list comprehension is executed for each sublist in c2.

Operation must use an updatable query. (Error 3073) Microsoft Access

In essence, while your SQL looks perfectly reasonable, Jet has never supported the SQL standard syntax for UPDATE. Instead, it uses its own proprietary syntax (different again from SQL Server's proprietary UPDATE syntax) which is very limited. Often, the only workarounds "Operation must use an updatable query" are very painful. Seriously consider switching to a more capable SQL product.

For some more details about your specific problems and some possible workarounds, see Update Query Based on Totals Query Fails.

ModelState.AddModelError - How can I add an error that isn't for a property?

Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");

What is Ruby's double-colon `::`?

It is all about preventing definitions from clashing with other code linked in to your project. It means you can keep things separate.

For example you can have one method called "run" in your code and you will still be able to call your method rather than the "run" method that has been defined in some other library that you have linked in.

Thread Safe C# Singleton Pattern

Another version of Singleton where the following line of code creates the Singleton instance at the time of application startup.

private static readonly Singleton singleInstance = new Singleton();

Here CLR (Common Language Runtime) will take care of object initialization and thread safety. That means we will not require to write any code explicitly for handling the thread safety for a multithreaded environment.

"The Eager loading in singleton design pattern is nothing a process in which we need to initialize the singleton object at the time of application start-up rather than on demand and keep it ready in memory to be used in future."

public sealed class Singleton
    {
        private static int counter = 0;
        private Singleton()
        {
            counter++;
            Console.WriteLine("Counter Value " + counter.ToString());
        }
        private static readonly Singleton singleInstance = new Singleton(); 

        public static Singleton GetInstance
        {
            get
            {
                return singleInstance;
            }
        }
        public void PrintDetails(string message)
        {
            Console.WriteLine(message);
        }
    }

from main :

static void Main(string[] args)
        {
            Parallel.Invoke(
                () => PrintTeacherDetails(),
                () => PrintStudentdetails()
                );
            Console.ReadLine();
        }
        private static void PrintTeacherDetails()
        {
            Singleton fromTeacher = Singleton.GetInstance;
            fromTeacher.PrintDetails("From Teacher");
        }
        private static void PrintStudentdetails()
        {
            Singleton fromStudent = Singleton.GetInstance;
            fromStudent.PrintDetails("From Student");
        }

Can I position an element fixed relative to parent?

first, set position: fixed and left: 50%, and second — now your start is a center and you can set new position with margin.

How to use icons and symbols from "Font Awesome" on Native Android Application

Initially create asset folder and copy the fontawesome icon (.ttf) How to create asset folder?

app-->right Click -->new-->folder --> asset folder

next step download how to download .ttf file? click here--> and click download button after download extract and open web fonts. finally choose true text style(ttf)paste asset folder.

how to design xml and java file in android ?

app-->res-->values string.xml

resources
    string name="calander_font" >&#xf073; <string
resources

this example of one font more Unicode click here

Activity_main.xml

 <TextView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:id="@+id/calander_view"/>

MainActivity.java

calander_tv = (TextView)findViewById(R.id.calander_view);

Typeface typeface = Typeface.createFromAsset(getAssets(),"/fonts/fa-solid-900.ttf");
calander_tv.setTypeface(typeface);
calander_tv.setText(R.string.calander_font);

Output:

Output image

Remove the last character in a string in T-SQL?

If for some reason your column logic is complex (case when ... then ... else ... end), then the above solutions causes you to have to repeat the same logic in the len() function. Duplicating the same logic becomes a mess. If this is the case then this is a solution worth noting. This example gets rid of the last unwanted comma. I finally found a use for the REVERSE function.

select reverse(stuff(reverse('a,b,c,d,'), 1, 1, ''))

spring autowiring with unique beans: Spring expected single matching bean but found 2

The issue is because you have a bean of type SuggestionService created through @Component annotation and also through the XML config . As explained by JB Nizet, this will lead to the creation of a bean with name 'suggestionService' created via @Component and another with name 'SuggestionService' created through XML .

When you refer SuggestionService by @Autowired, in your controller, Spring autowires "by type" by default and find two beans of type 'SuggestionService'

You could do the following

  1. Remove @Component from your Service and depend on mapping via XML - Easiest

  2. Remove SuggestionService from XML and autowire the dependencies - use util:map to inject the indexSearchers map.

  3. Use @Resource instead of @Autowired to pick the bean by its name .

     @Resource(name="suggestionService")
     private SuggestionService service;
    

or

    @Resource(name="SuggestionService")
    private SuggestionService service;

both should work.The third is a dirty fix and it's best to resolve the bean conflict through other ways.

Python JSON serialize a Decimal object

Simplejson 2.1 and higher has native support for Decimal type:

>>> json.dumps(Decimal('3.9'), use_decimal=True)
'3.9'

Note that use_decimal is True by default:

def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
    allow_nan=True, cls=None, indent=None, separators=None,
    encoding='utf-8', default=None, use_decimal=True,
    namedtuple_as_object=True, tuple_as_array=True,
    bigint_as_string=False, sort_keys=False, item_sort_key=None,
    for_json=False, ignore_nan=False, **kw):

So:

>>> json.dumps(Decimal('3.9'))
'3.9'

Hopefully, this feature will be included in standard library.

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

Hopefully people will find this answer as there are many, many posts about this on the web. Many people suggested it was an .htaccess problem, and for me it was. However, I had been looking in the .htaccess in the root, not in the .htaccess in the wp-admin folder. Normally, I work on this site in particular through terminal services, so when it booted me and I couldn't log back in, I was trying to access it from my home computer (and it's IP).

Silly me forgot the IP restriction I had placed in the wp-admin .htaccess file.

AuthName "Protected"
AuthType Basic
<Limit GET POST>
order deny,allow
deny from all
allow from 11.11.11.11
</Limit> 

If you have something like this in your wp-admin .htaccess files, that would easily explain why all the sites you work on ceased to function at the same time. Internet providers occasionally rotate IPs so that nobody is running a server from home without paying for it.