Programs & Examples On #Mixed mode

A mixed-mode application is any application that combines native code (C++) with managed code (such as Visual Basic, Visual C#, or C++/CLI that runs on the common language runtime).

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)

To quote the most relevant bits:

[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.

The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”

Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.

The full post explains this in more detail. At RTM, the MSDN docs on this should be better.

How to retrieve element value of XML using Java?

There are two general ways of doing that. You will either create a Domain Object Model of that XML file, take a look at this

and the second choice is using event driven parsing, which is an alternative to DOM xml representation. Imho you can find the best overall comparison of these two basic techniques here. Of course there are much more to know about processing xml, for instance if you are given XML schema definition (XSD), you could use JAXB.

Uninstall old versions of Ruby gems

For removing older versions of all installed gems, following 2 commands are useful:

 gem cleanup --dryrun

Above command will preview what gems are going to be removed.

 gem cleanup

Above command will actually remove them.

Implement a simple factory pattern with Spring 3 annotations

Following answer of DruidKuma

Litte refactor of his factory with autowired constructor:

@Service
public class MyServiceFactory {

    private static final Map<String, MyService> myServiceCache = new HashMap<>();

    @Autowired
    private MyServiceFactory(List<MyService> services) {
        for(MyService service : services) {
            myServiceCache.put(service.getType(), service);
        }
    }

    public static MyService getService(String type) {
        MyService service = myServiceCache.get(type);
        if(service == null) throw new RuntimeException("Unknown service type: " + type);
        return service;
    }
}

Set 4 Space Indent in Emacs in Text Mode

You may find it easier to set up your tabs as follows:

M-x customize-group

At the Customize group: prompt enter indent.

You'll see a screen where you can set all you indenting options and set them for the current session or save them for all future sessions.

If you do it this way you'll want to set up a customisations file.

How to count the occurrence of certain item in an ndarray?

If you don't want to use numpy or a collections module you can use a dictionary:

d = dict()
a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
for item in a:
    try:
        d[item]+=1
    except KeyError:
        d[item]=1

result:

>>>d
{0: 8, 1: 4}

Of course you can also use an if/else statement. I think the Counter function does almost the same thing but this is more transparant.

How to redirect siteA to siteB with A or CNAME records

I think several of the answers hit around the possible solution to your problem.

I agree the easiest (and best solution for SEO purposes) is the 301 redirect. In IIS this is fairly trivial, you'd create a site for subdomain.hostone.com, after creating the site, right-click on the site and go into properties. Click on the "Home Directory" tab of the site properties window that opens. Select the radio button "A redirection to a URL", enter the url for the new site (http://subdomain.hosttwo.com), and check the checkboxes for "The exact URL entered above", "A permanent redirection for this resource" (this second checkbox causes a 301 redirect, instead of a 302 redirect). Click OK, and you're done.

Or you could create a page on the site of http://subdomain.hostone.com, using one of the following methods (depending on what the hosting platform supports)

PHP Redirect:


<?
Header( "HTTP/1.1 301 Moved Permanently" ); 
Header( "Location: http://subdomain.hosttwo.com" ); 
?>

ASP Redirect:


<%@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently"
Response.AddHeader "Location","http://subdomain.hosttwo.com"
%>

ASP .NET Redirect:


<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://subdomain.hosttwo.com");
}
</script>

Now assuming your CNAME record is correctly created, then the only problem you are experiencing is that the site created for http://subdomain.hosttwo.com is using a shared IP, and host headers to determine which site should be displayed. To resolve this issue under IIS, in IIS Manager on the web server, you'd right-click on the site for subdomain.hosttwo.com, and click "Properties". On the displayed "Web Site" tab, you should see an "Advanced" button next to the IP address that you'll need to click. On the "Advanced Web Site Identification" window that appears, click "Add". Select the same IP address that is already being used by subdomain.hosttwo.com, enter 80 as the TCP port, and then enter subdomain.hosttwo.com as the Host Header value. Click OK until you are back to the main IIS Manager window, and you should be good to go. Open a browser, and browse to http://subdomain.hostone.com, and you'll see the site at http://subdomain.hosttwo.com appear, even though your URL shows http://subdomain.hostone.com

Hope that helps...

Date Conversion from String to sql Date in Java giving different output?

While using the date formats, you may want to keep in mind to always use MM for months and mm for minutes. That should resolve your problem.

How to check if array element exists or not in javascript?

If elements of array are also simple objects or arrays, you can use some function:

// search object
var element = { item:'book', title:'javasrcipt'};

[{ item:'handbook', title:'c++'}, { item:'book', title:'javasrcipt'}].some(function(el){
    if( el.item === element.item && el.title === element.title ){
        return true; 
     } 
});

[['handbook', 'c++'], ['book', 'javasrcipt']].some(function(el){
    if(el[0] == element.item && el[1] == element.title){
        return true;
    }
});

Return None if Dictionary key is not available

I usually use a defaultdict for situations like this. You supply a factory method that takes no arguments and creates a value when it sees a new key. It's more useful when you want to return something like an empty list on new keys (see the examples).

from collections import defaultdict
d = defaultdict(lambda: None)
print d['new_key']  # prints 'None'

Clear the value of bootstrap-datepicker

I was having similar trouble and the following worked for me:

$('#datepicker').val('').datepicker('update');

Both method calls were needed, otherwise it didn't clear.

Create directory if it does not exist

I had the exact same problem. You can use something like this:

$local = Get-Location;
$final_local = "C:\Processing";

if(!$local.Equals("C:\"))
{
    cd "C:\";
    if((Test-Path $final_local) -eq 0)
    {
        mkdir $final_local;
        cd $final_local;
        liga;
    }

    ## If path already exists
    ## DB Connect
    elseif ((Test-Path $final_local) -eq 1)
    {
        cd $final_local;
        echo $final_local;
        liga;  (function created by you TODO something)
    }
}

JavaScript file upload size validation

No Yes, using the File API in newer browsers. See TJ's answer for details.

If you need to support older browsers as well, you will have to use a Flash-based uploader like SWFUpload or Uploadify to do this.

The SWFUpload Features Demo shows how the file_size_limit setting works.

Note that this (obviously) needs Flash, plus the way it works is a bit different from normal upload forms.

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

try this :

 string getValue = Convert.ToString(cmd.ExecuteScalar());

Call php function from JavaScript

This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.

After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.

You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .

Plain Javascript

In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.

The javascript

// handles the click event for link 1, sends the query
function getOutput() {
  getRequest(
      'myAjax.php', // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  return false;
}  
// handles drawing an error message
function drawError() {
    var container = document.getElementById('output');
    container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return false;
            }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req.readyState == 4) {
            return req.status === 200 ? 
                success(req.responseText) : error(req.status);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}

The HTML

<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>

The PHP

// file myAjax.php
<?php
  echo 'hello world!';
?>

Try it out: http://jsfiddle.net/GRMule/m8CTk/


With a javascript library (jQuery et al)

Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.

Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:

// handles the click event, sends the query
function getOutput() {
   $.ajax({
      url:'myAjax.php',
      complete: function (response) {
          $('#output').html(response.responseText);
      },
      error: function () {
          $('#output').html('Bummer: there was an error!');
      }
  });
  return false;
}

Try it out: http://jsfiddle.net/GRMule/WQXXT/

Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.

If this is all you need to do, write the plain javascript once and you're done.

Documentation

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I would rather use plt.clf() after every plt.show() to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.

Similarly, you could do plt.cla() to just clear the current axes.

To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:

fig, axes = plt.subplots(nrows=2, ncols=2)

axes[0, 1].clear()

Django gives Bad Request (400) when DEBUG = False

Try to run your server with the --insecure just like this:

python manage.py runserver --insecure

How do I insert values into a Map<K, V>?

The two errors you have in your code are very different.

The first problem is that you're initializing and populating your Map in the body of the class without a statement. You can either have a static Map and a static {//TODO manipulate Map} statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor.

The second problem is that you cannot treat a Map syntactically like an array, so the statement data["John"] = "Taxi Driver"; should be replaced by data.put("John", "Taxi Driver"). If you already have a "John" key in your HashMap, its value will be replaced with "Taxi Driver".

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

Try to use GMT instead of UTC. They refer to the same time zone, yet the name GMT is more common and might work.

How to query a CLOB column in Oracle

This works

select DBMS_LOB.substr(myColumn, 3000) from myTable

How to use SVN, Branch? Tag? Trunk?

For committing, I use the following strategies:

  • commit as often as possible.

  • Each feature change/bugfix should get its own commit (don't commit many files at once since that will make the history for that file unclear -- e.g. If I change a logging module and a GUI module independently and I commit both at once, both changes will be visible in both file histories. This makes reading a file history difficult),

  • don't break the build on any commit -- it should be possible to retrieve any version of the repository and build it.

All files that are necessary for building and running the app should be in SVN. Test files and such should not, unless they are part of the unit tests.

Javascript change font color

You can use the HTML tag in order to apply font size, font color in one line on JavaScript, as well as you can use .fontcolor() method to define color, .fontsize() method to define the font size, .bold() method to define bold, etc. These are called JavaScript Built-in Functions.

  • Here is a list of some JavaScript built-in functions:

    .big()
    .small()
    .italics()
    .fixed()
    .strike()
    .sup()

  • The below built-in functions require parameters:

    .fontsize() //e.g.: the size to be applied in number .fontsize(4)

    .fontcolor("") //e.g.: the color to be applied in string .fontcolor("red")

    .txt.link("") //e.g.: the url to be linkable as string .link("www.test.com")

    .toUpperCase() //e.g.: the converted to uppercase to be applied in string .toUpperCase()

  • Remember the syntax is: string.functionName() e.g.:

    var txt = "Hello World!"; txt.bold();

  • This also can be done in one line:

    var txt = "Hello World!".bold();

    The result will be: Hello World!

  • You can use multiple built-in functions in one line, adding one next to the other. e.g.:

    "10/22/2018".fontcolor("red").fontsize(4).bold()

  • The following is an example how I used it on my JavaScript code to change font (color, size, bold) using both HTML tags and JavaScript functions:

vForm.message = "<HTML><font size = 4 color = 'red'><b> Application Deadline was </b></font></HTML> " + "10/22/2018".fontcolor("red").fontsize(4).bold(); /* setting HTML font color, size, bold and combined them with JavaScript functions to change font color, size, bold in JavaScript code */

  • Here is the result:

Application Deadline was  10/22/2018

Rotating and spacing axis labels in ggplot2

I'd like to provide an alternate solution, a robust solution similar to what I am about to propose was required in the latest version of ggtern, since introducing the canvas rotation feature.

Basically, you need to determine the relative positions using trigonometry, by building a function which returns an element_text object, given angle (ie degrees) and positioning (ie one of x,y,top or right) information.

#Load Required Libraries
library(ggplot2)
library(gridExtra)

#Build Function to Return Element Text Object
rotatedAxisElementText = function(angle,position='x'){
  angle     = angle[1]; 
  position  = position[1]
  positions = list(x=0,y=90,top=180,right=270)
  if(!position %in% names(positions))
    stop(sprintf("'position' must be one of [%s]",paste(names(positions),collapse=", ")),call.=FALSE)
  if(!is.numeric(angle))
    stop("'angle' must be numeric",call.=FALSE)
  rads  = (angle - positions[[ position ]])*pi/180
  hjust = 0.5*(1 - sin(rads))
  vjust = 0.5*(1 + cos(rads))
  element_text(angle=angle,vjust=vjust,hjust=hjust)
}

Frankly, in my opinion, I think that an 'auto' option should be made available in ggplot2 for the hjust and vjust arguments, when specifying the angle, anyway, lets demonstrate how the above works.

#Demonstrate Usage for a Variety of Rotations
df    = data.frame(x=0.5,y=0.5)
plots = lapply(seq(0,90,length.out=4),function(a){
  ggplot(df,aes(x,y)) + 
    geom_point() + 
    theme(axis.text.x = rotatedAxisElementText(a,'x'),
          axis.text.y = rotatedAxisElementText(a,'y')) +
    labs(title = sprintf("Rotated %s",a))
})
grid.arrange(grobs=plots)

Which produces the following:

Example

Get program path in VB.NET?

You can get path by this code

Dim CurDir as string = My.Application.Info.DirectoryPath

CSS media query to target iPad and iPad only?

I am a bit late to answer this but none of the above worked for me.

This is what worked for me

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
    //your styles here
   }

Checkout old commit and make it a new commit

The other answers so far create new commits that undo what is in older commits. It is possible to go back and "change history" as it were, but this can be a bit dangerous. You should only do this if the commit you're changing has not been pushed to other repositories.

The command you're looking for is git rebase --interactive

If you want to change HEAD~3, the command you want to issue is git rebase --interactive HEAD~4. This will open a text editor and allow you to specify which commits you want to change.

Practice on a different repository before you try this with something important. The man pages should give you all the rest of the information you need.

How to extract this specific substring in SQL Server?

If you need to split something into 3 pieces, such as an email address and you don't know the length of the middle part, try this (I just ran this on sqlserver 2012 so I know it works):

SELECT top 2000 
    emailaddr_ as email,
    SUBSTRING(emailaddr_, 1,CHARINDEX('@',emailaddr_) -1) as username,
    SUBSTRING(emailaddr_, CHARINDEX('@',emailaddr_)+1, (LEN(emailaddr_) - charindex('@',emailaddr_) - charindex('.',reverse(emailaddr_)) ))  domain 
FROM 
    emailTable
WHERE 
    charindex('@',emailaddr_)>0 
    AND 
    charindex('.',emailaddr_)>0;
GO

Hope this helps.

How to change language settings in R

on windows, when you have no admin right, just create a new program shortcut to Rgui.exe. Then in the properties of that shortcut, go to the 'Shortcut' tab and modify the target to include the system language of your choice, e.g. "C:\Program Files\R\R-3.5.3\bin\x64\Rgui.exe" LANGUAGE=en

Convert PDF to image with high resolution

The following python script will work on any Mac (Snow Leopard and upward). It can be used on the command line with successive PDF files as arguments, or you can put in into a Run Shell Script action in Automator, and make a Service (Quick Action in Mojave).

You can set the resolution of the output image in the script.

The script and a Quick Action can be downloaded from github.

#!/usr/bin/python
# coding: utf-8

import os, sys
import Quartz as Quartz
from LaunchServices import (kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG, kCFAllocatorDefault) 

resolution = 300.0 #dpi
scale = resolution/72.0

cs = Quartz.CGColorSpaceCreateWithName(Quartz.kCGColorSpaceSRGB)
whiteColor = Quartz.CGColorCreate(cs, (1, 1, 1, 1))
# Options: kCGImageAlphaNoneSkipLast (no trans), kCGImageAlphaPremultipliedLast 
transparency = Quartz.kCGImageAlphaNoneSkipLast

#Save image to file
def writeImage (image, url, type, options):
    destination = Quartz.CGImageDestinationCreateWithURL(url, type, 1, None)
    Quartz.CGImageDestinationAddImage(destination, image, options)
    Quartz.CGImageDestinationFinalize(destination)
    return

def getFilename(filepath):
    i=0
    newName = filepath
    while os.path.exists(newName):
        i += 1
        newName = filepath + " %02d"%i
    return newName

if __name__ == '__main__':

    for filename in sys.argv[1:]:
        pdf = Quartz.CGPDFDocumentCreateWithProvider(Quartz.CGDataProviderCreateWithFilename(filename))
        numPages = Quartz.CGPDFDocumentGetNumberOfPages(pdf)
        shortName = os.path.splitext(filename)[0]
        prefix = os.path.splitext(os.path.basename(filename))[0]
        folderName = getFilename(shortName)
        try:
            os.mkdir(folderName)
        except:
            print "Can't create directory '%s'"%(folderName)
            sys.exit()

        # For each page, create a file
        for i in range (1, numPages+1):
            page = Quartz.CGPDFDocumentGetPage(pdf, i)
            if page:
        #Get mediabox
                mediaBox = Quartz.CGPDFPageGetBoxRect(page, Quartz.kCGPDFMediaBox)
                x = Quartz.CGRectGetWidth(mediaBox)
                y = Quartz.CGRectGetHeight(mediaBox)
                x *= scale
                y *= scale
                r = Quartz.CGRectMake(0,0,x, y)
        # Create a Bitmap Context, draw a white background and add the PDF
                writeContext = Quartz.CGBitmapContextCreate(None, int(x), int(y), 8, 0, cs, transparency)
                Quartz.CGContextSaveGState (writeContext)
                Quartz.CGContextScaleCTM(writeContext, scale,scale)
                Quartz.CGContextSetFillColorWithColor(writeContext, whiteColor)
                Quartz.CGContextFillRect(writeContext, r)
                Quartz.CGContextDrawPDFPage(writeContext, page)
                Quartz.CGContextRestoreGState(writeContext)
        # Convert to an "Image"
                image = Quartz.CGBitmapContextCreateImage(writeContext) 
        # Create unique filename per page
                outFile = folderName +"/" + prefix + " %03d.png"%i
                url = Quartz.CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, outFile, len(outFile), False)
        # kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG
                type = kUTTypePNG
        # See the full range of image properties on Apple's developer pages.
                options = {
                    Quartz.kCGImagePropertyDPIHeight: resolution,
                    Quartz.kCGImagePropertyDPIWidth: resolution
                    }
                writeImage (image, url, type, options)
                del page

Creating a blurring overlay view

Here's an easy way to add custom blur without haggling with private APIs using UIViewPropertyAnimator:

First, declare class property:

var blurAnimator: UIViewPropertyAnimator!

Then set your blur view in viewDidLoad():

let blurEffectView = UIVisualEffectView()
blurEffectView.backgroundColor = .clear
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)

