Programs & Examples On #Srid

How to run Java program in command prompt

javac only compiles the code. You need to use java command to run the code. The error is because your classpath doesn't contain the class Subclass iwhen you tried to compile it. you need to add them with the -cp variable in javac command

java -cp classpath-entries mainjava arg1 arg2 should run your code with 2 arguments

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

in my case it was pulse secure vpn tripping up Visual Studio 2019 community edition for some reason ! workaround is to suspend vpn, start debug solution, then resume vpn connection.

Using port number in Windows host file

Fiddler2 -> Rules -> Custom Rules

then find function OnBeforeRequest on put in the next script at the end:

if (oSession.HostnameIs("mysite.com")){
    oSession.host="localhost:39901";
}

How can I compile LaTeX in UTF8?

I use LEd Editor with special "Filter" feature. It replaces \"{o} with ö and vice versa in its own editor, while maintaining original \"{o} in tex files. This makes text easily readable when viewed in LEd Editor and there is no need for special packages. It works with bibliography files too.

How to check if current thread is not main thread

A simple Toast message works also as a quick check.

Get selected key/value of a combo box using jQuery

$("#elementName option").text(); 

This will give selected text of Combo-Box.

$("#elementName option").val();

This will give selected value associated selected item in Combo-Box.

$("#elementName option").length;

It will give the multi-select combobox values in the array and length will give number of element of the array.

Note:#elementName is id the Combo-box.

How can I backup a Docker-container with its data-volumes?

If you want a complete backup, you will need to perform a few steps:

  1. Commit the container to an image
  2. Save the image
  3. Backup the container's volume by creating a tar file of the volume's mount point in the container.
  4. Repeat steps 1-3 for the database container as well.

Note that doing just a Docker commit of the container to an image does NOT include volumes attached to the container (ref: Docker commit documentation).

"The commit operation will not include any data contained in volumes mounted inside the container."

Why is HttpClient BaseAddress not working?

Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.

If base URI contains non-empty path, merge procedure discards it's last part (after last /). Relevant section:

5.2.3. Merge Paths

The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:

  • If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise

  • return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).

If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.

Linking dll in Visual Studio

Assume that the source file you want to compile is main.cpp and your example_dll.dll and example_dll.lib . now run cl.exe main.cpp /EHsc /link example_dll.lib now you may get main.exe

Get gateway ip address in android

Go to terminal

$ adb -s UDID shell
$ ip addr | grep inet 
or
$ netcfg | grep inet

Storing query results into a variable and modifying it inside a Stored Procedure

Try this example

CREATE PROCEDURE MyProc
BEGIN
    --Stored Procedure variables
    Declare @maxOr int; 
    Declare @maxCa int; 

    --Getting query result in the variable (first variant of syntax)
    SET @maxOr = (SELECT MAX(orId) FROM [order]); 

    --Another variant of seting variable from query
    SELECT @maxCa=MAX(caId) FROM [cart]; 

    --Updating record through the variable
    INSERT INTO [order_cart] (orId,caId)
    VALUES(@maxOr, @maxCa); 

    --return values to the program as dataset
    SELECT
       @maxOr AS maxOr,
       @maxCa AS maxCa

    -- return one int value as "return value"
    RETURN @maxOr
END
GO

SQL-command to call the stored procedure

EXEC MyProc

How to set a default value for an existing column

Just Found 3 simple steps to alter already existing column that was null before

update   orders
set BasicHours=0 where BasicHours is null

alter table orders 
add default(0) for BasicHours

alter table orders 
alter  column CleanBasicHours decimal(7,2) not null 

Why are C++ inline functions in the header?

The reason is that the compiler has to actually see the definition in order to be able to drop it in in place of the call.

Remember that C and C++ use a very simplistic compilation model, where the compiler always only sees one translation unit at a time. (This fails for export, which is the main reason only one vendor actually implemented it.)

