Programs & Examples On #Image segmentation

Segmentation is a basic operation in image processing: its purpose is to group similar pixels into coherent regions = segments.

How do I access Configuration in any class in ASP.NET Core?

I know there may be several ways to do this, I'm using Core 3.1 and was looking for the optimal/cleaner option and I ended up doing this:

  1. My startup class is as default
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
}
  1. My appsettings.json is like this
{
  "CompanySettings": {
    "name": "Fake Co"
  }
}

  1. My class is an API Controller, so first I added the using reference and then injected the IConfiguration interface
using Microsoft.Extensions.Configuration;

public class EmployeeController 
{
    private IConfiguration _configuration;
    public EmployeeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
}
  1. Finally I used the GetValue method
public async Task<IActionResult> Post([FromBody] EmployeeModel form)
{
    var companyName = configuration.GetValue<string>("CompanySettings:name");
    // companyName = "Fake Co"
}

How to display .svg image using swift

Try this code

var path: String = NSBundle.mainBundle().pathForResource("nameOfFile", ofType: "svg")!

        var url: NSURL = NSURL.fileURLWithPath(path)  //Creating a URL which points towards our path

       //Creating a page request which will load our URL (Which points to our path)
        var request: NSURLRequest = NSURLRequest(URL: url)
       webView.loadRequest(request)  //Telling our webView to load our above request

What is the convention in JSON for empty vs. null?

It is good programming practice to return an empty array [] if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}.

Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.

This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.

Here's a link to that part of his book:

http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

Well. Not long ago I also met this question. And finally I get the solutions which really address this issue.

My problem symptoms are also the pages not loading and find the json data was be randomly truncated.

Here are the solutions which I summary could help to solve this problem

1.Kill the anti-virus software process
2.Close chrome's Prerendering Instant pages feature
3.Try to close all the apps in your browser
4.Try to define your Content-Length header
  <?php
     header('Content-length: ' . strlen($output));
  ?>
5.Check your nginx fastcgi buffer is right 
6.Check your nginx gzip is open

How to replace innerHTML of a div using jQuery?

$("#regTitle").html("Hello World");

How do I turn off PHP Notices?

You can set ini_set('display_errors',0); in your script or define which errors you do want to display with error_reporting().

Closing a file after File.Create

The reason is because a FileStream is returned from your method to create a file. You should return the FileStream into a variable or call the close method directly from it after the File.Create.

It is a best practice to let the using block help you implement the IDispose pattern for a task like this. Perhaps what might work better would be:

if(!File.Exists(myPath)){
   using(FileStream fs = File.Create(myPath))
   using(StreamWriter writer = new StreamWriter(fs)){
      // do your work here
   }
}

How to change Label Value using javascript

This will work in Chrome

// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'

But after looking, labels doesn't seem to be widely supported..


You can use querySelector

// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'

Extracting text OpenCV

This is a C# version of the answer from dhanushka using OpenCVSharp

        Mat large = new Mat(INPUT_FILE);
        Mat rgb = new Mat(), small = new Mat(), grad = new Mat(), bw = new Mat(), connected = new Mat();

        // downsample and use it for processing
        Cv2.PyrDown(large, rgb);
        Cv2.CvtColor(rgb, small, ColorConversionCodes.BGR2GRAY);

        // morphological gradient
        var morphKernel = Cv2.GetStructuringElement(MorphShapes.Ellipse, new OpenCvSharp.Size(3, 3));
        Cv2.MorphologyEx(small, grad, MorphTypes.Gradient, morphKernel);

        // binarize
        Cv2.Threshold(grad, bw, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);

        // connect horizontally oriented regions
        morphKernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(9, 1));
        Cv2.MorphologyEx(bw, connected, MorphTypes.Close, morphKernel);

        // find contours
        var mask = new Mat(Mat.Zeros(bw.Size(), MatType.CV_8UC1), Range.All);
        Cv2.FindContours(connected, out OpenCvSharp.Point[][] contours, out HierarchyIndex[] hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple, new OpenCvSharp.Point(0, 0));

        // filter contours
        var idx = 0;
        foreach (var hierarchyItem in hierarchy)
        {
            idx = hierarchyItem.Next;
            if (idx < 0)
                break;
            OpenCvSharp.Rect rect = Cv2.BoundingRect(contours[idx]);
            var maskROI = new Mat(mask, rect);
            maskROI.SetTo(new Scalar(0, 0, 0));

            // fill the contour
            Cv2.DrawContours(mask, contours, idx, Scalar.White, -1);

            // ratio of non-zero pixels in the filled region
            double r = (double)Cv2.CountNonZero(maskROI) / (rect.Width * rect.Height);
            if (r > .45 /* assume at least 45% of the area is filled if it contains text */
                 &&
            (rect.Height > 8 && rect.Width > 8) /* constraints on region size */
            /* these two conditions alone are not very robust. better to use something 
            like the number of significant peaks in a horizontal projection as a third condition */
            )
            {
                Cv2.Rectangle(rgb, rect, new Scalar(0, 255, 0), 2);
            }
        }

        rgb.SaveImage(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "rgb.jpg"));

How to create a jQuery plugin with methods?

A simpler approach is to use nested functions. Then you can chain them in an object-oriented fashion. Example:

jQuery.fn.MyPlugin = function()
{
  var _this = this;
  var a = 1;

  jQuery.fn.MyPlugin.DoSomething = function()
  {
    var b = a;
    var c = 2;

    jQuery.fn.MyPlugin.DoSomething.DoEvenMore = function()
    {
      var d = a;
      var e = c;
      var f = 3;
      return _this;
    };

    return _this;
  };

  return this;
};

And here's how to call it:

var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();

Be careful though. You cannot call a nested function until it has been created. So you cannot do this:

var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();
pluginContainer.MyPlugin.DoSomething();

The DoEvenMore function doesn't even exist because the DoSomething function hasn't been run yet which is required to create the DoEvenMore function. For most jQuery plugins, you really are only going to have one level of nested functions and not two as I've shown here.
Just make sure that when you create nested functions that you define these functions at the beginning of their parent function before any other code in the parent function gets executed.

Finally, note that the "this" member is stored in a variable called "_this". For nested functions, you should return "_this" if you need a reference to the instance in the calling client. You cannot just return "this" in the nested function because that will return a reference to the function and not the jQuery instance. Returning a jQuery reference allows you to chain intrinsic jQuery methods on return.

CSS: How can I set image size relative to parent height?

you can use flex box for it.. this will solve your problem

.image-parent 
{
     height:33px; 
     display:flex; 
}

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

In my case I created a database and gave the collation 'utf8_general_ci' but the required collation was 'latin1'. After changing my collation type to latin1_bin the error was gone.

Get the current file name in gulp.src()

I'm not sure how you want to use the file names, but one of these should help:

  • If you just want to see the names, you can use something like gulp-debug, which lists the details of the vinyl file. Insert this anywhere you want a list, like so:

    var gulp = require('gulp'),
        debug = require('gulp-debug');
    
    gulp.task('examples', function() {
        return gulp.src('./examples/*.html')
            .pipe(debug())
            .pipe(gulp.dest('./build'));
    });
    
  • Another option is gulp-filelog, which I haven't used, but sounds similar (it might be a bit cleaner).

  • Another options is gulp-filesize, which outputs both the file and it's size.

  • If you want more control, you can use something like gulp-tap, which lets you provide your own function and look at the files in the pipe.

Extracting jar to specified directory

There is no such option available in jar command itself. Look into the documentation:

-C dir Temporarily changes directories (cd dir) during execution of the jar command while processing the following inputfiles argument. Its operation is intended to be similar to the -C option of the UNIX tar utility. For example: jar uf foo.jar -C classes bar.class changes to the classes directory and add the bar.class from that directory to foo.jar. The following command, jar uf foo.jar -C classes . -C bin xyz.class changes to the classes directory and adds to foo.jar all files within the classes directory (without creating a classes directory in the jar file), then changes back to the original directory before changing to the bin directory to add xyz.class to foo.jar. If classes holds files bar1 and bar2, then here's what the jar file contains using jar tf foo.jar: META-INF/

META-INF/MANIFEST.MF

bar1

bar2

xyz.class

How can I delete using INNER JOIN with SQL Server?

You could even do a sub-query. Like this code below:

DELETE FROM users WHERE id IN(
    SELECT user_id FROM Employee WHERE Company = '1' AND Date = '2013-05-06'
)

Array Index Out of Bounds Exception (Java)

for ( i = 0; i < total.length; i++ ); // remove this
{
    if (total[i]!=0)
        System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}

The for loop loops until i=26 (where 26 is total.length) and then your if is executed, going over the bounds of the array. Remove the ; at the end of the for loop.

list all files in the folder and also sub folders

Use FileUtils from Apache commons.

listFiles