blurAnimator = UIViewPropertyAnimator(duration: 1, curve: .linear) { [blurEffectView] in
    blurEffectView.effect = UIBlurEffect(style: .light)
}

blurAnimator.fractionComplete = 0.15 // set the blur intensity.    

Note: This solution is not suitable for UICollectionView/UITableView cells

Heap space out of memory

I would like to add that this problem is similar to common Java memory leaks.

When the JVM garbage collector is unable to clear the "waste" memory of your Java / Java EE application over time, OutOfMemoryError: Java heap space will be the outcome.

It is important to perform a proper diagnostic first:

  • Enable verbose:gc. This will allow you to understand the memory growing pattern over time.
  • Generate and analyze a JVM Heap Dump. This will allow you to understand your application memory footprint and pinpoint the source of the memory leak(s).
  • You can also use Java profilers and runtime memory leak analyzer such as Plumbr as well to help you with this task.

Access restriction on class due to restriction on required library rt.jar?

I met the same problem. I found the answer in the website:http://www.17ext.com.
First,delete the JRE System Libraries. Then,import JRE System Libraries again.

I don't know why.However it fixed my problem,hope it can help you.

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

To customize tool bar style, first create tool bar custom style inheriting Widget.AppCompat.Toolbar, override properties and then add it to custom app theme as shown below, see http://www.zoftino.com/android-toolbar-tutorial for more information tool bar and styles.

   <style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="toolbarStyle">@style/MyToolBarStyle</item>
    </style>
    <style name="MyToolBarStyle" parent="Widget.AppCompat.Toolbar">
        <item name="android:background">#80deea</item>
        <item name="titleTextAppearance">@style/MyTitleTextAppearance</item>
        <item name="subtitleTextAppearance">@style/MySubTitleTextAppearance</item>
    </style>
    <style name="MyTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
        <item name="android:textSize">35dp</item>
        <item name="android:textColor">#ff3d00</item>
    </style>
    <style name="MySubTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Subtitle">
        <item name="android:textSize">30dp</item>
        <item name="android:textColor">#1976d2</item>
    </style>

How to test web service using command line curl

Answering my own question.

curl -X GET --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X DELETE --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
     -d 'param2_name=param2_value' https://www.example.com/mobile/resource

POSTing a file and additional parameter

curl -X POST -F 'param_name=@/filepath/filename' \
     -F 'extra_param_name=extra_param_value' --basic --user username:password \
     https://www.example.com/mobile/resource

How to place a JButton at a desired location in a JFrame using Java

Following line should be called before you add your component

pnlButton.setLayout(null);

Above will set your content panel to use absolute layout. This means you'd always have to set your component's bounds explicitly by using setBounds method.

In general I wouldn't recommend using absolute layout.

Finding out the name of the original repository you cloned from in Git

Edited for clarity:

This will work to to get the value if the remote.origin.url is in the form protocol://auth_info@git_host:port/project/repo.git. If you find it doesn't work, adjust the -f5 option that is part of the first cut command.

For the example remote.origin.url of protocol://auth_info@git_host:port/project/repo.git the output created by the cut command would contain the following:

-f1: protocol: -f2: (blank) -f3: auth_info@git_host:port -f4: project -f5: repo.git

If you are having problems, look at the output of the git config --get remote.origin.url command to see which field contains the original repository. If the remote.origin.url does not contain the .git string then omit the pipe to the second cut command.

#!/usr/bin/env bash
repoSlug="$(git config --get remote.origin.url | cut -d/ -f5 | cut -d. -f1)"
echo ${repoSlug}

How to get keyboard input in pygame?

You can get the events from pygame and then watch out for the KEYDOWN event, instead of looking at the keys returned by get_pressed()(which gives you keys that are currently pressed down, whereas the KEYDOWN event shows you which keys were pressed down on that frame).

What's happening with your code right now is that if your game is rendering at 30fps, and you hold down the left arrow key for half a second, you're updating the location 15 times.

events = pygame.event.get()
for event in events:
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            location -= 1
        if event.key == pygame.K_RIGHT:
            location += 1

To support continuous movement while a key is being held down, you would have to establish some sort of limitation, either based on a forced maximum frame rate of the game loop or by a counter which only allows you to move every so many ticks of the loop.

move_ticker = 0
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
    if move_ticker == 0:
        move_ticker = 10
        location -= 1
        if location == -1:
            location = 0
if keys[K_RIGHT]:
    if move_ticker == 0:   
        move_ticker = 10     
        location+=1
        if location == 5:
            location = 4

Then somewhere during the game loop you would do something like this:

if move_ticker > 0:
    move_ticker -= 1

This would only let you move once every 10 frames (so if you move, the ticker gets set to 10, and after 10 frames it will allow you to move again)

How to create an installer for a .net Windows Service using Visual Studio

I follow Kelsey's first set of steps to add the installer classes to my service project, but instead of creating an MSI or setup.exe installer I make the service self installing/uninstalling. Here's a bit of sample code from one of my services you can use as a starting point.

public static int Main(string[] args)
{
    if (System.Environment.UserInteractive)
    {
        // we only care about the first two characters
        string arg = args[0].ToLowerInvariant().Substring(0, 2);

        switch (arg)
        {
            case "/i":  // install
                return InstallService();

            case "/u":  // uninstall
                return UninstallService();

            default:  // unknown option
                Console.WriteLine("Argument not recognized: {0}", args[0]);
                Console.WriteLine(string.Empty);
                DisplayUsage();
                return 1;
        }
    }
    else
    {
        // run as a standard service as we weren't started by a user
        ServiceBase.Run(new CSMessageQueueService());
    }

    return 0;
}

private static int InstallService()
{
    var service = new MyService();

    try
    {
        // perform specific install steps for our queue service.
        service.InstallService();

        // install the service with the Windows Service Control Manager (SCM)
        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
    }
    catch (Exception ex)
    {
        if (ex.InnerException != null && ex.InnerException.GetType() == typeof(Win32Exception))
        {
            Win32Exception wex = (Win32Exception)ex.InnerException;
            Console.WriteLine("Error(0x{0:X}): Service already installed!", wex.ErrorCode);
            return wex.ErrorCode;
        }
        else
        {
            Console.WriteLine(ex.ToString());
            return -1;
        }
    }

    return 0;
}