How read Doc or Docx file in java?

Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
{
    public static void main(String[] args)
    {
        File file = null;
        WordExtractor extractor = null;
        try
        {

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
            {
                if (fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch (Exception exep)
        {
            exep.printStackTrace();
        }
    }
}

What are the true benefits of ExpandoObject?

After valueTuples, what's the use of ExpandoObject class? this 6 lines code with ExpandoObject:

dynamic T = new ExpandoObject();
T.x = 1;
T.y = 2;
T.z = new ExpandoObject();
T.z.a = 3;
T.b= 4;

can be written in one line with tuples:

var T = (x: 1, y: 2, z: (a: 3, b: 4));

besides with tuple syntax you have strong type inference and intlisense support

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

git push rejected: error: failed to push some refs

for me following worked, just ran these command one by one

git pull -r origin master

git push -f origin your_branch

How to refer to relative paths of resources when working with a code repository

In Python, paths are relative to the current working directory, which in most cases is the directory from which you run your program. The current working directory is very likely not as same as the directory of your module file, so using a path relative to your current module file is always a bad choice.

Using absolute path should be the best solution:

import os
package_dir = os.path.dirname(os.path.abspath(__file__))
thefile = os.path.join(package_dir,'test.cvs')

Replace None with NaN in pandas dataframe

If you use df.replace([None], np.nan, inplace=True), this changed all datetime objects with missing data to object dtypes. So now you may have broken queries unless you change them back to datetime which can be taxing depending on the size of your data.

If you want to use this method, you can first identify the object dtype fields in your df and then replace the None:

obj_columns = list(df.select_dtypes(include=['object']).columns.values)
df[obj_columns] = df[obj_columns].replace([None], np.nan)

Is there a macro to conditionally copy rows to another worksheet?

If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?

Disable same origin policy in Chrome

Used below command in Ubuntu to start chrome (disable same origin policy and open chrome in detached mode):

nohup google-chrome --disable-web-security --user-data-dir='/tmp' &

How to use custom font in a project written in Android Studio

First create assets folder then create fonts folder in it.

Then you can set font from assets or directory like bellow :

public class FontSampler extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        TextView tv = (TextView) findViewById(R.id.custom);
        Typeface face = Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");

        tv.setTypeface(face);

        File font = new File(Environment.getExternalStorageDirectory(), "MgOpenCosmeticaBold.ttf");

        if (font.exists()) {
            tv = (TextView) findViewById(R.id.file);
            face = Typeface.createFromFile(font);

            tv.setTypeface(face);
        } else {
            findViewById(R.id.filerow).setVisibility(View.GONE);
        }
    }
} 

How to test REST API using Chrome's extension "Advanced Rest Client"

The discoverability is dismal, but it's quite clever how Advanced Rest Client handles basic authentication. The shortcut abraham mentioned didn't work for me, but a little poking around revealed how it does it.

The first thing you need to do is add the Authorization header: menus

Then, a nifty little thing pops up when you focus the value input (note the "construct" box in the lower right): construct the auth value

Clicking it will bring up a box. It even does OAuth, if you want! convenient inputs

Tada! If you leave the value field blank when you click "construct," it will add the Basic part to it (I assume it will also add the necessary OAuth stuff, too, but I didn't try that, as my current needs were for basic authentication), so you don't need to do anything. fills in the field as needed

Android difference between Two Dates

Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
Date today = new Date();
long diff =  today.getTime() - userDob.getTime();
int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
int hours = (int) (diff / (1000 * 60 * 60));
int minutes = (int) (diff / (1000 * 60));
int seconds = (int) (diff / (1000));

How to resize an Image C#

Use below function with below example for changing image size :

//Example : 
System.Net.Mime.MediaTypeNames.Image newImage = System.Net.Mime.MediaTypeNames.Image.FromFile("SampImag.jpg");
System.Net.Mime.MediaTypeNames.Image temImag = FormatImage(newImage, 100, 100);

//image size modification unction   
public static System.Net.Mime.MediaTypeNames.Image FormatImage(System.Net.Mime.MediaTypeNames.Image img, int outputWidth, int outputHeight)
{

    Bitmap outputImage = null;
    Graphics graphics = null;
    try
    {
         outputImage = new Bitmap(outputWidth, outputHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
         graphics = Graphics.FromImage(outputImage);
         graphics.DrawImage(img, new Rectangle(0, 0, outputWidth, outputHeight),
         new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);

         return outputImage;
     }
     catch (Exception ex)
     {
           return img;
     }
}

Docker command can't connect to Docker daemon

For Ubuntu 16.04

Inside file /lib/systemd/system/docker.service change:

ExecStart=/usr/bin/dockerd fd://

with:

ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375

Inside file /etc/init.d/docker change:

DOCKER_OPTS=

with:

DOCKER_OPTS="-H tcp://0.0.0.0:2375"

and then restart your computer.

Error TF30063: You are not authorized to access ... \DefaultCollection

I got this error, after all fiddling work I could do — the disk space was full!

Clearing it fixed my issue.

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

I found this question because having trouble with configparser.ConfigParser().read(fp) when opening files with UTF8 BOM header.

For those who are looking for a solution to remove the header so that ConfigPhaser could open the config file instead of reporting an error of: File contains no section headers, please open the file like the following:

configparser.ConfigParser().read(config_file_path, encoding="utf-8-sig")

This could save you tons of effort by making the remove of the BOM header of the file unnecessary.

(I know this sounds unrelated, but hopefully this could help people struggling like me.)

Using PHP Replace SPACES in URLS with %20

Use urlencode() rather than trying to implement your own. Be lazy.

Open text file and program shortcut in a Windows batch file

I was able to figure out the solution:

start notepad "myfile.txt"
"myshortcut.lnk"
exit

Firefox 'Cross-Origin Request Blocked' despite headers

I've found solution after 2 days :(.

Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials

How do I convert from BLOB to TEXT in MySQL?

None of these answers worked for me. When converting to UTF8, when the encoder encounters a set of bytes it can't convert to UTF8 it will result in a ? substitution which results in data loss. You need to use UTF16:

SELECT
    blobfield,
    CONVERT(blobfield USING utf16),
    CONVERT(CONVERT(blobfield USING utf16), BINARY),
    CAST(blobfield  AS CHAR(10000) CHARACTER SET utf16),
    CAST(CAST(blobfield  AS CHAR(10000) CHARACTER SET utf16) AS BINARY)

You can inspect the binary values in MySQL Workbench. Right click on the field -> Open Value in Viewer-> Binary. When converted back to BINARY the binary values should be the same as the original.

Alternatively, you can just use base-64 which was made for this purpose:

SELECT
    blobfield,
    TO_BASE64(blobfield),
    FROM_BASE64(TO_BASE64(blobfield))

Concatenating string and integer in python

String formatting, using the new-style .format() method (with the defaults .format() provides):

 '{}{}'.format(s, i)

Or the older, but "still sticking around", %-formatting:

 '%s%d' %(s, i)

In both examples above there's no space between the two items concatenated. If space is needed, it can simply be added in the format strings.

These provide a lot of control and flexibility about how to concatenate items, the space between them etc. For details about format specifications see this.

Homebrew: Could not symlink, /usr/local/bin is not writable

I found same problem, we can resolve in three steps:-

Step 1

sudo chown -R $(whoami) $(brew --prefix)/*

Step 2

brew doctor

Step 3

brew prune

If you still get any linking problem, lets say for mysql, just write

brew link mysql

This will work.

angular-cli server - how to specify default port

In Angular 2 [email protected],

To run a new project on the different port, one way is to specify the port while you run ng serve command.

ng serve --port 4201

or the other way, you can edit your package.json file scripts part and attached the port to your start variable like I mentioned below and then simply run "npm start"

 "scripts": {

    "ng": "ng",
    "start": "ng serve --port 4201",
    ... : ...,
    ... : ....
}

this way is much better where you don't need to define port explicitly every time.

@AspectJ pointcut for all methods of a class with specific annotation

Using annotations, as described in the question.

Annotation: @Monitor

Annotation on class, app/PagesController.java:

package app;
@Controller
@Monitor
public class PagesController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Annotation on method, app/PagesController.java:

package app;
@Controller
public class PagesController {
    @Monitor
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Custom annotation, app/Monitor.java:

package app;
@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Monitor {
}

Aspect for annotation, app/MonitorAspect.java:

package app;
@Component
@Aspect
public class MonitorAspect {
    @Before(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void before(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }

    @After(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void after(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }
}

Enable AspectJ, servlet-context.xml:

<aop:aspectj-autoproxy />

Include AspectJ libraries, pom.xml:

<artifactId>spring-aop</artifactId>
<artifactId>aspectjrt</artifactId>
<artifactId>aspectjweaver</artifactId>
<artifactId>cglib</artifactId>

Why should a Java class implement comparable?

Most of the examples above show how to reuse an existing comparable object in the compareTo function. If you would like to implement your own compareTo when you want to compare two objects of the same class, say an AirlineTicket object that you would like to sort by price(less is ranked first), followed by number of stopover (again, less is ranked first), you would do the following:

class AirlineTicket implements Comparable<Cost>
{
    public double cost;
    public int stopovers;
    public AirlineTicket(double cost, int stopovers)
    {
        this.cost = cost; this.stopovers = stopovers ;
    }

    public int compareTo(Cost o)
    {
        if(this.cost != o.cost)
          return Double.compare(this.cost, o.cost); //sorting in ascending order. 
        if(this.stopovers != o.stopovers)
          return this.stopovers - o.stopovers; //again, ascending but swap the two if you want descending
        return 0;            
    }
}

Created Button Click Event c#

    public MainWindow()
    {
        // This button needs to exist on your form.
        myButton.Click += myButton_Click;
    }

    void myButton_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Message here");
        this.Close();
    }

Is there a REAL performance difference between INT and VARCHAR primary keys?

For short codes, there's probably no difference. This is especially true as the table holding these codes are likely to be very small (a couple thousand rows at most) and not change often (when is the last time we added a new US State).

For larger tables with a wider variation among the key, this can be dangerous. Think about using e-mail address/user name from a User table, for example. What happens when you have a few million users and some of those users have long names or e-mail addresses. Now any time you need to join this table using that key it becomes much more expensive.

How to import local packages in go?

Well, I figured out the problem. Basically Go starting path for import is $HOME/go/src

So I just needed to add myapp in front of the package names, that is, the import should be:

import (
    "log"
    "net/http"
    "myapp/common"
    "myapp/routers"
)

delete image from folder PHP

First Check that is image exists? if yes then simply Call unlink(your file path) function to remove you file otherwise show message to the user.

              if (file_exists($filePath)) 
               {
                 unlink($filePath);
                  echo "File Successfully Delete."; 
              }
              else
              {
               echo "File does not exists"; 
              }

Real mouse position in canvas

You can get the mouse positions by using this snippet:

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
        y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
    };
}

This code takes into account both changing coordinates to canvas space (evt.clientX - rect.left) and scaling when canvas logical size differs from its style size (/ (rect.right - rect.left) * canvas.width see: Canvas width and height in HTML5).

Example: http://jsfiddle.net/sierawski/4xezb7nL/

Source: jerryj comment on http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/

7-zip commandline

I've not looked into this but shooting from the hip I'd say that they dropped command line support in the portable. The reason people don't do much command line stuff in portable applications is that the OS (windows in your case) requires that executables be added to the %path% inclusion list.

If that requirement is not met using command line utilities is rather tedious.

7z -a .

would be

d:\portable\z7\z7 -a c:\to\archive\folder*.*

Typing that out for everything is why GUI's make sense with things like portable apps it (the app) can remember it's own location and handle that stuff for you and if you can't run it you know it's not attached.

If you really want the portable app to contain that though you can always install the full version and pull the required 7z.exe out and put it into the portable folder making sure it's in with the required dll's.

You'll have to set your path when you hit the shell after making sure it's attached.

http://www.redfernplace.com/software-projects/patheditor/ -- a good path editor (down) usefull if you have lots of path information 20+ get's hard to read.

http://www.softpedia.com/get/System/System-Miscellaneous/Path-Editor.shtml -- alternet source for path editor

It's not advisable to modify your system path for temproary "portable" drives though manualy do that by:

set path=%path%;"d:\portable\z7\";

when you run dos cmd.exe or http://sourceforge.net/p/conemu/home/Home/

The other answers address other problems better I'm not going to try..

http://www.codejacked.com/zip-up-files-from-the-command-line/ -- good reference for command line usage of z7 and z7a.

PS: sorry for the necro but I figured it needed a more direct answer to why (even if it's just speculative).

Regex remove all special characters except numbers?

Use the global flag:

var name = name.replace(/[^a-zA-Z ]/g, "");
                                    ^

If you don't want to remove numbers, add it to the class:

var name = name.replace(/[^a-zA-Z0-9 ]/g, "");

How to encode URL to avoid special characters in Java?

If you don't want to do it manually use Apache Commons - Codec library. The class you are looking at is: org.apache.commons.codec.net.URLCodec

String final url = "http://www.google.com?...."
String final urlSafe = org.apache.commons.codec.net.URLCodec.encode(url);

How do I write a backslash (\) in a string?

The backslash ("\") character is a special escape character used to indicate other special characters such as new lines (\n), tabs (\t), or quotation marks (\").

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string:

var s = "\\Tasks";
// or 
var s = @"\Tasks";

Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.

Generally speaking, most C# .NET developers tend to favour using the @ verbatim strings when building file/folder paths since it saves them from having to write double backslashes all the time and they can directly copy/paste the path, so I would suggest that you get in the habit of doing the same.


That all said, in this case, I would actually recommend you use the Path.Combine utility method as in @lordkain's answer as then you don't need to worry about whether backslashes are already included in the paths and accidentally doubling-up the slashes or omitting them altogether when combining parts of paths.

jQuery: Selecting by class and input type

Try this:

$("input:checkbox").hasClass("myClass");

How to implement swipe gestures for mobile devices?

Have you tried Hammerjs? It supports swipe gestures by using the velocity of the touch. http://eightmedia.github.com/hammer.js/

linking jquery in html

Seeing the answers I have nothing else to add but one more thing:

in your test.html file you have written

link rel="stylesheet" type="css/text" href="test.css"/

see where you have written

type="css/text"

there you need to change into

type="text/css"

so it will look like that

link rel="stylesheet" type="text/css" href="test.css"/

and in this case the CSS file will be linked to HTML file

Angular2 change detection: ngOnChanges not firing for nested object

rawLapsData continues to point to the same array, even if you modify the contents of the array (e.g., add items, remove items, change an item).

During change detection, when Angular checks components' input properties for change, it uses (essentially) === for dirty checking. For arrays, this means the array references (only) are dirty checked. Since the rawLapsData array reference isn't changing, ngOnChanges() will not be called.

I can think of two possible solutions:

  1. Implement ngDoCheck() and perform your own change detection logic to determine if the array contents have changed. (The Lifecycle Hooks doc has an example.)

  2. Assign a new array to rawLapsData whenever you make any changes to the array contents. Then ngOnChanges() will be called because the array (reference) will appear as a change.

In your answer, you came up with another solution.

Repeating some comments here on the OP:

I still don't see how laps can pick up on the change (surely it must be using something equivalent to ngOnChanges() itself?) while map can't.

  • In the laps component your code/template loops over each entry in the lapsData array, and displays the contents, so there are Angular bindings on each piece of data that is displayed.
  • Even when Angular doesn't detect any changes to a component's input properties (using === checking), it still (by default) dirty checks all of the template bindings. When any of those change, Angular will update the DOM. That's what you are seeing.
  • The maps component likely doesn't have any bindings in its template to its lapsData input property, right? That would explain the difference.

Note that lapsData in both components and rawLapsData in the parent component all point to the same/one array. So even though Angular doesn't notice any (reference) changes to the lapsData input properties, the components "get"/see any array contents changes because they all share/reference that one array. We don't need Angular to propagate these changes, like we would with a primitive type (string, number, boolean). But with a primitive type, any change to the value would always trigger ngOnChanges() – which is something you exploit in your answer/solution.

As you probably figured out by now object input properties have the same behavior as array input properties.

"ImportError: no module named 'requests'" after installing with pip

One possible reason is that you have multiple python executables in your environment, for example 2.6.x, 2.7.x or virtaulenv. You might install the package into one of them and run your script with another.

Type python in the prompt, and press the tab key to see what versions of Python in your environment.

plotting different colors in matplotlib

Joe Kington's excellent answer is already 4 years old, Matplotlib has incrementally changed (in particular, the introduction of the cycler module) and the new major release, Matplotlib 2.0.x, has introduced stylistic differences that are important from the point of view of the colors used by default.

The color of individual lines

The color of individual lines (as well as the color of different plot elements, e.g., markers in scatter plots) is controlled by the color keyword argument,

plt.plot(x, y, color=my_color)

my_color is either

The color cycle

By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).

The color cycle is a property of the axes object, and in older releases was simply a sequence of valid color names (by default a string of one character color names, "bgrcmyk") and you could set it as in

my_ax.set_color_cycle(['kbkykrkg'])

(as noted in a comment this API has been deprecated, more on this later).

In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"], the Vega category10 palette.

enter image description here

(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)

The cycler module: composable cycles

The following code shows that the color cycle notion has been deprecated

In [1]: from matplotlib import rc_params

In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
Out[2]: 
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']

Now the relevant property is the 'axes.prop_cycle'

In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

Previously, the color_cycle was a generic sequence of valid color denominations, now by default it is a cycler object containing a label ('color') and a sequence of valid color denominations. The step forward with respect to the previous interface is that it is possible to cycle not only on the color of lines but also on other line attributes, e.g.,

In [5]: from cycler import cycler

In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])

In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}

As you have seen, the cycler objects are composable and when you iterate on a composed cycler what you get, at each iteration, is a dictionary of keyword arguments for plt.plot.

You can use the new defaults on a per axes object ratio,

my_ax.set_prop_cycle(new_prop_cycle)

or you can install temporarily the new default

plt.rc('axes', prop_cycle=new_prop_cycle)

or change altogether the default editing your .matplotlibrc file.

Last possibility, use a context manager

with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
    ...

to have the new cycler used in a group of different plots, reverting to defaults at the end of the context.

The doc string of the cycler() function is useful, but the (not so much) gory details about the cycler module and the cycler() function, as well as examples, can be found in the fine docs.

sendmail: how to configure sendmail on ubuntu?

Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth  #maybe not, because I cannot apply cmd "cd auth" if I do so.

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl

#run 
sudo sendmailconfig

Save a list to a .txt file

If you have more then 1 dimension array

with open("file.txt", 'w') as output:
    for row in values:
        output.write(str(row) + '\n')

Code to write without '[' and ']'

with open("file.txt", 'w') as file:
        for row in values:
            s = " ".join(map(str, row))
            file.write(s+'\n')

How to check that Request.QueryString has a specific value or not in ASP.NET?

You can also try:

if (!Request.QueryString.AllKeys.Contains("aspxerrorpath"))
   return;

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

Programmatically add custom event in the iPhone Calendar

You can add the event using the Event API like Tristan outlined and you can also add a Google Calendar event which shows up in the iOS calendar.

using Google's API Objective-C Client

  - (void)addAnEvent {
  // Make a new event, and show it to the user to edit
  GTLCalendarEvent *newEvent = [GTLCalendarEvent object];
  newEvent.summary = @"Sample Added Event";
  newEvent.descriptionProperty = @"Description of sample added event";

  // We'll set the start time to now, and the end time to an hour from now,
  // with a reminder 10 minutes before
  NSDate *anHourFromNow = [NSDate dateWithTimeIntervalSinceNow:60*60];
  GTLDateTime *startDateTime = [GTLDateTime dateTimeWithDate:[NSDate date]
                                                    timeZone:[NSTimeZone systemTimeZone]];
  GTLDateTime *endDateTime = [GTLDateTime dateTimeWithDate:anHourFromNow
                                                  timeZone:[NSTimeZone systemTimeZone]];

  newEvent.start = [GTLCalendarEventDateTime object];
  newEvent.start.dateTime = startDateTime;

  newEvent.end = [GTLCalendarEventDateTime object];
  newEvent.end.dateTime = endDateTime;

  GTLCalendarEventReminder *reminder = [GTLCalendarEventReminder object];
  reminder.minutes = [NSNumber numberWithInteger:10];
  reminder.method = @"email";

  newEvent.reminders = [GTLCalendarEventReminders object];
  newEvent.reminders.overrides = [NSArray arrayWithObject:reminder];
  newEvent.reminders.useDefault = [NSNumber numberWithBool:NO];

  // Display the event edit dialog
  EditEventWindowController *controller = [[[EditEventWindowController alloc] init] autorelease];
  [controller runModalForWindow:[self window]
                          event:newEvent
              completionHandler:^(NSInteger returnCode, GTLCalendarEvent *event) {
                // Callback
                if (returnCode == NSOKButton) {
                  [self addEvent:event];
                }
              }];
}

How to set DOM element as the first child?

2018 version - prepend

parent.prepend(newChild)  // [newChild, child1, child2]

This is modern JS! It is more readable than previous options. It is currently available in Chrome, FF, and Opera.

The equivalent for adding to the end is append, replacing the old appendChild

parent.append(newChild)  // [child1, child2, newChild]

Advanced usage

  1. You can pass multiple values (or use spread operator ...).
  2. Any string value will be added as a text element.

Examples:

parent.prepend(newChild, "foo")   // [newChild, "foo", child1, child2]

const list = ["bar", newChild]
parent.append(...list, "fizz")    // [child1, child2, "bar", newChild, "fizz"]

Related DOM methods

  1. Read More - child.before and child.after
  2. Read More - child.replaceWith

Mozilla Documentation

Can I Use

Generating a unique machine id

Why not use the MAC address of your network card?

Where is Maven Installed on Ubuntu

Ubuntu 11.10 doesn't have maven3 in repo.

Follow below step to install maven3 on ubuntu 11.10

sudo add-apt-repository ppa:natecarlson/maven3
sudo apt-get update && sudo apt-get install maven3

Open terminal: mvn3 -v

if you want mvn as a binary then execute below script:

sudo ln -s /usr/bin/mvn3 /usr/bin/mvn

I hope this will help you.

Thanks, Rajam

How to split an integer into an array of digits?

like @nd says but using the built-in function of int to convert to a different base

>>> [ int(i,16) for i in '0123456789ABCDEF' ]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

>>> [int(i,2) for i in "100 010 110 111".split()]
[4, 2, 6, 7]

I don't know what is the final objective but take a look also inside the decimal module of python for doing stuff like

>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')

How to use 'hover' in CSS

Not an answer, but explanation of why your css is not matching HTML.

In css space is used as a separator to tell browser to look in children, so your css

a .hover :hover{
   text-decoration:underline;
}

means "look for a element, then look for any descendants of it that have hover class and look of any descendants of those descendants that have hover state" and would match this markup

<a>
   <span class="hover">
      <span>
         I will become underlined when you hover on me
      <span/>
   </span>
</a> 

If you want to match <a class="hover">I will become underlined when you hover on me</a> you should use a.hover:hover, which means "look for any a element with class hover and with hover state"

ASP.NET MVC Global Variables

You can put them in the Application:

Application["GlobalVar"] = 1234;

They are only global within the current IIS / Virtual applicition. This means, on a webfarm they are local to the server, and within the virtual directory that is the root of the application.

What is the difference between screenX/Y, clientX/Y and pageX/Y?

I don't like and understand things, which can be explained visually, by words.

enter image description here

PDF Blob - Pop up window not showing content

I have been struggling for days finally the solution which worked for me is given below. I had to make the window.print() for PDF in new window needs to work.

 var xhr = new XMLHttpRequest();
      xhr.open('GET', pdfUrl, true);
      xhr.responseType = 'blob';

      xhr.onload = function(e) {
        if (this['status'] == 200) {          
          var blob = new Blob([this['response']], {type: 'application/pdf'});
          var url = URL.createObjectURL(blob);
          var printWindow = window.open(url, '', 'width=800,height=500');
          printWindow.print()
        }
      };

      xhr.send();

Some notes on loading PDF & printing in a new window.

  • Loading pdf in a new window via an iframe will work, but the print will not work if url is an external url.
  • Browser pop ups must be allowed, then only it will work.
  • If you try to load iframe from external url and try window.print() you will get empty print or elements which excludes iframe. But you can trigger print manually, which will work.

SQLAlchemy: What's the difference between flush() and commit()?

This does not strictly answer the original question but some people have mentioned that with session.autoflush = True you don't have to use session.flush()... And this is not always true.

If you want to use the id of a newly created object in the middle of a transaction, you must call session.flush().

# Given a model with at least this id
class AModel(Base):
   id = Column(Integer, primary_key=True)  # autoincrement by default on integer primary key

session.autoflush = True

a = AModel()
session.add(a)
a.id  # None
session.flush()
a.id  # autoincremented integer

This is because autoflush does NOT auto fill the id (although a query of the object will, which sometimes can cause confusion as in "why this works here but not there?" But snapshoe already covered this part).


One related aspect that seems pretty important to me and wasn't really mentioned:

Why would you not commit all the time? - The answer is atomicity.

A fancy word to say: an ensemble of operations have to all be executed successfully OR none of them will take effect.

For example, if you want to create/update/delete some object (A) and then create/update/delete another (B), but if (B) fails you want to revert (A). This means those 2 operations are atomic.

Therefore, if (B) needs a result of (A), you want to call flush after (A) and commit after (B).

Also, if session.autoflush is True, except for the case that I mentioned above or others in Jimbo's answer, you will not need to call flush manually.

Codeigniter : calling a method of one controller from other

Very simple way in codeigniter to call a method of one controller to other controller

1. Controller A 
   class A extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }
    function custom_a()
    {
    }
}

2. Controller B 

   class B extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }
    function custom_b()
    {
            require_once(APPPATH.'controllers/a.php'); //include controller
            $aObj = new a();  //create object 
            $aObj->custom_a(); //call function
    }
}

How to Return partial view of another controller by controller?

The control searches for a view in the following order:

  • First in shared folder
  • Then in the folder matching the current controller (in your case it's Views/DEF)

As you do not have xxx.cshtml in those locations, it returns a "view not found" error.

Solution: You can use the complete path of your view:

Like

 PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

Switching the order of block elements with CSS

Here is a "simple as possible" example, for changing the order of div-elements (when resizing the browser window):

<!DOCTYPE html>
<html>
  <head>
    <title>foobar</title>
    <style>
      @media screen and (max-width:300px){
        #parent{
          display:flex;
          flex-flow: column;
        }
        #a{order:2;}
        #c{order:1;}
        #b{order:3;}
      }
    </style>
  </head>
  <body>
    <div id="parent">
      <div id="a">one</div>
      <div id="b">two</div>
      <div id="c">three</div>
    </div>
  </body>
</html>

Example: http://jsfiddle.net/devnull/qyroxexv/ (change window-width to see the effect of changing the order of the divs)

How can I get the current page's full URL on a Windows/IIS server?

Oh, the fun of a snippet!

if (!function_exists('base_url')) {
    function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
        if (isset($_SERVER['HTTP_HOST'])) {
            $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
            $hostname = $_SERVER['HTTP_HOST'];
            $dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

            $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
            $core = $core[0];

            $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
            $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
            $base_url = sprintf( $tmplt, $http, $hostname, $end );
        }
        else $base_url = 'http://localhost/';

        if ($parse) {
            $base_url = parse_url($base_url);
            if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
        }

        return $base_url;
    }
}

It has beautiful returns like:

// A URL like http://stackoverflow.com/questions/189113/how-do-i-get-current-page-full-url-in-php-on-a-windows-iis-server:

echo base_url();    // Will produce something like: http://stackoverflow.com/questions/189113/
echo base_url(TRUE);    // Will produce something like: http://stackoverflow.com/
echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE); //Will produce something like: http://stackoverflow.com/questions/

// And finally:
echo base_url(NULL, NULL, TRUE);
// Will produce something like:
//      array(3) {
//          ["scheme"]=>
//          string(4) "http"
//          ["host"]=>
//          string(12) "stackoverflow.com"
//          ["path"]=>
//          string(35) "/questions/189113/"
//      }

How to send list of file in a folder to a txt file in Linux

If only names of regular files immediately contained within a directory (assume it's ~/dirs) are needed, you can do

find ~/docs -type f -maxdepth 1 > filenames.txt

Error: [ng:areq] from angular controller

This happened to me when I have multiple angular modules in the same page

I encountered this error when I used partial views

One partial view had

<script src="~/Scripts/Items.js"></script>
<div ng-app="SearchModule">
    <div ng-controller="SearchSomething" class="col-md-1">
        <input class="searchClass" type="text" placeholder="Search" />
    </div>
</div>

Other had

<div ng-app="FeaturedItems" ng-controller="featured">
    <ul>
        <li ng-repeat="item in Items">{{item.Name}}</li>
    </ul>
</div>

I had them in same module with different controller and it started working

How do I add a new class to an element dynamically?

This is how you do it:

var e = document.getElementById('myIdName');
var value = window.getComputedStyle(e, null).getPropertyValue("zIndex");
alert('z-index: ' + value);

Is iterating ConcurrentHashMap values thread safe?

This might give you a good insight

ConcurrentHashMap achieves higher concurrency by slightly relaxing the promises it makes to callers. A retrieval operation will return the value inserted by the most recent completed insert operation, and may also return a value added by an insertion operation that is concurrently in progress (but in no case will it return a nonsense result). Iterators returned by ConcurrentHashMap.iterator() will return each element once at most and will not ever throw ConcurrentModificationException, but may or may not reflect insertions or removals that occurred since the iterator was constructed. No table-wide locking is needed (or even possible) to provide thread-safety when iterating the collection. ConcurrentHashMap may be used as a replacement for synchronizedMap or Hashtable in any application that does not rely on the ability to lock the entire table to prevent updates.

Regarding this:

However, iterators are designed to be used by only one thread at a time.

It means, while using iterators produced by ConcurrentHashMap in two threads are safe, it may cause an unexpected result in the application.

What is inf and nan?

I use inf/-inf as initial values to find minimum/maximum value of a measurement. Lets say that you measure temperature with a sensor and you want to keep track of minimum/maximum temperature. The sensor might provide a valid temperature or might be broken. Pseudocode:

# initial value of the temperature
t = float('nan')          
# initial value of minimum temperature, so any measured temp. will be smaller
t_min = float('inf')      
# initial value of maximum temperature, so any measured temp. will be bigger
t_max = float('-inf')     
while True:
    # measure temperature, if sensor is broken t is not changed
    t = measure()     
    # find new minimum temperature
    t_min = min(t_min, t) 
    # find new maximum temperature
    t_max = max(t_max, t) 

The above code works because inf/-inf/nan are valid for min/max operation, so there is no need to deal with exceptions.

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

How to combine class and ID in CSS selector?

There's nothing wrong with combining an id and a class on one element, but you shouldn't need to identify it by both for one rule. If you really want to you can do:

#content.sectionA{some rules}

You don't need the div in front of the ID as others have suggested.

In general, CSS rules specific to that element should be set with the ID, and those are going to carry a greater weight than those of just the class. Rules specified by the class would be properties that apply to multiple items that you don't want to change in multiple places anytime you need to adjust.

That boils down to this:

 .sectionA{some general rules here}
 #content{specific rules, and overrides for things in .sectionA}

Make sense?

How to get a value from a Pandas DataFrame and not the index and object type

Use the values attribute to return the values as a np array and then use [0] to get the first value:

In [4]:
df.loc[df.Letters=='C','Letters'].values[0]

Out[4]:
'C'

EDIT

I personally prefer to access the columns using subscript operators:

df.loc[df['Letters'] == 'C', 'Letters'].values[0]

This avoids issues where the column names can have spaces or dashes - which mean that accessing using ..

Why powershell does not run Angular commands?

open windows powershell, run as administrater and SetExecution policy as Unrestricted then it will work.

What is username and password when starting Spring Boot with Tomcat?

If you can't find the password based on other answers that point to a default one, the log message wording in recent versions changed to

Using generated security password: <some UUID>

JRE installation directory in Windows

Following on from my other comment, here's a batch file which displays the current JRE or JDK based on the registry values.

It's different from the other solutions in instances where java is installed, but not on the PATH.

@ECHO off

SET KIT=JavaSoft\Java Runtime Environment
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=Wow6432Node\JavaSoft\Java Runtime Environment
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=JavaSoft\Java Development Kit
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=Wow6432Node\JavaSoft\Java Development Kit
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

ECHO Failed to find Java
GOTO :EOF

:FoundJRE
call:ReadRegValue JAVAPATH "HKLM\Software\%KIT%\%VER%" "JavaHome"
ECHO %JAVAPATH%
GOTO :EOF

:ReadRegValue
SET key=%2%
SET name=%3%
SET "%~1="
SET reg=reg
IF DEFINED ProgramFiles(x86) (
  IF EXIST %WINDIR%\sysnative\reg.exe SET reg=%WINDIR%\sysnative\reg.exe
)
FOR /F "usebackq tokens=3* skip=1" %%A IN (`%reg% QUERY %key% /v %name% 2^>NUL`) DO SET "%~1=%%A %%B"
GOTO :EOF

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

Long time reader, first time helper ;)

I'm going through the same hellish experience here with a Prolific USB <> Serial adapter and so far Linux is the easiest to get it to work.

On CentOS, I didn't need to install any drivers etc.. That said,

  • dmesg | grep -i tty or dmesg | grep -i usb showed me /dev/ttyUSB0.
  • screen ttyUSB0 9600 didn't do the trick for me like it did in OSX
  • minicom is new to me but it was complaining about lack of /dev/modem

However, this helped: https://www.centos.org/forums/viewtopic.php?t=21271

So install minicom (yum install minicom) then enter its settings (minicom -s).

Then select Serial Port Setup and change the Serial Device (Option A) to /dev/ttyUSB0, or whatever your device file is as it slightly differs per distro.

Then change the Bps (Option E) to 9600 and the rest should be default (8N1 Y N)

Save as default, then simply minicom and Bob's your uncle.

HTH.

Background color in input and text fields

input[type="text"], textarea {

  background-color : #d1d1d1; 

}

Hope that helps :)

Edit: working example, http://jsfiddle.net/C5WxK/

is it possible to add colors to python output?

IDLE's console does not support ANSI escape sequences, or any other form of escapes for coloring your output.

You can learn how to talk to IDLE's console directly instead of just treating it like normal stdout and printing to it (which is how it does things like color-coding your syntax), but that's pretty complicated. The idle documentation just tells you the basics of using IDLE itself, and its idlelib library has no documentation (well, there is a single line of documentation—"(New in 2.3) Support library for the IDLE development environment."—if you know where to find it, but that isn't very helpful). So, you need to either read the source, or do a whole lot of trial and error, to even get started.


Alternatively, you can run your script from the command line instead of from IDLE, in which case you can use whatever escape sequences your terminal handles. Most modern terminals will handle at least basic 16/8-color ANSI. Many will handle 16/16, or the expanded xterm-256 color sequences, or even full 24-bit colors. (I believe gnome-terminal is the default for Ubuntu, and in its default configuration it will handle xterm-256, but that's really a question for SuperUser or AskUbuntu.)

Learning to read the termcap entries to know which codes to enter is complicated… but if you only care about a single console—or are willing to just assume "almost everything handles basic 16/8-color ANSI, and anything that doesn't, I don't care about", you can ignore that part and just hardcode them based on, e.g., this page.

Once you know what you want to emit, it's just a matter of putting the codes in the strings before printing them.

But there are libraries that can make this all easier for you. One really nice library, which comes built in with Python, is curses. This lets you take over the terminal and do a full-screen GUI, with colors and spinning cursors and anything else you want. It is a little heavy-weight for simple uses, of course. Other libraries can be found by searching PyPI, as usual.

How to return a value from pthread threads in C?

You are returning a reference to ret which is a variable on the stack.

SVN change username

I believe you could create you own branch (using your own credential) from the same trunk as your workmate's branch, merge from your workmate's branch to your working copy and then merge from your branch. All future commit should be marked as coming from you.

python dict to numpy structured array

You could use np.array(list(result.items()), dtype=dtype):

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

names = ['id','data']
formats = ['f8','f8']
dtype = dict(names = names, formats=formats)
array = np.array(list(result.items()), dtype=dtype)

print(repr(array))

yields

array([(0.0, 1.1181753789488595), (1.0, 0.5566080288678394),
       (2.0, 0.4718269778030734), (3.0, 0.48716683119447185), (4.0, 1.0),
       (5.0, 0.1395076201641266), (6.0, 0.20941558441558442)], 
      dtype=[('id', '<f8'), ('data', '<f8')])

If you don't want to create the intermediate list of tuples, list(result.items()), then you could instead use np.fromiter:

In Python2:

array = np.fromiter(result.iteritems(), dtype=dtype, count=len(result))

In Python3:

array = np.fromiter(result.items(), dtype=dtype, count=len(result))

Why using the list [key,val] does not work:

By the way, your attempt,

numpy.array([[key,val] for (key,val) in result.iteritems()],dtype)

was very close to working. If you change the list [key, val] to the tuple (key, val), then it would have worked. Of course,

numpy.array([(key,val) for (key,val) in result.iteritems()], dtype)

is the same thing as

numpy.array(result.items(), dtype)

in Python2, or

numpy.array(list(result.items()), dtype)

in Python3.


np.array treats lists differently than tuples: Robert Kern explains:

As a rule, tuples are considered "scalar" records and lists are recursed upon. This rule helps numpy.array() figure out which sequences are records and which are other sequences to be recursed upon; i.e. which sequences create another dimension and which are the atomic elements.

Since (0.0, 1.1181753789488595) is considered one of those atomic elements, it should be a tuple, not a list.

How to copy a selection to the OS X clipboard

Shift cmd c – set copy mode Drag mouse, select text, cmd c to copy selected text Cmd v to paste

How to use Macro argument as string literal?

Perhaps you try this solution:

#define QUANTIDISCHI 6
#define QUDI(x) #x
#define QUdi(x) QUDI(x)
. . . 
. . .
unsigned char TheNumber[] = "QUANTIDISCHI = " QUdi(QUANTIDISCHI) "\n";

jquery: get elements by class name and add css to each of them

What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.

There is also a shorter form for $(document).ready(function(){...}) in $(function(){...}).

So, this is all you need:

$(function(){
  $('div.easy_editor').css('border','9px solid red');
});

If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:

$(function(){
  $('.easy_editor').css('border','9px solid red');
});

How to declare and add items to an array in Python?

Arrays (called list in python) use the [] notation. {} is for dict (also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.

If you actually want an array (list), use:

array = []
array.append(valueToBeInserted)

Vue-router redirect on page not found (404)

I think you should be able to use a default route handler and redirect from there to a page outside the app, as detailed below:

const ROUTER_INSTANCE = new VueRouter({
    mode: "history",
    routes: [
        { path: "/", component: HomeComponent },
        // ... other routes ...
        // and finally the default route, when none of the above matches:
        { path: "*", component: PageNotFound }
    ]
})

In the above PageNotFound component definition, you can specify the actual redirect, that will take you out of the app entirely:

Vue.component("page-not-found", {
    template: "",
    created: function() {
        // Redirect outside the app using plain old javascript
        window.location.href = "/my-new-404-page.html";
    }
}

You may do it either on created hook as shown above, or mounted hook also.

Please note:

  1. I have not verified the above. You need to build a production version of app, ensure that the above redirect happens. You cannot test this in vue-cli as it requires server side handling.

  2. Usually in single page apps, server sends out the same index.html along with app scripts for all route requests, especially if you have set <base href="/">. This will fail for your /404-page.html unless your server treats it as a special case and serves the static page.

Let me know if it works!

Update for Vue 3 onward:

You'll need to replace the '*' path property with '/:pathMatch(.*)*' if you're using Vue 3 as the old catch-all path of '*' is no longer supported. The route would then look something like this:

{ path: '/:pathMatch(.*)*', component: PathNotFound },

See the docs for more info on this update.

Adding a newline into a string in C#

Then just modify the previous answers to:

Console.Write(strToProcess.Replace("@", "@" + Environment.NewLine));

If you don't want the newlines in the text file, then don't preserve it.

Force a screen update in Excel VBA

I couldn't gain yet the survey of an inherited extensive code. And exact this problem bugged me for months. Many approches with DoEnvents were not helpful. Above answer helped. Placeing this Sub in meaningful positions in the code worked even in combination with progress bar

Sub ForceScreenUpdate()
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Wait Now + #12:00:01 AM#
    Application.ScreenUpdating = False
    Application.EnableEvents = False
End Sub

Postgresql tables exists, but getting "relation does not exist" when querying

I had to include double quotes with the table name.

db=> \d
                           List of relations
 Schema |                     Name                      | Type  | Owner 
--------+-----------------------------------------------+-------+-------
 public | COMMONDATA_NWCG_AGENCIES                      | table | dan
 ...

db=> \d COMMONDATA_NWCG_AGENCIES
Did not find any relation named "COMMONDATA_NWCG_AGENCIES".

???

Double quotes:

db=> \d "COMMONDATA_NWCG_AGENCIES"
                         Table "public.COMMONDATA_NWCG_AGENCIES"
          Column          |            Type             | Collation | Nullable | Default 
--------------------------+-----------------------------+-----------+----------+---------
 ID                       | integer                     |           | not null | 
 ...

Lots and lots of double quotes:

db=> select ID from COMMONDATA_NWCG_AGENCIES limit 1;
ERROR:  relation "commondata_nwcg_agencies" does not exist
LINE 1: select ID from COMMONDATA_NWCG_AGENCIES limit 1;
                       ^
db=> select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
ERROR:  column "id" does not exist
LINE 1: select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
               ^
db=> select "ID" from "COMMONDATA_NWCG_AGENCIES" limit 1;
 ID 
----
  1
(1 row)

This is postgres 11. The CREATE TABLE statements from this dump had double quotes as well:

DROP TABLE IF EXISTS "COMMONDATA_NWCG_AGENCIES";

CREATE TABLE "COMMONDATA_NWCG_AGENCIES" (
...

linux shell script: split string, put them in an array then loop through them

If you don't wish to mess with IFS (perhaps for the code within the loop) this might help.

If know that your string will not have whitespace, you can substitute the ';' with a space and use the for/in construct:

#local str
for str in ${STR//;/ } ; do 
   echo "+ \"$str\""
done

But if you might have whitespace, then for this approach you will need to use a temp variable to hold the "rest" like this:

#local str rest
rest=$STR
while [ -n "$rest" ] ; do
   str=${rest%%;*}  # Everything up to the first ';'
   # Trim up to the first ';' -- and handle final case, too.
   [ "$rest" = "${rest/;/}" ] && rest= || rest=${rest#*;}
   echo "+ \"$str\""
done

IIS 500.19 with 0x80070005 The requested page cannot be accessed because the related configuration data for the page is invalid error

Facepalm alert:

You will also get this error if the path to the config file is wrong. Double-check it to make sure the physical path is entered correctly in IIS.

lvalue required as left operand of assignment error when using C++

When you have an assignment operator in a statement, the LHS of the operator must be something the language calls an lvalue. If the LHS of the operator does not evaluate to an lvalue, the value from the RHS cannot be assigned to the LHS.

You cannot use:

10 = 20;

since 10 does not evaluate to an lvalue.

You can use:

int i;
i = 20;

since i does evaluate to an lvalue.

You cannot use:

int i;
i + 1 = 20;

since i + 1 does not evaluate to an lvalue.

In your case, p + 1 does not evaluate to an lavalue. Hence, you cannot use

p + 1 = p;

Get the client's IP address in socket.io

In socket.io 2.0: you can use:

socket.conn.transport.socket._socket.remoteAddress

works with transports: ['websocket']

jQuery Keypress Arrow Keys

You should use .keydown() because .keypress() will ignore "Arrows", for catching the key type use e.which

Press the result screen to focus (bottom right on fiddle screen) and then press arrow keys to see it work.

Notes:

  1. .keypress() will never be fired with Shift, Esc, and Delete but .keydown() will.
  2. Actually .keypress() in some browser will be triggered by arrow keys but its not cross-browser so its more reliable to use .keydown().

More useful information

  1. You can use .which Or .keyCode of the event object - Some browsers won't support one of them but when using jQuery its safe to use the both since jQuery standardizes things. (I prefer .which never had a problem with).
  2. To detect a ctrl | alt | shift | META press with the actual captured key you should check the following properties of the event object - They will be set to TRUE if they were pressed:
  3. Finally - here are some useful key codes ( For a full list - keycode-cheatsheet ):

    • Enter: 13
    • Up: 38
    • Down: 40
    • Right: 39
    • Left: 37
    • Esc: 27
    • SpaceBar: 32
    • Ctrl: 17
    • Alt: 18
    • Shift: 16

How to send string from one activity to another?

Say there is EditText et1 in ur MainActivity and u wanna pass this to SecondActivity

String s=et1.getText().toString();
Bundle basket= new Bundle();
basket.putString("abc", s);
Intent a=new Intent(MainActivity.this,SecondActivity.class);
a.putExtras(basket);
startActivity(a);

now in Second Activity, say u wanna put the string passed from EditText et1 to TextView txt1 of SecondActivity

Bundle gt=getIntent().getExtras();
str=gt.getString("abc");
txt1.setText(str);

Get last n lines of a file, similar to tail

Assumes a unix-like system on Python 2 you can do:

import os
def tail(f, n, offset=0):
  stdin,stdout = os.popen2("tail -n "+n+offset+" "+f)
  stdin.close()
  lines = stdout.readlines(); stdout.close()
  return lines[:,-offset]

For python 3 you may do:

import subprocess
def tail(f, n, offset=0):
    proc = subprocess.Popen(['tail', '-n', n + offset, f], stdout=subprocess.PIPE)
    lines = proc.stdout.readlines()
    return lines[:, -offset]

grep --ignore-case --only

It should be a problem in your version of grep.

Your test cases are working correctly here on my machine:

$ echo "abc" | grep -io abc
abc
$ echo "ABC" | grep -io abc
ABC

And my version is:

$ grep --version
grep (GNU grep) 2.10

fork: retry: Resource temporarily unavailable

Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

watch -n 5 -d "ps -eL <java_pid> | wc -l"

to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

How can I easily view the contents of a datatable or dataview in the immediate window

What I do is have a static class with the following code in my project:

    #region Dataset -> Immediate Window
public static void printTbl(DataSet myDataset)
{
    printTbl(myDataset.Tables[0]);
}
public static void printTbl(DataTable mytable)
{
    for (int i = 0; i < mytable.Columns.Count; i++)
    {
        Debug.Write(mytable.Columns[i].ToString() + " | ");
    }
    Debug.Write(Environment.NewLine + "=======" + Environment.NewLine);
    for (int rrr = 0; rrr < mytable.Rows.Count; rrr++)
    {
        for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
        {
            Debug.Write(mytable.Rows[rrr][ccc] + " | ");
        }
        Debug.Write(Environment.NewLine);
    }
}
public static void ResponsePrintTbl(DataTable mytable)
{
    for (int i = 0; i < mytable.Columns.Count; i++)
    {
        HttpContext.Current.Response.Write(mytable.Columns[i].ToString() + " | ");
    }
    HttpContext.Current.Response.Write("<BR>" + "=======" + "<BR>");
    for (int rrr = 0; rrr < mytable.Rows.Count; rrr++)
    {
        for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
        {
            HttpContext.Current.Response.Write(mytable.Rows[rrr][ccc] + " | ");
        }
        HttpContext.Current.Response.Write("<BR>");
    }
}

public static void printTblRow(DataSet myDataset, int RowNum)
{
    printTblRow(myDataset.Tables[0], RowNum);
}
public static void printTblRow(DataTable mytable, int RowNum)
{
    for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
    {
        Debug.Write(mytable.Columns[ccc].ToString() + " : ");
        Debug.Write(mytable.Rows[RowNum][ccc]);
        Debug.Write(Environment.NewLine);
    }
}
#endregion

I then I will call one of the above functions in the immediate window and the results will appear there as well. For example if I want to see the contents of a variable 'myDataset' I will call printTbl(myDataset). After hitting enter, the results will be printed to the immediate window

log4j configuration via JVM argument(s)?

Late to the party as since 2015, Log4J 1.x has reached EOL.

Log4J 2.x onwards the JVM option should be -Dlog4j.configurationFile=<filename>


P.S. <filename> could be a file relative to the class path without the file: as suggested in the other answers.

MySQL Removing Some Foreign keys

You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.

But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:

SHOW CREATE TABLE region; This should show you a row ,at left upper corner click the +option ,the click the full text raio button then click the go .there you will get the name of the index, something like this:

CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION Now simply issue an:

alter table region drop foreign key region_ibfk_1;

or

more simply just type:- alter table TableName drop foreign key TableName_ibfk_1;

remember the only thing is to add _ibfk_1 after your tablename to make like this:- TableName_ibfk_1

Get data from file input in JQuery

Html:

<input type="file" name="input-file" id="input-file">

jQuery:

var fileToUpload = $('#input-file').prop('files')[0];

We want to get first element only, because prop('files') returns array.

when I run mockito test occurs WrongTypeOfReturnValue Exception

In my case the problem was caused by trying to mock a static method and forgetting to call mockStatic on the class. Also I forgot to include the class into the @PrepareForTest()

What are native methods in Java and where should they be used?

The method is implemented in "native" code. That is, code that does not run in the JVM. It's typically written in C or C++.

Native methods are usually used to interface with system calls or libraries written in other programming languages.

Nginx -- static file serving confusion with root & alias

I have found answers to my confusions.

There is a very important difference between the root and the alias directives. This difference exists in the way the path specified in the root or the alias is processed.

In case of the root directive, full path is appended to the root including the location part, whereas in case of the alias directive, only the portion of the path NOT including the location part is appended to the alias.

To illustrate:

Let's say we have the config

location /static/ {
    root /var/www/app/static/;
    autoindex off;
}

In this case the final path that Nginx will derive will be

/var/www/app/static/static

This is going to return 404 since there is no static/ within static/

This is because the location part is appended to the path specified in the root. Hence, with root, the correct way is

location /static/ {
    root /var/www/app/;
    autoindex off;
}

On the other hand, with alias, the location part gets dropped. So for the config

location /static/ {
    alias /var/www/app/static/;
    autoindex off;           ?
}                            |
                             pay attention to this trailing slash

the final path will correctly be formed as

/var/www/app/static

The case of trailing slash for alias directive

There is no definitive guideline about whether a trailing slash is mandatory per Nginx documentation, but a common observation by people here and elsewhere seems to indicate that it is.

A few more places have discussed this, not conclusively though.

https://serverfault.com/questions/376162/how-can-i-create-a-location-in-nginx-that-works-with-and-without-a-trailing-slas

https://serverfault.com/questions/375602/why-is-my-nginx-alias-not-working

How to resize Image in Android?

Following is the function to resize bitmap by keeping the same Aspect Ratio. Here I have also written a detailed blog post on the topic to explain this method. Resize a Bitmap by Keeping the Same Aspect Ratio.

   public static Bitmap resizeBitmap(Bitmap source, int maxLength) {
       try {
           if (source.getHeight() >= source.getWidth()) {
               int targetHeight = maxLength;
               if (source.getHeight() <= targetHeight) { // if image already smaller than the required height
                   return source;
               }

               double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
               int targetWidth = (int) (targetHeight * aspectRatio);

               Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
               if (result != source) {
               }
               return result;
           } else {
               int targetWidth = maxLength;

               if (source.getWidth() <= targetWidth) { // if image already smaller than the required height
                   return source;
               }

               double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
               int targetHeight = (int) (targetWidth * aspectRatio);

               Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
               if (result != source) {
               }
               return result;

           }
       }
       catch (Exception e)
       {
           return source;
       }
   }

JAXB: How to ignore namespace during unmarshalling XML document?

In my situation, I have many namespaces and after some debug I find another solution just changing the NamespaceFitler class. For my situation (just unmarshall) this work fine.

 import javax.xml.namespace.QName;
 import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.SAXException;
 import org.xml.sax.helpers.XMLFilterImpl;
 import com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector;

 public class NamespaceFilter extends XMLFilterImpl {
    private SAXConnector saxConnector;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        if(saxConnector != null) {
            Collection<QName> expected = saxConnector.getContext().getCurrentExpectedElements();
            for(QName expectedQname : expected) {
                if(localName.equals(expectedQname.getLocalPart())) {
                    super.startElement(expectedQname.getNamespaceURI(), localName, qName, atts);
                    return;
                }
            }
        }
        super.startElement(uri, localName, qName, atts);
    }

    @Override
    public void setContentHandler(ContentHandler handler) {
        super.setContentHandler(handler);
        if(handler instanceof SAXConnector) {
            saxConnector = (SAXConnector) handler;
        }
    }
}

Concatenate two slices in Go

append([]int{1,2}, []int{3,4}...) will work. Passing arguments to ... parameters.

If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T.

If f is invoked with no actual arguments for p, the value passed to p is nil.

Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T. The length and capacity of the slice is therefore the number of arguments bound to p and may differ for each call site.

Given the function and calls

func Greeting(prefix string, who ...string)
Greeting("nobody")
Greeting("hello:", "Joe", "Anna", "Eileen")

Overwriting my local branch with remote branch

git reset --hard

This is to revert all your local changes to the origin head

How can I trim leading and trailing white space?

A simple function to remove leading and trailing whitespace:

trim <- function( x ) {
  gsub("(^[[:space:]]+|[[:space:]]+$)", "", x)
}

Usage:

> text = "   foo bar  baz 3 "
> trim(text)
[1] "foo bar  baz 3"

How to remove index.php from URLs?

Hi I'm late to the party.. just wanted to point out that the instructions from http://davidtsadler.com/archives/2012/06/03/how-to-install-magento-on-ubuntu/ were really useful.

I had Ubuntu server installed with Apache, MySql and Php so I thought I could jump to the heading Creating the directory from which Magento will be served from and I reached the same problem as the OP, i.e. I had 'index.php' needed in all the URLs (or I would get 404 not found). I then went back to Installing and configuring the Apache HTTP server and after restarting apache it works perfectly.

For reference, I was missing:

sudo bash -c "cat >> /etc/apache2/conf.d/servername.conf <<EOF
ServerName localhost
EOF"

... and

sudo a2enmod rewrite
sudo service apache2 restart

Hope this helps

Deploying Java webapp to Tomcat 8 running in Docker container

You are trying to copy the war file to a directory below webapps. The war file should be copied into the webapps directory.

Remove the mkdir command, and copy the war file like this:

COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war

Tomcat will extract the war if autodeploy is turned on.

Find object by id in an array of JavaScript objects

If you do this multiple times, you may set up a Map (ES6):

const map = new Map( myArray.map(el => [el.id, el]) );

Then you can simply do:

map.get(27).foo

Remove a CLASS for all child elements

You can also do like this :

  $("#table-filters li").parent().find('li').removeClass("active");

Get method arguments using Spring AOP?

If it's a single String argument, do: joinPoint.getArgs()[0];

AngularJS: How to clear query parameters in the URL?

You can delete a specific query parameter by using:

delete $location.$$search.nameOfParameter;

Or you can clear all the query params by setting search to an empty object:

$location.$$search = {};

Take a char input from the Scanner

// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}

How to include "zero" / "0" results in COUNT aggregate?

You must use LEFT JOIN instead of INNER JOIN

SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM person 
LEFT JOIN appointment ON person.person_id = appointment.person_id
GROUP BY person.person_id;

What determines the monitor my app runs on?

Important note: If you remember the position of your application and shutdown and then start up again at that position, keep in mind that the user's monitor configuration may have changed while your application was closed.

Laptop users, for example, frequently change their display configuration. When docked there may be a 2nd monitor that disappears when undocked. If the user closes an application that was running on the 2nd monitor and the re-opens the application when the monitor is disconnected, restoring the window to the previous coordinates will leave it completely off-screen.

To figure out how big the display really is, check out GetSystemMetrics.

How to create a DateTime equal to 15 minutes ago?

from datetime import timedelta    
datetime.datetime.now() - datetime.timedelta(0, 900)

Actually 900 is in seconds. Which is equal to 15 minutes. `15*60 = 900`

python: urllib2 how to send cookie with urlopen request

This answer is not working since the urllib2 module has been split across several modules in Python 3. You need to do

from urllib import request
opener = request.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

Load image with jQuery and append it to the DOM

I imagine that you define your image something like this:

<img id="image_portrait" src="" alt="chef etat"  width="120" height="135"  />

You can simply load/update image for this tag and chage/set atts (width,height):

var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);

Reading a .txt file using Scanner class in Java

File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file. Please log the file.getAbsolutePath() to verify that file is correct.

How to SUM two fields within an SQL query

Just a reminder on adding columns. If one of the values is NULL the total of those columns becomes NULL. Thus why some posters have recommended coalesce with the second parameter being 0

I know this was an older posting but wanted to add this for completeness.

How to check if a database exists in SQL Server?

From a Microsoft's script:

DECLARE @dbname nvarchar(128)
SET @dbname = N'Senna'

IF (EXISTS (SELECT name 
FROM master.dbo.sysdatabases 
WHERE ('[' + name + ']' = @dbname 
OR name = @dbname)))

-- code mine :)
PRINT 'db exists'

How can I customize the tab-to-space conversion factor?

You want to make sure your editorconfig is not conflicting with your user or workspace settings configuration, as I just had a bit of annoyance thinking the settings files settings were not being applied when it was my editor configuration undoing those changes.

assign value using linq

Be aware that it only updates the first company it found with company id 1. For multiple

 (from c in listOfCompany where c.id == 1 select c).First().Name = "Whatever Name";

For Multiple updates

 from c in listOfCompany where c.id == 1 select c => {c.Name = "Whatever Name";  return c;}

Swift: Sort array of objects alphabetically

let sortArray =  array.sorted(by: { $0.name.lowercased() < $1.name.lowercased() })

Is there any advantage of using map over unordered_map in case of trivial keys?

If you want to compare the speed of your std::map and std::unordered_map implementations, you could use Google's sparsehash project which has a time_hash_map program to time them. For example, with gcc 4.4.2 on an x86_64 Linux system

$ ./time_hash_map
TR1 UNORDERED_MAP (4 byte objects, 10000000 iterations):
map_grow              126.1 ns  (27427396 hashes, 40000000 copies)  290.9 MB
map_predict/grow       67.4 ns  (10000000 hashes, 40000000 copies)  232.8 MB
map_replace            22.3 ns  (37427396 hashes, 40000000 copies)
map_fetch              16.3 ns  (37427396 hashes, 40000000 copies)
map_fetch_empty         9.8 ns  (10000000 hashes,        0 copies)
map_remove             49.1 ns  (37427396 hashes, 40000000 copies)
map_toggle             86.1 ns  (20000000 hashes, 40000000 copies)

STANDARD MAP (4 byte objects, 10000000 iterations):
map_grow              225.3 ns  (       0 hashes, 20000000 copies)  462.4 MB
map_predict/grow      225.1 ns  (       0 hashes, 20000000 copies)  462.6 MB
map_replace           151.2 ns  (       0 hashes, 20000000 copies)
map_fetch             156.0 ns  (       0 hashes, 20000000 copies)
map_fetch_empty         1.4 ns  (       0 hashes,        0 copies)
map_remove            141.0 ns  (       0 hashes, 20000000 copies)
map_toggle             67.3 ns  (       0 hashes, 20000000 copies)

How do I negate a condition in PowerShell?

If you are like me and dislike the double parenthesis, you can use a function

function not ($cm, $pm) {
  if (& $cm $pm) {0} else {1}
}

if (not Test-Path C:\Code) {'it does not exist!'}

Example

How to change font-color for disabled input?

It is the solution that I found for this problem:

//If IE

inputElement.writeAttribute("unselectable", "on");

//Other browsers

inputElement.writeAttribute("disabled", "disabled");

By using this trick, you can add style sheet to your input element that works in IE and other browsers on your not-editable input box.

How to get the mouse position without events (without moving the mouse)?

I envision that maybe you have a parent page with a timer and after a certain amount of time or a task is completed, you forward the user to a new page. Now you want the cursor position, and because they are waiting, they aren't necessarily touching the mouse. So track the mouse on the parent page using standard events and pass the last value to the new page in a get or a post variable.

You can use JHarding's code on your parent page so that the latest position is always available in a global variable:

var cursorX;
var cursorY;
document.onmousemove = function(e){
    cursorX = e.pageX;
    cursorY = e.pageY;
}

This won't help users that navigate to this page by means other than your parent page.

How to declare std::unique_ptr and what is the use of it?

The constructor of unique_ptr<T> accepts a raw pointer to an object of type T (so, it accepts a T*).

In the first example:

unique_ptr<int> uptr (new int(3));

The pointer is the result of a new expression, while in the second example:

unique_ptr<double> uptr2 (pd);

The pointer is stored in the pd variable.

Conceptually, nothing changes (you are constructing a unique_ptr from a raw pointer), but the second approach is potentially more dangerous, since it would allow you, for instance, to do:

unique_ptr<double> uptr2 (pd);
// ...
unique_ptr<double> uptr3 (pd);

Thus having two unique pointers that effectively encapsulate the same object (thus violating the semantics of a unique pointer).

This is why the first form for creating a unique pointer is better, when possible. Notice, that in C++14 we will be able to do:

unique_ptr<int> p = make_unique<int>(42);

Which is both clearer and safer. Now concerning this doubt of yours:

What is also not clear to me, is how pointers, declared in this way will be different from the pointers declared in a "normal" way.

Smart pointers are supposed to model object ownership, and automatically take care of destroying the pointed object when the last (smart, owning) pointer to that object falls out of scope.

This way you do not have to remember doing delete on objects allocated dynamically - the destructor of the smart pointer will do that for you - nor to worry about whether you won't dereference a (dangling) pointer to an object that has been destroyed already:

{
    unique_ptr<int> p = make_unique<int>(42);
    // Going out of scope...
}
// I did not leak my integer here! The destructor of unique_ptr called delete

Now unique_ptr is a smart pointer that models unique ownership, meaning that at any time in your program there shall be only one (owning) pointer to the pointed object - that's why unique_ptr is non-copyable.

As long as you use smart pointers in a way that does not break the implicit contract they require you to comply with, you will have the guarantee that no memory will be leaked, and the proper ownership policy for your object will be enforced. Raw pointers do not give you this guarantee.

Add A Year To Today's Date

This code adds the amount of years required for a date.

var d = new Date();
// => Tue Oct 01 2017 00:00:00 GMT-0700 (PDT)

var amountOfYearsRequired = 2;
d.setFullYear(d.getFullYear() + amountOfYearsRequired);
// => Tue Oct 01 2019 00:00:00 GMT-0700 (PDT)

Extract column values of Dataframe as List in Apache Spark

I know the answer given and asked for is assumed for Scala, so I am just providing a little snippet of Python code in case a PySpark user is curious. The syntax is similar to the given answer, but to properly pop the list out I actually have to reference the column name a second time in the mapping function and I do not need the select statement.

i.e. A DataFrame, containing a column named "Raw"

To get each row value in "Raw" combined as a list where each entry is a row value from "Raw" I simply use:

MyDataFrame.rdd.map(lambda x: x.Raw).collect()

Pass variable to function in jquery AJAX success callback

I'm doing it this way:

    function f(data,d){
    console.log(d);
    console.log(data);
}
$.ajax({
    url:u,
    success:function(data){ f(data,d);  }
});

How to properly override clone method?

Sometimes it's more simple to implement a copy constructor:

public MyObject (MyObject toClone) {
}

It saves you the trouble of handling CloneNotSupportedException, works with final fields and you don't have to worry about the type to return.

Android REST client, Sample?

There is plenty of libraries out there and I'm using this one: https://github.com/nerde/rest-resource. This was created by me, and, as you can see in the documentation, it's way cleaner and simpler than the other ones. It's not focused on Android, but I'm using in it and it's working pretty well.

It supports HTTP Basic Auth. It does the dirty job of serializing and deserializing JSON objects. You will like it, specially if your API is Rails like.

How to use Utilities.sleep() function

Serge is right - my workaround:

function mySleep (sec)
{
  SpreadsheetApp.flush();
  Utilities.sleep(sec*1000);
  SpreadsheetApp.flush();
}

SELECT FOR UPDATE with SQL Server

perhaps making mvcc permanent could solve it (as opposed to specific batch only: SET TRANSACTION ISOLATION LEVEL SNAPSHOT):

ALTER DATABASE yourDbNameHere SET READ_COMMITTED_SNAPSHOT ON;

[EDIT: October 14]

After reading this: Better concurrency in Oracle than SQL Server? and this: http://msdn.microsoft.com/en-us/library/ms175095.aspx

When the READ_COMMITTED_SNAPSHOT database option is set ON, the mechanisms used to support the option are activated immediately. When setting the READ_COMMITTED_SNAPSHOT option, only the connection executing the ALTER DATABASE command is allowed in the database. There must be no other open connection in the database until ALTER DATABASE is complete. The database does not have to be in single-user mode.

i've come to conclusion that you need to set two flags in order to activate mssql's MVCC permanently on a given database:

ALTER DATABASE yourDbNameHere SET ALLOW_SNAPSHOT_ISOLATION ON;
ALTER DATABASE yourDbNameHere SET READ_COMMITTED_SNAPSHOT ON;

Setting DataContext in XAML in WPF

There are several issues here.

  1. You can't assign DataContext as DataContext="{Binding Employee}" because it's a complex object which can't be assigned as string. So you have to use <Window.DataContext></Window.DataContext> syntax.
  2. You assign the class that represents the data context object to the view, not an individual property so {Binding Employee} is invalid here, you just have to specify an object.
  3. Now when you assign data context using valid syntax like below
   <Window.DataContext>
      <local:Employee/>
   </Window.DataContext>

know that you are creating a new instance of the Employee class and assigning it as the data context object. You may well have nothing in default constructor so nothing will show up. But then how do you manage it in code behind file? You have typecast the DataContext.

    private void my_button_Click(object sender, RoutedEventArgs e)
    {
        Employee e = (Employee) DataContext;
    }
  1. A second way is to assign the data context in the code behind file itself. The advantage then is your code behind file already knows it and can work with it.

    public partial class MainWindow : Window
    {
       Employee employee = new Employee();
    
       public MainWindow()
       {
           InitializeComponent();
    
           DataContext = employee;
       }
    }
    

Protect image download

As other answers said, if you can see it you can copy/download it.

To add up to the other answers, just for your information, you can add invisible or tricky watermarks to your images: http://www.cgrats.com/create-an-invisible-watermark-in-photoshop.html (just an example, there are more techniques, just google for invisible watermarks)

Anyway if you want to prove the ownership of your image a good way is to have a bigger resolution copy for yourself, and always publish a lower resolution / size one. Or publish it also on a "public" media like ... deviantart or flickr or something where people can't change the upload date. This way you can prove you had that image before anybody else

Convert from MySQL datetime to another format with PHP

$valid_date = date( 'm/d/y g:i A', strtotime($date));

Reference: http://php.net/manual/en/function.date.php

Count a list of cells with the same background color

Excel has no way of gathering that attribute with it's built-in functions. If you're willing to use some VB, all your color-related questions are answered here:

http://www.cpearson.com/excel/colors.aspx

Example form the site:

The SumColor function is a color-based analog of both the SUM and SUMIF function. It allows you to specify separate ranges for the range whose color indexes are to be examined and the range of cells whose values are to be summed. If these two ranges are the same, the function sums the cells whose color matches the specified value. For example, the following formula sums the values in B11:B17 whose fill color is red.

=SUMCOLOR(B11:B17,B11:B17,3,FALSE)

ASP.NET Core - Swashbuckle not creating swagger.json file

In my case problem was in method type, should be HttpPOST but there was HttpGET Once I changed that, everything starts work.

https://c2n.me/44p7lRd.png

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

If you want to downgrade php from 7.1.1 to 5.6 in xampp follow the steps(For Windows):-

  1. Go to https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/5.6.36/
  2. Download and extract the file xampp-win32-5.6.36-0-VC11.zip see the image [image 1][1]
  3. Delete php folder and apache folder present in C:\xampp

  4. Copy php folder and apache folder from extracted file and paste it to C:\xampp

  5. Add " C: " before \xampp\ to php ini file present in php folder.

  6. Start your apache and MySQL and check php version. It will show php 5.6.36

How to get highcharts dates in the x axis?

You write like this-:

xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
           day: '%d %b %Y'    //ex- 01 Jan 2016
        }
}

also check for other datetime format

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

Prevent the keyboard from displaying on activity start

You can also write these lines of code in the direct parent layout of the .xml layout file in which you have the "problem":

android:focusable="true"
android:focusableInTouchMode="true"

For example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    ...
    android:focusable="true"
    android:focusableInTouchMode="true" >

    <EditText
        android:id="@+id/myEditText"
        ...
        android:hint="@string/write_here" />

    <Button
        android:id="@+id/button_ok"
        ...
        android:text="@string/ok" />
</LinearLayout>


EDIT :

Example if the EditText is contained in another layout:

<?xml version="1.0" encoding="utf-8"?>
<ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    ... >                                            <!--not here-->

    ...    <!--other elements-->

    <LinearLayout
        android:id="@+id/theDirectParent"
        ...
        android:focusable="true"
        android:focusableInTouchMode="true" >        <!--here-->

        <EditText
            android:id="@+id/myEditText"
            ...
            android:hint="@string/write_here" />

        <Button
            android:id="@+id/button_ok"
            ...
            android:text="@string/ok" />
    </LinearLayout>

</ConstraintLayout>

The key is to make sure that the EditText is not directly focusable.
Bye! ;-)

Making view resize to its parent when added with addSubview

Just copy the parent view's frame to the child-view then add it. After that autoresizing will work. Actually you should only copy the size CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height)

childView.frame = CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height);
[parentView addSubview:childView];

When to use malloc for char pointers

Use malloc() when you don't know the amount of memory needed during compile time. In case if you have read-only strings then you can use const char* str = "something"; . Note that the string is most probably be stored in a read-only memory location and you'll not be able to modify it. On the other hand if you know the string during compiler time then you can do something like: char str[10]; strcpy(str, "Something"); Here the memory is allocated from stack and you will be able to modify the str. Third case is allocating using malloc. Lets say you don'r know the length of the string during compile time. Then you can do char* str = malloc(requiredMem); strcpy(str, "Something"); free(str);

How to use class from other files in C# with visual studio?

It would be more beneficial for us if we could see the actual project structure, as the classes alone do not say that much.

Assuming that both .cs files are in the same project (if they are in different projects inside the same solution, you'd have to add a reference to the project containing Class2.cs), you can click on the Class2 occurrence in your code that is underlined in red and press CTRL + . (period) or click on the blue bar that should be there. The first option appearing will then add the appropriate using statement automatically. If there is no such menu, it may indicate that there is something wrong with the project structure or a reference missing.

You could try making Class2 public, but it sounds like this can't be a problem here, since by default what you did is internal class Class2 and thus Class2 should be accessible if both are living in the same project/assembly. If you are referencing a different assembly or project wherein Class2 is contained, you have to make it public in order to access it, as internal classes can't be accessed from outside their assembly.

As for renaming: You can click Program.cs in the Solution Explorer and press F2 to rename it. It will then open up a dialog window asking you if the class Program itself and all references thereof should be renamed as well, which is usually what you want. Or you could just rename the class Program in the declaration and again open up the menu with the small blue bar (or, again, CTRL+.) and do the same, but it won't automatically rename the actual file accordingly.

Edit after your question edit: I have never used this option you used, but from quick checking I think that it's really not inside the same project then. Do the following when adding new classes to a project: In the Solution Explorer, right click the project you created and select [Add] -> [Class] or [Add] -> [New Item...] and then select 'Class'. This will automatically make the new class part of the project and thus the assembly (the assembly is basically the 'end product' after building the project). For me, there is also the shortcut Alt+Shift+C working to create a new class.

How to execute raw SQL in Flask-SQLAlchemy app

result = db.engine.execute(text("<sql here>"))

executes the <sql here> but doesn't commit it unless you're on autocommit mode. So, inserts and updates wouldn't reflect in the database.

To commit after the changes, do

result = db.engine.execute(text("<sql here>").execution_options(autocommit=True))

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

Is it possible to return empty in react render function?

for those developers who came to this question about checking where they can return null from component instead of checking in ternary mode to render or not render the component, the answer is YES, You Can!

i mean instead of this junk ternary condition inside your jsx in render part of your component:

// some component body
return(
  <section>
   {/* some ui */}
   
   { someCondition && <MyComponent /> }
   or
   { someCondition ? <MyComponent /> : null }

   {/* more ui */}
  </section>
)

you can check than condition inside your component like:

const MyComponent:React.FC = () => {
  
  // get someCondition from context at here before any thing


  if(someCondition) return null; // i mean this part , checking inside component! 
  
  return (
    <section>   
     // some ui...
    </section>
  )
}

Just Consider that in my case i provide the someCondition variable from a context in upper level component ( for example, just consider in your mind ) and i don't need to prop drill the someCondition inside MyComponent.

Just look how clean view your code gets after that, i mean you don't need to user ternary operator inside your JSX, and your parent component would like below:

// some component body
return(
  <section>
   {/* some ui */}
   
   <MyComponent />

   {/* more ui */}
  </section>
)

and MyComponent would handle the rest for you!

base64 encode in MySQL

Yet another custom implementation that doesn't require support table:

drop function if exists base64_encode;
create function base64_encode(_data blob)
returns text
begin
    declare _alphabet char(64) default 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    declare _lim int unsigned default length(_data);
    declare _i int unsigned default 0;
    declare _chk3 char(6) default '';
    declare _chk3int int default 0;
    declare _enc text default '';

    while _i < _lim do
        set _chk3 = rpad(hex(binary substr(_data, _i + 1, 3)), 6, '0');
        set _chk3int = conv(_chk3, 16, 10);
        set _enc = concat(
            _enc
            ,                  substr(_alphabet, ((_chk3int >> 18) & 63) + 1, 1)
            , if (_lim-_i > 0, substr(_alphabet, ((_chk3int >> 12) & 63) + 1, 1), '=')
            , if (_lim-_i > 1, substr(_alphabet, ((_chk3int >>  6) & 63) + 1, 1), '=')
            , if (_lim-_i > 2, substr(_alphabet, ((_chk3int >>  0) & 63) + 1, 1), '=')
        );
        set _i = _i + 3;
    end while;

    return _enc;
end;

drop function if exists base64_decode;
create function base64_decode(_enc text)
returns blob
begin
    declare _alphabet char(64) default 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    declare _lim int unsigned default 0;
    declare _i int unsigned default 0;
    declare _chr1byte tinyint default 0;
    declare _chk4int int default 0;
    declare _chk4int_bits tinyint default 0;
    declare _dec blob default '';
    declare _rem tinyint default 0;
    set _enc = trim(_enc);
    set _rem = if(right(_enc, 3) = '===', 3, if(right(_enc, 2) = '==', 2, if(right(_enc, 1) = '=', 1, 0)));
    set _lim = length(_enc) - _rem;

    while _i < _lim
    do
        set _chr1byte = locate(substr(_enc, _i + 1, 1), binary _alphabet) - 1;
        if (_chr1byte > -1)
        then
            set _chk4int = (_chk4int << 6) | _chr1byte;
            set _chk4int_bits = _chk4int_bits + 6;

            if (_chk4int_bits = 24 or _i = _lim-1)
            then
                if (_i = _lim-1 and _chk4int_bits != 24)
                then
                    set _chk4int = _chk4int << 0;
                end if;

                set _dec = concat(
                    _dec
                    ,                        char((_chk4int >> (_chk4int_bits -  8)) & 0xff)
                    , if(_chk4int_bits >  8, char((_chk4int >> (_chk4int_bits - 16)) & 0xff), '\0')
                    , if(_chk4int_bits > 16, char((_chk4int >> (_chk4int_bits - 24)) & 0xff), '\0')
                );
                set _chk4int = 0;
                set _chk4int_bits = 0;
            end if;
        end if;
        set _i = _i + 1;
    end while;

    return substr(_dec, 1, length(_dec) - _rem);
end;

Gist

You should convert charset after decoding: convert(base64_decode(base64_encode('????')) using utf8)

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

How do I get a list of all the duplicate items using pandas in python?

With Pandas version 0.17, you can set 'keep = False' in the duplicated function to get all the duplicate items.

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(['a','b','c','d','a','b'])

In [3]: df
Out[3]: 
       0
    0  a
    1  b
    2  c
    3  d
    4  a
    5  b

In [4]: df[df.duplicated(keep=False)]
Out[4]: 
       0
    0  a
    1  b
    4  a
    5  b

ReferenceError: document is not defined (in plain JavaScript)

This happened with me because I was using Next JS which has server side rendering. When you are using server side rendering there is no browser. Hence, there will not be any variable window or document. Hence this error shows up.

Work around :

If you are using Next JS you can use the dynamic rendering to prevent server side rendering for the component.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
  ssr: false
})