public static Collection<File> listFiles(File directory,
                                         String[] extensions,
                                         boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

apache ProxyPass: how to preserve original IP address

This has a more elegant explanation and more than one possible solutions. http://kasunh.wordpress.com/2011/10/11/preserving-remote-iphost-while-proxying/

The post describes how to use one popular and one lesser known Apache modules to preserve host/ip while in a setup involving proxying.

Use mod_rpaf module, install and enable it in the backend server and add following directives in the module’s configuration. RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1

(2017 edit) Current location of mod_rpaf: https://github.com/gnif/mod_rpaf

conversion from string to json object android

You just need the lines of code as below:

   try {
        String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
        JSONObject jsonObject = new JSONObject(myjsonString );
        //displaying the JSONObject as a String
        Log.d("JSONObject = ", jsonObject.toString());
        //getting specific key values
        Log.d("phonetype = ", jsonObject.getString("phonetype"));
        Log.d("cat = ", jsonObject.getString("cat");
    }catch (Exception ex) {
         StringWriter stringWriter = new StringWriter();
         ex.printStackTrace(new PrintWriter(stringWriter));
         Log.e("exception ::: ", stringwriter.toString());
    }

Converting String to Int with Swift

Swift5 float or int string to int:

extension String {
    func convertStringToInt() -> Int {
        return Int(Double(self) ?? 0.0)
    }
}

let doubleStr = "4.2"
// print 4
print(doubleStr.convertStringToInt())

let intStr = "4"
// print 4
print(intStr.convertStringToInt())

Javascript string/integer comparisons

use parseInt and compare like below:

javascript:alert(parseInt("2")>parseInt("10"))

Get characters after last / in url

$str = "http://www.vimeo.com/1234567";
$s = explode("/",$str);
print end($s);

Byte array to image conversion

In one line:

Image.FromStream(new MemoryStream(byteArrayIn));

Save attachments to a folder and rename them

This is my Save Attachments script. You select all the messages that you want the attachments saved from, and it will save a copy there. It also adds text to the message body indicating where the attachment is saved. You could easily change the folder name to include the date, but you would need to make sure the folder existed before starting to save files.

Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String

' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next

' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")

' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection

' Set the Attachment folder.
strFolderpath = strFolderpath & "\Attachments\"

' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection

    ' This code only strips attachments from mail items.
    ' If objMsg.class=olMail Then
    ' Get the Attachments collection of the item.
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
    strDeletedFiles = ""

    If lngCount > 0 Then

        ' We need to use a count down loop for removing items
        ' from a collection. Otherwise, the loop counter gets
        ' confused and only every other item is removed.

        For i = lngCount To 1 Step -1

            ' Save attachment before deleting from item.
            ' Get the file name.
            strFile = objAttachments.Item(i).FileName

            ' Combine with the path to the Temp folder.
            strFile = strFolderpath & strFile

            ' Save the attachment as a file.
            objAttachments.Item(i).SaveAsFile strFile

            ' Delete the attachment.
            objAttachments.Item(i).Delete

            'write the save as path to a string to add to the message
            'check for html and use html tags in link
            If objMsg.BodyFormat <> olFormatHTML Then
                strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
            Else
                strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
                strFile & "'>" & strFile & "</a>"
            End If

            'Use the MsgBox command to troubleshoot. Remove it from the final code.
            'MsgBox strDeletedFiles

        Next i

        ' Adds the filename string to the message body and save it
        ' Check for HTML body
        If objMsg.BodyFormat <> olFormatHTML Then
            objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
        Else
            objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
        End If
        objMsg.Save
    End If
Next

ExitSub:

Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

Email address validation in C# MVC 4 application: with or without using Regex

Regex:

[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]

Or you can use just:

    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

How to create relationships in MySQL

Adding onto the comment by ehogue, you should make the size of the keys on both tables match. Rather than

customer_id INT( 4 ) NOT NULL ,

make it

customer_id INT( 10 ) NOT NULL ,

and make sure your int column in the customers table is int(10) also.

check if "it's a number" function in Oracle

@JustinCave - The "when value_error" replacement for "when others" is a nice refinement to your approach above. This slight additional tweak, while conceptually the same, removes the requirement for the definition of and consequent memory allocation to your l_num variable:

function validNumber(vSomeValue IN varchar2)
     return varchar2 DETERMINISTIC PARALLEL_ENABLE
     is
begin
  return case when abs(vSomeValue) >= 0 then 'T' end;
exception
  when value_error then
    return 'F';
end;

Just a note also to anyone preferring to emulate Oracle number format logic using the "riskier" REGEXP approach, please don't forget to consider NLS_NUMERIC_CHARACTERS and NLS_TERRITORY.

How to access form methods and controls from a class in C#?

You need to make the members in the for the form class either public or, if the service class is in the same assembly, internal. Windows controls' visibility can be controlled through their Modifiers properties.

Note that it's generally considered a bad practice to explicitly tie a service class to a UI class. Rather you should create good interfaces between the service class and the form class. That said, for learning or just generally messing around, the earth won't spin off its axis if you expose form members for service classes.

rp

How to copy text from a div to clipboard

Made a modification to the solutions, so it will work with multiple divs based on class instead of specific IDs. For example, if you have multiple blocks of code. This assumes that the div class is set to "code".

<script>
        $( document ).ready(function() {
            $(".code").click(function(event){
                var range = document.createRange();
                range.selectNode(this);
                window.getSelection().removeAllRanges(); // clear current selection
                window.getSelection().addRange(range); // to select text
                document.execCommand("copy");
                window.getSelection().removeAllRanges();// to deselect
            });
        });
    </script>

Could not find main class HelloWorld

Tell it where to look for you class: it's in ".", which is the current directory:

java -classpath . HelloWorld

No need to set JAVA_HOME or CLASSPATH in this case

Assign variable in if condition statement, good practice or not?

You can do this in Java too. And no, it's not a good practice. :)

(And use the === in Javascript for typed equality. Read Crockford's The Good Parts book on JS.)

Android List View Drag and Drop sort

Now it's pretty easy to implement for RecyclerView with ItemTouchHelper. Just override onMove method from ItemTouchHelper.Callback:

 @Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
    mMovieAdapter.swap(viewHolder.getAdapterPosition(), target.getAdapterPosition());
    return true;
}

Pretty good tutorial on this can be found at medium.com : Drag and Swipe with RecyclerView

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

You should replace WebDriver wb = new FirefoxDriver(); with driver = new FirefoxDriver(); in your @Before Annotation.

As you are accessing driver object with null or you can make wb reference variable as global variable.

Create a custom event in Java

You probably want to look into the observer pattern.

Here's some sample code to get yourself started:

import java.util.*;

// An interface to be implemented by everyone interested in "Hello" events
interface HelloListener {
    void someoneSaidHello();
}

// Someone who says "Hello"
class Initiater {
    private List<HelloListener> listeners = new ArrayList<HelloListener>();

    public void addListener(HelloListener toAdd) {
        listeners.add(toAdd);
    }

    public void sayHello() {
        System.out.println("Hello!!");

        // Notify everybody that may be interested.
        for (HelloListener hl : listeners)
            hl.someoneSaidHello();
    }
}

// Someone interested in "Hello" events
class Responder implements HelloListener {
    @Override
    public void someoneSaidHello() {
        System.out.println("Hello there...");
    }
}

class Test {
    public static void main(String[] args) {
        Initiater initiater = new Initiater();
        Responder responder = new Responder();

        initiater.addListener(responder);

        initiater.sayHello();  // Prints "Hello!!!" and "Hello there..."
    }
}

Related article: Java: Creating a custom event

Undoing accidental git stash pop

From git stash --help

Recovering stashes that were cleared/dropped erroneously
   If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms. However, you can try the
   following incantation to get a list of stashes that are still in your repository, but not reachable any more:

       git fsck --unreachable |
       grep commit | cut -d\  -f3 |
       xargs git log --merges --no-walk --grep=WIP

This helped me better than the accepted answer with the same scenario.

Generating a Random Number between 1 and 10 Java

As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.

Generally speaking, if you need to generate numbers from min to max (including both), you write

random.nextInt(max - min + 1) + min

How to properly set the 100% DIV height to match document/window height?

The easiest way is to add the:

$('#ID').css("height", $(document).height());

after the correct page height is determined by the browser. If the document height is changed once more re-run the above code.

SQL how to increase or decrease one for a int column in one command

UPDATE Orders Order
SET Order.Quantity =  Order.Quantity - 1
WHERE SomeCondition(Order)

As far as I know there is no build-in support for INSERT-OR-UPDATE in SQL. I suggest to create a stored procedure or use a conditional query to achiev this. Here you can find a collection of solutions for different databases.

How to call a button click event from another method

Use InvokeOnClick event. it works even if the button is invisible/disabled

How to Bootstrap navbar static to fixed on scroll?

Use the affix component included with Bootstrap. Start with a 'navbar-static-top' and this will change it to fixed when the height of your header (content above the navbar) is reached...

$('#nav').affix({
      offset: {
        top: $('header').height()
      }
}); 

http://bootply.com/107973

Embedding SVG into ReactJS

If you want to load it from a file, you may try to use React-inlinesvg - that's pretty simple and straight-forward.

import SVG from 'react-inlinesvg';

<SVG
  src="/path/to/myfile.svg"
  preloader={<Loader />}
  onLoad={(src) => {
    myOnLoadHandler(src);
  }}
>
  Here's some optional content for browsers that don't support XHR or inline
  SVGs. You can use other React components here too. Here, I'll show you.
  <img src="/path/to/myfile.png" />
</SVG>

How and where to use ::ng-deep?

I would emphasize the importance of limiting the ::ng-deep to only children of a component by requiring the parent to be an encapsulated css class.

For this to work it's important to use the ::ng-deep after the parent, not before otherwise it would apply to all the classes with the same name the moment the component is loaded.

Using the :host keyword before ::ng-deep will handle this automatically:

:host ::ng-deep .mat-checkbox-layout

Alternatively you can achieve the same behavior by adding a component scoped CSS class before the ::ng-deep keyword:

.my-component ::ng-deep .mat-checkbox-layout {
    background-color: aqua;
}

Component template:

<h1 class="my-component">
    <mat-checkbox ....></mat-checkbox>
</h1>

Resulting (Angular generated) css will then include the uniquely generated name and apply only to its own component instance:

.my-component[_ngcontent-c1] .mat-checkbox-layout {
    background-color: aqua;
}

What is the best way to implement nested dictionaries?

As for "obnoxious try/catch blocks":

d = {}
d.setdefault('key',{}).setdefault('inner key',{})['inner inner key'] = 'value'
print d

yields

{'key': {'inner key': {'inner inner key': 'value'}}}

You can use this to convert from your flat dictionary format to structured format:

fd = {('new jersey', 'mercer county', 'plumbers'): 3,
 ('new jersey', 'mercer county', 'programmers'): 81,
 ('new jersey', 'middlesex county', 'programmers'): 81,
 ('new jersey', 'middlesex county', 'salesmen'): 62,
 ('new york', 'queens county', 'plumbers'): 9,
 ('new york', 'queens county', 'salesmen'): 36}

for (k1,k2,k3), v in fd.iteritems():
    d.setdefault(k1, {}).setdefault(k2, {})[k3] = v

Import SQL file into mysql

mysql>c:/nitm.sql;

That would write the output of the mysql command to 'nitm.sql;' (What's the ';' supposed to do?) Assuming you've got a copy of the original file (before you overwrote it) then:

mysql < c:/nitm.sql

Add CSS3 transition expand/collapse

Here's a solution that doesn't use JS at all. It uses checkboxes instead.

You can hide the checkbox by adding this to your CSS:

.container input{
    display: none;
}

And then add some styling to make it look like a button.

Here's the source code that I modded.

AWS ssh access 'Permission denied (publickey)' issue

this worked for me:

ssh-keygen -R <server_IP>

to delete the old keys stored on the workstation also works with instead of

then doing the same ssh again it worked:

ssh -v -i <your_pem_file> ubuntu@<server_IP>

on ubuntu instances the username is: ubuntu on Amazon Linux AMI the username is: ec2-user

I didn't have to re-create the instance from an image.

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

How to make the division of 2 ints produce a float instead of another int?

Try:

v = (float)s / (float)t;

Casting the ints to floats will allow floating-point division to take place.

You really only need to cast one, though.

C++ -- expected primary-expression before ' '

You should not be repeating the string part when sending parameters.

int wordLength = wordLengthFunction(word); //you do not put string word here.

Change text (html) with .animate

refer to official jquery example: and play with it.

.animate({
    width: "70%",
    opacity: 0.4,
    marginLeft: "0.6in",
    fontSize: "3em",
    borderWidth: "10px"
  }, 1500 );

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

MySQL multiple instances present on Ubuntu.

step 1 : if it's listed as installed, you got it. Else you need to get it.

sudo ps -A | grep mysql

step 2 : remove the one MySQL

sudo apt-get remove mysql

sudo service mysql restart

step 3 : restart lamp

sudo /opt/lampp/lampp restart

SQL select statements with multiple tables

Like that:

SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299'

How do I get the height and width of the Android Navigation Bar programmatically?

I hope this helps you

public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

public int getNavigationBarHeight()
{
    boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
    int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
    if (resourceId > 0 && !hasMenuKey)
    {
        return getResources().getDimensionPixelSize(resourceId);
    }
    return 0;
}

Pointers in Python?

I wrote the following simple class as, effectively, a way to emulate a pointer in python:

class Parameter:
    """Syntactic sugar for getter/setter pair
    Usage:

    p = Parameter(getter, setter)

    Set parameter value:
    p(value)
    p.val = value
    p.set(value)

    Retrieve parameter value:
    p()
    p.val
    p.get()
    """
    def __init__(self, getter, setter):
        """Create parameter

        Required positional parameters:
        getter: called with no arguments, retrieves the parameter value.
        setter: called with value, sets the parameter.
        """
        self._get = getter
        self._set = setter

    def __call__(self, val=None):
        if val is not None:
            self._set(val)
        return self._get()

    def get(self):
        return self._get()

    def set(self, val):
        self._set(val)

    @property
    def val(self):
        return self._get()

    @val.setter
    def val(self, val):
        self._set(val)

Here's an example of use (from a jupyter notebook page):

l1 = list(range(10))
def l1_5_getter(lst=l1, number=5):
    return lst[number]

def l1_5_setter(val, lst=l1, number=5):
    lst[number] = val

[
    l1_5_getter(),
    l1_5_setter(12),
    l1,
    l1_5_getter()
]

Out = [5, None, [0, 1, 2, 3, 4, 12, 6, 7, 8, 9], 12]

p = Parameter(l1_5_getter, l1_5_setter)

print([
    p(),
    p.get(),
    p.val,
    p(13),
    p(),
    p.set(14),
    p.get()
])
p.val = 15
print(p.val, l1)

[12, 12, 12, 13, 13, None, 14]
15 [0, 1, 2, 3, 4, 15, 6, 7, 8, 9]

Of course, it is also easy to make this work for dict items or attributes of an object. There is even a way to do what the OP asked for, using globals():

def setter(val, dict=globals(), key='a'):
    dict[key] = val

def getter(dict=globals(), key='a'):
    return dict[key]

pa = Parameter(getter, setter)
pa(2)
print(a)
pa(3)
print(a)

This will print out 2, followed by 3.

Messing with the global namespace in this way is kind of transparently a terrible idea, but it shows that it is possible (if inadvisable) to do what the OP asked for.

The example is, of course, fairly pointless. But I have found this class to be useful in the application for which I developed it: a mathematical model whose behavior is governed by numerous user-settable mathematical parameters, of diverse types (which, because they depend on command line arguments, are not known at compile time). And once access to something has been encapsulated in a Parameter object, all such objects can be manipulated in a uniform way.

Although it doesn't look much like a C or C++ pointer, this is solving a problem that I would have solved with pointers if I were writing in C++.

Python equivalent of D3.js

There is an interesting port of NetworkX to Javascript that might do what you want. See http://felix-kling.de/JSNetworkX/

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

my experience tells me that missing persistence.xml,will generate the same exception too.

i caught the same error msg today when i tried to run a jar package packed by ant.

when i used jar tvf to check the content of the jar file, i realized that "ant" forgot to pack the persistnece.xml for me.

after I manually repacked the jar file ,the error msg disappered.

so i believe maybe you should try simplely putting META-INF under src directory and placing your persistence.xml there.

How can I load webpage content into a div on page load?

You can't inject content from another site (domain) using AJAX. The reason an iFrame is suited for these kinds of things is that you can specify the source to be from another domain.

Algorithm to detect overlapping periods

Check this simple method (It is recommended to put This method in your dateUtility

public static bool isOverlapDates(DateTime dtStartA, DateTime dtEndA, DateTime dtStartB, DateTime dtEndB)
        {
            return dtStartA < dtEndB && dtStartB < dtEndA;
        }

How to convert comma-delimited string to list in Python?

In the case of integers that are included at the string, if you want to avoid casting them to int individually you can do:

mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]

It is called list comprehension, and it is based on set builder notation.

ex:

>>> mStr = "1,A,B,3,4"
>>> mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]
>>> mList
>>> [1,'A','B',3,4]

Copying formula to the next row when inserting a new row

Private Sub Worksheet_Change(ByVal Target As Range)

'data starts on row 3 which has the formulas
'the sheet is protected - input cells not locked - formula cells locked
'this routine is triggered on change of any cell on the worksheet so first check if
' it's a cell that we're interested in - and the row doesn't already have formulas
If Target.Column = 3 And Target.Row > 3 _
And Range("M" & Target.Row).Formula = "" Then

    On Error GoTo ERROR_OCCURRED

    'unprotect the sheet - otherwise can't copy and paste
    ActiveSheet.Unprotect
    'disable events - this prevents this routine from triggering again when
    'copy and paste below changes the cell values
    Application.EnableEvents = False

    'copy col D (with validation list) from row above to new row (not locked)
    Range("D" & Target.Row - 1).Copy
    Range("D" & Target.Row).PasteSpecial

    'copy col M to P (with formulas) from row above to new row
    Range("M" & Target.Row - 1 & ":P" & Target.Row - 1).Copy
    Range("M" & Target.Row).PasteSpecial

'make sure if an error occurs (or not) events are re-enabled and sheet re-protected

ERROR_OCCURRED:

    If Err.Number <> 0 Then
        MsgBox "An error occurred. Formulas may not have been copied." & vbCrLf & vbCrLf & _
            Err.Number & " - " & Err.Description
    End If

    're-enable events
    Application.EnableEvents = True
    're-protect the sheet
    ActiveSheet.Protect

    'put focus back on the next cell after routine was triggered
    Range("D" & Target.Row).Select

End If

End Sub

How are ssl certificates verified?

It's worth noting that in addition to purchasing a certificate (as mentioned above), you can also create your own for free; this is referred to as a "self-signed certificate". The difference between a self-signed certificate and one that's purchased is simple: the purchased one has been signed by a Certificate Authority that your browser already knows about. In other words, your browser can easily validate the authenticity of a purchased certificate.

Unfortunately this has led to a common misconception that self-signed certificates are inherently less secure than those sold by commercial CA's like GoDaddy and Verisign, and that you have to live with browser warnings/exceptions if you use them; this is incorrect.

If you securely distribute a self-signed certificate (or CA cert, as bobince suggested) and install it in the browsers that will use your site, it's just as secure as one that's purchased and is not vulnerable to man-in-the-middle attacks and cert forgery. Obviously this means that it's only feasible if only a few people need secure access to your site (e.g., internal apps, personal blogs, etc.).

MySQL Select Query - Get only first 10 characters of a value

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

How to bind Dataset to DataGridView in windows application

following will show one table of dataset

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = ds; // dataset
DataGridView1.DataMember = "TableName"; // table name you need to show

if you want to show multiple tables, you need to create one datatable or custom object collection out of all tables.

if two tables with same table schema

dtAll = dtOne.Copy(); // dtOne = ds.Tables[0]
dtAll.Merge(dtTwo); // dtTwo = dtOne = ds.Tables[1]

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ; // datatable

sample code to mode all tables

DataTable dtAll = ds.Tables[0].Copy();
for (var i = 1; i < ds.Tables.Count; i++)
{
     dtAll.Merge(ds.Tables[i]);
}
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ;

How do I change UIView Size?

Swift 3 and Swift 4:

myView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)

Detecting a redirect in ajax request?

While the other folks who answered this question are (sadly) correct that this information is hidden from us by the browser, I thought I'd post a workaround I came up with:

I configured my server app to set a custom response header (X-Response-Url) containing the url that was requested. Whenever my ajax code receives a response, it checks if xhr.getResponseHeader("x-response-url") is defined, in which case it compares it to the url that it originally requested via $.ajax(). If the strings differ, I know there was a redirect, and additionally, what url we actually arrived at.

This does have the drawback of requiring some server-side help, and also may break down if the url gets munged (due to quoting/encoding issues etc) during the round trip... but for 99% of cases, this seems to get the job done.


On the server side, my specific case was a python application using the Pyramid web framework, and I used the following snippet:

import pyramid.events

@pyramid.events.subscriber(pyramid.events.NewResponse)
def set_response_header(event):
    request = event.request
    if request.is_xhr:
        event.response.headers['X-Response-URL'] = request.url

Can a variable number of arguments be passed to a function?

Adding to unwinds post:

You can send multiple key-value args too.

def myfunc(**kwargs):
    # kwargs is a dictionary.
    for k,v in kwargs.iteritems():
         print "%s = %s" % (k, v)

myfunc(abc=123, efh=456)
# abc = 123
# efh = 456

And you can mix the two:

def myfunc2(*args, **kwargs):
   for a in args:
       print a
   for k,v in kwargs.iteritems():
       print "%s = %s" % (k, v)

myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123

They must be both declared and called in that order, that is the function signature needs to be *args, **kwargs, and called in that order.

xlrd.biffh.XLRDError: Excel xlsx file; not supported

As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:

xlrd has explicitly removed support for anything other than xls files.

In your case, the solution is to:

  • make sure you are on a recent version of Pandas, at least 1.0.1, and preferably the latest release. 1.2 will make his even clearer.
  • install openpyxl: https://openpyxl.readthedocs.io/en/stable/
  • change your Pandas code to be:
    df1 = pd.read_excel(
         os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
         engine='openpyxl',
    )
    

What does localhost:8080 mean?

http uses port 80, and understandably, your internet browser will automatically use that port when you type in an address - unless you specify another port. Now, when running a web server on your computer, you need to access that server somehow - and since port 80 is already busy, you need to use a different port to successfully connect to it. Although any open port is fair game, usually such a server is configured to use port 8080, hence when accessing your server you type in:

http:// (protocol) localhost (your computer) :8080 (port 8080) / (path pointing to the root of the public folder of your server)

MySQL delete multiple rows in one query conditions unique to each row

A slight extension to the answer given, so, hopefully useful to the asker and anyone else looking.

You can also SELECT the values you want to delete. But watch out for the Error 1093 - You can't specify the target table for update in FROM clause.

DELETE FROM
    orders_products_history
WHERE
    (branchID, action) IN (
    SELECT
        branchID,
        action
    FROM
        (
        SELECT
            branchID,
            action
        FROM
            orders_products_history
        GROUP BY
            branchID,
            action
        HAVING
            COUNT(*) > 10000
        ) a
    );

I wanted to delete all history records where the number of history records for a single action/branch exceed 10,000. And thanks to this question and chosen answer, I can.

Hope this is of use.

Richard.

Assigning the return value of new by reference is deprecated

I recently moved a site using SimplePie (http://simplepie.org/) from a server that was using PHP 5.2.17 to one that is using PHP 5.3.2. It was after this move that I began receiving a list of error messages such as this one:

Deprecated: Assigning the return value of new by reference is deprecated in .../php/simplepie.inc on line 738

After reviewing several discussions of this issue, I cleared things up by replacing all the instances of =& new with = new in the simplepie.inc file.

I'm not experienced enough to know if this will work in all instances where these error messages are received but it worked in this particular case and it may be worth trying.

How do I get the width and height of a HTML5 canvas?

Well, all the answers before aren't entirely correct. 2 of major browsers don't support those 2 properties (IE is one of them) or use them differently.

Better solution (supported by most browsers, but I didn't check Safari):

var canvas = document.getElementById('mycanvas');
var width = canvas.scrollWidth;
var height = canvas.scrollHeight;

At least I get correct values with scrollWidth and -Height and MUST set canvas.width and height when it is resized.

How to concatenate characters in java?

I wasn't going to answer this question but there are two answers here (that are getting voted up!) that are just plain wrong. Consider these expressions:

String a = "a" + "b" + "c";
String b = System.getProperty("blah") + "b";

The first is evaluated at compile-time. The second is evaluated at run-time.

So never replace constant concatenations (of any type) with StringBuilder, StringBuffer or the like. Only use those where variables are invovled and generally only when you're appending a lot of operands or you're appending in a loop.

If the characters are constant, this is fine:

String s = "" + 'a' + 'b' + 'c';

If however they aren't, consider this:

String concat(char... chars) {
  if (chars.length == 0) {
    return "";
  }
  StringBuilder s = new StringBuilder(chars.length);
  for (char c : chars) {
    s.append(c);
  }
  return s.toString();
}

as an appropriate solution.

However some might be tempted to optimise:

String s = "Name: '" + name + "'"; // String name;

into this:

String s = new StringBuilder().append("Name: ").append(name).append("'").toString();

While this is well-intentioned, the bottom line is DON'T.

Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.

For low-level optimisation the compiler is better at optimising code than you are.

Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.

Fastest Way to Find Distance Between Two Lat/Long Points

   select
   (((acos(sin(('$latitude'*pi()/180)) * sin((`lat`*pi()/180))+cos(('$latitude'*pi()/180)) 
    * cos((`lat`*pi()/180)) * cos((('$longitude'- `lng`)*pi()/180))))*180/pi())*60*1.1515) 
    AS distance
    from table having distance<22;

MySQL date formats - difficulty Inserting a date

The date format for mysql insert query is YYYY-MM-DD

example:

INSERT INTO table_name (date_column) VALUE ('YYYY-MM-DD');

jQuery serialize does not register checkboxes

The trick is to intercept the form post and change the check boxes to hidden input fields.

Example: Plain Submit

$('form').on("submit", function (e) {
    //find the checkboxes
    var $checkboxes = $(this).find('input[type=checkbox]');

    //loop through the checkboxes and change to hidden fields
    $checkboxes.each(function() {
        if ($(this)[0].checked) {
            $(this).attr('type', 'hidden');
            $(this).val(1);
        } else {
            $(this).attr('type', 'hidden');
            $(this).val(0);
        }
    });
});

Example: AJAX

You need to jump through a few more hoops if you are posting the form via ajax to not update the UI.

$('form').on("submit", function (e) {
    e.preventDefault();

    //clone the form, we don't want this to impact the ui
    var $form = $('form').clone();

    //find the checkboxes
    var $checkboxes = $form.find('input[type=checkbox]');

    //loop through the checkboxes and change to hidden fields
    $checkboxes.each(function() {
        if ($(this)[0].checked) {
            $(this).attr('type', 'hidden');
            $(this).val(1);
        } else {
            $(this).attr('type', 'hidden');
            $(this).val(0);
        }
    });

    $.post("/your/path", $form.serialize());

Why do I have ORA-00904 even when the column is present?

Have you compared the table definitions in Prod and Dev?

And when you are running it in SQL Developer, are you running the query in Prod (same database as the application) and with the same user?

If there are some additional columns that you are adding (using an alter command) and these changes are not yet promoted to prod, this issue is possible.

Can you post the definition of the table and your actual Query?

$ is not a function - jQuery error

In Wordpress jQuery.noConflict() is called on the jQuery file it includes (scroll to the bottom of the file it's including for jQuery to see this), which means $ doesn't work, but jQuery does, so your code should look like this:

<script type="text/javascript">
  jQuery(function($) {
    for(var i=0; i <= 20; i++) 
      $("ol li:nth-child(" + i + ")").addClass('olli' + i);
  });
</script>

How do I connect to a MySQL Database in Python?

Even though some of you may mark this as a duplicate and get upset that I am copying someone else's answer, I would REALLY like to highlight an aspect of Mr. Napik's response. Because I missed this, I caused nationwide website downtime (9min). If only someone shared this information, I could have prevented it!

Here is his code:

import mysql.connector    
cnx = mysql.connector.connect(user='scott', password='tiger',
                              host='127.0.0.1',
                              database='employees')
try:
   cursor = cnx.cursor()
   cursor.execute("""select 3 from your_table""")
   result = cursor.fetchall()
   print(result)
finally:
    cnx.close()

The important thing here is the Try and Finally clause. This allows connections to ALWAYS be closed, regardless of what happens in the cursor/sqlstatement portion of the code. A lot of active connections cause DBLoadNoCPU to spike and could crash a db server.

I hope this warning helps to save servers and ultimately jobs! :D

Int to byte array

This may be OT but if you are serializing a lot of primitive types or POD structures, Google Protocol Buffers for .Net might be useful to you. This addresses the endianness issue @Marc raised above, among other useful features.

combining two string variables

IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:

the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])

Edit: Note that join wants an iterable (e.g. a list) as its single argument.

Publish to IIS, setting Environment Variable

For those of you looking to this in an azure devops pipeline, this can be achieved by adding the PowerShell on target machines task and running the following script:

$envVariables = (
  @{name='VARIABLE1';value='Value1'},
  @{name='VARIABLE2';value='Value2'}
)

Set-WebConfigurationProperty -PSPath IIS:\ -Location $('mySite') -Filter /system.webServer/aspNetCore/environmentVariables -Name . -Value $envVariables

How to convert JSON object to JavaScript array?

function json2array(json){
    var result = [];
    var keys = Object.keys(json);
    keys.forEach(function(key){
        result.push(json[key]);
    });
    return result;
}

See this complete explanation: http://book.mixu.net/node/ch5.html

cleanest way to skip a foreach if array is empty

I wouldn't recommend suppressing the warning output. I would, however, recommend using is_array instead of !empty. If $items happens to be a nonzero scalar, then the foreach will still error out if you use !empty.

Array to String PHP?

The implode() function returns a string from the elements of an array.

<?php
    $arr = array('Hello','World!','Beautiful','Day!');
    echo implode(" ",$arr);
?>

Output: Hello World! Beautiful Day!

<?php
    $arr = array('Hello','World!','Beautiful','Day!');
    echo implode("|",$arr);
?>

Output: Hello|World!|Beautiful|Day!

POI setting Cell Background to a Custom Color

You can set custom color using this-

check out this - click hear

XSSFWorkbook workbook = new XSSFWorkbook();

IndexedColorMap colorMap = workbook.getStylesSource().getIndexedColors();
Font tableHeadOneFontStyle = workbook.createFont();
        tableHeadOneFontStyle.setBold( true );
        tableHeadOneFontStyle.setColor( IndexedColors.BLACK.getIndex() );

XSSFCellStyle tableHeaderOneColOneStyle = workbook.createCellStyle();
        tableHeaderOneColOneStyle.setFont( tableHeadOneFontStyle );
        tableHeaderOneColOneStyle
                .setFillForegroundColor( new XSSFColor( new java.awt.Color( 255, 231, 153 ), colorMap ) );
        tableHeaderOneColOneStyle.setFillPattern( FillPatternType.SOLID_FOREGROUND );
        tableHeaderOneColOneStyle = setLeftRightBorderColor( tableHeaderOneColOneStyle );
        tableHeaderOneColOneStyle = alignCenter( tableHeaderOneColOneStyle );

take(1) vs first()

Operators first() and take(1) aren't the same.

The first() operator takes an optional predicate function and emits an error notification when no value matched when the source completed.

For example this will emit an error:

import { EMPTY, range } from 'rxjs';
import { first, take } from 'rxjs/operators';

EMPTY.pipe(
  first(),
).subscribe(console.log, err => console.log('Error', err));

... as well as this:

range(1, 5).pipe(
  first(val => val > 6),
).subscribe(console.log, err => console.log('Error', err));

While this will match the first value emitted:

range(1, 5).pipe(
  first(),
).subscribe(console.log, err => console.log('Error', err));

On the other hand take(1) just takes the first value and completes. No further logic is involved.

range(1, 5).pipe(
  take(1),
).subscribe(console.log, err => console.log('Error', err));

Then with empty source Observable it won't emit any error:

EMPTY.pipe(
  take(1),
).subscribe(console.log, err => console.log('Error', err));

Jan 2019: Updated for RxJS 6

Disable copy constructor

Make SymbolIndexer( const SymbolIndexer& ) private. If you're assigning to a reference, you're not copying.

Why doesn't JUnit provide assertNotEquals methods?

I'd argue that the absence of assertNotEqual is indeed an asymmetry and makes JUnit a bit less learnable. Mind that this is a neat case when adding a method would diminish the complexity of the API, at least for me: Symmetry helps ruling the bigger space. My guess is that the reason for the omission may be that there are too few people calling for the method. Yet, I remember a time when even assertFalse did not exist; hence, I have a positive expectation that the method might eventually be added, given that it is not a difficult one; even though I acknowledge that there are numerous workarounds, even elegant ones.

MySQL Update Column +1?

The easiest way is to not store the count, relying on the COUNT aggregate function to reflect the value as it is in the database:

   SELECT c.category_name,
          COUNT(p.post_id) AS num_posts
     FROM CATEGORY c
LEFT JOIN POSTS p ON p.category_id = c.category_id

You can create a view to house the query mentioned above, so you can query the view just like you would a table...

But if you're set on storing the number, use:

UPDATE CATEGORY
   SET count = count + 1
 WHERE category_id = ?

..replacing "?" with the appropriate value.

Allow scroll but hide scrollbar

Try this:

HTML:

<div id="container">
    <div id="content">
        // Content here
    </div>
</div>

CSS:

#container{
    height: 100%;
    width: 100%;
    overflow: hidden;
}

#content{
    width: 100%;
    height: 99%;
    overflow: auto;
    padding-right: 15px;
}

html, body{
    height: 99%;
    overflow:hidden;
}

JSFiddle Demo

Tested on FF and Safari.

INSERT VALUES WHERE NOT EXISTS

More of a comment link for suggested further reading...A really good blog article which benchmarks various ways of accomplishing this task can be found here.

They use a few techniques: "Insert Where Not Exists", "Merge" statement, "Insert Except", and your typical "left join" to see which way is the fastest to accomplish this task.

The example code used for each technique is as follows (straight copy/paste from their page) :

INSERT INTO #table1 (Id, guidd, TimeAdded, ExtraData)
SELECT Id, guidd, TimeAdded, ExtraData
FROM #table2
WHERE NOT EXISTS (Select Id, guidd From #table1 WHERE #table1.id = #table2.id)
-----------------------------------
MERGE #table1 as [Target]
USING  (select Id, guidd, TimeAdded, ExtraData from #table2) as [Source]
(id, guidd, TimeAdded, ExtraData)
    on [Target].id =[Source].id
WHEN NOT MATCHED THEN
    INSERT (id, guidd, TimeAdded, ExtraData)
    VALUES ([Source].id, [Source].guidd, [Source].TimeAdded, [Source].ExtraData);
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT id, guidd, TimeAdded, ExtraData from #table2
EXCEPT
SELECT id, guidd, TimeAdded, ExtraData from #table1
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT #table2.id, #table2.guidd, #table2.TimeAdded, #table2.ExtraData
FROM #table2
LEFT JOIN #table1 on #table1.id = #table2.id
WHERE #table1.id is null

It's a good read for those who are looking for speed! On SQL 2014, the Insert-Except method turned out to be the fastest for 50 million or more records.

How to add values in a variable in Unix shell scripting?

I don't have a unix system under my hands, but try this:

count7=$((${count7} + ${count1}))

Or maybe you have a shell that doesn't support this expression. I think bash does support it, but sh doesn't.

EDIT: There is another syntax, try:

count7=`expr $count7 + $count1`

How can I create 2 separate log files with one log4j config file?

Modify your log4j.properties file accordingly:

log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog

Change the log levels for each logger depending to your needs.

store return json value in input hidden field

Although I have seen the suggested methods used and working, I think that setting the value of an hidden field only using the JSON.stringify breaks the HTML...

Here I'll explain what I mean:

<input type="hidden" value="{"name":"John"}">

As you can see the first double quote after the open chain bracket could be interpreted by some browsers as:

<input type="hidden" value="{" rubbish >

So for a better approach to this I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we shold have something like the following:

> encodeURIComponent(JSON.stringify({"name":"John"}))
> "%7B%22name%22%3A%22John%22%7D"

Now that value can be safely stored in an input hidden type like so:

<input type="hidden" value="%7B%22name%22%3A%22John%22%7D">

or (even better) using the data- attribute of the HTML element manipulated by the script that will consume the data, like so:

<div id="something" data-json="%7B%22name%22%3A%22John%22%7D"></div>

Now to read the data back we can do something like:

> var data = JSON.parse(decodeURIComponent(div.getAttribute("data-json")))
> console.log(data)
> Object {name: "John"}

Calculating time difference between 2 dates in minutes

Try this one:

select * from MyTab T where date_add(T.runTime, INTERVAL 20 MINUTE) < NOW()

NOTE: this should work if you're using MySQL DateTime format. If you're using Unix Timestamp (integer), then it would be even easier:

select * from MyTab T where UNIX_TIMESTAMP() - T.runTime > 20*60

UNIX_TIMESTAMP() function returns you current unix timestamp.

MySQL duplicate entry error even though there is no duplicate entry

As looking on your error #1062 - Duplicate entry '2-S. Name' for key 'PRIMARY' it is saying that you use primary key in your number field that's why it is showing duplicate Error on Number Field. So Remove this primary Key then it inset duplicate also.

Powershell equivalent of bash ampersand (&) for forking/running background processes

You can use PowerShell job cmdlets to achieve your goals.

There are 6 job related cmdlets available in PowerShell.

  • Get-Job
    • Gets Windows PowerShell background jobs that are running in the current session
  • Receive-Job
    • Gets the results of the Windows PowerShell background jobs in the current session
  • Remove-Job
    • Deletes a Windows PowerShell background job
  • Start-Job
    • Starts a Windows PowerShell background job
  • Stop-Job
    • Stops a Windows PowerShell background job
  • Wait-Job
    • Suppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are complete

If interesting about it, you can download the sample How to create background job in PowerShell

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

Mike Goodwin answer is great but it seemed, when I tried it, that it was aimed at MVC5/WebApi 2.1. The dependencies for Microsoft.AspNet.WebApi.Cors didn't play nicely with my MVC4 project.

The simplest way to enable CORS on WebApi with MVC4 was the following.

Note that I have allowed all, I suggest you limit the Origin's to just the clients you want your API to serve. Allowing everything is a security risk.

Web.config:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

BaseApiController.cs:

We do this to allow the OPTIONS http verb

 public class BaseApiController : ApiController
  {
    public HttpResponseMessage Options()
    {
      return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
    }
  }

error LNK2005, already defined?

In the Project’s Settings, add /FORCE:MULTIPLE to the Linker’s Command Line options.

From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."

Spring not autowiring in unit tests with JUnit

You need to add annotations to the Junit class, telling it to use the SpringJunitRunner. The ones you want are:

@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)

This tells Junit to use the test-context.xml file in same directory as your test. This file should be similar to the real context.xml you're using for spring, but pointing to test resources, naturally.

Implicit function declarations in C

C is a very low-level language, so it permits you to create almost any legal object (.o) file that you can conceive of. You should think of C as basically dressed-up assembly language.

In particular, C does not require functions to be declared before they are used. If you call a function without declaring it, the use of the function becomes it's (implicit) declaration. In a simple test I just ran, this is only a warning in the case of built-in library functions like printf (at least in GCC), but for random functions, it will compile just fine.

Of course, when you try to link, and it can't find foo, then you will get an error.

In the case of library functions like printf, some compilers contain built-in declarations for them so they can do some basic type checking, so when the implicit declaration (from the use) doesn't match the built-in declaration, you'll get a warning.

How do I put two increment statements in a C++ 'for' loop?

int main(){
    int i=0;
    int a=0;
    for(i;i<5;i++,a++){
        printf("%d %d\n",a,i);
    } 
}

How to get current foreground activity context in android?

Update 3: There is an official api added for this, please use ActivityLifecycleCallbacks instead.

Track a new remote branch created on GitHub

If you don't have an existing local branch, it is truly as simple as:

git fetch
git checkout <remote-branch-name>

For instance if you fetch and there is a new remote tracking branch called origin/feature/Main_Page, just do this:

git checkout feature/Main_Page

This creates a local branch with the same name as the remote branch, tracking that remote branch. If you have multiple remotes with the same branch name, you can use the less ambiguous:

git checkout -t <remote>/<remote-branch-name>

If you already made the local branch and don't want to delete it, see How do you make an existing Git branch track a remote branch?.

How to get row number in dataframe in Pandas?

df.index[df.LastName == 'Smith']

Or

df.query('LastName == "Smith"').index

Will return all row indices where LastName is Smith

Int64Index([1], dtype='int64')

SQL SELECT everything after a certain character

select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;

Please use http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php for further reference.

Parse query string in JavaScript

Me too! http://jsfiddle.net/drzaus/8EE8k/

(Note: without fancy nested or duplicate checking)

deparam = (function(d,x,params,p,i,j) {
return function (qs) {
    // start bucket; can't cheat by setting it in scope declaration or it overwrites
    params = {};
    // remove preceding non-querystring, correct spaces, and split
    qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
    // march and parse
    for (i = qs.length; i > 0;) {
        p = qs[--i];
        // allow equals in value
        j = p.indexOf('=');
        // what if no val?
        if(j === -1) params[d(p)] = undefined;
        else params[d(p.substring(0,j))] = d(p.substring(j+1));
    }

    return params;
};//--  fn  deparam
})(decodeURIComponent, /\+/g);

And tests:

var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';

var $output = document.getElementById('output');
function output(msg) {
    msg = Array.prototype.slice.call(arguments, 0).join("\n");
    if($output) $output.innerHTML += "\n" + msg + "\n";
    else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
    var q = deparam(test);
    results[msg] = q;
    output(msg, test, JSON.stringify(q), $.param(q));
    output('-------------------');
});

output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
    output(msg, JSON.stringify(result));
    output('-------------------');
});