private static int UninstallService()
{
    var service = new MyQueueService();

    try
    {
        // perform specific uninstall steps for our queue service
        service.UninstallService();

        // uninstall the service from the Windows Service Control Manager (SCM)
        ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
    }
    catch (Exception ex)
    {
        if (ex.InnerException.GetType() == typeof(Win32Exception))
        {
            Win32Exception wex = (Win32Exception)ex.InnerException;
            Console.WriteLine("Error(0x{0:X}): Service not installed!", wex.ErrorCode);
            return wex.ErrorCode;
        }
        else
        {
            Console.WriteLine(ex.ToString());
            return -1;
        }
    }

    return 0;
}

java.util.zip.ZipException: error in opening zip file

Simply to overcome the ZipException's, i have used a wrapper for commons-compress1.14 called jarchivelibwritten by thrau that makes it easy to extract or compress from and into File objects.

Example:

public static void main(String[] args) {
        String zipfilePath = 
                "E:/Selenium_Server/geckodriver-v0.19.0-linux64.tar.gz";
                //"E:/Selenium_Server/geckodriver-v0.19.0-win32.zip";
        String outdir = "E:/Selenium_Server/";
        exratctFileList(zipfilePath, outdir );
}
public void exratctFileList( String zipfilePath, String outdir ) throws IOException {
    File archive = new File( zipfilePath );
    File destinationDir = new File( outdir );

    Archiver archiver = null;
    if( zipfilePath.endsWith(".zip") ) {
        archiver = ArchiverFactory.createArchiver( ArchiveFormat.ZIP );
    } else if ( zipfilePath.endsWith(".tar.gz") ) {
        archiver = ArchiverFactory.createArchiver( ArchiveFormat.TAR, CompressionType.GZIP );
    }
    archiver.extract(archive, destinationDir);

    ArchiveStream stream = archiver.stream( archive );
    ArchiveEntry entry;

    while( (entry = stream.getNextEntry()) != null ) {
        String entryName = entry.getName();
        System.out.println("Entery Name : "+ entryName );
    }
    stream.close();
}

Maven dependency « You can download the jars from the Sonatype Maven Repository at org/rauschig/jarchivelib/.

<dependency>
  <groupId>org.rauschig</groupId>
  <artifactId>jarchivelib</artifactId>
  <version>0.7.1</version>
</dependency>

@see

Getting a count of rows in a datatable that meet certain criteria

int numberOfRecords = 0;

numberOfRecords = dtFoo.Select().Length;

MessageBox.Show(numberOfRecords.ToString());

IsNull function in DB2 SQL?

I'm not familiar with DB2, but have you tried COALESCE?

ie:


SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product

.htaccess rewrite to redirect root URL to subdirectory

A little googling, gives me these results:

RewriteEngine On
RewriteBase /
RewriteRule ^index.(.*)?$ http://domain.com/subfolder/ [r=301]

This will redirect any attempt to access a file named index.something to your subfolder, whether the file exists or not.

Or try this:

RewriteCond %{HTTP_HOST} !^www.sample.com$ [NC]
RewriteRule ^(.*)$ %{HTTP_HOST}/samlse/$1 [R=301,L]

I haven't done much redirect in the .htaccess file, so I'm not sure if this will work.

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

Node.js Error: connect ECONNREFUSED

You're trying to connect to localhost:8080 ... is any service running on your localhost and on this port? If not, the connection is refused which cause this error. I would suggest to check if there is anything running on localhost:8080 first.

In STL maps, is it better to use map::insert than []?

This is a rather restricted case, but judging from the comments I've received I think it's worth noting.

I've seen people in the past use maps in the form of

map< const key, const val> Map;

to evade cases of accidental value overwriting, but then go ahead writing in some other bits of code:

const_cast< T >Map[]=val;

Their reason for doing this as I recall was because they were sure that in these certain bits of code they were not going to be overwriting map values; hence, going ahead with the more 'readable' method [].

I've never actually had any direct trouble from the code that was written by these people, but I strongly feel up until today that risks - however small - should not be taken when they can be easily avoided.

In cases where you're dealing with map values that absolutely must not be overwritten, use insert. Don't make exceptions merely for readability.

Rails DB Migration - How To Drop a Table?

You won't always be able to simply generate the migration to already have the code you want. You can create an empty migration and then populate it with the code you need.

You can find information about how to accomplish different tasks in a migration here:

http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

More specifically, you can see how to drop a table using the following approach:

drop_table :table_name

Vertical Align Center in Bootstrap 4

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
</head>
<body>  
<div class="container">
    <div class="row align-items-center justify-content-center" style="height:100vh;">     
         <div>Center Div Here</div>
    </div>
</div>
</body>
</html>

Loop through an array in JavaScript

It seems that all the variants were listed, except forEach by lodash:

_.forEach([1, 2], (value) => {
  console.log(value);
});

Is there a naming convention for git repositories?

Maybe it is just my Java and C background showing, but I prefer CamelCase (CapCase) over punctuation in the name. My workgroup uses such names, probably to match the names of the app or service the repository contains.

PHP: Split a string in to an array foreach char

You can access a string using [], as you do for arrays:

$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
    $char = $str[$i];

No module named pkg_resources

the simple resoluition is that you can use conda to upgrade setuptools or entire enviroment. (Specially for windows user.)

conda upgrade -c anaconda setuptools

if the setuptools is removed, you need to install setuptools again.

conda install -c anaconda setuptools

if these all methodes doesn't work, you can upgrade conda environement. But I do not recommend that you need to reinstall and uninstall some packages because after that it will exacerbate the situation.

How can I get a list of all classes within current module in Python?

I frequently find myself writing command line utilities wherein the first argument is meant to refer to one of many different classes. For example ./something.py feature command —-arguments, where Feature is a class and command is a method on that class. Here's a base class that makes this easy.

The assumption is that this base class resides in a directory alongside all of its subclasses. You can then call ArgBaseClass(foo = bar).load_subclasses() which will return a dictionary. For example, if the directory looks like this:

  • arg_base_class.py
  • feature.py

Assuming feature.py implements class Feature(ArgBaseClass), then the above invocation of load_subclasses will return { 'feature' : <Feature object> }. The same kwargs (foo = bar) will be passed into the Feature class.

#!/usr/bin/env python3
import os, pkgutil, importlib, inspect

class ArgBaseClass():
    # Assign all keyword arguments as properties on self, and keep the kwargs for later.
    def __init__(self, **kwargs):
        self._kwargs = kwargs
        for (k, v) in kwargs.items():
            setattr(self, k, v)
        ms = inspect.getmembers(self, predicate=inspect.ismethod)
        self.methods = dict([(n, m) for (n, m) in ms if not n.startswith('_')])

    # Add the names of the methods to a parser object.
    def _parse_arguments(self, parser):
        parser.add_argument('method', choices=list(self.methods))
        return parser

    # Instantiate one of each of the subclasses of this class.
    def load_subclasses(self):
        module_dir = os.path.dirname(__file__)
        module_name = os.path.basename(os.path.normpath(module_dir))
        parent_class = self.__class__
        modules = {}
        # Load all the modules it the package:
        for (module_loader, name, ispkg) in pkgutil.iter_modules([module_dir]):
            modules[name] = importlib.import_module('.' + name, module_name)

        # Instantiate one of each class, passing the keyword arguments.
        ret = {}
        for cls in parent_class.__subclasses__():
            path = cls.__module__.split('.')
            ret[path[-1]] = cls(**self._kwargs)
        return ret

How to add property to object in PHP >= 5.3 strict mode without generating error

If you absolutely have to add the property to the object, I believe you could cast it as an array, add your property (as a new array key), then cast it back as an object. The only time you run into stdClass objects (I believe) is when you cast an array as an object or when you create a new stdClass object from scratch (and of course when you json_decode() something - silly me for forgetting!).

Instead of:

$foo = new StdClass();
$foo->bar = '1234';

You'd do:

$foo = array('bar' => '1234');
$foo = (object)$foo;

Or if you already had an existing stdClass object:

$foo = (array)$foo;
$foo['bar'] = '1234';
$foo = (object)$foo;

Also as a 1 liner:

$foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) );

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

An explanation of the following error:

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.

Summary:

You opened up more than the allowed limit of connections to the database. You ran something like this: Connection conn = myconn.Open(); inside of a loop, and forgot to run conn.close();. Just because your class is destroyed and garbage collected does not release the connection to the database. The quickest fix to this is to make sure you have the following code with whatever class that creates a connection:

protected void finalize() throws Throwable  
{  
    try { your_connection.close(); } 
    catch (SQLException e) { 
        e.printStackTrace();
    }
    super.finalize();  
}  

Place that code in any class where you create a Connection. Then when your class is garbage collected, your connection will be released.

Run this SQL to see postgresql max connections allowed:

show max_connections;

The default is 100. PostgreSQL on good hardware can support a few hundred connections at a time. If you want to have thousands, you should consider using connection pooling software to reduce the connection overhead.

Take a look at exactly who/what/when/where is holding open your connections:

SELECT * FROM pg_stat_activity;

The number of connections currently used is:

SELECT COUNT(*) from pg_stat_activity;

Debugging strategy

  1. You could give different usernames/passwords to the programs that might not be releasing the connections to find out which one it is, and then look in pg_stat_activity to find out which one is not cleaning up after itself.

  2. Do a full exception stack trace when the connections could not be created and follow the code back up to where you create a new Connection, make sure every code line where you create a connection ends with a connection.close();

How to set the max_connections higher:

max_connections in the postgresql.conf sets the maximum number of concurrent connections to the database server.

  1. First find your postgresql.conf file
  2. If you don't know where it is, query the database with the sql: SHOW config_file;
  3. Mine is in: /var/lib/pgsql/data/postgresql.conf
  4. Login as root and edit that file.
  5. Search for the string: "max_connections".
  6. You'll see a line that says max_connections=100.
  7. Set that number bigger, check the limit for your postgresql version.
  8. Restart the postgresql database for the changes to take effect.

What's the maximum max_connections?

Use this query:

select min_val, max_val from pg_settings where name='max_connections';

I get the value 8388607, in theory that's the most you are allowed to have, but then a runaway process can eat up thousands of connections, and surprise, your database is unresponsive until reboot. If you had a sensible max_connections like 100. The offending program would be denied a new connection.

Requested bean is currently in creation: Is there an unresolvable circular reference?

In my case, I was defining a bean and autowiring it in the constructor of the same class file.

@SpringBootApplication
public class MyApplication {
    private MyBean myBean;

    public MyApplication(MyBean myBean) {
        this.myBean = myBean;
    }

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

My solution was to move the bean definition to another class file.

@Configuration
public CustomConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

Unstage a deleted file in git

Assuming you're wanting to undo the effects of git rm <file> or rm <file> followed by git add -A or something similar:

# this restores the file status in the index
git reset -- <file>
# then check out a copy from the index
git checkout -- <file>

To undo git add <file>, the first line above suffices, assuming you haven't committed yet.

Oracle: SQL query that returns rows with only numeric values

The complete list of the regexp_like and other regexp functions in Oracle 11.1:

http://66.221.222.85/reference/regexp.html

In your example:

SELECT X
FROM test
WHERE REGEXP_LIKE(X, '^[[:digit:]]$');

When & why to use delegates?

Delegates Overview

Delegates have the following properties:

  • Delegates are similar to C++ function pointers, but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • Methods don't need to match the delegate signature exactly. For more information, see Covariance and Contra variance.
  • C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.

How to remove gem from Ruby on Rails application?

You can use

gem uninstall <gem-name>

Undo a particular commit in Git that's been pushed to remote repos

I don't like the auto-commit that git revert does, so this might be helpful for some.

If you just want the modified files not the auto-commit, you can use --no-commit

% git revert --no-commit <commit hash>

which is the same as the -n

% git revert -n <commit hash>

Gets last digit of a number

You have just created an empty integer array. The array guess does not contain anything to my knowledge. The rest you should work out to get better.

Escaping a forward slash in a regular expression

If the delimiter is /, you will need to escape.

SQL Error: ORA-12899: value too large for column

In my case I'm using C# OracleCommand with OracleParameter, and I set all the the parameters Size property to max length of each column, then the error solved.

OracleParameter parm1 = new OracleParameter();
param1.OracleDbType = OracleDbType.Varchar2;
param1.Value = "test1";
param1.Size = 8;

OracleParameter parm2 = new OracleParameter();
param2.OracleDbType = OracleDbType.Varchar2;
param2.Value = "test1";
param2.Size = 12;

jQuery prevent change for select

Another option to consider is disabling it when you do not want it to be able to be changed and enabling it:

//When select should be disabled:
{
    $('#my_select').attr('disabled', 'disabled');
}

//When select should not be disabled
{
    $('#my_select').removeAttr('disabled');
}

Update since your comment (if I understand the functionality you want):

$("#dropdown").change(function()
{
    var answer = confirm("Are you sure you want to change your selection?")
    {
        if(answer)
        {
            //Update dropdown (Perform update logic)
        }
        else
        {
            //Allow Change (Do nothing - allow change)
        } 
    }            
}); 

Demo

Save array in mysql database

Use the PHP function serialize() to convert arrays to strings. These strings can easily be stored in MySQL database. Using unserialize() they can be converted to arrays again if needed.

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

Since JsonSerializer is deprecated in .Net 4.0+ I used http://www.newtonsoft.com/json to solve this issue.

NuGet- > Install-Package Newtonsoft.Json

How to fix "'System.AggregateException' occurred in mscorlib.dll"

As the message says, you have a task which threw an unhandled exception.

Turn on Break on All Exceptions (Debug, Exceptions) and rerun the program.
This will show you the original exception when it was thrown in the first place.


(comment appended): In VS2015 (or above). Select Debug > Options > Debugging > General and unselect the "Enable Just My Code" option.

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I had many connections I couldn't delete but didn't want to delete them all. So, I extended Dang Thanh and Richard Ho 's solution so it would prompt user to decide which connections to delete.

To delete some but not all connections in a Workbook:

Public Function deleteConnections()

    Dim xlBook As Workbook
    Dim cn As WorkbookConnection
    Dim Result As Variant

    Set xlBook = ActiveWorkbook

    For Each cn In xlBook.Connections

        Dim strMsg As String
        strMsg = "Would you like to delete: " & vbNewLine & cn.Name
        Result = MsgBox(strMsg, vbYesNo)

        If Result = vbYes Then
            cn.Delete
        End If

    Next cn

End Function

Removing address bar from browser (to view on Android)

I hope it also useful

window.addEventListener("load", function() 
{
    if(!window.pageYOffset)
    { 
        hideAddressBar(); 
    }
    window.addEventListener("orientationchange", hideAddressBar);
});

Android studio - Failed to find target android-18

This will also happen if you have written compileSdkVersion = 22 e.g. (as used in the "new new" Android build system) instead of compileSdkVersion 22.

Display Bootstrap Modal using javascript onClick

I was looking for the onClick option to set the title and body of the modal based on the item in a list. T145's answer helped a lot, so I wanted to share how I used it.

Make sure the tag containing the JavaScript function is of type text/javascript to avoid conflicts:

<script type="text/javascript"> function showMyModalSetTitle(myTitle, myBodyHtml) {

   /*
    * '#myModayTitle' and '#myModalBody' refer to the 'id' of the HTML tags in
    * the modal HTML code that hold the title and body respectively. These id's
    * can be named anything, just make sure they are added as necessary.
    *
    */

   $('#myModalTitle').html(myTitle);
   $('#myModalBody').html(myBodyHtml);

   $('#myModal').modal('show');
}</script>

This function can now be called in the onClick method from inside an element such as a button:

<button type="button" onClick="javascript:showMyModalSetTitle('Some Title', 'Some body txt')"> Click Me! </button>

Trigger change event <select> using jquery

Based on Mohamed23gharbi's answer:

function change(selector, value) {
    var sortBySelect = document.querySelector(selector);
    sortBySelect.value = value;
    sortBySelect.dispatchEvent(new Event("change"));
}

function click(selector) {
    var sortBySelect = document.querySelector(selector);
    sortBySelect.dispatchEvent(new Event("click"));
}

function test() {
    change("select#MySelect", 19);
    click("button#MyButton");
    click("a#MyLink");
}

In my case, where the elements were created by vue, this is the only way that works.

Disable vertical scroll bar on div overflow: auto

if you want to disable the scrollbar, but still able to scroll the content of inner DIV, use below code in css,

.divHideScroll::-webkit-scrollbar {
    width: 0 !important
}
.divHideScroll {
    overflow: -moz-scrollbars-none;
}
.divHideScroll {
    -ms-overflow-style: none;
}

divHideScroll is the class name of the target div.

It will work in all major browser (Chrome, Safari, Mozilla, Opera, and IE)

What is the purpose of Looper and how to use it?

A Looper has a synchronized MessageQueue that's used to process Messages placed on the queue.

It implements a Thread Specific Storage Pattern.

Only one Looper per Thread. Key methods include prepare(),loop() and quit().

prepare() initializes the current Thread as a Looper. prepare() is static method that uses the ThreadLocal class as shown below.

   public static void prepare(){
       ...
       sThreadLocal.set
       (new Looper());
   }
  1. prepare() must be called explicitly before running the event loop.
  2. loop() runs the event loop which waits for Messages to arrive on a specific Thread's messagequeue. Once the next Message is received,the loop() method dispatches the Message to its target handler
  3. quit() shuts down the event loop. It doesn't terminate the loop,but instead it enqueues a special message

Looper can be programmed in a Thread via several steps

  1. Extend Thread

  2. Call Looper.prepare() to initialize Thread as a Looper

  3. Create one or more Handler(s) to process the incoming messages

  4. Call Looper.loop() to process messages until the loop is told to quit().

How to properly create an SVN tag from trunk?

@victor hugo and @unwind are correct, and victor's solution is by far the simplest. However BEWARE of externals in your SVN project. If you reference external libraries, the external's revision reference (whether a tag, or HEAD, or number) will remain unchanged when you tag directories that have external references.

It is possible to create a script to handle this aspect of tagging, for a discussion on that topic, see this SO article: Tagging an SVN checkout with externals

SQL Insert into table only if record doesn't exist

Assuming you cannot modify DDL (to create a unique constraint) or are limited to only being able to write DML then check for a null on filtered result of your values against the whole table

FIDDLE

insert into funds (ID, date, price) 
select 
    T.* 
from 
    (select 23 ID,  '2013-02-12' date,  22.43 price) T  
        left join 
    funds on funds.ID = T.ID and funds.date = T.date
where 
    funds.ID is null

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

THIS IS JUST A NOTE FOR ANYONE DEALING WITH THIS PROBLEM USING THE RUBY DRIVER

I had this same problem when using the Ruby Gem.

To set slaveOk in Ruby, you just pass it as an argument when you create the client like this:

mongo_client = MongoClient.new("localhost", 27017, { slave_ok: true })

https://github.com/mongodb/mongo-ruby-driver/wiki/Tutorial#making-a-connection

mongo_client = MongoClient.new # (optional host/port args)

Notice that 'args' is the third optional argument.

How to encrypt String in Java

Here's my implementation from meta64.com as a Spring Singleton. If you want to create a ciper instance for each call that would work also, and then you could remove the 'synchronized' calls, but beware 'cipher' is not thread-safe.

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("singleton")
public class Encryptor {

    @Value("${aeskey}")
    private String keyStr;

    private Key aesKey = null;
    private Cipher cipher = null;

    synchronized private void init() throws Exception {
        if (keyStr == null || keyStr.length() != 16) {
            throw new Exception("bad aes key configured");
        }
        if (aesKey == null) {
            aesKey = new SecretKeySpec(keyStr.getBytes(), "AES");
            cipher = Cipher.getInstance("AES");
        }
    }

    synchronized public String encrypt(String text) throws Exception {
        init();
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        return toHexString(cipher.doFinal(text.getBytes()));
    }

    synchronized public String decrypt(String text) throws Exception {
        init();
        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        return new String(cipher.doFinal(toByteArray(text)));
    }

    public static String toHexString(byte[] array) {
        return DatatypeConverter.printHexBinary(array);
    }

    public static byte[] toByteArray(String s) {
        return DatatypeConverter.parseHexBinary(s);
    }

    /*
     * DO NOT DELETE
     * 
     * Use this commented code if you don't like using DatatypeConverter dependency
     */
    // public static String toHexStringOld(byte[] bytes) {
    // StringBuilder sb = new StringBuilder();
    // for (byte b : bytes) {
    // sb.append(String.format("%02X", b));
    // }
    // return sb.toString();
    // }
    //
    // public static byte[] toByteArrayOld(String s) {
    // int len = s.length();
    // byte[] data = new byte[len / 2];
    // for (int i = 0; i < len; i += 2) {
    // data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i +
    // 1), 16));
    // }
    // return data;
    // }
}

How do I toggle an ng-show in AngularJS based on a boolean?

You just need to toggle the value of "isReplyFormOpen" on ng-click event

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
 <div ng-show="isReplyFormOpen" id="replyForm">
   </div>

How to extract text from a PDF?

QuickPDF seems to be a reasonable library that should do what you want for a reasonable price.

http://www.quickpdflibrary.com/ - They have a 30 day trial.

PHP Composer behind http proxy

iconoclast's answer did not work for me.

I upgraded my php from 5.3.* (xampp 1.7.4) to 5.5.* (xampp 1.8.3) and the problem was solved.

Try iconoclast's answer first, if it doesn't work then upgrading might solve the problem.

How to use orderby with 2 fields in linq?

VB.NET

 MyList.OrderBy(Function(f) f.StartDate).ThenByDescending(Function(f) f.EndDate)

OR

  From l In MyList Order By l.StartDate Ascending, l.EndDate Descending

grid controls for ASP.NET MVC?

I just discovered Telerik has some great components, including Grid, and they are open source too. http://demos.telerik.com/aspnet-mvc/

Alter SQL table - allow NULL column value

The following MySQL statement should modify your column to accept NULLs.

ALTER TABLE `MyTable`
ALTER COLUMN `Col3` varchar(20) DEFAULT NULL

Select first 4 rows of a data.frame in R

In case someone is interested in dplyr solution, it's very intuitive:

dt <- dt %>%
  slice(1:4)

Java generics - get class?

I'm able to get the Class of the generic type this way:

class MyList<T> {
  Class<T> clazz = (Class<T>) DAOUtil.getTypeArguments(MyList.class, this.getClass()).get(0);
}

You need two functions from this file: http://code.google.com/p/hibernate-generic-dao/source/browse/trunk/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil.java

For more explanation: http://www.artima.com/weblogs/viewpost.jsp?thread=208860

Move an item inside a list?

Use the insert method of a list:

l = list(...)
l.insert(index, item)

Alternatively, you can use a slice notation:

l[index:index] = [item]

If you want to move an item that's already in the list to the specified position, you would have to delete it and insert it at the new position:

l.insert(newindex, l.pop(oldindex))

wp_nav_menu change sub-menu class name?

There is no option for this, but you can extend the 'walker' object that WordPress uses to create the menu HTML. Only one method needs to be overridden:

class My_Walker_Nav_Menu extends Walker_Nav_Menu {
  function start_lvl(&$output, $depth) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=\"my-sub-menu\">\n";
  }
}

Then you just pass an instance of your walker as an argument to wp_nav_menu like so:

'walker' => new My_Walker_Nav_Menu()

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