export default () => <DynamicComponentWithNoSSR />

If you are using any other server side rendering library. Then add the code that you want to run at the client side in componentDidMount. If you are using React Hooks then use useEffects in the place of componentsDidMount.

import React, {useState, useEffects} from 'react';

const DynamicComponentWithNoSSR = <>Some JSX</>

export default function App(){

[a,setA] = useState();
useEffect(() => {
    setA(<DynamicComponentWithNoSSR/>)
  });


return (<>{a}<>)
}

References :

  1. https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
  2. https://reactjs.org/docs/hooks-effect.html

jQuery: Scroll down page a set increment (in pixels) on click?

var y = $(window).scrollTop();  //your current y position on the page
$(window).scrollTop(y+150);

Relational Database Design Patterns?

AskTom is probably the single most helpful resource on best practices on Oracle DBs. (I usually just type "asktom" as the first word of a google query on a particular topic)

I don't think it's really appropriate to speak of design patterns with relational databases. Relational databases are already the application of a "design pattern" to a problem (the problem being "how to represent, store and work with data while maintaining its integrity", and the design being the relational model). Other approches (generally considered obsolete) are the Navigational and Hierarchical models (and I'm nure many others exist).

Having said that, you might consider "Data Warehousing" as a somewhat separate "pattern" or approach in database design. In particular, you might be interested in reading about the Star schema.

Trigger Change event when the Input value changed programmatically?

If someone is using react, following will be useful:

https://stackoverflow.com/a/62111884/1015678

const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));