Results in:

simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"}   <-- it's there, i swear!
qux=quux&baz=&foo=bar        <-- ...see, jQuery found it
-------------------

Convert List<Object> to String[] in Java

You have to loop through the list and fill your String[].

String[] array = new String[lst.size()];
int index = 0;
for (Object value : lst) {
  array[index] = (String) value;
  index++;
}

If the list would be of String values, List then this would be as simple as calling lst.toArray(new String[0]);

CheckBox in RecyclerView keeps on checking different items

As stated above, the checked state of the object should be included within object properties. In some cases you may need also to change the object selection state by clicking on the object itself and let the CheckBox inform about the actual state (either selected or unselected). The checkbox will then use the state of the object at the actual position of the given adapter which is (by default/in most cases) the position of the element in the list.

Check the snippet below, it may be useful.

_x000D_
_x000D_
import android.content.Context;_x000D_
import android.graphics.Bitmap;_x000D_
import android.net.Uri;_x000D_
import android.provider.MediaStore;_x000D_
import android.support.v7.widget.RecyclerView;_x000D_
import android.view.LayoutInflater;_x000D_
import android.view.View;_x000D_
import android.view.ViewGroup;_x000D_
import android.widget.CheckBox;_x000D_
import android.widget.CompoundButton;_x000D_
import android.widget.ImageView;_x000D_
_x000D_
import java.io.File;_x000D_
import java.io.IOException;_x000D_
import java.util.List;_x000D_
_x000D_
public class TakePicImageAdapter extends RecyclerView.Adapter<TakePicImageAdapter.ViewHolder>{_x000D_
    private Context context;_x000D_
    private List<Image> imageList;_x000D_
_x000D_
    public TakePicImageAdapter(Context context, List<Image> imageList) {_x000D_
        this.context = context;_x000D_
        this.imageList = imageList;_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public TakePicImageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {_x000D_
        View view= LayoutInflater.from(context).inflate(R.layout.image_item,parent,false);_x000D_
        return new ViewHolder(view);_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public void onBindViewHolder(final TakePicImageAdapter.ViewHolder holder, final int position) {_x000D_
        File file=new File(imageList.get(position).getPath());_x000D_
        try {_x000D_
            Bitmap bitmap= MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.fromFile(file));_x000D_
            holder.image.setImageBitmap(bitmap_x000D_
            );_x000D_
        } catch (IOException e) {_x000D_
            e.printStackTrace();_x000D_
        }_x000D_
        holder.selectImage.setOnCheckedChangeListener(null);_x000D_
        holder.selectImage.setChecked(imageList.get(position).isSelected());_x000D_
        holder.selectImage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {_x000D_
            @Override_x000D_
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {_x000D_
                holder.selectImage.setChecked(isChecked);_x000D_
                imageList.get(position).setSelected(isChecked);_x000D_
            }_x000D_
        });_x000D_
        holder.image.setOnClickListener(new View.OnClickListener() {_x000D_
            @Override_x000D_
            public void onClick(View v) {_x000D_
                if (imageList.get(position).isSelected())_x000D_
                {_x000D_
                    imageList.get(position).setSelected(false);_x000D_
                    holder.selectImage.setChecked(false);_x000D_
                }else_x000D_
                {_x000D_
                    imageList.get(position).setSelected(true);_x000D_
                    holder.selectImage.setChecked(true);_x000D_
                }_x000D_
            }_x000D_
        });_x000D_
_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public int getItemCount() {_x000D_
        return imageList.size();_x000D_
    }_x000D_
_x000D_
    public class ViewHolder extends RecyclerView.ViewHolder {_x000D_
        public ImageView image;public CheckBox selectImage;_x000D_
        public ViewHolder(View itemView) {_x000D_
            super(itemView);_x000D_
            image=(ImageView)itemView.findViewById(R.id.image);_x000D_
            selectImage=(CheckBox) itemView.findViewById(R.id.ch);_x000D_
_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How can I change the color of pagination dots of UIPageControl?

You can fix it with ease by adding the following code to your appdelegate.m file in your didFinishLaunchingWithOptions method:

UIPageControl *pageControl = [UIPageControl appearance];
pageControl.pageIndicatorTintColor = [UIColor darkGrayColor];
pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
pageControl.backgroundColor = [UIColor whiteColor]

How do you dynamically allocate a matrix?

arr = new int[cols*rows];

If you either don't mind syntax

arr[row * cols + col] = Aij;

or use operator[] overaloading somewhere. This may be more cache-friendly than array of arrays, or may be not, more probably you shouldn't care about it. I just want to point out that a) array of arrays is not only solution, b) some operations are more easier to implement if matrix located in one block of memory. E.g.

for(int i=0;i < rows*cols;++i)
   matrix[i]=someOtherMatrix[i];

one line shorter than

for(int r=0;i < rows;++r)
  for(int c=0;i < cols;++s)
     matrix[r][c]=someOtherMatrix[r][c];

though adding rows to such matrix is more painful

How to quickly drop a user with existing privileges

In commandline, there is a command dropuser available to do drop user from postgres.

$ dropuser someuser

Array.push() and unique items

Push always unique value in array

ab = [
     {"id":"1","val":"value1"},
     {"id":"2","val":"value2"},
     {"id":"3","val":"value3"}
   ];



var clickId = [];
var list = JSON.parse(ab);
$.each(list, function(index, value){
    if(clickId.indexOf(value.id) < 0){
        clickId.push(value.id);
    }
});

How to locate the Path of the current project directory in Java (IDE)?

Two ways

System.getProperty("user.dir");

or this

File currentDirFile = new File(".");
String helper = currentDirFile.getAbsolutePath();
String currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());//this line may need a try-catch block

The idea is to get the current folder with ".", and then fetch the absolute position to it and remove the filename from it, so from something like

/home/shark/eclipse/workspace/project/src/com/package/name/bin/Class.class

when you remove Class.class you'd get

/home/shark/eclipse/workspace/project/src/com/package/name/bin/

which is kinda what you want.

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

public function convertToUtf8($text) {
    if(!$this->html)
        $this->html = cURL('http://'.$this->url, array('timeout' => 15));

    $html = $this->html;
    preg_match('/<meta.*?charset=(|\")(.*?)("|\")/i', $html, $matches);

    $charset = $matches[2];

    if($charset)
        return mb_convert_encoding($text, 'UTF-8', $charset);
    else
        return $text;
}

cURL default options:

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

I tried something like this. It helped me. If found on meta charset info, I'm converting, otherwise doing nothing.

Android: How can I get the current foreground activity (from a service)?

Use this code for API 21 or above. This works and gives better result compared to the other answers, it detects perfectly the foreground process.

if (Build.VERSION.SDK_INT >= 21) {
    String currentApp = null;
    UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
    long time = System.currentTimeMillis();
    List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
    if (applist != null && applist.size() > 0) {
        SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
        for (UsageStats usageStats : applist) {
            mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);

        }
        if (mySortedMap != null && !mySortedMap.isEmpty()) {
            currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
        }
    }

How to count check-boxes using jQuery?

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;

Open fancybox from function

function myfunction(){
    $('.classname').fancybox().trigger('click'); 
}

It works for me..

UTF-8 encoding problem in Spring MVC

I've figured it out, you can add to request mapping produces = "text/plain;charset=UTF-8"

@RequestMapping(value = "/rest/create/document", produces = "text/plain;charset=UTF-8")
@ResponseBody
public void create(Document document, HttpServletRespone respone) throws UnsupportedEncodingException {

    Document newDocument = DocumentService.create(Document);

    return jsonSerializer.serialize(newDocument);
}

see this blog post for more details on the solution

SQL INSERT INTO from multiple tables

I would suggest instead of creating a new table, you just use a view that combines the two tables, this way if any of the data in table 1 or table 2 changes, you don't need to update the third table:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t1.ID, t2.Number
    FROM    Table1 t1
            INNER JOIN Table2 t2
                ON t1.ID = t2.ID;

If you could have records in one table, and not in the other, then you would need to use a full join:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, ID = ISNULL(t1.ID, t2.ID), t2.Number
    FROM    Table1 t1
            FULL JOIN Table2 t2
                ON t1.ID = t2.ID;

If you know all records will be in table 1 and only some in table 2, then you should use a LEFT JOIN:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t1.ID, t2.Number
    FROM    Table1 t1
            LEFT JOIN Table2 t2
                ON t1.ID = t2.ID;

If you know all records will be in table 2 and only some in table 2 then you could use a RIGHT JOIN

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t2.ID, t2.Number
    FROM    Table1 t1
            RIGHT JOIN Table2 t2
                ON t1.ID = t2.ID;

Or just reverse the order of the tables and use a LEFT JOIN (I find this more logical than a right join but it is personal preference):

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t2.ID, t2.Number
    FROM    Table2 t2
            LEFT JOIN Table1 t1
                ON t1.ID = t2.ID;

Correct format specifier for double in printf

"%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it'll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard -- the l is specified as having no effect if followed by the f conversion specifier (among others).

Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it's worth, for a long double, you use %Lf for either printf or scanf).


1. C99, §6.5.2.2/6: "If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions." In C++ the wording is somewhat different (e.g., it doesn't use the word "prototype") but the effect is the same: all the variadic parameters undergo default promotions before they're received by the function.

remove legend title in ggplot

This works too and also demonstrates how to change the legend title:

ggplot(df, aes(x, y, colour=g)) +
  geom_line(stat="identity") + 
  theme(legend.position="bottom") +
  scale_color_discrete(name="")

How to deal with SQL column names that look like SQL keywords?

Your question seems to be well answered here, but I just want to add one more comment to this subject.

Those designing the database should be well aware of the reserved keywords and avoid using them. If you discover someone using it, inform them about it (in a polite way). The keyword here is reserved word.

More information:

"Reserved keywords should not be used as object names. Databases upgraded from earlier versions of SQL Server may contain identifiers that include words not reserved in the earlier version, but that are reserved words for the current version of SQL Server. You can refer to the object by using delimited identifiers until the name can be changed." http://msdn.microsoft.com/en-us/library/ms176027.aspx

and

"If your database does contain names that match reserved keywords, you must use delimited identifiers when you refer to those objects. For more information, see Identifiers (DMX)." http://msdn.microsoft.com/en-us/library/ms132178.aspx

Can I find events bound on an element with jQuery?

When I pass a little complex DOM query to $._data like this: $._data($('#outerWrap .innerWrap ul li:last a'), 'events') it throws undefined in the browser console.

So I had to use $._data on the parent div: $._data($('#outerWrap')[0], 'events') to see the events for the a tags. Here is a JSFiddle for the same: http://jsfiddle.net/giri_jeedigunta/MLcpT/4/

Difference between java HH:mm and hh:mm on SimpleDateFormat

Please take a look here

HH is hour in a day (starting from 0 to 23)

hh are hours in am/pm format

kk is hour in day (starting from 1 to 24)

mm is minute in hour

ss are the seconds in a minute

How to check if a date is in a given range?

Converting them to timestamps is the way to go alright, using strtotime, e.g.

$start_date = '2009-06-17';

$end_date = '2009-09-05';

$date_from_user = '2009-08-28';

check_in_range($start_date, $end_date, $date_from_user);


function check_in_range($start_date, $end_date, $date_from_user)
{
  // Convert to timestamp
  $start_ts = strtotime($start_date);
  $end_ts = strtotime($end_date);
  $user_ts = strtotime($date_from_user);

  // Check that user date is between start & end
  return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}

How to set default Checked in checkbox ReactJS?

If the checkbox is created only with React.createElement then the property defaultChecked is used.

React.createElement('input',{type: 'checkbox', defaultChecked: false});

Credit to @nash_ag

How to update/refresh specific item in RecyclerView

I think I have an Idea on how to deal with this. Updating is the same as deleting and replacing at the exact position. So I first remove the item from that position using the code below:

public void removeItem(int position){
    mData.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, mData.size());
}

and then I would add the item at that particular position as shown below:

public void addItem(int position, Landscape landscape){
    mData.add(position, landscape);
    notifyItemInserted(position);
    notifyItemRangeChanged(position, mData.size());
}

I'm trying to implement this now. I would give you a feedback when I'm through!

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

Another option is to use

$_SERVER['REQUEST_METHOD'] == 'POST'

How to check if NSString begins with a certain character

Another approach to do it..

May it help someone...

if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
  //starts with http
}

Bat file to run a .exe at the command prompt

it is very simple code for executing notepad bellow code type into a notepad and save to extension .bat Exapmle:notepad.bat

start "c:\windows\system32" notepad.exe   

(above code "c:\windows\system32" is path where you kept your .exe program and notepad.exe is your .exe program file file)

enjoy!

How do I verify that a string only contains letters, numbers, underscores and dashes?

Regular expression can be very flexible.

import re;
re.fullmatch("^[\w-]+$", target_string) # fullmatch looks also workable for python 3.4

\w: Only [a-zA-Z0-9_]

So you need to add - char for justify hyphen char.

+: Match one or more repetitions of the preceding char. I guess you don't accept blank input. But if you do, change to * .

^: Matches the start of the string.

$: Matches the end of the string.

You need these two special characters since you need to avoid the following case. The unwanted chars like & here might appear between the matched pattern.

&&&PATTERN&&PATTERN

Safe String to BigDecimal conversion

I needed a solution to convert a String to a BigDecimal without knowing the locale and being locale-independent. I couldn't find any standard solution for this problem so i wrote my own helper method. May be it helps anybody else too:

Update: Warning! This helper method works only for decimal numbers, so numbers which always have a decimal point! Otherwise the helper method could deliver a wrong result for numbers between 1000 and 999999 (plus/minus). Thanks to bezmax for his great input!

static final String EMPTY = "";
static final String POINT = '.';
static final String COMMA = ',';
static final String POINT_AS_STRING = ".";
static final String COMMA_AS_STRING = ",";

/**
     * Converts a String to a BigDecimal.
     *     if there is more than 1 '.', the points are interpreted as thousand-separator and will be removed for conversion
     *     if there is more than 1 ',', the commas are interpreted as thousand-separator and will be removed for conversion
     *  the last '.' or ',' will be interpreted as the separator for the decimal places
     *  () or - in front or in the end will be interpreted as negative number
     *
     * @param value
     * @return The BigDecimal expression of the given string
     */
    public static BigDecimal toBigDecimal(final String value) {
        if (value != null){
            boolean negativeNumber = false;

            if (value.containts("(") && value.contains(")"))
               negativeNumber = true;
            if (value.endsWith("-") || value.startsWith("-"))
               negativeNumber = true;

            String parsedValue = value.replaceAll("[^0-9\\,\\.]", EMPTY);

            if (negativeNumber)
               parsedValue = "-" + parsedValue;

            int lastPointPosition = parsedValue.lastIndexOf(POINT);
            int lastCommaPosition = parsedValue.lastIndexOf(COMMA);

            //handle '1423' case, just a simple number
            if (lastPointPosition == -1 && lastCommaPosition == -1)
                return new BigDecimal(parsedValue);
            //handle '45.3' and '4.550.000' case, only points are in the given String
            if (lastPointPosition > -1 && lastCommaPosition == -1){
                int firstPointPosition = parsedValue.indexOf(POINT);
                if (firstPointPosition != lastPointPosition)
                    return new BigDecimal(parsedValue.replace(POINT_AS_STRING, EMPTY));
                else
                    return new BigDecimal(parsedValue);
            }
            //handle '45,3' and '4,550,000' case, only commas are in the given String
            if (lastPointPosition == -1 && lastCommaPosition > -1){
                int firstCommaPosition = parsedValue.indexOf(COMMA);
                if (firstCommaPosition != lastCommaPosition)
                    return new BigDecimal(parsedValue.replace(COMMA_AS_STRING, EMPTY));
                else
                    return new BigDecimal(parsedValue.replace(COMMA, POINT));
            }
            //handle '2.345,04' case, points are in front of commas
            if (lastPointPosition < lastCommaPosition){
                parsedValue = parsedValue.replace(POINT_AS_STRING, EMPTY);
                return new BigDecimal(parsedValue.replace(COMMA, POINT));
            }
            //handle '2,345.04' case, commas are in front of points
            if (lastCommaPosition < lastPointPosition){
                parsedValue = parsedValue.replace(COMMA_AS_STRING, EMPTY);
                return new BigDecimal(parsedValue);
            }
            throw new NumberFormatException("Unexpected number format. Cannot convert '" + value + "' to BigDecimal.");
        }
        return null;
    }

Of course i've tested the method:

@Test(dataProvider = "testBigDecimals")
    public void toBigDecimal_defaultLocaleTest(String stringValue, BigDecimal bigDecimalValue){
        BigDecimal convertedBigDecimal = DecimalHelper.toBigDecimal(stringValue);
        Assert.assertEquals(convertedBigDecimal, bigDecimalValue);
    }
    @DataProvider(name = "testBigDecimals")
    public static Object[][] bigDecimalConvertionTestValues() {
        return new Object[][] {
                {"5", new BigDecimal(5)},
                {"5,3", new BigDecimal("5.3")},
                {"5.3", new BigDecimal("5.3")},
                {"5.000,3", new BigDecimal("5000.3")},
                {"5.000.000,3", new BigDecimal("5000000.3")},
                {"5.000.000", new BigDecimal("5000000")},
                {"5,000.3", new BigDecimal("5000.3")},
                {"5,000,000.3", new BigDecimal("5000000.3")},
                {"5,000,000", new BigDecimal("5000000")},
                {"+5", new BigDecimal("5")},
                {"+5,3", new BigDecimal("5.3")},
                {"+5.3", new BigDecimal("5.3")},
                {"+5.000,3", new BigDecimal("5000.3")},
                {"+5.000.000,3", new BigDecimal("5000000.3")},
                {"+5.000.000", new BigDecimal("5000000")},
                {"+5,000.3", new BigDecimal("5000.3")},
                {"+5,000,000.3", new BigDecimal("5000000.3")},
                {"+5,000,000", new BigDecimal("5000000")},
                {"-5", new BigDecimal("-5")},
                {"-5,3", new BigDecimal("-5.3")},
                {"-5.3", new BigDecimal("-5.3")},
                {"-5.000,3", new BigDecimal("-5000.3")},
                {"-5.000.000,3", new BigDecimal("-5000000.3")},
                {"-5.000.000", new BigDecimal("-5000000")},
                {"-5,000.3", new BigDecimal("-5000.3")},
                {"-5,000,000.3", new BigDecimal("-5000000.3")},
                {"-5,000,000", new BigDecimal("-5000000")},
                {null, null}
        };
    }

Change status bar text color to light in iOS 9 with Objective-C

First set

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

Go to your AppDelegate, find itsdidFinishLaunchingWithOptions method and do:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

}

and then set View controller-based status bar appearance equal to NO in plist.

How to send password securely over HTTP?

You can use SRP to use secure passwords over an insecure channel. The advantage is that even if an attacker sniffs the traffic, or compromises the server, they can't use the passwords on a different server. https://github.com/alax/jsrp is a javascript library that supports secure passwords over HTTP in the browser, or server side (via node).

SQL SELECT from multiple tables

SELECT p.pid, p.cid, p.pname, c1.name1, c2.name2
FROM product p
LEFT JOIN customer1 c1 ON p.cid = c1.cid
LEFT JOIN customer2 c2 ON p.cid = c2.cid

How to compare LocalDate instances Java 8

I believe this snippet will also be helpful in a situation where the dates comparison spans more than two entries.

static final int COMPARE_EARLIEST = 0;

static final int COMPARE_MOST_RECENT = 1;


public LocalDate getTargetDate(List<LocalDate> datesList, int comparatorType) { 
   LocalDate refDate = null;
   switch(comparatorType)
   {
       case COMPARE_EARLIEST:         
       //returns the most earliest of the date entries
          refDate = (LocalDate) datesList.stream().min(Comparator.comparing(item -> 
                      item.toDateTimeAtCurrentTime())).get();
          break;

       case COMPARE_MOST_RECENT:
          //returns the most recent of the date entries 
          refDate = (LocalDate) datesList.stream().max(Comparator.comparing(item -> 
                    item.toDateTimeAtCurrentTime())).get();
          break;
   }

   return refDate;
}

Get Android shared preferences value in activity/normal class

I tried this code, to retrieve shared preferences from an activity, and could not get it to work:

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences.getAll();
    Log.d("AddNewRecord", "getAll: " + sharedPreferences.getAll());
    Log.d("AddNewRecord", "Size: " + sharedPreferences.getAll().size());

Every time I tried, my preferences returned 0, even though I have 14 preferences saved by the preference activity. I finally found the answer. I added this to the preferences in the onCreate section.

getPreferenceManager().setSharedPreferencesName("defaultPreferences");

After I added this statement, my saved preferences returned as expected. I hope that this helps someone else who may experience the same issue that I did.

Sprintf equivalent in Java

You can do a printf to anything that is an OutputStream with a PrintStream. Somehow like this, printing into a string stream:

PrintStream ps = new PrintStream(baos);
ps.printf("there is a %s from %d %s", "hello", 3, "friends");
System.out.println(baos.toString());
baos.reset(); //need reset to write new string
ps.printf("there is a %s from %d %s", "flip", 5, "haters");
System.out.println(baos.toString());
baos.reset();

The string stream can be created like this ByteArrayOutputStream:

ByteArrayOutputStream baos = new ByteArrayOutputStream();

What does "wrong number of arguments (1 for 0)" mean in Ruby?

You passed an argument to a function which didn't take any. For example:

def takes_no_arguments
end

takes_no_arguments 1
# ArgumentError: wrong number of arguments (1 for 0)

How to remove unused imports from Eclipse

Better way is just to add "save action" so when you save the project it will clear the unused import's and format the code as well if you like .

Go to Window > Preferences > Java > Editor > Save Actions

and pick what ever you want .

Using SED with wildcard

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt

Remove rows not .isin('X')

You can use the DataFrame.select method:

In [1]: df = pd.DataFrame([[1,2],[3,4]], index=['A','B'])

In [2]: df
Out[2]: 
   0  1
A  1  2
B  3  4

In [3]: L = ['A']

In [4]: df.select(lambda x: x in L)
Out[4]: 
   0  1
A  1  2

How to play an android notification sound

I had pretty much the same question. After some research, I think that if you want to play the default system "notification sound", you pretty much have to display a notification and tell it to use the default sound. And there's something to be said for the argument in some of the other answers that if you're playing a notification sound, you should be presenting some notification message as well.

However, a little tweaking of the notification API and you can get close to what you want. You can display a blank notification and then remove it automatically after a few seconds. I think this will work for me; maybe it will work for you.

I've created a set of convenience methods in com.globalmentor.android.app.Notifications.java which allow you create a notification sound like this:

Notifications.notify(this);

The LED will also flash and, if you have vibrate permission, a vibration will occur. Yes, a notification icon will appear in the notification bar but will disappear after a few seconds.

At this point you may realize that, since the notification will go away anyway, you might as well have a scrolling ticker message in the notification bar; you can do that like this:

Notifications.notify(this, 5000, "This text will go away after five seconds.");

There are many other convenience methods in this class. You can download the whole library from its Subversion repository and build it with Maven. It depends on the globalmentor-core library, which can also be built and installed with Maven.

Swift - How to convert String to Double

I find more readable to add an extension to String as follow:

extension String {
    var doubleValue: Double {
        return (self as NSString).doubleValue
    }
}

and then you just could write your code:

myDouble = myString.doubleValue

Split string into list in jinja?

You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.

For your purpose, it would make most sense to define a custom filter, so you could for example do the following:

The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{  splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{  splitpart(1) }}

The filter function could then look like this:

def splitpart (value, index, char = ','):
    return value.split(char)[index]

An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

If your problem is like the following while using Google Chrome:

[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]

Then create a batch file by following these steps:

Open notepad in Desktop.