In JUnit 4:

  • For the Class Under Test, initialize in a @Before method, to catch failures.
  • For other classes, initialize in the declaration...
    • ...for brevity, and to mark fields final, exactly as stated in the question,
    • ...unless it is complex initialization that could fail, in which case use @Before, to catch failures.
  • For global state (esp. slow initialization, like a database), use @BeforeClass, but be careful of dependencies between tests.
  • Initialization of an object used in a single test should of course be done in the test method itself.

Initializing in a @Before method or test method allows you to get better error reporting on failures. This is especially useful for instantiating the Class Under Test (which you might break), but is also useful for calling external systems, like filesystem access ("file not found") or connecting to a database ("connection refused").

It is acceptable to have a simple standard and always use @Before (clear errors but verbose) or always initialize in declaration (concise but gives confusing errors), since complex coding rules are hard to follow, and this isn't a big deal.

Initializing in setUp is a relic of JUnit 3, where all test instances were initialized eagerly, which causes problems (speed, memory, resource exhaustion) if you do expensive initialization. Thus best practice was to do expensive initialization in setUp, which was only run when the test was executed. This no longer applies, so it is much less necessary to use setUp.

This summarizes several other replies that bury the lede, notably by Craig P. Motlin (question itself and self-answer), Moss Collum (class under test), and dsaff.

Create Excel files from C# without office

Try EPPlus if you use Excel 2007. Supports ranges, cellstyling, charts, shapes, pictures and a lot of other stuff

How to reduce a huge excel file

I have worked extensively in Excel and have found the following 3 points very useful

Find if there are cells which apparently do not hold any data but Excel considers them to have data

You can find this by using the following property on a sheet

ActiveSheet.UsedRange.Rows.Count
ActiveSheet.UsedRange.Columns.Count

If this range is more than the cells on which you have data, delete the rest of the rows/columns

You will be surprised to see the amount of space it can free

Convert files to .xlsb format

XLSM format is to make Excel compliant with Open XML, but there are very few instances when we actually use the XML format of Excel. This reduces size by almost 50% if not more

Optimum way of storing information

For example if you have to save the stock price for around 10 years, and you need to save Open, High, Low, Close for a stock, this would result in (252*10) * (4) cells being used

Instead, of using separate columns for Open,High,Low,Close save them in a single column with a field separator Open:High:Low:Close

You can easily write a function to extract info from the single column whenever you want to, but it will free up almost 2/3rd space that you are currently taking up

How can I kill a process by name instead of PID?

If you run GNOME, you can use the system monitor (System->Administration->System Monitor) to kill processes as you would under Windows. KDE will have something similar.

Cancel split window in Vim

Two alternatives for closing the current window are ZZ and ZQ, which will, respectively, save and not save changes to the displayed buffer.

Submit form on pressing Enter with AngularJS

Just wanted to point out that in the case of having a hidden submit button, you can just use the ngShow directive and set it to false like so:

HTML

<form ng-submit="myFunc()">
    <input type="text" name="username">
    <input type="submit" value="submit" ng-show="false">
</form>

how to refresh my datagridview after I add new data

this.tablenameTableAdapter.Fill(this.databasenameDataSet.tablename)

Prevent flex items from overflowing a container

If you want the overflow to wrap: flex-flow: row wrap

How to add a border just on the top side of a UIView

extension UIView {

    func addBorder(edge: UIRectEdge, color: UIColor, borderWidth: CGFloat) {

        let seperator = UIView()
        self.addSubview(seperator)
        seperator.translatesAutoresizingMaskIntoConstraints = false

        seperator.backgroundColor = color

        if edge == .top || edge == .bottom
        {
            seperator.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
            seperator.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
            seperator.heightAnchor.constraint(equalToConstant: borderWidth).isActive = true

            if edge == .top
            {
                seperator.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            }
            else
            {
                seperator.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            }
        }
        else if edge == .left || edge == .right
        {
            seperator.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            seperator.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            seperator.widthAnchor.constraint(equalToConstant: borderWidth).isActive = true

            if edge == .left
            {
                seperator.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
            }
            else
            {
                seperator.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
            }
        }
    }

}

Move a view up only when the keyboard covers an input field

Swift 4.2

My solution will (vertically) center the view on a UITextField if its position is under the keyboard.

Step 1: Create new swift file and copy-paste UIViewWithKeyboard class.
Step 2: In Interface Builder set it as a Custom Class for your top most UIView.

import UIKit

class UIViewWithKeyboard: UIView {
    @IBInspectable var offsetMultiplier: CGFloat = 0.75
    private var keyboardHeight = 0 as CGFloat
    private weak var activeTextField: UITextField?
    override func awakeFromNib() {
        super.awakeFromNib()
        NotificationCenter.default.addObserver(self, selector: #selector(UIViewWithKeyboard.textDidBeginEditing),
                                               name: UITextField.textDidBeginEditingNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(UIViewWithKeyboard.keyboardWillShow),
                                               name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(UIViewWithKeyboard.keyboardWillHide),
                                               name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    @objc func textDidBeginEditing(_ notification: NSNotification) {
        self.activeTextField = notification.object as? UITextField
    }

    @objc func keyboardWillShow(_ notification: Notification) {
        if let frameValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
            keyboardHeight = frameValue.cgRectValue.size.height
            if let textField = self.activeTextField {
                let offset = textField.frame.maxY < frame.maxY - keyboardHeight ? 0
                           : textField.frame.maxY - (frame.maxY - keyboardHeight) * offsetMultiplier
                self.setView(offset: offset)
            }
        }
    }

    @objc func keyboardWillHide(_ notification: NSNotification) {
        self.setView(offset: 0)
    }

    func setView(offset: CGFloat) {
        UIView.animate(withDuration: 0.25) {
            self.bounds.origin.y = offset
        }
    }
}

symfony 2 twig limit the length of the text and put three dots

Another one is:

{{ myentity.text[:50] ~ '...' }}

Android Fragment no view found for ID?

I had this same issue, let me post my code so that you can all see it, and not do the same thing that I did.

@Override
protected void onResume()
{
    super.onResume();

    fragManager = getSupportFragmentManager();

    Fragment answerPad=getDefaultAnswerPad();
    setAnswerPad(answerPad);
    setContentView(R.layout.abstract_test_view);
}
protected void setAnswerPad(AbstractAnswerFragment pad)
{
    fragManager.beginTransaction()
        .add(R.id.AnswerArea, pad, "AnswerArea")
        .commit();
    fragManager.executePendingTransactions();
}

Note that I was setting up fragments before I setContentView. Ooops.

Is Google Play Store supported in avd emulators?

Starting from Android Studio 2.3.2 now you can create an AVD that has Play Store pre-installed on it. Currently, it is supported on the AVD's running

  • A device definition of Nexus 5 or 5X phone, or any Android Wear
  • A system image since Android 7.0 (API 24)

Official Source

For other emulators, you can try the solution mentioned in this answer.

Using File.listFiles with FileNameExtensionFilter

With java lambdas (available since java 8) you can simply convert javax.swing.filechooser.FileFilter to java.io.FileFilter in one line.

javax.swing.filechooser.FileFilter swingFilter = new FileNameExtensionFilter("jpeg files", "jpeg");
java.io.FileFilter ioFilter = file -> swingFilter.accept(file);
new File("myDirectory").listFiles(ioFilter);

New to MongoDB Can not run command mongo

Check that path to database data files exists ;) :

Sun Nov 06 18:48:37 [initandlisten] exception in initAndListen: 10296 dbpath (/data/db) does not exist, terminating

powershell is missing the terminator: "

Look closely at the two dashes in

unzipRelease –Src '$ReleaseFile' -Dst '$Destination'

This first one is not a normal dash but an en-dash (&ndash; in HTML). Replace that with the dash found before Dst.

Laravel Migration table already exists, but I want to add new not the older

EDIT: (for laravel)

Just Came across this issue while working on a project in laravel. My tables were messed up, needed to frequent changes on columns. Once the tables were there I wasn't able to run php artisan migrate anymore.

I've done following to get rid of the issue-

  1. Drop the tables in the database [every one, including the migration table]
  2. $ composer dump-autoload -o
  3. php artisan migrate

Previous Comment, regarding lumen

[Well, pretty late to the party (and possibly a different party than what I was looking for). I banged my head, screamed out loud and by the grace of gray skull just found a solution.]

I'm developing an restful app using lumen and I'm new to it. This is my first project/experiment using laraval and lumen. My dependencies-

"require": {
    "php": ">=5.6.4",
    "laravel/lumen-framework": "5.4.*",
    "vlucas/phpdotenv": "~2.2",
    "barryvdh/laravel-cors": "^0.8.6",
    "league/fractal": "^0.13.0"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "phpunit/phpunit": "~5.0",
    "mockery/mockery": "~0.9.4"
}

Anyway, everything was fine until yesterday night but suddenly phpunit started complaining about an already existed table.

Caused by
PDOException: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'items' already exists

Duh! Items table should exist in the database, or else how am i supposed to save items!

Anyway the problem only persisted in the test classes, but strangely not in the browser (I checked with chrome, firefox and postman altering headers). I was getting JSON responses with data as expected.

I dropped the database and recreated it with lots of migrate, refresh, rollback. Everything was fine but in phpunit.

Out of desperation I removed my migration files (of course I took a backup first ) then hit phpunit in the terminal. Same thing all over again.

Suddenly I remembered that I put a different database name in the phpunit.xml file for testing purpose only. I checked that database and guess what! There was a table named items. I removed this table manually, run phpunit, everything started working just fine.

I'm documenting my experience for future references only and with hope this might help someone in future.

Unicode character as bullet for list-item in CSS

Using Text As Bullets

Use li:before with an escaped Hex HTML Entity (or any plain text).


Example

My example will produce lists with check marks as bullets.

CSS:

ul {
    list-style: none;
    padding: 0px;
}

ul li:before
{
    content: '\2713';
    margin: 0 1em;    /* any design */
}

Browser Compatibility

Haven't tested myself, but it should be supported as of IE8. At least that's what quirksmode & css-tricks say.

You can use conditional comments to apply older/slower solutions like images, or scripts. Better yet, use both with <noscript> for the images.

HTML:

<!--[if lt IE 8]>
    *SCRIPT SOLUTION*
    <noscript>
        *IMAGE SOLUTION*
    </noscript>
<![endif]-->

About background images

Background images are indeed easy to handle, but...

  1. Browser support for background-size is actually only as of IE9.
  2. HTML text colors and special (crazy) fonts can do a lot, with less HTTP requests.
  3. A script solution can just inject the HTML Entity, and let the same CSS do the work.
  4. A good resetting CSS code might make list-style (the more logical choice) easier.

Enjoy.

Deleting all files from a folder using PHP?

Posted a general purpose file and folder handling class for copy, move, delete, calculate size, etc., that can handle a single file or a set of folders.

https://gist.github.com/4689551

To use:

To copy (or move) a single file or a set of folders/files:

$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');

Delete a single file or all files and folders in a path:

$files = new Files();
$results = $files->delete('source/folder/optional-file.name');

Calculate the size of a single file or a set of files in a set of folders:

$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');

Command not found error in Bash variable assignment

Drop the spaces around the = sign:

#!/bin/bash 
STR="Hello World" 
echo $STR 

I just assigned a variable, but echo $variable shows something else

You may want to know why this is happening. Together with the great explanation by that other guy, find a reference of Why does my shell script choke on whitespace or other special characters? written by Gilles in Unix & Linux:

Why do I need to write "$foo"? What happens without the quotes?

$foo does not mean “take the value of the variable foo”. It means something much more complex:

  • First, take the value of the variable.
  • Field splitting: treat that value as a whitespace-separated list of fields, and build the resulting list. For example, if the variable contains foo * bar ? then the result of this step is the 3-element list foo, *, bar.
  • Filename generation: treat each field as a glob, i.e. as a wildcard pattern, and replace it by the list of file names that match this pattern. If the pattern doesn't match any files, it is left unmodified. In our example, this results in the list containing foo, following by the list of files in the current directory, and finally bar. If the current directory is empty, the result is foo, *, bar.