How to add an item to a drop down list in ASP.NET?

Try this, it will insert the list item at index 0;

DropDownList1.Items.Insert(0, new ListItem("Add New", ""));

Run a JAR file from the command line and specify classpath

You can do a Runtime.getRuntime.exec(command) to relaunch the jar including classpath with args.

Getting values from JSON using Python

What error is it giving you?

If you do exactly this:

data = json.loads('{"lat":444, "lon":555}')

Then:

data['lat']

SHOULD NOT give you any error at all.

"Undefined reference to" template class constructor

This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.

The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...) and cola<string>::cola(...) until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T> also.)

Understanding the problem

The problem is caused by the fact that main.cpp and cola.cpp will be compiled separately first. In main.cpp, the compiler will implicitly instantiate the template classes cola<float> and cola<string> because those particular instantiations are used in main.cpp. The bad news is that the implementations of those member functions are not in main.cpp, nor in any header file included in main.cpp, and therefore the compiler can't include complete versions of those functions in main.o. When compiling cola.cpp, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float> or cola<string>. Remember, when compiling cola.cpp, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>, cola<char>, cola<ostream>, cola< cola<int> > ... and so on ...)

The two answers are:

  • Tell the compiler, at the end of cola.cpp, which particular template classes will be required, forcing it to compile cola<float> and cola<string>.
  • Put the implementation of the member functions in a header file that will be included every time any other 'translation unit' (such as main.cpp) uses the template class.