  1. Just copy and paste the followings in your currently opened notepad file:

start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit

  1. Note: In the previous line, Replace the full absolute address with your location of chrome installation. [To find it...Right click your short cut of chrome.exe link or icon and Click on Properties and copy-paste the target link][Remember : start to files in one line, & exit in another line by pressing enter]
  2. Save the file as fileName.bat [Very important: .bat]
  3. If you want to change the file later then right-click on the .bat file and click on edit. After modifying, save the file.

This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.

Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.

ProgressDialog in AsyncTask

Don't know what parameter should I use?

A lot of Developers including have hard time at the beginning writing an AsyncTask because of the ambiguity of the parameters. The big reason is we try to memorize the parameters used in the AsyncTask. The key is Don't memorize. If you can visualize what your task really needs to do then writing the AsyncTask with the correct signature would be a piece of cake.

What is an AsyncTask?

AsyncTask are background task which run in the background thread. It takes an Input, performs Progress and gives Output.

ie AsyncTask<Input,Progress,Output>

Just figure out what your Input, Progress and Output are and you will be good to go.

For example

enter image description here

How does doInbackground() changes with AsyncTask parameters?

enter image description here

How doInBackground() and onPostExecute(),onProgressUpdate() are related?

enter image description here

How can You write this in a code?

 DownloadTask extends AsyncTask<String,Integer,String>{

    @Override
    public void onPreExecute(){
    }

    @Override
    public String doInbackGround(String... params)
    {
         // Download code
         int downloadPerc = // calculate that
         publish(downloadPerc);

         return "Download Success";
    }

    @Override
    public void onPostExecute(String result)
    {
         super.onPostExecute(result);
    }

    @Override
    public void onProgressUpdate(Integer... params)
    {
         // show in spinner, access UI elements
    }

}

How will you run this Task in Your Activity?

new DownLoadTask().execute("Paradise.mp3");

How to convert from int to string in objective c: example code

If you just need an int to a string as you suggest, I've found the easiest way is to do as below:

[NSString stringWithFormat:@"%d",numberYouAreTryingToConvert]

Get the Id of current table row with Jquery

Your code would be more like so:

$('tr input[type=button]').click(function(){
    id = $(this).closest('tr').attr('id');
});

jquery.ajax Access-Control-Allow-Origin

At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON AJAX method because it easily returns JSONP using the ?callback=? without having any issues with CORS.

data ='USER=<?echo trim($USER)?>' +
         '&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();