Note that the result is a list of strings. There are two contexts in shell syntax: list context and string context. Field splitting and filename generation only happen in list context, but that's most of the time. Double quotes delimit a string context: the whole double-quoted string is a single string, not to be split. (Exception: "$@" to expand to the list of positional parameters, e.g. "$@" is equivalent to "$1" "$2" "$3" if there are three positional parameters. See What is the difference between $* and $@?)

The same happens to command substitution with $(foo) or with `foo`. On a side note, don't use `foo`: its quoting rules are weird and non-portable, and all modern shells support $(foo) which is absolutely equivalent except for having intuitive quoting rules.

The output of arithmetic substitution also undergoes the same expansions, but that isn't normally a concern as it only contains non-expandable characters (assuming IFS doesn't contain digits or -).

See When is double-quoting necessary? for more details about the cases when you can leave out the quotes.

Unless you mean for all this rigmarole to happen, just remember to always use double quotes around variable and command substitutions. Do take care: leaving out the quotes can lead not just to errors but to security holes.

How to do a FULL OUTER JOIN in MySQL?

The answer that Pablo Santa Cruz gave is correct; however, in case anybody stumbled on this page and wants more clarification, here is a detailed breakdown.

Example Tables

Suppose we have the following tables:

-- t1
id  name
1   Tim
2   Marta

-- t2
id  name
1   Tim
3   Katarina

Inner Joins

An inner join, like this:

SELECT *
FROM `t1`
INNER JOIN `t2` ON `t1`.`id` = `t2`.`id`;

Would get us only records that appear in both tables, like this:

1 Tim  1 Tim

Inner joins don't have a direction (like left or right) because they are explicitly bidirectional - we require a match on both sides.

Outer Joins

Outer joins, on the other hand, are for finding records that may not have a match in the other table. As such, you have to specify which side of the join is allowed to have a missing record.

LEFT JOIN and RIGHT JOIN are shorthand for LEFT OUTER JOIN and RIGHT OUTER JOIN; I will use their full names below to reinforce the concept of outer joins vs inner joins.

Left Outer Join

A left outer join, like this:

SELECT *
FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;

...would get us all the records from the left table regardless of whether or not they have a match in the right table, like this:

1 Tim   1    Tim
2 Marta NULL NULL

Right Outer Join

A right outer join, like this:

SELECT *
FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;

...would get us all the records from the right table regardless of whether or not they have a match in the left table, like this:

1    Tim   1  Tim
NULL NULL  3  Katarina

Full Outer Join

A full outer join would give us all records from both tables, whether or not they have a match in the other table, with NULLs on both sides where there is no match. The result would look like this:

1    Tim   1    Tim
2    Marta NULL NULL
NULL NULL  3    Katarina

However, as Pablo Santa Cruz pointed out, MySQL doesn't support this. We can emulate it by doing a UNION of a left join and a right join, like this:

SELECT *
FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`

UNION

SELECT *
FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;

You can think of a UNION as meaning "run both of these queries, then stack the results on top of each other"; some of the rows will come from the first query and some from the second.

It should be noted that a UNION in MySQL will eliminate exact duplicates: Tim would appear in both of the queries here, but the result of the UNION only lists him once. My database guru colleague feels that this behavior should not be relied upon. So to be more explicit about it, we could add a WHERE clause to the second query:

SELECT *
FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`

UNION