Answer 1: Explicitly instantiate the template, and its member definitions

At the end of cola.cpp, you should add lines explicitly instantiating all the relevant templates, such as

template class cola<float>;
template class cola<string>;

and you add the following two lines at the end of nodo_colaypila.cpp:

template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;

This will ensure that, when the compiler is compiling cola.cpp that it will explicitly compile all the code for the cola<float> and cola<string> classes. Similarly, nodo_colaypila.cpp contains the implementations of the nodo_colaypila<...> classes.

In this approach, you should ensure that all the of the implementation is placed into one .cpp file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).

Answer 2: Copy the code into the relevant header file

The common answer is to move all the code from the implementation files cola.cpp and nodo_colaypila.cpp into cola.h and nodo_colaypila.h. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.

Summary

The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float> and cola<string>, if you want to use something else, tell me first and will can verify it works before enabling it.").

Finally, there are three other minor typos in the code in your question:

  • You are missing an #endif at the end of nodo_colaypila.h
  • in cola.h nodo_colaypila<T>* ult, pri; should be nodo_colaypila<T> *ult, *pri; - both are pointers.
  • nodo_colaypila.cpp: The default parameter should be in the header file nodo_colaypila.h, not in this implementation file.

How to bind DataTable to Datagrid

You could use DataGrid in WPF