        //Call the REST program/method returns: JSONP 
        $.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
        .done(function( json ) {        

              //  loading...
                if ($.trim(json.ERROR) != '') {
                    $("#error-msg").text(message).show();
                }
                else{
                    $(".error").hide();
                    $("#jsonp").text(json.whatever);

                }

        })  
        .fail(function( jqXHR, textStatus, error ) {
        var err = textStatus + ", " + error;
        alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
        });     

How to change navigation bar color in iOS 7 or 6?

I'm using following code (in C#) to change the color of the NavigationBar:

NavigationController.NavigationBar.SetBackgroundImage (new UIImage (), UIBarMetrics.Default);
NavigationController.NavigationBar.SetBackgroundImage (new UIImage (), UIBarMetrics.LandscapePhone);
NavigationController.NavigationBar.BackgroundColor = UIColor.Green;

The trick is that you need to get rid of the default background image and then the color will appear.

How to change users in TortoiseSVN

Replace the line in htpasswd file:

Go to: http://www.htaccesstools.com/htpasswd-generator-windows/

(If the link is expired, search another generator from google.com.)

Enter your username and password. The site will generate an encrypted line. Copy that line and replace it with the previous line in the file "repo/htpasswd".

You might also need to Clear the 'Authentication data' from TortoiseSVN ? Settings ? Saved Data.

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

Check in Deployment Assembly,

I have the same error, when i generate the war file with the "maven clean install" way and deploy manualy, it works fine, but when i use the runtime enviroment (eclipse) the problems come.

The solution for me (for eclipse IDE) go to: "proyect properties" --> "Deployment Assembly" --> "Add" --> "the jar you need", in my case java "build path entries". Maybe can help a litle!

What is the best way to modify a list in a 'foreach' loop?

You can't change the enumerable collection while it is being enumerated, so you will have to make your changes before or after enumerating.

The for loop is a nice alternative, but if your IEnumerable collection does not implement ICollection, it is not possible.

Either:

1) Copy collection first. Enumerate the copied collection and change the original collection during the enumeration. (@tvanfosson)