SELECT *
FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`
WHERE `t1`.`id` IS NULL;

On the other hand, if you wanted to see duplicates for some reason, you could use UNION ALL.

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

new Buffer(number)            // Old
Buffer.alloc(number)          // New

new Buffer(string)            // Old
Buffer.from(string)           // New

new Buffer(string, encoding)  // Old
Buffer.from(string, encoding) // New

new Buffer(...arguments)      // Old
Buffer.from(...arguments)     // New

Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.

Close Android Application

The answer depends on what you mean by "close app". In android's terms its either about an "activity", or a group of activities in a temporal/ancestral order called "task".

End activity: just call finish()

End task:

  1. clear activity task-stack
  2. navigate to root activity
  3. then call finish on it.

This will end the entire "task"

Print number of keys in Redis

Go to redis-cli and use below command

info keyspace

It may help someone

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

What's the best way to check if a file exists in C?

Usually when you want to check if a file exists, it's because you want to create that file if it doesn't. Graeme Perrow's answer is good if you don't want to create that file, but it's vulnerable to a race condition if you do: another process could create the file in between you checking if it exists, and you actually opening it to write to it. (Don't laugh... this could have bad security implications if the file created was a symlink!)

If you want to check for existence and create the file if it doesn't exist, atomically so that there are no race conditions, then use this:

#include <fcntl.h>
#include <errno.h>

fd = open(pathname, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
  /* failure */
  if (errno == EEXIST) {
    /* the file already existed */
    ...
  }
} else {
  /* now you can use the file */
}

How to do Base64 encoding in node.js?

crypto now supports base64 (reference):

cipher.final('base64') 

So you could simply do:

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');

Build error, This project references NuGet

First I would check if your MusicKarma project has Microsoft.Net.Compilers in its packages.config file. If not then you could remove everything to do with that NuGet package from your MusicKarma.csproj.

If you are using the Microsoft.Net.Compilers NuGet package then my guess is that the path is incorrect. Looking at the directory name in the error message I would guess that the MusicKarma solution file (.sln) is in the same directory as the MusicKarma.csproj. If so then the packages directory is probably wrong since by default the packages directory would be inside the solution directory. So I am assuming that your packages directory is:

C:\Users\Bryan\Documents\Visual Studio 2015\Projects\MusicKarma\packages

Whilst your MusicKarma.csproj file is looking for the props file in:

C:\Users\Bryan\Documents\Visual Studio 2015\Projects\packages\Microsoft.Net.Compilers.1.1.1\build

So if that is the case then you can fix the problem by editing the path in your MusicKarma.csproj file or by reinstalling the NuGet package.

How to check whether a string is a valid HTTP URL?

Try this to validate HTTP URLs (uriName is the URI you want to test):

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && uriResult.Scheme == Uri.UriSchemeHttp;

Or, if you want to accept both HTTP and HTTPS URLs as valid (per J0e3gan's comment):

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

Negative matching using grep (match lines that do not contain foo)

grep -v is your friend:

grep --help | grep invert  

-v, --invert-match select non-matching lines

Also check out the related -L (the complement of -l).

-L, --files-without-match only print FILE names containing no match

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

We have the following string which is a valid JSON ...

Clearly the JSON parser disagrees!

However, the exception says that the error is at "line 1: column 9", and there is no "http" token near the beginning of the JSON. So I suspect that the parser is trying to parse something different than this string when the error occurs.

You need to find what JSON is actually being parsed. Run the application within a debugger, set a breakpoint on the relevant constructor for JsonParseException ... then find out what is in the ByteArrayInputStream that it is attempting to parse.

How to install PHP mbstring on CentOS 6.2

*Make sure you update your linux box first

yum update

In case someone still has this problem, this is a valid solution:

centos-release : rpm -q centos-release

Centos 6.*

wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -ivh epel-release-6-8.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
rpm -Uvh remi-release-6*.rpm

Centos 5.*

wget http://ftp.jaist.ac.jp/pub/Linux/Fedora/epel/5/x86_64/epel-release-5-4.noarch.rpm
rpm -ivh epel-release-5-4.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
rpm -Uvh remi-release-5*.rpm

Then just do this to update:

yum --enablerepo=remi upgrade php-mbstring

Or this to install:

yum --enablerepo=remi install php-mbstring

Counting words in string

You got some mistakes in your code.

function WordCount(str) {
    var totalSoFar = 0;
    for (var i = 0; i < str.length; i++) {
        if (str[i] === " ") {
            totalSoFar += 1;
        }
    }
    return totalSoFar + 1; // you need to return something.
}
console.log(WordCount("Random String"));

There is another easy way using regular expressions:

(text.split(/\b/).length - 1) / 2

The exact value can differ about 1 word, but it also counts word borders without space, for example "word-word.word". And it doesn't count words that don't contain letters or numbers.

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

How do I check for null values in JavaScript?

Strict equality operator:-

We can check null by ===

if ( value === null ){

}

Just by using if

if( value ) {

}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • false
  • 0

Running shell command and capturing the output

If you need to run a shell command on multiple files, this did the trick for me.

import os
import subprocess

# Define a function for running commands and capturing stdout line by line
# (Modified from Vartec's solution because it wasn't printing all lines)
def runProcess(exe):    
    p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return iter(p.stdout.readline, b'')

# Get all filenames in working directory
for filename in os.listdir('./'):
    # This command will be run on each file
    cmd = 'nm ' + filename

    # Run the command and capture the output line by line.
    for line in runProcess(cmd.split()):
        # Eliminate leading and trailing whitespace
        line.strip()
        # Split the output 
        output = line.split()

        # Filter the output and print relevant lines
        if len(output) > 2:
            if ((output[2] == 'set_program_name')):
                print filename
                print line

Edit: Just saw Max Persson's solution with J.F. Sebastian's suggestion. Went ahead and incorporated that.

Use string value from a cell to access worksheet of same name

You can use the formula INDIRECT().

This basically takes a string and treats it as a reference. In your case, you would use:

=INDIRECT("'"&A5&"'!G7")

The double quotes are to show that what's inside are strings, and only A5 here is a reference.

How to exit an if clause

There is another way which doesn't rely on defining functions (because sometimes that's less readable for small code snippets), doesn't use an extra outer while loop (which might need special appreciation in the comments to even be understandable on first sight), doesn't use goto (...) and most importantly let's you keep your indentation level for the outer if so you don't have to start nesting stuff.

if some_condition:
   ...
   if condition_a:
       # do something
       exit_if=True # and then exit the outer if block
if some condition and not exit_if: # if and only if exit_if wasn't set we want to execute the following code
   # keep doing something
   if condition_b:
       # do something
       exit_if=True # and then exit the outer if block
if some condition and not exit_if:
   # keep doing something

Yes, that also needs a second look for readability, however, if the snippets of code are small this doesn't require to track any while loops that will never repeat and after understanding what the intermediate ifs are for, it's easily readable, all in one place and with the same indentation.

And it should be pretty efficient.

Select specific row from mysql table

Your table will need to be created with a unique ID field that will ideally have the AUTO_INCREMENT attribute. example:

CREATE TABLE Persons
(
P_Id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (P_Id)
)

Then you can access the 3rd record in this table with:

SELECT * FROM Persons WHERE P_Id = 3

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

You should use "merge a range of revision".

To merge changes from the trunk to a branch, inside the branch working copy choose "merge range of revisions" and enter the trunk URL and the start and end revisions to merge.

The same in the opposite way to merge a branch in the trunk.

About the --reintegrate flag, check the manual here: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-merge.html#tsvn-dug-merge-reintegrate

Change New Google Recaptcha (v2) Width

unfortunately none of the above worked. I finally could do it using the following stuffs: This solution works 100% (adapt it to your need)

_x000D_
_x000D_
.g-recaptcha-wrapper {_x000D_
    position: relative;_x000D_
    border: 1px solid #ededed;_x000D_
    background: #f9f9f9;_x000D_
    border-radius: 4px;_x000D_
    padding: 0;_x000D_
    #topHider {_x000D_
        position: absolute;_x000D_
        top: 0;_x000D_
        left: 0;_x000D_
        height: 2px !important;_x000D_
        width: 100%;_x000D_
        background-color: #f9f9f9;_x000D_
    }_x000D_
    #rightHider {_x000D_
        position: absolute;_x000D_
        top: 0;_x000D_
        left: 295px;_x000D_
        height: 100% !important;_x000D_
        width: 15px;_x000D_
        background-color: #f9f9f9;_x000D_
    }_x000D_
    #leftHider {_x000D_
        position: absolute;_x000D_
        top: 0;_x000D_
        left: 0;_x000D_
        height: 100% !important;_x000D_
        width: 2px;_x000D_
        background-color: #f9f9f9;_x000D_
    }_x000D_
    #bottomHider {_x000D_
        position: absolute;_x000D_
        bottom: 1px;_x000D_
        left: 0;_x000D_
        height: 2px !important;_x000D_
        width: 100%;_x000D_
        background-color: #f9f9f9;_x000D_
    }_x000D_
}
_x000D_
<div class="g-recaptcha-wrapper">_x000D_
  <re-captcha #captchaRef="reCaptcha" (resolved)="onCaptchaResolved($event)" siteKey="{{captchaSiteKey}}"></re-captcha>_x000D_
  <div id="topHider"></div>_x000D_
  <div id="rightHider"></div>_x000D_
  <div id="bottomHider"></div>_x000D_
  <div id="leftHider"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Result enter image description here

Docker and securing passwords

Something simply like this will work I guess if it is bash shell.

read -sp "db_password:" password | docker run -itd --name <container_name> --build-arg mysql_db_password=$db_password alpine /bin/bash

Simply read it silently and pass as argument in Docker image. You need to accept the variable as ARG in Dockerfile.

How to use Greek symbols in ggplot2?

You do not need the latex2exp package to do what you wanted to do. The following code would do the trick.

ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) + 
  geom_point() + 
  labs(title=expression("Fuel Efficiency"~(alpha*Omega)), 
color=expression(alpha*Omega), x=expression(Delta~price))

enter image description here

Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*") works, so I suggest giving it a try.

More comments asked about getting ? Price and I find the most straightforward way to achieve that is expression(Delta~price)). If you need to add something before the Greek letter, you can also do this: expression(Indicative~Delta~price) which gets you:

enter image description here

SQL Server Pivot Table with multiple column aggregates

I used your own pivot as a nested query and came to this result:

SELECT
  [sub].[chardate],
  SUM(ISNULL([Australia], 0)) AS [Transactions Australia],
  SUM(CASE WHEN [Australia] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Australia],
  SUM(ISNULL([Austria], 0)) AS [Transactions Austria],
  SUM(CASE WHEN [Austria] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Austria]
FROM
(
  select * 
  from  mytransactions
  pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
) AS [sub]
GROUP BY
  [sub].[chardate],
  [sub].[numericmonth]
ORDER BY 
  [sub].[numericmonth] ASC

Here is the Fiddle.

Python ValueError: too many values to unpack

Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity into (m, k).

My crystal ball says m.type and m.purity are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)

To fix this, you can iterate explicitly over the items of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.

(In 2.x, itervalues, iterkeys, and iteritems are typically a better idea; the non-iter versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter versions which just set up an iterator.)

How to change text color and console color in code::blocks?

system("COLOR 0A");'

where 0A is a combination of background and font color 0

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

If you don't wish to compile bootstrap, copy the following and insert it in your custom css file. It's not recommended to change the original bootstrap css file. Also, you won't be able to modify the bootstrap original css if you are loading it from a cdn.

Paste this in your custom css file:

@media (min-width:992px)
    {
        .container{width:960px}
    }
@media (min-width:1200px)
    {
        .container{width:960px}
    }

I am here setting my container to 960px for anything that can accommodate it, and keeping the rest media sizes to default values. You can set it to 940px for this problem.

jquery, selector for class within id

Always use

//Super Fast
$('#my_id').find('.my_class'); 

instead of

// Fast:
$('#my_id .my_class');

Have look at JQuery Performance Rules.

Also at Jquery Doc

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

Git reset has 5 main modes: soft, mixed, merged, hard, keep. The difference between them is to change or not change head, stage (index), working directory.

Git reset --hard will change head, index and working directory.
Git reset --soft will change head only. No change to index, working directory.

So in other words if you want to undo your commit, --soft should be good enough. But after that you still have the changes from bad commit in your index and working directory. You can modify the files, fix them, add them to index and commit again.

With the --hard, you completely get a clean slate in your project. As if there hasn't been any change from the last commit. If you are sure this is what you want then move forward. But once you do this, you'll lose your last commit completely. (Note: there are still ways to recover the lost commit).

UnicodeEncodeError: 'charmap' codec can't encode characters

if you are using windows try to pass encoding='latin1', encoding='iso-8859-1' or encoding='cp1252' example:

csv_data = pd.read_csv(csvpath,encoding='iso-8859-1')
print(print(soup.encode('iso-8859-1')))

How to delete directory content in Java?

You have to do this for each File:

public static void deleteFolder(File folder) {
    File[] files = folder.listFiles();
    if(files!=null) { //some JVMs return null for empty dirs
        for(File f: files) {
            if(f.isDirectory()) {
                deleteFolder(f);
            } else {
                f.delete();
            }
        }
    }
    folder.delete();
}

Then call

deleteFolder(outputFolder);

Draw text in OpenGL ES

Rendering text to a texture is simpler than what the Sprite Text demo make it looks like, the basic idea is to use the Canvas class to render to a Bitmap and then pass the Bitmap to an OpenGL texture:

// Create an empty, mutable bitmap
Bitmap bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_4444);
// get a canvas to paint over the bitmap
Canvas canvas = new Canvas(bitmap);
bitmap.eraseColor(0);

// get a background image from resources
// note the image format must match the bitmap format
Drawable background = context.getResources().getDrawable(R.drawable.background);
background.setBounds(0, 0, 256, 256);
background.draw(canvas); // draw the background to our bitmap

// Draw the text
Paint textPaint = new Paint();
textPaint.setTextSize(32);
textPaint.setAntiAlias(true);
textPaint.setARGB(0xff, 0x00, 0x00, 0x00);
// draw the text centered
canvas.drawText("Hello World", 16,112, textPaint);

//Generate one texture pointer...
gl.glGenTextures(1, textures, 0);
//...and bind it to our array
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

//Create Nearest Filtered Texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

//Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);

//Use the Android GLUtils to specify a two-dimensional texture image from our bitmap
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

//Clean up
bitmap.recycle();

How do I find the location of Python module sources?

Running python -v from the command line should tell you what is being imported and from where. This works for me on Windows and Mac OS X.

C:\>python -v
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# C:\Python24\lib\site.pyc has bad mtime
import site # from C:\Python24\lib\site.py
# wrote C:\Python24\lib\site.pyc
# C:\Python24\lib\os.pyc has bad mtime
import os # from C:\Python24\lib\os.py
# wrote C:\Python24\lib\os.pyc
import nt # builtin
# C:\Python24\lib\ntpath.pyc has bad mtime
...

I'm not sure what those bad mtime's are on my install!

Can I change the name of `nohup.out`?

As the file handlers points to i-nodes (which are stored independently from file names) on Linux/Unix systems You can rename the default nohup.out to any other filename any time after starting nohup something&. So also one could do the following:

$ nohup something&
$ mv nohup.out nohup2.out
$ nohup something2&

Now something adds lines to nohup2.out and something2 to nohup.out.

Max size of an iOS application

150MB is the constraint for over-the-air downloads via the cellular network. Anything above that and users will be suggested Wi-Fi or iTunes sync to actually get your app.

This will not prevent a purchase though, at point of sale.

Using malloc for allocation of multi-dimensional arrays with different row lengths

Equivalent memory allocation for char a[10][20] would be as follows.

char **a;

a=(char **) malloc(10*sizeof(char *));

for(i=0;i<10;i++)
    a[i]=(char *) malloc(20*sizeof(char));

I hope this looks simple to understand.

Remote debugging Tomcat with Eclipse

Let me share the simple way to enable the remote debugging mode in tomcat7 with eclipse (Windows).

Step 1: open bin/startup.bat file
Step 2: add the below lines for debugging with JDPA option (it should starting line of the file )

    set JPDA_ADDRESS=8000  
    set JPDA_TRANSPORT=dt_socket  

Step 3: in the same file .. go to end of the file modify this line -

    call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%  
    instead of line  
    call "%EXECUTABLE%" start %CMD_LINE_ARGS%  

step 4: then just run bin>startup.bat (so now your tomcat server ran in remote mode with port 8000).

step 5: after that lets connect your source project by eclipse IDE with remote client.

step6: In the Eclipse IDE go to "debug Configuration"

step7:click "remote java application" and on that click "New"

step8. in the "connect" tab set the parameter value

   project= your source project  
   connection Type: standard (socket attached)   
   host: localhost  
   port:8000  

step9: click apply and debug.

so finally your eclipse remote client is connected with the running tomcat server (debug mode).

Hope this approach might be help you.

Regards..

How to change the text color of first select option

What about this:

_x000D_
_x000D_
select{
  width: 150px;
  height: 30px;
  padding: 5px;
  color: green;
}
select option { color: black; }
select option:first-child{
  color: green;
}
_x000D_
<select>
  <option>one</option>
  <option>two</option>
</select>
_x000D_
_x000D_
_x000D_

http://jsbin.com/acucan/9

Manipulate a url string by adding GET parameters

$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

$queryString =  http_build_query($data);
//$queryString = foo=bar&baz=boom&cow=milk&php=hypertext+processor

echo 'http://domain.com?'.$queryString;
//output: http://domain.com?foo=bar&baz=boom&cow=milk&php=hypertext+processor

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.

This compilation unit is not on the build path of a Java project

For those who still have problems after attempting the suggestions above: I solved the issue by updating the maven project.

Can a CSS class inherit one or more other classes?

You can add multiple classes to a single DOM element, e.g.

<div class="firstClass secondClass thirdclass fourthclass"></div>

Rules given in later classes (or which are more specific) override. So the fourthclass in that example kind of prevails.

Inheritance is not part of the CSS standard.

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

Splitting on last delimiter in Python string?

Use .rsplit() or .rpartition() instead:

s.rsplit(',', 1)
s.rpartition(',')

str.rsplit() lets you specify how many times to split, while str.rpartition() only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.

Demo:

>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')

Both methods start splitting from the right-hand-side of the string; by giving str.rsplit() a maximum as the second argument, you get to split just the right-hand-most occurrences.

How do I create a constant in Python?

In Python instead of language enforcing something, people use naming conventions e.g __method for private methods and using _method for protected methods.

So in same manner you can simply declare the constant as all caps e.g.

MY_CONSTANT = "one"

If you want that this constant never changes, you can hook into attribute access and do tricks, but a simpler approach is to declare a function

def MY_CONSTANT():
    return "one"

Only problem is everywhere you will have to do MY_CONSTANT(), but again MY_CONSTANT = "one" is the correct way in python(usually).

You can also use namedtuple to create constants:

>>> from collections import namedtuple
>>> Constants = namedtuple('Constants', ['pi', 'e'])
>>> constants = Constants(3.14, 2.718)
>>> constants.pi
3.14
>>> constants.pi = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

How to print a groupby object

I found a tricky way, just for brainstorm, see the code:

df['a'] = df['A']  # create a shadow column for MultiIndexing
df.sort_values('A', inplace=True)
df.set_index(["A","a"], inplace=True)
print(df)

the output:

             B
A     a
one   one    0
      one    1
      one    5
three three  3
      three  4
two   two    2

The pros is so easy to print, as it returns a dataframe, instead of Groupby Object. And the output looks nice. While the con is that it create a series of redundant data.

Error handling in AngularJS http get then construct

You can make this bit more cleaner by using:

$http.get(url)
    .then(function (response) {
        console.log('get',response)
    })
    .catch(function (data) {
        // Handle error here
    });

Similar to @this.lau_ answer, different approach.

How can I make a horizontal ListView in Android?

This might be a very late reply but it is working for us. We are using the same gallery provided by Android, just that, we have adjusted the left margin such a way that the screens left end is considered as Gallery's center. That really worked well for us.

Date Comparison using Java

Use java.util.Calendar if you have extensive date related processing.

Date has before(), after() methods. you could use them as well.

android View not attached to window manager

according to the code of the windowManager (link here), this occurs when the view you are trying to update (which probably belongs to a dialog, but not necessary) is no longer attached to the real root of the windows.

as others have suggested, you should check the status of the activity before performing special operations on your dialogs.

here's the relavant code, which is the cause to the problem (copied from Android source code) :

public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
    if (!(params instanceof WindowManager.LayoutParams)) {
        throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
    }

    final WindowManager.LayoutParams wparams
            = (WindowManager.LayoutParams)params;

    view.setLayoutParams(wparams);

    synchronized (this) {
        int index = findViewLocked(view, true);
        ViewRootImpl root = mRoots[index];
        mParams[index] = wparams;
        root.setLayoutParams(wparams, false);
    }
}

private int findViewLocked(View view, boolean required) {
        synchronized (this) {
            final int count = mViews != null ? mViews.length : 0;
            for (int i=0; i<count; i++) {
                if (mViews[i] == view) {
                    return i;
                }
            }
            if (required) {
                throw new IllegalArgumentException(
                        "View not attached to window manager");
            }
            return -1;
        }
    }

Reusing output from last command in Bash

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

Bootstrap Dropdown with Hover

Use the mouseover() function to trigger the click. In this way the previous click event will not harm. User can use both hover and click/touch. It will be mobile friendly.

$(".dropdown-toggle").mouseover(function(){
    $(this).trigger('click');
})

Create Directory When Writing To File In Node.js

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

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

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

Java : Convert formatted xml file to one line string

Underscore-java library has static method U.formatXml(xmlstring). I am the maintainer of the project. Live example

import com.github.underscore.lodash.U;
import com.github.underscore.lodash.Xml;

public class MyClass {
    public static void main(String[] args) {
        System.out.println(U.formatXml("<a>\n  <b></b>\n  <b></b>\n</a>",
        Xml.XmlStringBuilder.Step.COMPACT));
    }
}

// output: <a><b></b><b></b></a>

How to convert SQL Server's timestamp column to datetime format

Works fine, except this message:

Implicit conversion from data type varchar to timestamp is not allowed. Use the CONVERT function to run this query

So yes, TIMESTAMP (RowVersion) is NOT a DATE :)

To be honest, I fidddled around quite some time myself to find a way to convert it to a date.

Best way is to convert it to INT and compare. That's what this type is meant to be.

If you want a date - just add a Datetime column and live happily ever after :)

cheers mac

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You're looking for Select which can be used to transform\project the input sequence:

IEnumerable<string> strings = integers.Select(i => i.ToString());

How to set default value to the input[type="date"]

Here are three statements for three different dates in the form with three type=date fields.

$inv_date is the current date:

$inv_date = date("Y-m-d");

$inv_date_from is the first day of the current month:

$inv_date_from = date("Y") . "-" . date("m") . "-" . "01";

$inv_date_to is the last day of the month:

$inv_date_to = date("Y-m-t", strtotime(date("Y-m-t")));

I hope this helps :)

Apache server keeps crashing, "caught SIGTERM, shutting down"

try to disable the rewrite module in ubuntu using sudo a2dismod rewrite. This will perhaps stop your apache server to crash.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

Check to see if you have previously disabled caching in Chrome when the developer console is open - the setting is under the console, settings icon > General tab: Disable cache (while DevTools is open)

Where is the Microsoft.IdentityModel dll

Install Both of the below links

  1. Windows Identity Foundation

    Note: (For Vista and Windows Server 2008 >>> Windows6.0 and For Windows 7 and Windows Server 2008 R2, >>> Windows6.1. )

  2. Windows Identity Foundation SDK

    Note: Download the 3.5 version for Visual Studio 2008 and .NET 3.5, the 4.0 version for Visual Studio 2010 and .NET 4.0.

Then Only, You will able to get the assembly called Microsoft.IdentityModel

DataGrid get selected rows' column values

I used a similar way to solve this problem using the animescm sugestion, indeed we can obtain the specific cells values from a group of selected cells using an auxiliar list:

private void dataGridCase_SelectionChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        foreach (var item in e.AddedCells)
        {
            var col = item.Column as DataGridColumn;
            var fc = col.GetCellContent(item.Item);
            lstTxns.Items.Add((fc as TextBlock).Text);
        }
    }

Exception is never thrown in body of corresponding try statement

Any class which extends Exception class will be a user defined Checked exception class where as any class which extends RuntimeException will be Unchecked exception class. as mentioned in User defined exception are checked or unchecked exceptions So, not throwing the checked exception(be it user-defined or built-in exception) gives compile time error.

Checked exception are the exceptions that are checked at compile time.

Unchecked exception are the exceptions that are not checked at compiled time

pull/push from multiple remote locations

You'll need a script to loop through them. Git doesn't a provide a "push all." You could theoretically do a push in multiple threads, but a native method is not available.

Fetch is even more complicated, and I'd recommend doing that linearly.

I think your best answer is to have once machine that everybody does a push / pull to, if that's at all possible.

Remote origin already exists on 'git push' to a new repository

You could also change the repository name you wish to push to in the REPOHOME/.git/config file

(where REPOHOME is the path to your local clone of the repository).

Javascript: How to loop through ALL DOM elements on a page?

You can try with document.getElementsByClassName('special_class');

Build query string for System.Net.HttpClient get

Good part of accepted answer, modified to use UriBuilder.Uri.ParseQueryString() instead of HttpUtility.ParseQueryString():

var builder = new UriBuilder("http://example.com");
var query = builder.Uri.ParseQueryString();
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
builder.Query = query.ToString();
string url = builder.ToString();

Array of PHP Objects

Arrays can hold pointers so when I want an array of objects I do that.

$a = array();
$o = new Whatever_Class();
$a[] = &$o;
print_r($a);

This will show that the object is referenced and accessible through the array.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

Using INSERT INTO ... VALUES syntax like in Daniel Vassallo's answer there is one annoying limitation:

From MSDN

The maximum number of rows that can be constructed by inserting rows directly in the VALUES list is 1000

The easiest way to omit this limitation is to use derived table like:

INSERT INTO dbo.Mytable(ID, Name)
SELECT ID, Name 
FROM (
   VALUES (1, 'a'),
          (2, 'b'),
          --...
          -- more than 1000 rows
)sub (ID, Name);

LiveDemo


This will work starting from SQL Server 2008+

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

The ternary operator is just a shorthand for and if/else block. Your working code does not have an else condition, so is not suitable for this.

The following example will work:

echo empty($address['street2']) ? 'empty' : 'not empty';

What are these ^M's that keep showing up in my files in emacs?

I ran into this issue a while back. The ^M represents a Carriage Return, and searching on Ctrl-Q Ctrl-M (This creates a literal ^M) will allow you get a handle on this character within Emacs. I did something along these lines:

M-x replace-string [ENTER] C-q C-m [ENTER] \n [ENTER]

Reading InputStream as UTF-8

Solved my own problem. This line:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

needs to be:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

or since Java 7:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

How do you make strings "XML safe"?

1) You can wrap your text as CDATA like this:

<mytag>
    <![CDATA[Your text goes here. Btw: 5<6 and 6>5]]>
</mytag>

see http://www.w3schools.com/xml/xml_cdata.asp

2) As already someone said: Escape those chars. E.g. like so:

5&lt;6 and 6&gt;5

How to cherry pick a range of commits and merge into another branch?

$ git cherry-pick start_commit_sha_id^..end_commit_sha_id

e.g. git cherry-pick 3a7322ac^..7d7c123c

Assuming you are on branchA where you want to pick commits (start & end commit SHA for the range is given and left commit SHA is older) from branchB. The entire range of commits (both inclusive) will be cherry picked in branchA.

The examples given in the official documentation are quite useful.

dynamic_cast and static_cast in C++

First, to describe dynamic cast in C terms, we have to represent classes in C. Classes with virtual functions use a "VTABLE" of pointers to the virtual functions. Comments are C++. Feel free to reformat and fix compile errors...

// class A { public: int data; virtual int GetData(){return data;} };
typedef struct A { void**vtable; int data;} A;
int AGetData(A*this){ return this->data; }
void * Avtable[] = { (void*)AGetData };
A * newA() { A*res = malloc(sizeof(A)); res->vtable = Avtable; return res; }

// class B : public class A { public: int moredata; virtual int GetData(){return data+1;} }
typedef struct B { void**vtable; int data; int moredata; } B;
int BGetData(B*this){ return this->data + 1; }
void * Bvtable[] = { (void*)BGetData };
B * newB() { B*res = malloc(sizeof(B)); res->vtable = Bvtable; return res; }

// int temp = ptr->GetData();
int temp = ((int(*)())ptr->vtable[0])();

Then a dynamic cast is something like:

// A * ptr = new B();
A * ptr = (A*) newB();
// B * aB = dynamic_cast<B>(ptr);
B * aB = ( ptr->vtable == Bvtable ? (B*) aB : (B*) 0 );

Express.js - app.listen vs server.listen

The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io within the same HTTP server instance:

var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
...
server.listen(1234);

However, app.listen() also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:

var express   = require('express');
var app       = express();

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  ...
});

Eclipse shows errors but I can't find them

Take a look at

Window ? Show View ? Problems

or

Window ? Show View ? Error Log

How to check if a json key exists?

Try this:

let json=yourJson

if(json.hasOwnProperty(yourKey)){
    value=json[yourKey]
}

Push items into mongo array via mongoose

Use $push to update document and insert new value inside an array.

find:

db.getCollection('noti').find({})

result for find:

{
    "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
    "count" : 1.0,
    "color" : "green",
    "icon" : "circle",
    "graph" : [ 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 2.0
        }
    ],
    "name" : "online visitor",
    "read" : false,
    "date" : ISODate("2018-10-12T08:57:20.853Z"),
    "__v" : 0.0
}

update:

db.getCollection('noti').findOneAndUpdate(
   { _id: ObjectId("5bc061f05a4c0511a9252e88") }, 
   { $push: { 
             graph: {
               "date" : ISODate("2018-10-24T08:55:13.331Z"),
               "count" : 3.0
               }  
           } 
   })

result for update:

{
    "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
    "count" : 1.0,
    "color" : "green",
    "icon" : "circle",
    "graph" : [ 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 2.0
        }, 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 3.0
        }
    ],
    "name" : "online visitor",
    "read" : false,
    "date" : ISODate("2018-10-12T08:57:20.853Z"),
    "__v" : 0.0
}

How can you get the first digit in an int (C#)?

Try this

public int GetFirstDigit(int number) {
  if ( number < 10 ) {
    return number;
  }
  return GetFirstDigit ( (number - (number % 10)) / 10);
}

EDIT

Several people have requested the loop version

public static int GetFirstDigitLoop(int number)
{
    while (number >= 10)
    {
        number = (number - (number % 10)) / 10;
    }
    return number;
}

Error Installing Homebrew - Brew Command Not Found

This was just happening to me, but none of the suggestions above worked. I changed directories ("cd ~/tmp") and suddenly the command

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

worked for me. Prior to changing directories I had been in a directory that is a Git repository. Perhaps that was interfering with the ruby and Git commands in the Brew install script.

How to use If Statement in Where Clause in SQL?

select * from xyz where (1=(CASE WHEN @AnnualFeeType = 'All' THEN 1 ELSE 0 END) OR AnnualFeeType = @AnnualFeeType)

Ansible - Save registered variable to file

I am using Ansible 1.9.4 and this is what worked for me -

- local_action: copy content="{{ foo_result.stdout }}" dest="/path/to/destination/file"

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

HTML:

<div class="container">
    <div class="box">
        <img src="http://lorempixel.com/1600/1200/" alt="">
    </div>
</div>

CSS:

.container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: stretch;

  width: 100%;
  height: 100%;

  border-radius: 4px;
  background-color: hsl(0, 0%, 96%);
}

.box {
  border-radius: 4px;
  display: flex;
}

.box img {
  width: 100%;
  object-fit: contain;
  border-radius: 4px;
}