SqlDataAdapter da = new SqlDataAdapter("Select * from Table",con);
DataTable dt = new DataTable("Call Reciept");
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.ItemsSource = dt.DefaultView;

View's getWidth() and getHeight() returns 0

This is a little old, but was having trouble with this myself (needing to animate objects in a fragment when it is created). This solution worked for me, I believe it is self explanatory.

class YourFragment: Fragment() {
    var width = 0
    var height = 0


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val root = inflater.inflate(R.layout.fragment_winner_splash, container, false)
    container?.width.let {
        if (it != null) {
            width = it
        }
    }
    container?.height.let {
        if (it != null) {
            height = it
        }
    }
    
    return root
}
 

How to POST form data with Spring RestTemplate?

How to POST mixed data: File, String[], String in one request.

You can use only what you need.

private String doPOST(File file, String[] array, String name) {
    RestTemplate restTemplate = new RestTemplate(true);

    //add file
    LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));

    //add array
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
    for (String item : array) {
        builder.queryParam("array", item);
    }

    //add some String
    builder.queryParam("name", name);

    //another staff
    String result = "";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(params, headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(
            builder.build().encode().toUri(),
            HttpMethod.POST,
            requestEntity,
            String.class);

    HttpStatus statusCode = responseEntity.getStatusCode();
    if (statusCode == HttpStatus.ACCEPTED) {
        result = responseEntity.getBody();
    }
    return result;
}