or

2) Keep a list of changes and commit them after the enumeration.

How to upload (FTP) files to server in a bash script?

No need to complicate stuff - this should work:

#/bin/bash
echo "
 verbose
 open ftp.mydomain.net
 user myusername mypassword
 ascii
 put textfile1
 put textfile2
 bin
 put binaryfile1
 put binaryfile2
 bye
" | ftp -n > ftp_$$.log

or you can use mput if you have many files ...

Remove all stylings (border, glow) from textarea

The glow effect is most-likely controlled by box-shadow. In addition to adding what Pavel said, you can add the box-shadow property for the different browser engines.

textarea {
    border: none;
    overflow: auto;
    outline: none;

    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;

    resize: none; /*remove the resize handle on the bottom right*/
}

You may also try adding !important to prioritize this CSS.

Remove json element

I recommend splice method to remove an object from JSON objects array.

jQuery(json).each(function (index){
        if(json[index].FirstName == "Test1"){
            json.splice(index,1); // This will remove the object that first name equals to Test1
            return false; // This will stop the execution of jQuery each loop.
        }
});

I use this because when I use delete method, I get null object after I do JSON.stringify(json)

Django, creating a custom 500/404 error page

As one single line (for 404 generic page):

from django.shortcuts import render_to_response
from django.template import RequestContext