The POST request will have File in its Body and next structure:

POST https://my_url?array=your_value1&array=your_value2&name=bob 

How to set an environment variable only for the duration of the script?

Just put

export HOME=/blah/whatever

at the point in the script where you want the change to happen. Since each process has its own set of environment variables, this definition will automatically cease to have any significance when the script terminates (and with it the instance of bash that has a changed environment).

How to set the title of UIButton as left alignment?

Try

button.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;

How do you access the value of an SQL count () query in a Java program

It's similar to above but you can try like

public Integer count(String tableName) throws CrateException {
        String query = String.format("Select count(*) as size from %s", tableName);
        try (Statement s = connection.createStatement()) {
            try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
                Preconditions.checkArgument(resultSet.next(), "Result set is empty");
                return resultSet.getInt("size");
            }
        } catch (SQLException e) {
            throw new CrateException(e);
        }
    }
}

Insert data into table with result from another select query

Below is an example of such a query:

INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));

SQL Server : converting varchar to INT

This is more for someone Searching for a result, than the original post-er. This worked for me...

declare @value varchar(max) = 'sad';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));

returns 0

declare @value varchar(max) = '3';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));

returns 3

How to compare two floating point numbers in Bash?

Use korn shell, in bash you may have to compare the decimal part separately

#!/bin/ksh
X=0.2
Y=0.2
echo $X
echo $Y