return render_to_response('error/404.html', {'exception': ex},
                                      context_instance=RequestContext(request), status=404)

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

Add those source code to your Java file as below:

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());

Difference between "\n" and Environment.NewLine

Environment.NewLine will give "\r\n" when run on Windows. If you are generating strings for Unix based environments, you don't want the "\r".

How to drop all tables from the database with manage.py CLI in Django?

As far as I know there is no management command to drop all tables. If you don't mind hacking Python you can write your own custom command to do that. You may find the sqlclear option interesting. Documentation says that ./manage.py sqlclear Prints the DROP TABLE SQL statements for the given app name(s).

Update: Shamelessly appropriating @Mike DeSimone's comment below this answer to give a complete answer.

./manage.py sqlclear | ./manage.py dbshell

As of django 1.9 it's now ./manage.py sqlflush

Response Buffer Limit Exceeded

Thank you so much! <%Response.Buffer = False%> worked like a charm! My asp/HTML table that was returning a blank page at about 2700 records. The following debugging lines helped expose the buffering problem: I replace the Do While loop as follows and played with my limit numbers to see what was happening:

Replace

Do While not rs.EOF

'etc .... your block of code that writes the table rows

rs.moveNext

Loop

with

Do While reccount < 2500

if rs.EOF then recount = 2501

'etc .... your block of code that writes the table rows

rs.moveNext

Loop

response.write "recount = " & recount

raise or lower the 2500 and 2501 to see if it is a buffer problem. for my record set, I could see that the blank page return, blank table, was happening at about 2700 records, good luck to all and thank you again for solving this problem! Such a simple great solution!

JSON Array iteration in Android/Java

On Arrays, look for:

JSONArray menuitemArray = popupObject.getJSONArray("menuitem"); 

putting a php variable in a HTML form value

You can do it like this,

<input type="text" name="name" value="<?php echo $name;?>" />

But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.

<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />

time data does not match format

You have the month and day swapped:

'%m/%d/%Y %H:%M:%S.%f'

28 will never fit in the range for the %m month parameter otherwise.

With %m and %d in the correct order parsing works:

>>> from datetime import datetime
>>> datetime.strptime('07/28/2014 18:54:55.099000', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

You don't need to add '000'; %f can parse shorter numbers correctly:

>>> datetime.strptime('07/28/2014 18:54:55.099', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

how to get the 30 days before date from Todays Date

Try adding this to your where clause:

dateadd(day, -30, getdate())

How to print a debug log?

error_log(print_r($variable, TRUE)); 

might be useful

How can I trim leading and trailing white space?

To manipulate the white space, use str_trim() in the stringr package. The package has manual dated Feb 15, 2013 and is in CRAN. The function can also handle string vectors.

install.packages("stringr", dependencies=TRUE)
require(stringr)
example(str_trim)
d4$clean2<-str_trim(d4$V2)

(Credit goes to commenter: R. Cotton)

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

Set an environment variable in git bash

If you want to set environment variables permanently in Git-Bash, you have two options:

  1. Set a regular Windows environment variable. Git-bash gets all existing Windows environment variables at startupp.

  2. Set up env variables in .bash_profile file.

.bash_profile is by default located in a user home folder, like C:\users\userName\git-home\.bash_profile. You can change the path to the bash home folder by setting HOME Windows environment variable.

.bash_profile file uses the regular Bash syntax and commands

# Export a variable in .bash_profile
export DIR=c:\dir
# Nix path style works too
export DIR=/c/dir

# And don't forget to add quotes if a variable contains whitespaces
export ANOTHER_DIR="c:\some dir"

Read more information about Bash configurations files.

Disable and later enable all table indexes in Oracle

From here: http://forums.oracle.com/forums/thread.jspa?messageID=2354075

alter session set skip_unusable_indexes = true;

alter index your_index unusable;

do import...

alter index your_index rebuild [online];

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

In my case, It seems like I wasnt really able to kill the mysql process, when I run

sudo service mysql stop
ps -ef | grep mysql

The mysql process was always there, it looks like it was blocking the socket file and new mysql process wasnt able to create it itself.

so this helped

cd /var/run
sudo cp mysqld/ mysqld.bc -rf
sudo chown mysql:mysql mysqld.bc/
sudo service mysql stop
sudo cp mysqld.bc/ mysqld -rf
sudo chown mysql:mysql mysqld -R
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &

Now Im able to log in database using

mysql -u root

Then to update root password:

UPDATE user SET authentication_string=password('YOURPASSWORDHERE') WHERE user='root';
FLUSH PRIVILEGES;

PS: I had trouble updating root passwod, seems like problem with "auth_socket" plugin, so I had to create new user with full privileges

insert into user set `Host` = "localhost", `User` = "super", `plugin` = "mysql_native_password", `authentication_string` = NULL, `password_expired` = "N", `password_lifetime` = NULL, `account_locked` = "N", `Select_priv` = "Y",
`Insert_priv` = "Y", `Update_priv` = "Y", `Delete_priv` = "Y", `Create_priv` = "Y", `Drop_priv` = "Y", `Reload_priv` = "Y", `Shutdown_priv` = "Y", `Process_priv` = "Y", `File_priv` = "Y",
`Grant_priv` = "Y",  `References_priv` = "Y", `Index_priv` = "Y", `Alter_priv` = "Y", `Show_db_priv` = "Y", `Super_priv` = "Y", `Create_tmp_table_priv` = "Y", `Lock_tables_priv` = "Y",
`Execute_priv` = "Y", `Repl_slave_priv` = "Y",  `Repl_client_priv` = "Y",  `Create_view_priv` = "Y", `Show_view_priv` = "Y", `Create_routine_priv` = "Y", `Alter_routine_priv` = "Y",
`Create_user_priv` = "Y",  `Event_priv` = "Y", `Trigger_priv` = "Y", `Create_tablespace_priv` = "Y";

This creates user "super" with no password and then you can connect with mysql -u super

How can I debug my JavaScript code?

I'm using Venkman, a JavaScript debugger for XUL applications.

select and echo a single field from mysql db using PHP

Read the manual, it covers it very well: http://php.net/manual/en/function.mysql-query.php

Usually you do something like this:

while ($row = mysql_fetch_assoc($result)) {
  echo $row['firstname'];
  echo $row['lastname'];
  echo $row['address'];
  echo $row['age'];
}

Assign static IP to Docker container

You can access other containers' service by their name(ping apachewill get the ip or curl http://apache would access the http service) And this can be a alternative of a static ip.

jQuery "blinking highlight" effect on div?

I couldn't find exactly what I was looking for so wrote something as basic as I could make it. The highlighted class could just be a background color.

var blinking = false; // global scope

function start_blinking() {
    blinking = true;
    blink();
}

function stop_blinking() {
    blinking = false;
}

function blink(x=0) {
    $("#element").removeClass("highlighted"); // default to not highlighted to account for the extra iteration after stopping

    if (blinking) {
        if (x%2 == 0) $("#element").addClass("highlighted"); // highlight on even numbers of x
        setTimeout(function(){blink(++x)},500); // increment x and recurse
    }
}

library not found for -lPods

In my case nr 4 of the FAQ in this link helped out: https://github.com/CocoaPods/CocoaPods/wiki/Creating-a-project-that-uses-CocoaPods

There are a couple of additional things you can try out if the problem persists.

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

This might be a bug of built-in ImagePickerController. My code is working, but occasionally crashes on iPhone 6 Plus.

I've tried all solutions suggested by other answers but there were no luck. Problem finally solved after switching to JPSImagePickerController.

When is JavaScript synchronous?

Is synchronous on all cases.

Example of blocking thread with Promises:

  const test = () => new Promise((result, reject) => {
    const time = new Date().getTime() + (3 * 1000);

    console.info('Test start...');

    while (new Date().getTime() < time) {
      // Waiting...
    }

    console.info('Test finish...');
  });

  test()
    .then(() => console.info('Then'))
    .finally(() => console.info('Finally'));

  console.info('Finish!');

The output will be:

Test start...
Test finish...
Finish!

Git: How configure KDiff3 as merge tool and diff tool

I needed to add the command line parameters or KDiff3 would only open without files and prompt me for base, local and remote. I used the version supplied with TortoiseHg.

Additionally, I needed to resort to the good old DOS 8.3 file names.

[merge]
    tool = kdiff3

[mergetool "kdiff3"]
    cmd = /c/Progra~1/TortoiseHg/lib/kdiff3.exe $BASE $LOCAL $REMOTE -o $MERGED

However, it works correctly now.

C/C++ check if one bit is set in, i.e. int variable

The precedent answers show you how to handle bit checks, but more often then not, it is all about flags encoded in an integer, which is not well defined in any of the precedent cases.

In a typical scenario, flags are defined as integers themselves, with a bit to 1 for the specific bit it refers to. In the example hereafter, you can check if the integer has ANY flag from a list of flags (multiple error flags concatenated) or if EVERY flag is in the integer (multiple success flags concatenated).

Following an example of how to handle flags in an integer.

Live example available here: https://rextester.com/XIKE82408

//g++  7.4.0

#include <iostream>
#include <stdint.h>

inline bool any_flag_present(unsigned int value, unsigned int flags) {
    return bool(value & flags);
}

inline bool all_flags_present(unsigned int value, unsigned int flags) {
    return (value & flags) == flags;
}

enum: unsigned int {
    ERROR_1 = 1U,
    ERROR_2 = 2U, // or 0b10
    ERROR_3 = 4U, // or 0b100
    SUCCESS_1 = 8U,
    SUCCESS_2 = 16U,
    OTHER_FLAG = 32U,
};

int main(void)
{
    unsigned int value = 0b101011; // ERROR_1, ERROR_2, SUCCESS_1, OTHER_FLAG
    unsigned int all_error_flags = ERROR_1 | ERROR_2 | ERROR_3;
    unsigned int all_success_flags = SUCCESS_1 | SUCCESS_2;
    
    std::cout << "Was there at least one error: " << any_flag_present(value, all_error_flags) << std::endl;
    std::cout << "Are all success flags enabled: " << all_flags_present(value, all_success_flags) << std::endl;
    std::cout << "Is the other flag enabled with eror 1: " << all_flags_present(value, ERROR_1 | OTHER_FLAG) << std::endl;
    return 0;
}

How to get an array of specific "key" in multidimensional array without looping

You can also use array_reduce() if you prefer a more functional approach

For instance:

$userNames = array_reduce($users, function ($carry, $user) {
    array_push($carry, $user['name']);
    return $carry;
}, []);

Or if you like to be fancy,

$userNames = [];
array_map(function ($user) use (&$userNames){
    $userNames[]=$user['name'];
}, $users);

This and all the methods above do loop behind the scenes though ;)

Set an empty DateTime variable

Option 1: Use a nullable DateTime?

Option 2: Use DateTime.MinValue

Personally, I'd prefer option 1.

LINQ Joining in C# with multiple conditions

If you need not equal object condition use cross join sequences:

var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]

Java Web Service client basic authentication

The easiest option to get this working is to include Username and Password under of request. See sample below.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:typ="http://xml.demo.com/types" xmlns:ser="http://xml.demo.com/location/services"
    xmlns:typ1="http://xml.demo.com/location/types">
    <soapenv:Header>
        <typ:requestHeader>
            <typ:timestamp>?</typ:timestamp>
            <typ:sourceSystemId>TEST</typ:sourceSystemId>
            <!--Optional: -->
            <typ:sourceSystemUserId>1</typ:sourceSystemUserId>
            <typ:sourceServerId>1</typ:sourceServerId>
            <typ:trackingId>HYD-12345</typ:trackingId>
        </typ:requestHeader>

        <wsse:Security soapenv:mustUnderstand="1"
            xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <wsse:UsernameToken wsu:Id="UsernameToken-emmprepaid"
                xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
                <wsse:Username>your-username</wsse:Username>
                <wsse:Password
                    Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">your-password</wsse:Password>
            </wsse:UsernameToken>
        </wsse:Security>
    </soapenv:Header>
    <soapenv:Body>
        <ser:getLocation>
            <!--Optional: -->
            <ser:GetLocation>
                <typ1:locationID>HYD-GoldenTulipsEstates</typ1:locationID>
            </ser:GetLocation>
        </ser:getLocation>
    </soapenv:Body>
</soapenv:Envelope>

Best way to check if MySQL results returned in PHP?

mysqli_fetch_array() returns NULL if there is no row.

In procedural style:

if ( ! $row = mysqli_fetch_array( $result ) ) {
    ... no result ...
}
else {
    ... get the first result in $row ...
}

In Object oriented style:

if ( ! $row = $result->fetch_array() ) {
    ...
}
else {
    ... get the first result in $row ...
}

T-SQL XOR Operator

MS SQL only short form (since SQL Server 2012):

1=iif( a=b ,1,0)^iif( c=d ,1,0)

When should I use GC.SuppressFinalize()?

That method must be called on the Dispose method of objects that implements the IDisposable, in this way the GC wouldn't call the finalizer another time if someones calls the Dispose method.

See: GC.SuppressFinalize(Object) Method - Microsoft Docs

simple vba code gives me run time error 91 object variable or with block not set

You need Set with objects:

 Set rng = Sheet8.Range("A12")

Sheet8 is fine.

 Sheet1.[a1]

Install psycopg2 on Ubuntu

This worked for me:

pip install psycopg2-binary

OTP (token) should be automatically read from the message

**activity_main.xml**

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mukundwn.broadcastreceiver.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>



**MainActivity.java**
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private BroadcastReceiver broadcastReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        broadcastReceiver =new MyBroadcastReceiver();
    }

@Override
    protected void onStart()
{
    super.onStart();
    IntentFilter intentFilter=new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(broadcastReceiver,intentFilter);
}
@Override
    protected void onStop()
{
    super.onStop();
    unregisterReceiver(broadcastReceiver);
}

}


**MyBroadcastReceiver.java**

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * Created by mukundwn on 12/02/18.
 */

public class MyBroadcastReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"hello received an sms",Toast.LENGTH_SHORT).show();
    }
}


**Manifest.xml**

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mukundwn.broadcastreceiver">

    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".MyBroadcastReceiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVE"></action>
        </intent-filter>
        </receiver>
    </application>

</manifest>

Store a closure as a variable in Swift

Depends on your needs there is an addition to accepted answer. You may also implement it like this:

var parseCompletion: (() ->Void)!

and later in some func assign to it

func someHavyFunc(completion: @escaping () -> Void){
    self.parseCompletion = completion
}

and in some second function use it

func someSecondFunc(){
    if let completion = self.parseCompletion {
        completion()
    }
}

note that @escaping parameter is a mandatory here

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

Update user table in mysql DB. And set some password where it is blank, i was using root user so i set password for root user.

update mysql.user set password = PASSWORD('123456') where password = '';
flush privileges;

And then again tried from ATG CIM by providing password and it worked fine.

After update

http://i.stack.imgur.com/3Lchp.png

PHP cURL HTTP PUT

Just been doing that myself today... here is code I have working for me...

$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

$response = curl_exec($ch);

if (!$response) 
{
    return false;
}

src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl

How to count down in for loop?

If you google. "Count down for loop python" you get these, which are pretty accurate.

how to loop down in python list (countdown)
Loop backwards using indices in Python?

I recommend doing minor searches before posting. Also "Learn Python The Hard Way" is a good place to start.

Preferred way to create a Scala list

Uhmm.. these seem too complex to me. May I propose

def listTestD = (0 to 3).toList

or

def listTestE = for (i <- (0 to 3).toList) yield i