if [[ $X -lt $Y ]]
then
     echo "X is less than Y"
elif [[ $X -gt $Y ]]
then
     echo "X is greater than Y"
elif [[ $X -eq $Y ]]
then
     echo "X is equal to Y"
fi

How to return the output of stored procedure into a variable in sql server

You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success.

If no return is explicitly set, then the stored procedure returns zero.

   CREATE PROCEDURE GetImmediateManager
      @employeeID INT,
      @managerID INT OUTPUT
   AS
   BEGIN
     SELECT @managerID = ManagerID 
     FROM HumanResources.Employee 
     WHERE EmployeeID = @employeeID

     if @@rowcount = 0 -- manager not found?
       return 1;
   END

And you call it this way:

DECLARE @return_status int;
DECLARE @managerID int;

EXEC @return_status = GetImmediateManager 2, @managerID output;
if @return_status = 1
  print N'Immediate manager not found!';
else 
  print N'ManagerID is ' + @managerID;
go

You should use the return value for status codes only. To return data, you should use output parameters.

If you want to return a dataset, then use an output parameter of type cursor.

more on RETURN statement

Get json value from response

var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301

results is now an object.

ImageButton in Android

you are setting the image with the property "src"

android:src="@drawable/eye">

use "background" property instead "src" property:

android:background="@drawable/eye"

like:

<ImageButton
  android:id="@+id/Button01"
  android:scaleType="fitXY" 
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:cropToPadding="false"
  android:paddingLeft="10dp"
  android:background="@drawable/eye"> // this is the image(eye)
</ImageButton>

How to create nested directories using Mkdir in Golang?

This way you don't have to use any magic numbers:

os.MkdirAll(newPath, os.ModePerm)

Also, rather than using + to create paths, you can use:

import "path/filepath"
path := filepath.Join(someRootPath, someSubPath)

The above uses the correct separators automatically on each platform for you.

Is it possible to GROUP BY multiple columns using MySQL?

Yes, but what does grouping by more two columns mean? Well, it's the same as grouping by each unique pair per row. The order you list the columns changes the way the rows are sorted.

In your example, you would write

GROUP BY fV.tier_id, f.form_template_id

Meanwhile, the code

GROUP BY f.form_template_id, fV.tier_id

would give similar results, but sorted differently.

Angular 2 execute script after template render

I have found that the best place is in NgAfterViewChecked(). I tried to execute code that would scroll to an ng-accordion panel when the page was loaded. I tried putting the code in NgAfterViewInit() but it did not work there (NPE). The problem was that the element had not been rendered yet. There is a problem with putting it in NgAfterViewChecked(). NgAfterViewChecked() is called several times as the page is rendered. Some calls are made before the element is rendered. This means a check for null may be required to guard the code from NPE. I am using Angular 8.

ImportError: No module named 'django.core.urlresolvers'

urlresolver has been removed in the higher version of Django - Please upgrade your django installation. I fixed it using the following command.

pip install django==2.0 --upgrade

Select distinct values from a list using LINQ in C#

You can use GroupBy with anonymous type, and then get First:

list.GroupBy(e => new { 
                          empLoc = e.empLoc, 
                          empPL = e.empPL, 
                          empShift = e.empShift 
                       })

    .Select(g => g.First());

How can you profile a Python script?

It's worth pointing out that using the profiler only works (by default) on the main thread, and you won't get any information from other threads if you use them. This can be a bit of a gotcha as it is completely unmentioned in the profiler documentation.

If you also want to profile threads, you'll want to look at the threading.setprofile() function in the docs.

You could also create your own threading.Thread subclass to do it:

class ProfiledThread(threading.Thread):
    # Overrides threading.Thread.run()
    def run(self):
        profiler = cProfile.Profile()
        try:
            return profiler.runcall(threading.Thread.run, self)
        finally:
            profiler.dump_stats('myprofile-%d.profile' % (self.ident,))

and use that ProfiledThread class instead of the standard one. It might give you more flexibility, but I'm not sure it's worth it, especially if you are using third-party code which wouldn't use your class.

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

You can use a function with an array, a for loop, and a Math.random() variable to solve that. The for loop pushes numbers into the array, which will contain all the numbers in your range. Then the Math.random() randomly selects one, based on the array's length.

function randNumInRange(min, max) {
  var range = []
  for(var count = min; count <= max; count++) {
    range.push(count);
  }
  var randNum = Math.floor(Math.random() * range.length);
  alert(range[randNum]);
}

Nth max salary in Oracle

Select min(salary) from (
  select distinct(salary) from empdetails order by salary desc
) where rownum <=&rn

Just enter nth number which you want.

How to hide the bar at the top of "youtube" even when mouse hovers over it?

To remove you tube controls and title you can do something like this.

<iframe width="560" height="315" src="https://www.youtube.com/embed/zP0Wnb9RI9Q?autoplay=1&showinfo=0&controls=0" frameborder="0" allowfullscreen ></iframe>

check this example how it look

showinfo=0 is used to remove title and &controls=0 is used for remove controls like volume,play,pause,expend.

"Press Any Key to Continue" function in C

You can try more system indeppended method: system("pause");

How to only get file name with Linux 'find'?

On mac (BSD find) use:

find /dir1 -type f -exec basename {} \;

Why am I getting the error "connection refused" in Python? (Sockets)

This error means that for whatever reason the client cannot connect to the port on the computer running server script. This can be caused by few things, like lack of routing to the destination, but since you can ping the server, it should not be the case. The other reason might be that you have a firewall somewhere between your client and the server - it could be on server itself or on the client. Given your network addressing, I assume both server and client are on the same LAN, so there shouldn't be any router/firewall involved that could block the traffic. In this case, I'd try the following:

  • check if you really have that port listening on the server (this should tell you if your code does what you think it should): based on your OS, but on linux you could do something like netstat -ntulp
  • check from the server, if you're accepting the connections to the server: again based on your OS, but telnet LISTENING_IP LISTENING_PORT should do the job
  • check if you can access the port of the server from the client, but not using the code: just us the telnet (or appropriate command for your OS) from the client

and then let us know the findings.

How to calculate the difference between two dates using PHP?

I voted for jurka's answer as that's my favorite, but I have a pre-php.5.3 version...

I found myself working on a similar problem - which is how I got to this question in the first place - but just needed a difference in hours. But my function solved this one pretty nicely as well and I don't have anywhere in my own library to keep it where it won't get lost and forgotten, so... hope this is useful to someone.

/**
 *
 * @param DateTime $oDate1
 * @param DateTime $oDate2
 * @return array 
 */
function date_diff_array(DateTime $oDate1, DateTime $oDate2) {
    $aIntervals = array(
        'year'   => 0,
        'month'  => 0,
        'week'   => 0,
        'day'    => 0,
        'hour'   => 0,
        'minute' => 0,
        'second' => 0,
    );

    foreach($aIntervals as $sInterval => &$iInterval) {
        while($oDate1 <= $oDate2){ 
            $oDate1->modify('+1 ' . $sInterval);
            if ($oDate1 > $oDate2) {
                $oDate1->modify('-1 ' . $sInterval);
                break;
            } else {
                $iInterval++;
            }
        }
    }

    return $aIntervals;
}

And the test:

$oDate = new DateTime();
$oDate->modify('+111402189 seconds');
var_dump($oDate);
var_dump(date_diff_array(new DateTime(), $oDate));

And the result:

object(DateTime)[2]
  public 'date' => string '2014-04-29 18:52:51' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'America/New_York' (length=16)

array
  'year'   => int 3
  'month'  => int 6
  'week'   => int 1
  'day'    => int 4
  'hour'   => int 9
  'minute' => int 3
  'second' => int 8

I got the original idea from here, which I modified for my uses (and I hope my modification will show on that page as well).

You can very easily remove intervals you don't want (say "week") by removing them from the $aIntervals array, or maybe adding an $aExclude parameter, or just filter them out when you output the string.

How to select the first, second, or third element with a given class name?

You probably finally realized this between posting this question and today, but the very nature of selectors makes it impossible to navigate through hierarchically unrelated HTML elements.

Or, to put it simply, since you said in your comment that

there are no uniform parent containers

... it's just not possible with selectors alone, without modifying the markup in some way as shown by the other answers.

You have to use the jQuery .eq() solution.

Differences between action and actionListener

TL;DR:

The ActionListeners (there can be multiple) execute in the order they were registered BEFORE the action

Long Answer:

A business action typically invokes an EJB service and if necessary also sets the final result and/or navigates to a different view if that is not what you are doing an actionListener is more appropriate i.e. for when the user interacts with the components, such as h:commandButton or h:link they can be handled by passing the name of the managed bean method in actionListener attribute of a UI Component or to implement an ActionListener interface and pass the implementation class name to actionListener attribute of a UI Component.

Right way to reverse a pandas DataFrame?

This works:

    for i,r in data[::-1].iterrows():
        print(r['Odd'], r['Even'])