Programs & Examples On #Mailmerge

A software function which provides the ability to create multiple (and potentially large numbers of) documents from a single template form and a structured data source.

Convert DataTable to CSV stream

If you can turn your datatable into an IEnumerable this should work for you...

    Response.Clear();
    Response.Buffer = true;

    Response.AddHeader("content-disposition", "attachment;filename=FileName.csv");
    Response.Charset = "";
    Response.ContentType = "application/text";
    Response.Output.Write(ExampleClass.ConvertToCSV(GetListOfObject(), typeof(object)));
    Response.Flush();
    Response.End();



public static string ConvertToCSV(IEnumerable col, Type type)
        {
            StringBuilder sb = new StringBuilder();
            StringBuilder header = new StringBuilder();

            // Gets all  properies of the class
            PropertyInfo[] pi = type.GetProperties();

            // Create CSV header using the classes properties
            foreach (PropertyInfo p in pi)
            {
                header.Append(p.Name + ",");
            }

            sb.AppendLine(header.ToString().Remove(header.Length));

            foreach (object t in col)
            {
                StringBuilder body = new StringBuilder();

                // Create new item
                foreach (PropertyInfo p in pi)
                {
                    object o = p.GetValue(t, null);
                    body.Append(o.ToString() + ",");
                }

                sb.AppendLine(body.ToString().Remove(body.Length));
            }
            return sb.ToString();
        }

Android: How to get a custom View's height and width?

The difference between getHeight() and getMeasuredHeight() is that first method will return actual height of the View, the second one will return summary height of View's children. In ohter words, getHeight() returns view height, getMeasuredHeight() returns height which this view needs to show all it's elements

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Perhaps the error message is somewhat misleading, but the gist is that X_train is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:

out_images = np.array(X_train)[indices.astype(int)]

How to set enum to null

Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 

Setting background color for a JFrame

Here's another method:

private void RenkMouseClicked(java.awt.event.MouseEvent evt) {
    renk = JColorChooser.showDialog(null, "Select the background color",
            renk);
    Container a = this.getContentPane();
    a.setBackground(renk);
}

I'm using netbeans ide. For me, JFrame.getContentPane() didn't run. I used JFrame.getContentPane()'s class equivalent this.getContentPane.

How to compare pointers?

To sum up. If we want to see if two pointers point to the same memory location we can do that. Also if we want to compare the contents of the memory pointed to by two pointers we can do that too, just remeber to dereference them first.

If we have

int *a = something; 
int *b = something;

which are two pointers of the same type we can:

Compare memory address:

a==b

and compare contents:

*a==*b

UIImage resize (Scale proportion)

I used this single line of code to create a new UIImage which is scaled. Set the scale and orientation params to achieve what you want. The first line of code just grabs the image.

    // grab the original image
    UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];
    // scaling set to 2.0 makes the image 1/2 the size. 
    UIImage *scaledImage = 
                [UIImage imageWithCGImage:[originalImage CGImage] 
                              scale:(originalImage.scale * 2.0)
                                 orientation:(originalImage.imageOrientation)];

Compare two DataFrames and output their differences side-by-side

A different approach using concat and drop_duplicates:

import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO
import pandas as pd

DF1 = StringIO("""id   Name   score                    isEnrolled           Comment
111  Jack   2.17                     True                 "He was late to class"
112  Nick   1.11                     False                "Graduated"
113  Zoe    NaN                     True                  " "
""")
DF2 = StringIO("""id   Name   score                    isEnrolled           Comment
111  Jack   2.17                     True                 "He was late to class"
112  Nick   1.21                     False                "Graduated"
113  Zoe    NaN                     False                "On vacation" """)

df1 = pd.read_table(DF1, sep='\s+', index_col='id')
df2 = pd.read_table(DF2, sep='\s+', index_col='id')
#%%
dictionary = {1:df1,2:df2}
df=pd.concat(dictionary)
df.drop_duplicates(keep=False)

Output:

       Name  score isEnrolled      Comment
  id                                      
1 112  Nick   1.11      False    Graduated
  113   Zoe    NaN       True             
2 112  Nick   1.21      False    Graduated
  113   Zoe    NaN      False  On vacation

How do I open workbook programmatically as read-only?

Check out the language reference:

http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

Can't find how to use HttpContent

For JSON Post:

var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

Non-JSON:

var stringContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("field1", "value1"),
    new KeyValuePair<string, string>("field2", "value2"),
});
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

https://blog.pedrofelix.org/2012/01/16/the-new-system-net-http-classes-message-content/

Best way to convert IList or IEnumerable to Array

In case you don't have Linq, I solved it the following way:

    private T[] GetArray<T>(IList<T> iList) where T: new()
    {
        var result = new T[iList.Count];

        iList.CopyTo(result, 0);

        return result;
    }

Hope it helps

jQuery UI - Close Dialog When Clicked Outside

Check out the jQuery Outside Events plugin

Lets you do:

$field_hint.bind('clickoutside',function(){
    $field_hint.dialog('close');
});

Parse strings to double with comma and point

try this... it works for me.

double vdouble = 0;
string sparam = "2,1";

if ( !Double.TryParse( sparam, NumberStyles.Float, CultureInfo.InvariantCulture, out vdouble ) )
{
    if ( sparam.IndexOf( '.' ) != -1 )
    {
        sparam = sparam.Replace( '.', ',' );
    }
    else
    {
        sparam = sparam.Replace( ',', '.' );
    }

    if ( !Double.TryParse( sparam, NumberStyles.Float, CultureInfo.InvariantCulture, out vdouble ) )
    {
        vdouble = 0;
    }
}

test attribute in JSTL <c:if> tag

You can also use something like

<c:if test="${ testObject.testPropert == "testValue" }">...</c:if>

How to remove all listeners in an element?

If you’re not opposed to jquery, this can be done in one line:

jQuery 1.7+

$("#myEl").off()

jQuery < 1.7

$('#myEl').replaceWith($('#myEl').clone());

Here’s an example:

http://jsfiddle.net/LkfLezgd/3/

Parser Error when deploy ASP.NET application

I know i am too late to answer but it could help others and save time.

Following might be other solutions.

Solution 1: See Creating a Virtual Directory for Your Application for detailed instructions on creating a virtual directory for your application.

Solution 2: Your application’s Bin folder is missing or the application’s DLL file is missing. See Copying Your Application Files to a Production Server for detailed instructions.

Solution 3: You may have deployed to the web root folder, but have not changed some of the settings in the Web.config file. See Deploying to web root for detailed instructions.

In my case Solution 2 works, while deploying to server some DLL's from bin directory has not been uploaded to server successfully. I have re-upload all DLL's again and it works!!

Here is the reference link to solve asp.net parser error.

What exactly does the .join() method do?

To expand a bit more on what others are saying, if you wanted to use join to simply concatenate your two strings, you would do this:

strid = repr(595)
print ''.join([array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring(), strid])

When to use AtomicReference in Java?

You can use AtomicReference when applying optimistic locks. You have a shared object and you want to change it from more than 1 thread.

  1. You can create a copy of the shared object
  2. Modify the shared object
  3. You need to check that the shared object is still the same as before - if yes, then update with the reference of the modified copy.

As other thread might have modified it and/can modify between these 2 steps. You need to do it in an atomic operation. this is where AtomicReference can help

How do I implement a callback in PHP?

well... with 5.3 on the horizon, all will be better, because with 5.3, we'll get closures and with them anonymous functions

http://wiki.php.net/rfc/closures

How can I URL encode a string in Excel VBA?

No, nothing built-in (until Excel 2013 - see this answer).

There are three versions of URLEncode() in this answer.

  • A function with UTF-8 support. You should probably use this one (or the alternative implementation by Tom) for compatibility with modern requirements.
  • For reference and educational purposes, two functions without UTF-8 support:
    • one found on a third party website, included as-is. (This was the first version of the answer)
    • one optimized version of that, written by me

A variant that supports UTF-8 encoding and is based on ADODB.Stream (include a reference to a recent version of the "Microsoft ActiveX Data Objects" library in your project):

Public Function URLEncode( _
   ByVal StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String
  Dim bytes() As Byte, b As Byte, i As Integer, space As String

  If SpaceAsPlus Then space = "+" Else space = "%20"

  If Len(StringVal) > 0 Then
    With New ADODB.Stream
      .Mode = adModeReadWrite
      .Type = adTypeText
      .Charset = "UTF-8"
      .Open
      .WriteText StringVal
      .Position = 0
      .Type = adTypeBinary
      .Position = 3 ' skip BOM
      bytes = .Read
    End With

    ReDim result(UBound(bytes)) As String

    For i = UBound(bytes) To 0 Step -1
      b = bytes(i)
      Select Case b
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Chr(b)
        Case 32
          result(i) = space
        Case 0 To 15
          result(i) = "%0" & Hex(b)
        Case Else
          result(i) = "%" & Hex(b)
      End Select
    Next i

    URLEncode = Join(result, "")
  End If
End Function

This function was found on freevbcode.com:

Public Function URLEncode( _
   StringToEncode As String, _
   Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String

  Dim TempAns As String
  Dim CurChr As Integer
  CurChr = 1

  Do Until CurChr - 1 = Len(StringToEncode)
    Select Case Asc(Mid(StringToEncode, CurChr, 1))
      Case 48 To 57, 65 To 90, 97 To 122
        TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
      Case 32
        If UsePlusRatherThanHexForSpace = True Then
          TempAns = TempAns & "+"
        Else
          TempAns = TempAns & "%" & Hex(32)
        End If
      Case Else
        TempAns = TempAns & "%" & _
          Right("0" & Hex(Asc(Mid(StringToEncode, _
          CurChr, 1))), 2)
    End Select

    CurChr = CurChr + 1
  Loop

  URLEncode = TempAns
End Function

I've corrected a little bug that was in there.


I would use more efficient (~2× as fast) version of the above:

Public Function URLEncode( _
   StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String

  Dim StringLen As Long: StringLen = Len(StringVal)

  If StringLen > 0 Then
    ReDim result(StringLen) As String
    Dim i As Long, CharCode As Integer
    Dim Char As String, Space As String

    If SpaceAsPlus Then Space = "+" Else Space = "%20"

    For i = 1 To StringLen
      Char = Mid$(StringVal, i, 1)
      CharCode = Asc(Char)
      Select Case CharCode
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Char
        Case 32
          result(i) = Space
        Case 0 To 15
          result(i) = "%0" & Hex(CharCode)
        Case Else
          result(i) = "%" & Hex(CharCode)
      End Select
    Next i
    URLEncode = Join(result, "")
  End If
End Function

Note that neither of these two functions support UTF-8 encoding.

How to import local packages without gopath

Perhaps you're trying to modularize your package. I'm assuming that package1 and package2 are, in a way, part of the same package but for readability you're splitting those into multiple files.

If the previous case was yours, you could use the same package name into those multiples files and it will be like if there were the same file.

This is an example:

add.go

package math

func add(n1, n2 int) int {
   return n1 + n2
}

subtract.go

package math

func subtract(n1, n2 int) int {
    return n1 - n2
}

donothing.go

package math

func donothing(n1, n2 int) int {
    s := add(n1, n2)
    s = subtract(n1, n2)
    return s
}

I am not a Go expert and this is my first post in StackOveflow, so if you have some advice it will be well received.

jQuery location href

Ideally, you want to be using window.location.replace(...).

See this answer here for a full explanation: How do I redirect to another webpage?

WebView link click open default browser

I had to do the same thing today and I have found a very useful answer on StackOverflow that I want to share here in case someone else needs it.

Source (from sven)

webView.setWebViewClient(new WebViewClient(){
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
            view.getContext().startActivity(
                new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
});

Counting the number of elements in array

Best practice of getting length is use length filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}

But you can calculate count of elements in for loop. For example:

{% set count = 0 %}
{% for nc in notcount %}
    {% set count = count + 1 %}
{% endfor %}

{{ count }}

This solution helps if you want to calculate count of elements by condition, for example you have a property name inside object and you want to calculate count of objects with not empty names:

{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
    {% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}

{{ countNotEmpty }}

Useful links:

Oracle - how to remove white spaces?

Use the following to insure there is no whitespace in your output:

select first_name || ',' || last_name from table x;

Output

John,Smith

Jane,Doe

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

< one-way binding

= two-way binding

& function binding

@ pass only strings

Difference between Inheritance and Composition

In Simple Word Aggregation means Has A Relationship ..

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Why Use Aggregation

Code Reusability

When Use Aggregation

Code reuse is also best achieved by aggregation when there is no is a Relation ship

Inheritance

Inheritance is a Parent Child Relationship Inheritance Means Is A RelationShip

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Using inheritance in Java 1 Code Reusability. 2 Add Extra Feature in Child Class as well as Method Overriding (so runtime polymorphism can be achieved).

CSS Animation and Display None

The following will get you to animate an element when

  1. Giving it a Display - None
  2. Giving it a Display - Block

CSS

.MyClass {
       opacity: 0;
       display:none;
       transition: opacity 0.5s linear;
       -webkit-transition: opacity 0.5s linear;
       -moz-transition: opacity 0.5s linear;
       -o-transition: opacity 0.5s linear;
       -ms-transition: opacity 0.5s linear;
 }

JavaScript

function GetThisHidden(){
    $(".MyClass").css("opacity", "0").on('transitionend webkitTransitionEnd oTransitionEnd otransitionend', HideTheElementAfterAnimation);
}

function GetThisDisplayed(){
    $(".MyClass").css("display", "block").css("opacity", "1").unbind("transitionend webkitTransitionEnd oTransitionEnd otransitionend");
}

function HideTheElementAfterAnimation(){
    $(".MyClass").css("display", "none");
}

How to make an Android Spinner with initial text "Select One"?

I ended up using a Button instead. While a Button is not a Spinner, the behavior is easy to customize.

First create the Adapter as usual:

String[] items = new String[] {"One", "Two", "Three"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_spinner_dropdown_item, items);

Note that I am using the simple_spinner_dropdown_item as the layout id. This will help create a better look when creating the alert dialog.

In the onClick handler for my Button I have:

public void onClick(View w) {
  new AlertDialog.Builder(this)
  .setTitle("the prompt")
  .setAdapter(adapter, new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {

      // TODO: user specific action

      dialog.dismiss();
    }
  }).create().show();
}

And that's it!

How to get the previous url using PHP

$_SERVER['HTTP_REFERER'] will give you incomplete url.

If you want http://bawse.3owl.com/jayz__magna_carta_holy_grail.php, $_SERVER['HTTP_REFERER'] will give you http://bawse.3owl.com/ only.

Byte Array to Image object

Since it sounds like you already know what format the byte[] array is in (e.g. RGB, ARGB, BGR etc.) you might be able to use BufferedImage.setRGB(...), or a combination of BufferedImage.getRaster() and WritableRaster.setPixels(...) or WritableRaster.setSamples(...). Unforunately both of these methods require you transform your byte[] into one of int[], float[] or double[] depending on the image format.

Deny access to one specific folder in .htaccess

Create site/includes/.htaccess file and add this line:

Deny from all

no debugging symbols found when using gdb

The application has to be both compiled and linked with -g option. I.e. you need to put -g in both CPPFLAGS and LDFLAGS.

how to print a string to console in c++

All you have to do is add:

#include <string>
using namespace std;

at the top. (BTW I know this was posted in 2013 but I just wanted to answer)

How to add/update an attribute to an HTML element using JavaScript?

What seems easy is actually tricky if you want to be completely compatible.

var e = document.createElement('div');

Let's say you have an id of 'div1' to add.

e['id'] = 'div1';
e.id = 'div1';
e.attributes['id'] = 'div1';
e.createAttribute('id','div1')
These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP's default with no updates).

But there are contingencies, of course. Will not work in IE prior to 8:e.attributes['style'] Will not error but won't actually set the class, it must be className:e['class'] .
However, if you're using attributes then this WILL work:e.attributes['class']

In summary, think of attributes as literal and object-oriented.

In literal, you just want it to spit out x='y' and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE's style exception). But because these are really objects things can get confused.

Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = 'fooClass' and e.id = 'fooID'. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.

It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it's style.width not style="width:50px". Also remember tagName but this is already set by createElement so you shouldn't need to worry about it.

This was longer than I wanted, but CSS manipulation in JS is tricky business.

How to debug (only) JavaScript in Visual Studio?

Yes you can put the break-point on client side page in Visual studio

First Put the debugger in java-script code and run the page in browser

debugger

enter image description here

After that open your page in browser and view the inspect element you see the following view

enter image description here

Skip download if files exist in wget?

The -nc, --no-clobber option isn't the best solution as newer files will not be downloaded. One should use -N instead which will download and overwrite the file only if the server has a newer version, so the correct answer is:

wget -N http://www.example.com/images/misc/pic.png

Then running Wget with -N, with or without -r or -p, the decision as to whether or not to download a newer copy of a file depends on the local and remote timestamp and size of the file. -nc may not be specified at the same time as -N.

-N, --timestamping: Turn on time-stamping.

How is an HTTP POST request made in node.js?

request is now deprecated. It is recommended you use an alternative

In no particular order and dreadfully incomplete:

Stats comparision Some code examples

Original answer:

This gets a lot easier if you use the request library.

var request = require('request');

request.post(
    'http://www.yoursite.com/formpage',
    { json: { key: 'value' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
        }
    }
);

Aside from providing a nice syntax it makes json requests easy, handles oauth signing (for twitter, etc.), can do multi-part forms (e.g. for uploading files) and streaming.

To install request use command npm install request

How to convert a string to number in TypeScript?

_x000D_
_x000D_
var myNumber: number = 1200;_x000D_
//convert to hexadecimal value_x000D_
console.log(myNumber.toString(16)); //will return  4b0_x000D_
//Other way of converting to hexadecimal_x000D_
console.log(Math.abs(myNumber).toString(16)); //will return  4b0_x000D_
//convert to decimal value_x000D_
console.log(parseFloat(myNumber.toString()).toFixed(2)); //will return  1200.00
_x000D_
_x000D_
_x000D_

Online Number Conversion Tool

Number Converter

1064 error in CREATE TABLE ... TYPE=MYISAM

CREATE TABLE `admnih` (
  `id` int(255) NOT NULL auto_increment,
  `asim` varchar(255) NOT NULL default '',
  `brid` varchar(255) NOT NULL default '',
  `rwtbah` int(1) NOT NULL default '0',
  `esmmwkeh` varchar(255) NOT NULL default '',
  `mrwr` varchar(255) NOT NULL default '',
  `tid` int(255) NOT NULL default '0',
  `alksmfialdlil` int(255) NOT NULL default '0',
  `tariktsjil` varchar(255) NOT NULL default '',
  `aimwke` varchar(255) NOT NULL default '',
  `twkie` text NOT NULL,
  `rwtbahkasah` int(255) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;

What are the benefits of learning Vim?

You can get good functionality out of vim by learning the meanings of only 16 keys: ijkdbw9:q!%s/nNEsc. You can do the bare bones with just i:wqEsc.

The first two keys you need to know are: Esc takes you to command mode (the mode you start in), and i takes you to insert mode (normal typing).


To save you need to

  1. get out of typing mode (Esc)
  2. type a colon :
  3. type lowercase w then Enter

To save-and-quit you need to

  1. get out of typing mode (Esc)
  2. type a colon :
  3. type lowercase wq then Enter

To not-save-and-force-quit you need to

  1. get out of typing mode (Esc)
  2. type a colon :
  3. type lowercase q! then Enter

To learn more you can run vimtutor at the command line. It's a medium-length, well-structured lesson.

Beyond i and Esc: you can replicate or surpass some MS Word functionality with only jkwbd3:%s/nN.

  1. b takes you back a word (Ctrl+)
  2. w takes you forward a word (Ctrl+)
  3. 9w takes you forward nine words
  4. db deletes the preceding word (Ctrl+Backspace)
  5. d3b deletes three preceding words
  6. 9j moves down 9 lines
  7. / ornithopter Enter takes you to the next instance of the word "ornithopter", then n and N to the next and previous occurrence of "ornithopter" respectively.
  8. :%s/confounded/dangfangled/ Enter substitutes every "confounded" with "dangfangled" (like find and replace all in MS Word)

Any of those should be run in "command" mode (Esc), not insert mode (i).

Check if a value is an object in JavaScript

The Ramda functional library has a wonderful function for detecting JavaScript types.

Paraphrasing the full function:

function type(val) {
  return val === null      ? 'Null'      :
         val === undefined ? 'Undefined' :
         Object.prototype.toString.call(val).slice(8, -1);
}

I had to laugh when I realized how simple and beautiful the solution was.

Example usage from Ramda documentation:

R.type({}); //=> "Object"
R.type(1); //=> "Number"
R.type(false); //=> "Boolean"
R.type('s'); //=> "String"
R.type(null); //=> "Null"
R.type([]); //=> "Array"
R.type(/[A-z]/); //=> "RegExp"
R.type(() => {}); //=> "Function"
R.type(undefined); //=> "Undefined"

Can't execute jar- file: "no main manifest attribute"

I had the same problem. A lot of the solutions mentioned here didn't give me the whole picture, so I'll try to give you a summary of how to pack jar files from the command line.

  1. If you want to have your .class files in packages, add the package in the beginning of the .java.

    Test.java

    package testpackage;
    
    public class Test
    {
        ...
    }
    
  2. To compile your code with your .class files ending up with the structure given by the package name use:

    javac -d . Test.java
    

    The -d . makes the compiler create the directory structure you want.

  3. When packaging the .jar file, you need to instruct the jar routine on how to pack it. Here we use the option set cvfeP. This is to keep the package structure (option P), specify the entry point so that the manifest file contains meaningful information (option e). Option f lets you specify the file name, option c creates an archive and option v sets the output to verbose. The important things to note here are P and e.

    Then comes the name of the jar we want test.jar.

    Then comes the entry point .

    And then comes -C . <packagename>/ to get the class files from that folder, preserving the folder structure.

    jar cvfeP test.jar testpackage.Test -C . testpackage/
    
  4. Check your .jar file in a zip program. It should have the following structure

    test.jar

    META-INF
    | MANIFEST.MF
    testpackage
    | Test.class
    

    The MANIFEST.MF should contain the following

    Manifest-Version: 1.0
    Created-By: <JDK Version> (Oracle Corporation)
    Main-Class: testpackage.Test
    

    If you edit your manifest by hand be sure to keep the newline at the end otherwise java doesn't recognize it.

  5. Execute your .jar file with

    java -jar test.jar
    

Date formatting in WPF datagrid

This is a very old question, but I found a new solution, so I wrote about it.

First of all, is this way of solution possible while using AutoGenerateColumns?

Yes, that can be done with AttachedProperty as follows.

<DataGrid AutoGenerateColumns="True" 
   local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
   ItemsSource="{Binding}" />

AttachedProperty

There are two AttachedProperty defined that allow you to specify two formats. DateTimeFormatAutoGenerate for DateTime and TimeSpanFormatAutoGenerate for TimeSpan.

class DataGridOperation
{
    public static string GetDateTimeFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(DateTimeFormatAutoGenerateProperty);
    public static void SetDateTimeFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(DateTimeFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty DateTimeFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("DateTimeFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<DateTime>(d, e)));

    public static string GetTimeSpanFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(TimeSpanFormatAutoGenerateProperty);
    public static void SetTimeSpanFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(TimeSpanFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty TimeSpanFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("TimeSpanFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<TimeSpan>(d, e)));

    private static void AddEventHandlerOnGenerating<T>(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is DataGrid dGrid))
            return;

        if ((e.NewValue is string format))
            dGrid.AutoGeneratingColumn += (o, e) => AddFormat_OnGenerating<T>(e, format);
    }

    private static void AddFormat_OnGenerating<T>(DataGridAutoGeneratingColumnEventArgs e, string format)
    {
        if (e.PropertyType == typeof(T))
            (e.Column as DataGridTextColumn).Binding.StringFormat = format;
    }
}

How to use

View

<Window
   x:Class="DataGridAutogenerateCustom.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="clr-namespace:DataGridAutogenerateCustom"
   Width="400" Height="250">
   <Window.DataContext>
      <local:MainWindowViewModel />
   </Window.DataContext>
   <StackPanel>
      <TextBlock Text="DEFAULT FORMAT" />
      <DataGrid ItemsSource="{Binding Dates}" />

      <TextBlock Margin="0,30,0,0" Text="CUSTOM FORMAT" />
      <DataGrid
         local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
         local:DataGridOperation.TimeSpanFormatAutoGenerate="dd\-hh\-mm\-ss"
         ItemsSource="{Binding Dates}" />
   </StackPanel>
</Window>

ViewModel

public class MainWindowViewModel
{
    public DatePairs[] Dates { get; } = new DatePairs[]
    {
        new (){StartDate= new (2011,1,1), EndDate= new (2011,2,1) },
        new (){StartDate= new (2020,1,1), EndDate= new (2021,1,1) },
    };
}

public class DatePairs
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public TimeSpan Span => EndDate - StartDate;
}

demo_wpf_datagrid

Page Redirect after X seconds wait using JavaScript

You actually need to pass a function inside the window.setTimeout() which you want to execute after 5000 milliseconds, like this:

$(document).ready(function () {
    // Handler for .ready() called.
    window.setTimeout(function () {
        location.href = "https://www.google.co.in";
    }, 5000);
});

For More info: .setTimeout()

What does the question mark operator mean in Ruby?

It is a code style convention; it indicates that a method returns a boolean value.

The question mark is a valid character at the end of a method name.

Setting equal heights for div's with jQuery

You can write the function this way also Which helps to build your code one time just to add class name or ID at the end

function equalHeight(group) {
               tallest = 0;
               group.each(function() {
                  thisHeight = jQuery(this).height();
                  if(thisHeight > tallest) {
                     tallest = thisHeight;
                  }
               });
               group.height(tallest);
            }
            equalHeight(jQuery("Add your class"));

How to make a GUI for bash scripts?

You can gtk-server for this. Gtk-server is a program that runs in background and provides text-based interface to allow other programs (including bash scripts) to control it. It has examples for Bash (http://www.gtk-server.org/demo-ipc.bash.txt, http://www.gtk-server.org/demo-fifo.bash.txt)

How to get filename without extension from file path in Ruby

In case the extension is not known (it needs the / separator):

irb(main):024:0> f = 'C:\foobar\blah.txt'.gsub("\\","/")
=> "C:/foobar/blah.txt"
irb(main):027:0> File.basename(f,File.extname(f))
=> "blah"

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

You could use the add-on module for Jackson which handles Hibernate lazy-loading.

More info on https://github.com/FasterXML/jackson-datatype-hibernate wich support hibernate 3 and 4 separately.

A weighted version of random.choice

Here is another version of weighted_choice that uses numpy. Pass in the weights vector and it will return an array of 0's containing a 1 indicating which bin was chosen. The code defaults to just making a single draw but you can pass in the number of draws to be made and the counts per bin drawn will be returned.

If the weights vector does not sum to 1, it will be normalized so that it does.

import numpy as np

def weighted_choice(weights, n=1):
    if np.sum(weights)!=1:
        weights = weights/np.sum(weights)

    draws = np.random.random_sample(size=n)

    weights = np.cumsum(weights)
    weights = np.insert(weights,0,0.0)

    counts = np.histogram(draws, bins=weights)
    return(counts[0])

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

How to add a column in TSQL after a specific column?

This is absolutely possible. Although you shouldn't do it unless you know what you are dealing with. Took me about 2 days to figure it out. Here is a stored procedure where i enter: ---database name (schema name is "_" for readability) ---table name ---column ---column data type (column added is always null, otherwise you won't be able to insert) ---the position of the new column.

Since I'm working with tables from SAM toolkit (and some of them have > 80 columns) , the typical variable won't be able to contain the query. That forces the need of external file. Now be careful where you store that file and who has access on NTFS and network level.

Cheers!

USE [master]
GO
/****** Object:  StoredProcedure [SP_Set].[TrasferDataAtColumnLevel]    Script Date: 8/27/2014 2:59:30 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [SP_Set].[TrasferDataAtColumnLevel]
(
    @database varchar(100),
    @table varchar(100),
    @column varchar(100),
    @position int,
    @datatype varchar(20)    
)
AS
BEGIN
set nocount on
exec  ('
declare  @oldC varchar(200), @oldCDataType varchar(200), @oldCLen int,@oldCPos int
create table Test ( dummy int)
declare @columns varchar(max) = ''''
declare @columnVars varchar(max) = ''''
declare @columnsDecl varchar(max) = ''''
declare @printVars varchar(max) = ''''

DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR 
select column_name, data_type, character_maximum_length, ORDINAL_POSITION  from ' + @database + '.INFORMATION_SCHEMA.COLUMNS where table_name = ''' + @table + '''
OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO @oldC, @oldCDataType, @oldCLen, @oldCPos WHILE @@FETCH_STATUS = 0 BEGIN

if(@oldCPos = ' + @position + ')
begin
    exec(''alter table Test add [' + @column + '] ' + @datatype + ' null'')
end

if(@oldCDataType != ''timestamp'')
begin

    set @columns += @oldC + '' , '' 
    set @columnVars += ''@'' + @oldC + '' , ''

    if(@oldCLen is null)
    begin
        if(@oldCDataType != ''uniqueidentifier'')
        begin
            set @printVars += '' print convert('' + @oldCDataType + '',@'' + @oldC + '')'' 
            set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', '' 
            exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
        end
        else
        begin
            set @printVars += '' print convert(varchar(50),@'' + @oldC + '')'' 
            set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', '' 
            exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
        end
    end
    else
    begin 
        if(@oldCLen < 0)
        begin
            set @oldCLen = 4000
        end
        set @printVars += '' print @'' + @oldC 
        set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + ''('' + convert(character,@oldCLen) + '') , '' 
        exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + ''('' + @oldCLen + '') null'')
    end
end

if exists (select column_name from INFORMATION_SCHEMA.COLUMNS where table_name = ''Test'' and column_name = ''dummy'')
begin
    alter table Test drop column dummy
end

FETCH NEXT FROM MY_CURSOR INTO  @oldC, @oldCDataType, @oldCLen, @oldCPos END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR

set @columns = reverse(substring(reverse(@columns), charindex('','',reverse(@columns)) +1, len(@columns)))
set @columnVars = reverse(substring(reverse(@columnVars), charindex('','',reverse(@columnVars)) +1, len(@columnVars)))
set @columnsDecl = reverse(substring(reverse(@columnsDecl), charindex('','',reverse(@columnsDecl)) +1, len(@columnsDecl)))
set @columns = replace(replace(REPLACE(@columns, ''       '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnVars = replace(replace(REPLACE(@columnVars, ''       '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnsDecl = replace(replace(REPLACE(@columnsDecl, ''  '', ''''), char(9) + char(9),'' ''),char(9), '''')
set @printVars = REVERSE(substring(reverse(@printVars), charindex(''+'',reverse(@printVars))+1, len(@printVars))) 

create table query (id int identity(1,1), string varchar(max))

insert into query values  (''declare '' + @columnsDecl + ''
DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR '')

insert into query values   (''select '' + @columns + '' from ' + @database + '._.' + @table + ''')

insert into query values  (''OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO '' + @columnVars + '' WHILE @@FETCH_STATUS = 0 BEGIN '')

insert into query values   (@printVars )

insert into query values   ( '' insert into Test ('')
insert into query values   (@columns) 
insert into query values   ( '') values ( '' + @columnVars + '')'')

insert into query values  (''FETCH NEXT FROM MY_CURSOR INTO  '' + @columnVars + '' END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR'')

declare @path varchar(100) = ''C:\query.sql''
declare @query varchar(500) = ''bcp "select string from query order by id" queryout '' + @path + '' -t, -c -S  '' + @@servername +  '' -T''

exec master..xp_cmdshell @query

set @query  = ''sqlcmd -S '' + @@servername + '' -i '' + @path

EXEC xp_cmdshell  @query

set @query = ''del ''  + @path

exec xp_cmdshell @query

drop table ' + @database + '._.' + @table + '

select * into ' + @database + '._.' + @table + ' from Test 

drop table query
drop table Test  ')

END

What should I do when 'svn cleanup' fails?

This answer only applies to versions before 1.7 (thanks @LukaszBachman).

Subversion stores its information per folder (in .svn), so if you are just dealing with a subfolder you don't need checkout the whole repository - just the folder that has borked:

cd dir_above_borked
mv borked_dir borked_dir.bak
svn update borked_dir

This will give you a good working copy of the borked folder, but you still have your changes backed up in borked_dir.bak. The same principle applies with Windows/TortoiseSVN.

If you have changes in an isolated folder have a look at the

svn checkout -N borked_dir   # Non-recursive, but deprecated

or

svn checkout --depth=files borked_dir
# 'depth' is new territory to me, but do 'svn help checkout'

SQL Inner-join with 3 tables?

SELECT table1.col,table2.col,table3.col 
FROM table1 
INNER JOIN 
(table2 INNER JOIN table3 
ON table3.id=table2.id) 
ON table1.id(f-key)=table2.id
AND //add any additional filters HERE

"%%" and "%/%" for the remainder and the quotient

Have a look at the examples below for a clearer understanding of the differences between the different operators:

> # Floating Division:
> 5/2
[1] 2.5
> 
> # Integer Division:
> 5%/%2
[1] 2
> 
> # Remainder:
> 5%%2
[1] 1

Anaconda Navigator won't launch (windows 10)

You need to run the cmd prompt from the Scripts directory of Anaconda where ever you have the Anaconda parent folder installed. I happen to have in the root directory of the C drive on my Windows machine. If you are not familiar there are two ways to do that:

A) Use the key combination Win-key + R then type cmd and hit return to launch the terminal window and then type: cd C:\Anaconda\Scripts (or whatever directory path yours is).

B) Navigate using windows explorer to that Scripts directory then type cmd in the address bar of that window and hit return (that will launch the terminal already set to that directory).

Next type the follow commands waiting in between for each to complete:

activate root
conda update -n root conda
conda update --all

When complete type the following and Navigator hopefully should launch:

anaconda-navigator

Slide right to left Android Animations

<translate
    android:fromXDelta="100%p"
    android:toXDelta="0%p"
    android:duration="500" />

Paste a multi-line Java String in Eclipse

The EclipsePasteAsJavaString plug-in allows you to insert text as a Java string by Ctrl + Shift + V

Example

Paste as usual via Ctrl+V:

some text with tabs and new lines

Paste as Java string via Ctrl+Shift+V

"some text\twith tabs\r\n" + "and new \r\n" + "lines"

How to wait in a batch script?

You can ping an address that doesn't exist and specify the desired timeout:

ping 192.0.2.2 -n 1 -w 10000 > nul

And since the address does not exist, it'll wait 10,000 ms (10 seconds) and return.

  • The -w 10000 part specifies the desired timeout in milliseconds.
  • The -n 1 part tells ping that it should only try once (normally it'd try 4 times).
  • The > nul part is appended so the ping command doesn't output anything to screen.

You can easily make a sleep command yourself by creating a sleep.bat somewhere in your PATH and using the above technique:

rem SLEEP.BAT - sleeps by the supplied number of seconds

@ping 192.0.2.2 -n 1 -w %1000 > nul

NOTE (September 2002): The 192.0.2.x address is reserved as per RFC 3330 so it definitely will not exist in the real world. Quoting from the spec:

192.0.2.0/24 - This block is assigned as "TEST-NET" for use in documentation and example code. It is often used in conjunction with domain names example.com or example.net in vendor and protocol documentation. Addresses within this block should not appear on the public Internet.

How can I align button in Center or right using IONIC framework?

Another Ionic way. Using this ion-buttons tag, and the right keyword puts all the buttons in this group to the right. I made some custom toggle buttons that i wanted on one line, but the group to be right justified.

_x000D_
_x000D_
<ion-buttons right>_x000D_
<button ....>1</button>_x000D_
<button ....>2</button>_x000D_
<button ....>3</button>_x000D_
</ion-buttons>
_x000D_
_x000D_
_x000D_

How do I clone into a non-empty directory?

I had a similar problem with a new Apache web directory (account created with WHM) that I planned to use as a staging web server. I needed to initially clone my new project with the code base there and periodically deploy changes by pulling from repository.

The problem was that the account already contained web server files like:

.bash_history
.bash_logout
.bash_profile
.bashrc
.contactemail
.cpanel/
...

...that I did not want to either delete or commit to my repository. I needed them to just stay there unstaged and untracked.

What I did:

I went to my web folder (existing_folder):

cd /home/existing_folder

and then:

git init
git remote add origin PATH/TO/REPO
git pull origin master
git status

It displayed (as expected) a list of many not staged files - those that already existed initially from my cPanel web account.

Then, thanks to this article, I just added the list of those files to:

**.git/info/exclude**

This file, almost like the .gitignore file, allows you to ignore files from being staged. After this I had nothing to commit in the .git/ directory - it works like a personal .gitignore that no one else can see.

Now checking git status returns:

On branch master
nothing to commit, working tree clean

Now I can deploy changes to this web server by simply pulling from my git repository. Hope this helps some web developers to easily create a staging server.

JavaScript - Hide a Div at startup (load)

Barring the CSS solution. The fastest possible way is to hide it immediatly with a script.

<div id="hideme"></div>
<script type="text/javascript">
    $("#hideme").hide();
</script>

In this case I would recommend the CSS solution by Vega. But if you need something more complex (like an animation) you can use this approach.

This has some complications (see comments below). If you want this piece of script to really run as fast as possible you can't use jQuery, use native JS only and defer loading of all other scripts.

Is it possible to get element from HashMap by its position?

you can use below code to get key : String [] keys = (String[]) item.keySet().toArray(new String[0]);

and get object or list that insert in HashMap with key of this item like this : item.get(keys[position]);

How to get the width and height of an android.widget.ImageView?

I just set this property and now Android OS is taking care of every thing.

android:adjustViewBounds="true"

Use this in your layout.xml where you have planted your ImageView :D

java.io.InvalidClassException: local class incompatible:

Serialisation in java is not meant as long term persistence or transport format - it is too fragile for this. With the slightest difference in class bytecode and JVM, your data is not readable anymore. Use XML or JSON data-binding for your task (XStream is fast and easy to use, and there are a ton of alternatives)

Spring Boot application as a Service

The following configuration is required in build.gradle file in Spring Boot projects.

build.gradle

jar {
    baseName = 'your-app'
    version = version
}

springBoot {
    buildInfo()
    executable = true   
    mainClass = "com.shunya.App"
}

executable = true

This is required to make fully executable jar on unix system (Centos and Ubuntu)

Create a .conf file

If you want to configure custom JVM properties or Spring Boot application run arguments, then you can create a .conf file with the same name as the Spring Boot application name and place it parallel to jar file.

Considering that your-app.jar is the name of your Spring Boot application, then you can create the following file.

JAVA_OPTS="-Xms64m -Xmx64m"
RUN_ARGS=--spring.profiles.active=prod
LOG_FOLDER=/custom/log/folder

This configuration will set 64 MB ram for the Spring Boot application and activate prod profile.

Create a new user in linux

For enhanced security we must create a specific user to run the Spring Boot application as a service.

Create a new user

sudo useradd -s /sbin/nologin springboot

On Ubuntu / Debian, modify the above command as follow:

sudo useradd -s /usr/sbin/nologin springboot

Set password

sudo passwd springboot

Make springboot owner of the executable file

chown springboot:springboot your-app.jar

Prevent the modification of jar file

chmod 500 your-app.jar

This will configure jar’s permissions so that it can not be written and can only be read or executed by its owner springboot.

You can optionally make your jar file as immutable using the change attribute (chattr) command.

sudo chattr +i your-app.jar

Appropriate permissions should be set for the corresponding .conf file as well. .conf requires just read access (Octal 400) instead of read + execute (Octal 500) access

chmod 400 your-app.conf

Create Systemd service

/etc/systemd/system/your-app.service

[Unit]
Description=Your app description
After=syslog.target

[Service]
User=springboot
ExecStart=/var/myapp/your-app.jar
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

Automatically restart process if it gets killed by OS

Append the below two attributes (Restart and RestartSec) to automatically restart the process on failure.

/etc/systemd/system/your-app.service

[Service]
User=springboot
ExecStart=/var/myapp/your-app.jar
SuccessExitStatus=143
Restart=always
RestartSec=30

The change will make Spring Boot application restart in case of failure with a delay of 30 seconds. If you stop the service using systemctl command then restart will not happen.

Schedule service at system startup

To flag the application to start automatically on system boot, use the following command:

Enable Spring Boot application at system startup

sudo systemctl enable your-app.service

Start an Stop the Service

systemctl can be used in Ubuntu 16.04 LTS and 18.04 LTS to start and stop the process.

Start the process

sudo systemctl start your-app

Stop the process

sudo systemctl stop your-app

References

https://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html

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

i was trying the same, so i downloaded the .7zip version of XAMPP with php 5.6.33 from https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/5.6.33/

then followed the steps below: 1. rename c:\xampp\php to c:\xampp\php7 2. raname C:\xampp\apache\conf\extra\httpd-xampp.conf to httpd-xampp7.OLD 3. copy php folder from XAMPP_5.6 7zip archive to c:\xampp\ 4. copy file httpd-xampp.conf from XAMPP_5.6 7zip archive to C:\xampp\apache\conf\extra\

open xampp control panel and start Apache and then visit ( i am using port 82 instead of default 80) http://localhost and then click PHPInfo to see if it is working as expected.

Opening localhost shows dashboard

Opening phpinfo shows version 5.6

What's the difference between ViewData and ViewBag?

Below is the point to point difference about ViewData, ViewBag, TempData & Session. Credit/copied askforprogram.in , Follow the link for code example that i haven't mentioned here.

  1. ViewData in MVC

    • ViewData is property of ControllerBase class.
    • ViewData is a type of dictionary object.
    • ViewData is key-value dictionary collection.
    • ViewData was introduced in MVC 1.0 version.
    • ViewData works with .Net framework 3.5 and above.
    • Need to do type conversion of code while enumerating.
    • ViewData object keeps data only for current request.
  2. ViewBag in MVC

    • ViewBag is property of ControllerBase class.
    • ViewBag is a type of dynamic object.
    • ViewBag is a type of object.
    • ViewBag was introduced in MVC 3.0 version.
    • ViewBag works with .Net framework 4.0 and above.
    • ViewBag uses property and handles it, so no need to do type conversion while enumerating.
    • ViewBag object keeps data only for current request.
  3. TempData in MVC

    • TempData is property of ControllerBase class.
    • TempData is a type of dictionary object.
    • TempData is key-value dictionary collection.
    • TempData was introduced in MVC 1.0 version.
    • TempData works with .Net framework 3.5 and above.
    • Need to do type conversion of code while enumerating.
    • TempData object is used to data between current request and subsequent request.
  4. Session in MVC

    • Session is property of Controller(Abstract Class).
    • Session is a type of HttpSessionStateBase.
    • Session is key-value dictionary collection.
    • Session was introduced in MVC 1.0 version.
    • TempData works with .Net framework 1.0 and above.
    • Need to do type conversion of code while enumerating.
    • Session object keeps data for all requests. Valid for all requests, never expires.

How to call a parent class function from derived class function?

If your base class is called Base, and your function is called FooBar() you can call it directly using Base::FooBar()

void Base::FooBar()
{
   printf("in Base\n");
}

void ChildOfBase::FooBar()
{
  Base::FooBar();
}

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

If you don't have to do any group functions (sum, average etc in case you want to add numeric data to the table), use SELECT DISTINCT. I suspect it's faster, but i have nothing to show for it.

In any case, if you're worried about speed, create an index on the column.

How to generate an openSSL key using a passphrase from the command line?

If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.

You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar):

openssl genrsa -aes128 -passout pass:foobar 3072

However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.

A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:

openssl genrsa -aes128 -passout file:passphrase.txt 3072

Or supply the passphrase on standard input:

openssl genrsa -aes128 -passout stdin 3072

You can also used a named pipe with the file: option, or a file descriptor.


To then obtain the matching public key, you need to use openssl rsa, supplying the same passphrase with the -passin parameter as was used to encrypt the private key:

openssl rsa -passin file:passphrase.txt -pubout

(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>).


Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar:

openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub

Restrict varchar() column to specific values?

Have you already looked at adding a check constraint on that column which would restrict values? Something like:

CREATE TABLE SomeTable
(
   Id int NOT NULL,
   Frequency varchar(200),
   CONSTRAINT chk_Frequency CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
)

mysql: get record count between two date-time

select * from yourtable 
   where created < now() 
     and created > concat(curdate(),' 4:30:00 AM') 

Responsive image map

The following method works perfectly for me, so here's my full implementation:

<img id="my_image" style="display: none;" src="my.png" width="924" height="330" border="0" usemap="#map" />

<map name="map" id="map">
    <area shape="poly" coords="774,49,810,21,922,130,920,222,894,212,885,156,874,146" href="#mylink" />
    <area shape="poly" coords="649,20,791,157,805,160,809,217,851,214,847,135,709,1,666,3" href="#myotherlink" />
</map>

<script>
$(function(){
    var image_is_loaded = false;
    $("#my_image").on('load',function() {
        $(this).data('width', $(this).attr('width')).data('height', $(this).attr('height'));
        $($(this).attr('usemap')+" area").each(function(){
            $(this).data('coords', $(this).attr('coords'));
        });

        $(this).css('width', '100%').css('height','auto').show();

        image_is_loaded = true;
        $(window).trigger('resize');
    });


    function ratioCoords (coords, ratio) {
        coord_arr = coords.split(",");

        for(i=0; i < coord_arr.length; i++) {
            coord_arr[i] = Math.round(ratio * coord_arr[i]);
        }

        return coord_arr.join(',');
    }
    $(window).on('resize', function(){
        if (image_is_loaded) {
            var img = $("#my_image");
            var ratio = img.width()/img.data('width');

            $(img.attr('usemap')+" area").each(function(){
                console.log('1: '+$(this).attr('coords'));
                $(this).attr('coords', ratioCoords($(this).data('coords'), ratio));
            });
        }
    });
});
</script>

`IF` statement with 3 possible answers each based on 3 different ranges

Your formula should be of the form =IF(X2 >= 85,0.559,IF(X2 >= 80,0.327,IF(X2 >=75,0.255,0))). This simulates the ELSE-IF operand Excel lacks. Your formulas were using two conditions in each, but the second parameter of the IF formula is the value to use if the condition evaluates to true. You can't chain conditions in that manner.

open link of google play store in mobile version android

Below code may helps you for display application link of google play sore in mobile version.

For Application link :

Uri uri = Uri.parse("market://details?id=" + mContext.getPackageName());
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);

  try {
        startActivity(myAppLinkToMarket);

      } catch (ActivityNotFoundException e) {

        //the device hasn't installed Google Play
        Toast.makeText(Setting.this, "You don't have Google Play installed", Toast.LENGTH_LONG).show();
              }

For Developer link :

Uri uri = Uri.parse("market://search?q=pub:" + YourDeveloperName);
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);

            try {

                startActivity(myAppLinkToMarket);

            } catch (ActivityNotFoundException e) {

                //the device hasn't installed Google Play
                Toast.makeText(Settings.this, "You don't have Google Play installed", Toast.LENGTH_LONG).show();

            } 

How do I create a comma delimited string from an ArrayList?

The solutions so far are all quite complicated. The idiomatic solution should doubtless be:

String.Join(",", x.Cast(Of String)().ToArray())

There's no need for fancy acrobatics in new framework versions. Supposing a not-so-modern version, the following would be easiest:

Console.WriteLine(String.Join(",", CType(x.ToArray(GetType(String)), String())))

mspmsp's second solution is a nice approach as well but it's not working because it misses the AddressOf keyword. Also, Convert.ToString is rather inefficient (lots of unnecessary internal evaluations) and the Convert class is generally not very cleanly designed. I tend to avoid it, especially since it's completely redundant.

Best way to parse RSS/Atom feeds with PHP

If feed isn't well-formed XML, you're supposed to reject it, no exceptions. You're entitled to call feed creator a bozo.

Otherwise you're paving way to mess that HTML ended up in.

How to format date string in java?

If you are looking for a solution to your particular case, it would be:

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2012-05-20T09:00:00.000Z");
String formattedDate = new SimpleDateFormat("dd/MM/yyyy, Ka").format(date);

How do I put text on ProgressBar?

I have used this simple code, and it works!

for (int i = 0; i < N * N; i++)
     {
        Thread.Sleep(50);
        progressBar1.BeginInvoke(new Action(() => progressBar1.Value = i));
        progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial",
        (float)10.25, FontStyle.Bold),
        Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
     }

It just has one simple problem and this is it: when progress bar start to rising, percentage some times hide, and then appear again. I did't write it myself.I found it here: text on progressbar in c#

I used this code, and it does work.

css to make bootstrap navbar transparent

This works for 4.0.

<nav class="navbar navbar-expand-sm fixed-top navbar-light">
or
<nav class="navbar navbar-expand-lg fixed-top navbar-dark">

key item is fixed-top, otherwise, white or default page background is displayed even if there is a image top. navbar-light gives dark letters, navbar-dark shows light text.

Can't get value of input type="file"?

@BozidarS: FileAPI is supported quite well nowadays and provides a number of useful options.

var file = document.forms['formName']['inputName'].files[0];
//file.name == "photo.png"
//file.type == "image/png"
//file.size == 300821

Inline IF Statement in C#

The literal answer is:

return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);

Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:

return (value == 1
    ? Periods.VariablePeriods
    : (value == 2
        ? Periods.FixedPeriods
        : Periods.Unknown));

If you add more values an inline if will become unreadable and a switch would be preferred:

switch (value)
{
case 1:
    return Periods.VariablePeriods;
case 2:
    return Periods.FixedPeriods;
}

The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.

How do I trim() a string in angularjs?

use trim() method of javascript after all angularjs is also a javascript framework and it is not necessary to put $ to apply trim()

for example

var x="hello world";
x=x.trim()

To the power of in C?

Actually in C, you don't have an power operator. You will need to manually run a loop to get the result. Even the exp function just operates in that way only. But if you need to use that function, include the following header

#include <math.h>

then you can use pow().

How do you debug MySQL stored procedures?

MySql Connector/NET also includes a stored procedure debugger integrated in visual studio as of version 6.6, You can get the installer and the source here: http://dev.mysql.com/downloads/connector/net/

Some documentation / screenshots: https://dev.mysql.com/doc/visual-studio/en/visual-studio-debugger.html

You can follow the annoucements here: http://forums.mysql.com/read.php?38,561817,561817#msg-561817

UPDATE: The MySql for Visual Studio was split from Connector/NET into a separate product, you can pick it (including the debugger) from here https://dev.mysql.com/downloads/windows/visualstudio/1.2.html (still free & open source).

DISCLAIMER: I was the developer who authored the Stored procedures debugger engine for MySQL for Visual Studio product.

How to make a simple collection view with Swift

UICollectionView implementation is quite interesting. You can use the simple source code and watch a video tutorial using these links :

https://github.com/Ady901/Demo02CollectionView.git

https://www.youtube.com/watch?v=5SrgvZF67Yw

extension ViewController : UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return nameArr.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DummyCollectionCell", for: indexPath) as! DummyCollectionCell
        cell.titleLabel.text = nameArr[indexPath.row]
        cell.userImageView.backgroundColor = .blue
        return cell
    }

}

extension ViewController : UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let alert = UIAlertController(title: "Hi", message: "\(nameArr[indexPath.row])", preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(action)
        self.present(alert, animated: true, completion: nil)
    }

}

What is the difference between `new Object()` and object literal notation?

Also, according to some of the O'Really javascript books....(quoted)

Another reason for using literals as opposed to the Object constructor is that there is no scope resolution. Because it’s possible that you have created a local constructor with the same name, the interpreter needs to look up the scope chain from the place you are calling Object() all the way up until it finds the global Object constructor.

Finding all cycles in a directed graph

There are two steps (algorithms) involved in finding all cycles in a DAG.

The first step is to use Tarjan's algorithm to find the set of strongly connected components.

  1. Start from any arbitrary vertex.
  2. DFS from that vertex. For each node x, keep two numbers, dfs_index[x] and dfs_lowval[x]. dfs_index[x] stores when that node is visited, while dfs_lowval[x] = min(dfs_low[k]) where k is all the children of x that is not the directly parent of x in the dfs-spanning tree.
  3. All nodes with the same dfs_lowval[x] are in the same strongly connected component.

The second step is to find cycles (paths) within the connected components. My suggestion is to use a modified version of Hierholzer's algorithm.

The idea is:

  1. Choose any starting vertex v, and follow a trail of edges from that vertex until you return to v. It is not possible to get stuck at any vertex other than v, because the even degree of all vertices ensures that, when the trail enters another vertex w there must be an unused edge leaving w. The tour formed in this way is a closed tour, but may not cover all the vertices and edges of the initial graph.
  2. As long as there exists a vertex v that belongs to the current tour but that has adjacent edges not part of the tour, start another trail from v, following unused edges until you return to v, and join the tour formed in this way to the previous tour.

Here is the link to a Java implementation with a test case:

http://stones333.blogspot.com/2013/12/find-cycles-in-directed-graph-dag.html

How do I set up Vim autoindentation properly for editing Python files?

I use this on my macbook:

" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set expandtab
au BufRead,BufNewFile *.h set expandtab
au BufRead,BufNewFile Makefile* set noexpandtab

" --------------------------------------------------------------------------------
" configure editor with tabs and nice stuff...
" --------------------------------------------------------------------------------
set expandtab           " enter spaces when tab is pressed
set textwidth=120       " break lines when line length increases
set tabstop=4           " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4        " number of spaces to use for auto indent
set autoindent          " copy indent from current line when starting a new line

" make backspaces more powerfull
set backspace=indent,eol,start

set ruler                           " show line and column number
syntax on               " syntax highlighting
set showcmd             " show (partial) command in status line

(edited to only show stuff related to indent / tabs)

How to change the default collation of a table?

may need to change the SCHEMA not only table

ALTER SCHEMA `<database name>`  DEFAULT CHARACTER SET utf8mb4  DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);

(mariaDB 10)

Enter key press behaves like a Tab in Javascript

Many answers here uses e.keyCode and e.which that are deprecated.

Instead you should use e.key === 'Enter'.

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

  • I'm sorry but I can't test these snippets just now. Will come back later after testing it.

With HTML:

<body onkeypress="if(event.key==='Enter' && event.target.form){focusNextElement(event); return false;}">

With jQuery:

$(window).on('keypress', function (ev)
{
    if (ev.key === "Enter" && ev.currentTarget.form) focusNextElement(ev)
}

And with Vanilla JS:

document.addEventListener('keypress', function (ev) {
    if (ev.key === "Enter" && ev.currentTarget.form) focusNextElement(ev);
});

You can take focusNextElement() function from here: https://stackoverflow.com/a/35173443/3356679

Suppress command line output

mysqldump doesn't work with: >nul 2>&1
Instead use: 2> nul
This suppress the stderr message: "Warning: Using a password on the command line interface can be insecure"

git: How to ignore all present untracked files?

-u no doesn't show unstaged files either. -uno works as desired and shows unstaged, but hides untracked.

NodeJs : TypeError: require(...) is not a function

I think this means that module.exports in your ./app/routes module is not assigned to be a function so therefore require('./app/routes') does not resolve to a function so therefore, you cannot call it as a function like this require('./app/routes')(app, passport).

Show us ./app/routes if you want us to comment further on that.

It should look something like this;

module.exports = function(app, passport) {
    // code here
}

You are exporting a function that can then be called like require('./app/routes')(app, passport).


One other reason a similar error could occur is if you have a circular module dependency where module A is trying to require(B) and module B is trying to require(A). When this happens, it will be detected by the require() sub-system and one of them will come back as null and thus trying to call that as a function will not work. The fix in that case is to remove the circular dependency, usually by breaking common code into a third module that both can separately load though the specifics of fixing a circular dependency are unique for each situation.

How do I get the max ID with Linq to Entity?

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();

Determine if char is a num or letter

Neither of these does anything useful. Use isalpha() or isdigit() from the standard library. They're in <ctype.h>.

Clearing the terminal screen?

You could try:

Serial.write(13);

Which will provide a carriage return, returning to the start of the line every iteration - which should do what you're chasing? (Especially if everything is fixed width).

How to set bot's status

Bumping this all the way from 2018, sorry not sorry. But the newer users questioning how to do this need to know that game does not work anymore for this task.

bot.user.setStatus('available')
bot.user.setPresence({
    game: {
        name: 'with depression',
        type: "STREAMING",
        url: "https://www.twitch.tv/monstercat"
    }
}

does not work anymore. You will now need to do this:

bot.user.setPresence({
    status: 'online',
    activity: {
        name: 'with depression',
        type: 'STREAMING',
        url: 'https://www.twitch.tv/monstercat'
    }
})

This is referenced here as "game" is not a valid property of setPresence anymore. Read the PresenceData Documentation for more information about this.

How to map with index in Ruby?

module Enumerable
  def map_with_index(&block)
    i = 0
    self.map { |val|
      val = block.call(val, i)
      i += 1
      val
    }
  end
end

["foo", "bar"].map_with_index {|item, index| [item, index] } => [["foo", 0], ["bar", 1]]

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

For those of you experiencing this error on Windows using Task Manager end the instance of "mongod.exe" that is running. Once that is done permanently delete the mongo.lock file and run mongod.exe. It should work perfectly after that.

How do I split a string with multiple separators in JavaScript?

Lets keep it simple: (add a "[ ]+" to your RegEx means "1 or more")

This means "+" and "{1,}" are the same.

var words = text.split(/[ .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/); // note ' and - are kept

how to delete all commit history in github?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D main

  5. Rename the current branch to main

    git branch -m main

  6. Finally, force update your repository

    git push -f origin main

PS: this will not keep your old commit history around

How to give color to each class in scatter plot in R?

Here is how I do it in 2018. Who knows, maybe an R newbie will see it one day and fall in love with ggplot2.

library(ggplot2)

ggplot(data = iris, aes(Petal.Length, Petal.Width, color = Species)) +
  geom_point() +
  scale_color_manual(values = c("setosa" = "red", "versicolor" = "blue", "virginica" = "yellow"))

how to display employee names starting with a and then b in sql

Here what I understood from the question is starting with "a " and then "b" ex:

  • abhay
  • abhishek
  • abhinav

So there should be two conditions and both should be true means you cant use "OR" operator Ordered by is not not compulsory but its good if you use.

Select e_name from emp 
where  e_name like 'a%' AND e_name like '_b%'
Ordered by e_name

Django datetime issues (default=datetime.now())

The datetime.now() is evaluated when the class is created, not when new record is being added to the database.

To achieve what you want define this field as:

date = models.DateTimeField(auto_now_add=True)

This way the date field will be set to current date for each new record.

How to query data out of the box using Spring data JPA by both Sort and Pageable?

in 2020, the accepted answer is kinda out of date since the PageRequest is deprecated, so you should use code like this :

Pageable page = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by("id").descending());
return repository.findAll(page);

How to convert an array to object in PHP?

one liner

$object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));

mongodb: insert if not exists

Summary

  • You have an existing collection of records.
  • You have a set records that contain updates to the existing records.
  • Some of the updates don't really update anything, they duplicate what you have already.
  • All updates contain the same fields that are there already, just possibly different values.
  • You want to track when a record was last changed, where a value actually changed.

Note, I'm presuming PyMongo, change to suit your language of choice.

Instructions:

  1. Create the collection with an index with unique=true so you don't get duplicate records.

  2. Iterate over your input records, creating batches of them of 15,000 records or so. For each record in the batch, create a dict consisting of the data you want to insert, presuming each one is going to be a new record. Add the 'created' and 'updated' timestamps to these. Issue this as a batch insert command with the 'ContinueOnError' flag=true, so the insert of everything else happens even if there's a duplicate key in there (which it sounds like there will be). THIS WILL HAPPEN VERY FAST. Bulk inserts rock, I've gotten 15k/second performance levels. Further notes on ContinueOnError, see http://docs.mongodb.org/manual/core/write-operations/

    Record inserts happen VERY fast, so you'll be done with those inserts in no time. Now, it's time to update the relevant records. Do this with a batch retrieval, much faster than one at a time.

  3. Iterate over all your input records again, creating batches of 15K or so. Extract out the keys (best if there's one key, but can't be helped if there isn't). Retrieve this bunch of records from Mongo with a db.collectionNameBlah.find({ field : { $in : [ 1, 2,3 ...}) query. For each of these records, determine if there's an update, and if so, issue the update, including updating the 'updated' timestamp.

    Unfortunately, we should note, MongoDB 2.4 and below do NOT include a bulk update operation. They're working on that.

Key Optimization Points:

  • The inserts will vastly speed up your operations in bulk.
  • Retrieving records en masse will speed things up, too.
  • Individual updates are the only possible route now, but 10Gen is working on it. Presumably, this will be in 2.6, though I'm not sure if it will be finished by then, there's a lot of stuff to do (I've been following their Jira system).

Cannot set content-type to 'application/json' in jQuery.ajax

I found the solution for this problem here. Don't forget to allow verb OPTIONS on IIS app service handler.

Works fine. Thank you André Pedroso. :-)

How to use awk sort by column 3

  1. Use awk to put the user ID in front.
  2. Sort
  3. Use sed to remove the duplicate user ID, assuming user IDs do not contain any spaces.

    awk -F, '{ print $3, $0 }' user.csv | sort | sed 's/^.* //'
    

How to check if another instance of the application is running

It's not sure what you mean with 'the program', but if you want to limit your application to one instance then you can use a Mutex to make sure that your application isn't already running.

[STAThread]
static void Main()
{
    Mutex mutex = new System.Threading.Mutex(false, "MyUniqueMutexName");
    try
    {
        if (mutex.WaitOne(0, false))
        {
            // Run the application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
        else
        {
            MessageBox.Show("An instance of the application is already running.");
        }
    }
    finally
    {
        if (mutex != null)
        {
            mutex.Close();
            mutex = null;
        }
    }
}

powershell - list local users and their groups

For Googlers, another way to get a list of users is to use:

Get-WmiObject -Class Win32_UserAccount

From http://buckeyejeeps.com/blog/?p=764

Convert Unix timestamp to a date string

Slight correction to dabest1's answer above. Specify the timezone as UTC, not GMT:

$ date -d '1970-01-01 1416275583 sec GMT'
Tue Nov 18 00:53:03 GMT 2014
$ date -d '1970-01-01 1416275583 sec UTC'
Tue Nov 18 01:53:03 GMT 2014

The second one is correct. I think the reason is that in the UK, daylight saving was in force continually from 1968 to 1971.

java: run a function after a specific number of seconds

new java.util.Timer().schedule( 
        new java.util.TimerTask() {
            @Override
            public void run() {
                // your code here
            }
        }, 
        5000 
);

EDIT:

javadoc says:

After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur.

docker cannot start on windows

Solved for me by running a docker desktop app, check-in notification. Setup if necessary.

$ net start com.docker.service

The Docker for Windows Service service is starting. The Docker for Windows Service service was started successfully.

$ docker version

$ net start com.docker.service

The requested service has already been started.

Importing the private-key/public-certificate pair in the Java KeyStore

A keystore needs a keystore file. The KeyStore class needs a FileInputStream. But if you supply null (instead of FileInputStream instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool.

Following code creates an empty keystore with empty password

  KeyStore ks2 = KeyStore.getInstance("jks");
  ks2.load(null,"".toCharArray());
  FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore");
  ks2.store(out, "".toCharArray());

Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.

PHP JSON String, escape Double Quotes for JS output

I just ran into this problem and the actual issue was that I forgot to add a proper application/json header before spitting out the actual JSON data.

header('Content-Type: application/json');

Plotting multiple lines, in different colors, with pandas dataframe

Another simple way is to use the pivot function to format the data as you need first.

df.plot() does the rest

df = pd.DataFrame([
    ['red', 0, 0],
    ['red', 1, 1],
    ['red', 2, 2],
    ['red', 3, 3],
    ['red', 4, 4],
    ['red', 5, 5],
    ['red', 6, 6],
    ['red', 7, 7],
    ['red', 8, 8],
    ['red', 9, 9],
    ['blue', 0, 0],
    ['blue', 1, 1],
    ['blue', 2, 4],
    ['blue', 3, 9],
    ['blue', 4, 16],
    ['blue', 5, 25],
    ['blue', 6, 36],
    ['blue', 7, 49],
    ['blue', 8, 64],
    ['blue', 9, 81],
], columns=['color', 'x', 'y'])

df = df.pivot(index='x', columns='color', values='y')

df.plot()

result

pivot effectively turns the data into:

enter image description here

Spring Security redirect to previous page after successful login

I want to extend Olcay's nice answer. His approach is good, your login page controller should be like this to put the referrer url into session:

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(HttpServletRequest request, Model model) {
    String referrer = request.getHeader("Referer");
    request.getSession().setAttribute("url_prior_login", referrer);
    // some other stuff
    return "login";
}

And you should extend SavedRequestAwareAuthenticationSuccessHandler and override its onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) method. Something like this:

public class MyCustomLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    public MyCustomLoginSuccessHandler(String defaultTargetUrl) {
        setDefaultTargetUrl(defaultTargetUrl);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        HttpSession session = request.getSession();
        if (session != null) {
            String redirectUrl = (String) session.getAttribute("url_prior_login");
            if (redirectUrl != null) {
                // we do not forget to clean this attribute from session
                session.removeAttribute("url_prior_login");
                // then we redirect
                getRedirectStrategy().sendRedirect(request, response, redirectUrl);
            } else {
                super.onAuthenticationSuccess(request, response, authentication);
            }
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}

Then, in your spring configuration, you should define this custom class as a bean and use it on your security configuration. If you are using annotation config, it should look like this (the class you extend from WebSecurityConfigurerAdapter):

@Bean
public AuthenticationSuccessHandler successHandler() {
    return new MyCustomLoginSuccessHandler("/yourdefaultsuccessurl");
}

In configure method:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            // bla bla
            .formLogin()
                .loginPage("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(successHandler())
                .permitAll()
            // etc etc
    ;
}

Creating email templates with Django

Use EmailMultiAlternatives and render_to_string to make use of two alternative templates (one in plain text and one in html):

from django.core.mail import EmailMultiAlternatives
from django.template import Context
from django.template.loader import render_to_string

c = Context({'username': username})    
text_content = render_to_string('mail/email.txt', c)
html_content = render_to_string('mail/email.html', c)

email = EmailMultiAlternatives('Subject', text_content)
email.attach_alternative(html_content, "text/html")
email.to = ['[email protected]']
email.send()

Can you explain the HttpURLConnection connection process?

On which point does HTTPURLConnection try to establish a connection to the given URL?

On the port named in the URL if any, otherwise 80 for HTTP and 443 for HTTPS. I believe this is documented.

On which point can I know that I was able to successfully establish a connection?

When you call getInputStream() or getOutputStream() or getResponseCode() without getting an exception.

Are establishing a connection and sending the actual request done in one step/method call? What method is it?

No and none.

Can you explain the function of getOutputStream() and getInputStream() in layman's term?

Either of them first connects if necessary, then returns the required stream.

I notice that when the server I'm trying to connect to is down, I get an Exception at getOutputStream(). Does it mean that HTTPURLConnection will only start to establish a connection when I invoke getOutputStream()? How about the getInputStream()? Since I'm only able to get the response at getInputStream(), then does it mean that I didn't send any request at getOutputStream() yet but simply establishes a connection? Do HttpURLConnection go back to the server to request for response when I invoke getInputStream()?

See above.

Am I correct to say that openConnection() simply creates a new connection object but does not establish any connection yet?

Yes.

How can I measure the read overhead and connect overhead?

Connect: take the time getInputStream() or getOutputStream() takes to return, whichever you call first. Read: time from starting first read to getting the EOS.

lexical or preprocessor issue file not found occurs while archiving?

Spaces in a folder name in your header search path can cause this problem. Make sure the folders in your project do not have spaces in their names.

How to download a file with Node.js (without using third-party libraries)?

Hi,I think you can use child_process module and curl command.

const cp = require('child_process');

let download = async function(uri, filename){
    let command = `curl -o ${filename}  '${uri}'`;
    let result = cp.execSync(command);
};


async function test() {
    await download('http://zhangwenning.top/20181221001417.png', './20181221001417.png')
}

test()

In addition,when you want download large?multiple files,you can use cluster module to use more cpu cores.

Native query with named parameter fails with "Not all named parameters have been set"

Use set Parameter from query.

Query q = (Query) em.createNativeQuery("SELECT count(*) FROM mytable where username = ?1");
q.setParameter(1, "test");

Download file from web in Python 3

You can use wget which is popular downloading shell tool for that. https://pypi.python.org/pypi/wget This will be the simplest method since it does not need to open up the destination file. Here is an example.

import wget
url = 'https://i1.wp.com/python3.codes/wp-content/uploads/2015/06/Python3-powered.png?fit=650%2C350'  
wget.download(url, '/Users/scott/Downloads/cat4.jpg') 

Python set to list

This will work:

>>> t = [1,1,2,2,3,3,4,5]
>>> print list(set(t))
[1,2,3,4,5]

However, if you have used "list" or "set" as a variable name you will get the:

TypeError: 'set' object is not callable

eg:

>>> set = [1,1,2,2,3,3,4,5]
>>> print list(set(set))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

Same error will occur if you have used "list" as a variable name.

How to implement the factory method pattern in C++ correctly

I don't try to answer all of my questions, as I believe it is too broad. Just a couple of notes:

there are cases when object construction is a task complex enough to justify its extraction to another class.

That class is in fact a Builder, rather than a Factory.

In the general case, I don't want to force the users of the factory to be restrained to dynamic allocation.

Then you could have your factory encapsulate it in a smart pointer. I believe this way you can have your cake and eat it too.

This also eliminates the issues related to return-by-value.

Conclusion: Making a factory by returning an object is indeed a solution for some cases (such as the 2-D vector previously mentioned), but still not a general replacement for constructors.

Indeed. All design patterns have their (language specific) constraints and drawbacks. It is recommended to use them only when they help you solve your problem, not for their own sake.

If you are after the "perfect" factory implementation, well, good luck.

jQuery - Redirect with post data

why not just use a button instead of submit. clicking the button will let you construct a proper url for your browser to redirect to.

$("#button").click(function() {
   var url = 'site.com/process.php?';
   $('form input').each(function() {
       url += 'key=' + $(this).val() + "&";
   });
   // handle removal of last &.

   window.location.replace(url);
});

Extract the filename from a path

You could get the result you want like this.

$file = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$a = $file.Split("\")
$index = $a.count - 1
$a.GetValue($index)

If you use "Get-ChildItem" to get the "fullname", you could also use "name" to just get the name of the file.

HTML Upload MAX_FILE_SIZE does not appear to work

Before I start, please let me emphasize that the size of the file must be checked on the server side. If not checked on server side, malicious users can override your client side limits, and upload huge files to your server. DO NOT TRUST THE USERS.

I played a bit with PHP's MAX_FILE_SIZE, it seemed to work only after the file was uploaded, which makes it irrelevant (again, malicious user can override it quite easily).

The javascript code below (tested in Firefox and Chrome), based on Matthew's post, will warn the user (the good, innocent one) a priori to uploading a large file, saving both traffic and the user's time:

<form method="post" enctype="multipart/form-data" 
onsubmit="return checkSize(2097152)">    
<input type="file" id="upload" />
<input type="submit" />

<script type="text/javascript">
function checkSize(max_img_size)
{
    var input = document.getElementById("upload");
    // check for browser support (may need to be modified)
    if(input.files && input.files.length == 1)
    {           
        if (input.files[0].size > max_img_size) 
        {
            alert("The file must be less than " + (max_img_size/1024/1024) + "MB");
            return false;
        }
    }

    return true;
}
</script>

PDF Editing in PHP?

<?php

//getting new instance
$pdfFile = new_pdf();

PDF_open_file($pdfFile, " ");

//document info
pdf_set_info($pdfFile, "Auther", "Ahmed Elbshry");
pdf_set_info($pdfFile, "Creator", "Ahmed Elbshry");
pdf_set_info($pdfFile, "Title", "PDFlib");
pdf_set_info($pdfFile, "Subject", "Using PDFlib");

//starting our page and define the width and highet of the document
pdf_begin_page($pdfFile, 595, 842);

//check if Arial font is found, or exit
if($font = PDF_findfont($pdfFile, "Arial", "winansi", 1)) {
    PDF_setfont($pdfFile, $font, 12);
} else {
    echo ("Font Not Found!");
    PDF_end_page($pdfFile);
    PDF_close($pdfFile);
    PDF_delete($pdfFile);
    exit();
}

//start writing from the point 50,780
PDF_show_xy($pdfFile, "This Text In Arial Font", 50, 780);
PDF_end_page($pdfFile);
PDF_close($pdfFile);

//store the pdf document in $pdf
$pdf = PDF_get_buffer($pdfFile);
//get  the len to tell the browser about it
$pdflen = strlen($pdfFile);

//telling the browser about the pdf document
header("Content-type: application/pdf");
header("Content-length: $pdflen");
header("Content-Disposition: inline; filename=phpMade.pdf");
//output the document
print($pdf);
//delete the object
PDF_delete($pdfFile);
?>

"Prevent saving changes that require the table to be re-created" negative effects

SQL Server drops and recreates the tables only if you:

  • Add a new column
  • Change the Allow Nulls setting for a column
  • Change the column order in the table
  • Change the column data type

Using ALTER is safer, as in case the metadata is lost while you re-create the table, your data will be lost.

How to Empty Caches and Clean All Targets Xcode 4 and later

When using a "Data Model" , there are options in the inspector to generare classes, for me this was the case as there was already a class with the existing name.

Codegen: solved it for me.

enter image description here

React eslint error missing in props validation

It seems that the problem is in eslint-plugin-react.

It can not correctly detect what props were mentioned in propTypes if you have annotated named objects via destructuring anywhere in the class.

There was similar problem in the past

How to replace all special character into a string using C#

You can use a regular expresion to for example replace all non-alphanumeric characters with commas:

s = Regex.Replace(s, "[^0-9A-Za-z]+", ",");

Note: The + after the set will make it replace each group of non-alphanumeric characters with a comma. If you want to replace each character with a comma, just remove the +.

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

In my case this (a with caret) occurred in code I generated from visual studio using my own tool for generating code. It was easy to solve:

Select single spaces ( ) in the document. You should be able to see lots of single spaces that are looking different from the other single spaces, they are not selected. Select these other single spaces - they are the ones responsible for the unwanted characters in the browser. Go to Find and Replace with single space ( ). Done.

PS: It's easier to see all similar characters when you place the cursor on one or if you select it in VS2017+; I hope other IDEs may have similar features

Enum String Name from Value

you can just cast it

int dbValue = 2;
EnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue;
string stringName = enumValue.ToString(); //Visible

ah.. kent beat me to it :)

Disabling radio buttons with jQuery

First, the valid syntax is

jQuery("input[name=ticketID]")

second, have you tried:

jQuery(":radio")

instead?

third, why not assign a class to all the radio buttons, and select them by class?

error: RPC failed; curl transfer closed with outstanding read data remaining

For me, the issue was that the connection closes before the whole clone complete. I used ethernet instead of wifi connection. Then it solves for me

Is it possible to have different Git configuration for different projects?

There are 3 levels of git config; project, global and system.

  • project: Project configs are only available for the current project and stored in .git/config in the project's directory.
  • global: Global configs are available for all projects for the current user and stored in ~/.gitconfig.
  • system: System configs are available for all the users/projects and stored in /etc/gitconfig.

Create a project specific config, you have to execute this under the project's directory:

$ git config user.name "John Doe" 

Create a global config:

$ git config --global user.name "John Doe"

Create a system config:

$ git config --system user.name "John Doe" 

And as you may guess, project overrides global and global overrides system.

Note: Project configs are local to just one particular copy/clone of this particular repo, and need to be reapplied if the repo is recloned clean from the remote. It changes a local file that is not sent to the remote with a commit/push.

How to include a sub-view in Blade templates?

When you use laravel modules, you may add the name's module:

@include('cimple::shared.posts_list')

How to change port for jenkins window service when 8080 is being used

Restart Jenkins service

Just restart the Jenkins service after you changed the port in jenkins.xml.

  1. Press Win + R
  2. Type "services.msc"
  3. Right click on the "Jenkins" line > Restart

    Restart Jenkins

  4. Type http://localhost:8081/ in your browser to test the change.

How to check the Angular version?

Angular CLI ng v does output few more thing than just the version.

If you only want the version from it the you can add pipe grep and filter for angular like:

ng v | grep 'Angular:'

OUTPUT:

Angular: #.#.# <-- VERSION

For this, I have an alias which is

alias ngv='ng v | grep 'Angular:''

Then just use ngv

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this

 $(function(){
   $("input[type='number']").prop('min',1);
   $("input[type='number']").prop('max',10);
});

Demo

Android - How to decode and decompile any APK file?

You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.

load iframe in bootstrap modal

It seems that your

$(".modal").on('shown.bs.modal')   // One way Or

You can do this in a slight different way, like this

$('.btn').click(function(){
    // Send the src on click of button to the iframe. Which will make it load.
    $(".openifrmahere").find('iframe').attr("src","http://www.hf-dev.info");
    $('.modal').modal({show:true});
    // Hide the loading message
    $(".openifrmahere").find('iframe').load(function() {
        $('.loading').hide();
    });
})

Arduino error: does not name a type?

I found the solution to this problem in a "}". I did some changes to my sketch and forgot to check for "}" and I had an extra one. As soon as I deleted it and compiled everything was fine.

Parsing JSON Object in Java

I'm assuming you want to store the interestKeys in a list.

Using the org.json library:

JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");

List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
    list.add(array.getJSONObject(i).getString("interestKey"));
}

Restart container within pod

We use a pretty convenient command line to force re-deployment of fresh images on integration pod.
We noticed that our alpine containers all run their "sustaining" command on PID 5. Therefore, sending it a SIGTERM signal takes the container down. imagePullPolicy being set to Always has the kubelet re-pull the latest image when it brings the container back.

kubectl exec -i [pod name] -c [container-name] -- kill -15 5

How to compile makefile using MinGW?

You have to actively choose to install MSYS to get the make.exe. So you should always have at least (the native) mingw32-make.exe if MinGW was installed properly. And if you installed MSYS you will have make.exe (in the MSYS subfolder probably).

Note that many projects require first creating a makefile (e.g. using a configure script or automake .am file) and it is this step that requires MSYS or cygwin. Makes you wonder why they bothered to distribute the native make at all.

Once you have the makefile, it is unclear if the native executable requires a different path separator than the MSYS make (forward slashes vs backward slashes). Any autogenerated makefile is likely to have unix-style paths, assuming the native make can handle those, the compiled output should be the same.

bash shell nested for loop

One one line (semi-colons necessary):

for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done

Formatted for legibility (no semi-colons needed):

for i in 0 1 2 3 4 5 6 7 8 9
do
    for j in 0 1 2 3 4 5 6 7 8 9
    do 
        echo "$i$j"
    done
done

There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do (saving two lines here).

Ruby/Rails: converting a Date to a UNIX timestamp

DateTime.new(2012, 1, 15).to_time.to_i

disable Bootstrap's Collapse open/close animation

If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...

Just add this somewhere in your code:

$(document).ready(
    $('.collapse').on('show.bs.collapse hide.bs.collapse', function(e) {
        e.preventDefault();
    }),
    $('[data-toggle="collapse"]').on('click', function(e) {
        e.preventDefault();
        $($(this).data('target')).toggleClass('in');
    })
);

PHP Constants Containing Arrays?

Since PHP 5.6, you can declare an array constant with const:

<?php
const DEFAULT_ROLES = array('guy', 'development team');

The short syntax works too, as you'd expect:

<?php
const DEFAULT_ROLES = ['guy', 'development team'];

If you have PHP 7, you can finally use define(), just as you had first tried:

<?php
define('DEFAULT_ROLES', array('guy', 'development team'));

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

I was having an issue in my project where I was using ng-repeat track by $index but the products were not getting reflecting when data comes from database. My code is as below:

<div ng-repeat="product in productList.productList track by $index">
  <product info="product"></product>
 </div>

In the above code, product is a separate directive to display the product.But i came to know that $index causes issue when we pass data out from the scope. So the data losses and DOM can not be updated.

I found the solution by using product.id as a key in ng-repeat like below:

<div ng-repeat="product in productList.productList track by product.id">
  <product info="product"></product>
 </div>

But the above code again fails and throws the below error when more than one product comes with same id:

angular.js:11706 Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater

So finally i solved the problem by making dynamic unique key of ng-repeat like below:

<div ng-repeat="product in productList.productList track by (product.id + $index)">
  <product info="product"></product>
 </div>

This solved my problem and hope this will help you in future.

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

For Cordova OR Ionic Hybrid App

I have the very similar problem with my Ionic 1 Cordova Build after Integrating the Firebase Cloud Messaging ( FCM )

I fixed this issue by the following steps

So one fix will be: inside platforms/android open project.properties (Its a file ) , you will have something like this

cordova.system.library.1=com.google.android.gms:play-services-ads:+
cordova.system.library.2=com.google.firebase:firebase-core:+
cordova.system.library.3=com.google.firebase:firebase-messaging:+

Replace the

+

Sign with your target version number - like the following

cordova.system.library.1=com.google.android.gms:play-services-ads:9.0.0
cordova.system.library.2=com.google.firebase:firebase-core:9.0.0
cordova.system.library.3=com.google.firebase:firebase-messaging:9.0.0

Save the file

Then take build using

 ionic cordova run android

I hope this will work for everyone

JavaScript alert not working in Android WebView

webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        return super.onJsAlert(view, url, message, result);
    }
});

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

Since GDB 7.5 you can use these native Convenience Functions:

$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)

Seems quite less problematic than having to execute a "foreign" strcmp() on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.

Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running show configuration inside GDB and searching for --with-python. This little oneliner does the trick, too:

$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python'
             --with-python=/usr (relocatable)

For your demo case, the usage would be

break <where> if $_streq(x, "hello")

or, if your breakpoint already exists and you just want to add the condition to it

condition <breakpoint number> $_streq(x, "hello")

$_streq only matches the whole string, so if you want something more cunning you should use $_regex, which supports the Python regular expression syntax.

ReactJS SyntheticEvent stopPropagation() only works with React events?

Worth noting (from this issue) that if you're attaching events to document, e.stopPropagation() isn't going to help. As a workaround, you can use window.addEventListener() instead of document.addEventListener, then event.stopPropagation() will stop event from propagating to the window.

This Handler class should be static or leaks might occur: IncomingHandler

I'm confused. The example I found avoids the static property entirely and uses the UI thread:

    public class example extends Activity {
        final int HANDLE_FIX_SCREEN = 1000;
        public Handler DBthreadHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                int imsg;
                imsg = msg.what;
                if (imsg == HANDLE_FIX_SCREEN) {
                    doSomething();
                }
            }
        };
    }

The thing I like about this solution is there is no problem trying to mix class and method variables.

How to replace all double quotes to single quotes using jquery?

You can also use replaceAll(search, replaceWith) [MDN].

Then, make sure you have a string by wrapping one type of quotes by a different type:

 'a "b" c'.replaceAll('"', "'")
 // result: "a 'b' c"
    
 'a "b" c'.replaceAll(`"`, `'`)
 // result: "a 'b' c"

 // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
 'a "b" c'.replaceAll(/\"/g, "'")
 // result: "a 'b' c"

Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

Junit - run set up method once

I solved this problem like this:

Add to your Base abstract class (I mean abstract class where you initialize your driver in setUpDriver() method) this part of code:

private static boolean started = false;
static{
    if (!started) {
        started = true;
        try {
            setUpDriver();  //method where you initialize your driver
        } catch (MalformedURLException e) {
        }
    }
}

And now, if your test classes will extends from Base abstract class -> setUpDriver() method will be executed before first @Test only ONE time per run.

Sending email in .NET through Gmail

I hope this code will work fine. You can have a try.

// Include this.                
using System.Net.Mail;

string fromAddress = "[email protected]";
string mailPassword = "*****";       // Mail id password from where mail will be sent.
string messageBody = "Write the body of the message here.";


// Create smtp connection.
SmtpClient client = new SmtpClient();
client.Port = 587;//outgoing port for the mail.
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(fromAddress, mailPassword);


// Fill the mail form.
var send_mail = new MailMessage();

send_mail.IsBodyHtml = true;
//address from where mail will be sent.
send_mail.From = new MailAddress("[email protected]");
//address to which mail will be sent.           
send_mail.To.Add(new MailAddress("[email protected]");
//subject of the mail.
send_mail.Subject = "put any subject here";

send_mail.Body = messageBody;
client.Send(send_mail);

Force page scroll position to top at page refresh in HTML

This is one of the best way to do so:

_x000D_
_x000D_
<script>
$(window).on('beforeunload', function() {
  $('body').hide();
  $(window).scrollTop(0);
});
</script>
_x000D_
_x000D_
_x000D_

java : convert float to String and String to float

Float to string - String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

String to Float - Float.parseFloat()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

Seeing if data is normally distributed in R

library(DnE)
x<-rnorm(1000,0,1)
is.norm(x,10,0.05)

How to join (merge) data frames (inner, outer, left, right)

dplyr since 0.4 implemented all those joins including outer_join, but it was worth noting that for the first few releases prior to 0.4 it used not to offer outer_join, and as a result there was a lot of really bad hacky workaround user code floating around for quite a while afterwards (you can still find such code in SO, Kaggle answers, github from that period. Hence this answer still serves a useful purpose.)

Join-related release highlights:

v0.5 (6/2016)

  • Handling for POSIXct type, timezones, duplicates, different factor levels. Better errors and warnings.
  • New suffix argument to control what suffix duplicated variable names receive (#1296)

v0.4.0 (1/2015)

  • Implement right join and outer join (#96)
  • Mutating joins, which add new variables to one table from matching rows in another. Filtering joins, which filter observations from one table based on whether or not they match an observation in the other table.

v0.3 (10/2014)

  • Can now left_join by different variables in each table: df1 %>% left_join(df2, c("var1" = "var2"))

v0.2 (5/2014)

  • *_join() no longer reorders column names (#324)

v0.1.3 (4/2014)

Workarounds per hadley's comments in that issue:

  • right_join(x,y) is the same as left_join(y,x) in terms of the rows, just the columns will be different orders. Easily worked around with select(new_column_order)
  • outer_join is basically union(left_join(x, y), right_join(x, y)) - i.e. preserve all rows in both data frames.

Facebook how to check if user has liked page and show content?

With Javascript SDK, you can change the code as below, this should be added after FB.init call.

     // Additional initialization code such as adding Event Listeners goes here
FB.getLoginStatus(function(response) {
      if (response.status === 'connected') {
        // the user is logged in and has authenticated your
        // app, and response.authResponse supplies
        // the user's ID, a valid access token, a signed
        // request, and the time the access token 
        // and signed request each expire
        var uid = response.authResponse.userID;
        var accessToken = response.authResponse.accessToken;
        alert('we are fine');
      } else if (response.status === 'not_authorized') {
        // the user is logged in to Facebook, 
        // but has not authenticated your app
        alert('please like us');
         $("#container_notlike").show();
      } else {
        // the user isn't logged in to Facebook.
        alert('please login');
      }
     });

FB.Event.subscribe('edge.create',
function(response) {
    alert('You liked the URL: ' + response);
      $("#container_like").show();
}

How to increase MySQL connections(max_connections)?

I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:

  1. in the navigator (on the left side), under the section "management", click on "Status and System variables",
  2. then choose "system variables" (tab at the top),
  3. then search for "connection" in the search field,
  4. and 5. you will see two fields that need to be adjusted to fit your needs (max_connections and mysqlx_max_connections).

Hope that helps!

The system does not allow me to upload pictures, instead please click on this link and you can see my screenshot...

Using CSS to align a button bottom of the screen using relative positions

<button style="position: absolute; left: 20%; right: 20%; bottom: 5%;"> Button </button>

Kubernetes Pod fails with CrashLoopBackOff

I faced similar issue "CrashLoopBackOff" when I debugged getting pods and logs of pod. Found out that my command arguments are wrong

C++11 thread-safe queue

You may like lfqueue, https://github.com/Taymindis/lfqueue. It’s lock free concurrent queue. I’m currently using it to consuming the queue from multiple incoming calls and works like a charm.

How to bundle vendor scripts separately and require them as needed with Webpack?

In case you're interested in bundling automatically your scripts separately from vendors ones:

var webpack = require('webpack'),
    pkg     = require('./package.json'),  //loads npm config file
    html    = require('html-webpack-plugin');

module.exports = {
  context : __dirname + '/app',
  entry   : {
    app     : __dirname + '/app/index.js',
    vendor  : Object.keys(pkg.dependencies) //get npm vendors deps from config
  },
  output  : {
    path      : __dirname + '/dist',
    filename  : 'app.min-[hash:6].js'
  },
  plugins: [
    //Finally add this line to bundle the vendor code separately
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.min-[hash:6].js'),
    new html({template : __dirname + '/app/index.html'})
  ]
};

You can read more about this feature in official documentation.

How to detect when a UIScrollView has finished scrolling

I had a case of tapping and dragging actions and I found out that the dragging was calling scrollViewDidEndDecelerating

And the change offset manually with code ([_scrollView setContentOffset:contentOffset animated:YES];) was calling scrollViewDidEndScrollingAnimation.

//This delegate method is called when the dragging scrolling happens, but no when the     tapping
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //do whatever you want to happen when the scroll is done
}

//This delegate method is called when the tapping scrolling happens, but no when the  dragging
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
     //do whatever you want to happen when the scroll is done
}

Pandas - Get first row value of a given column

Another way of getting the first row and preserving the index:

x = df.first('d') # Returns the first day. '3d' gives first three days.

How to send data in request body with a GET when using jQuery $.ajax()

Just in case somebody ist still coming along this question:

There is a body query object in any request. You do not need to parse it yourself.

E.g. if you want to send an accessToken from a client with GET, you could do it like this:

_x000D_
_x000D_
const request = require('superagent');_x000D_
_x000D_
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {_x000D_
  if (err) throw new Error(err);_x000D_
  console.log(res);_x000D_
});
_x000D_
_x000D_
_x000D_

The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

If hasClass then addClass to parent

You probably want to change the condition to if ($(this).hasClass('active'))

Also, hasClass and addClass take classnames, not selectors.
Therefore, you shouldn't include a ..

How to print jquery object/array

I was having similar problem and

var dataObj = JSON.parse(data);

console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie

This solved my problem. Thanks Selvakumar Arumugam

Display JSON Data in HTML Table

HTML:
 <div id="container"></div>   
JS:


$('#search').click(function() {
    $.ajax({
        type: 'POST',
        url: 'cityResults.htm',
        data: $('#cityDetails').serialize(),
        dataType:"json", //to parse string into JSON object,
        success: function(data){ 

                var len = data.length;
                var txt = "";
                if(len > 0){
                    for(var i=0;i<len;i++){

                            txt = "<tr><td>"+data[i].city+"</td><td>"+data[i].cStatus+"</td></tr>";
                            $("#container").append(txt);
                    }



        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('error: ' + textStatus + ': ' + errorThrown);
        }
    });
    return false;
});

Hibernate JPA Sequence (non-Id)

I know this is a very old question, but it's showed firstly upon the results and jpa has changed a lot since the question.

The right way to do it now is with the @Generated annotation. You can define the sequence, set the default in the column to that sequence and then map the column as:

@Generated(GenerationTime.INSERT)
@Column(name = "column_name", insertable = false)

How can I format a list to print each element on a separate line in python?

Use str.join:

In [27]: mylist = ['10', '12', '14']

In [28]: print '\n'.join(mylist)
10
12
14

Difference between HashSet and HashMap?

HashMaps allow one null key and null values. They are not synchronized, which increases efficiency. If it is required, you can make them synchronized using Collections.SynchronizedMap()

Hashtables don't allow null keys and are synchronized.

Mockito - difference between doReturn() and when()

The two syntaxes for stubbing are roughly equivalent. However, you can always use doReturn/when for stubbing; but there are cases where you can't use when/thenReturn. Stubbing void methods is one such. Others include use with Mockito spies, and stubbing the same method more than once.

One thing that when/thenReturn gives you, that doReturn/when doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test.

I strongly recommend only using doReturn/when. There is no point in learning two syntaxes when one will do.

You may wish to refer to my answer at Forming Mockito "grammars" - a more detailed answer to a very closely related question.

How do I retrieve query parameters in Spring Boot?

While the accepted answer by afraisse is absolutely correct in terms of using @RequestParam, I would further suggest to use an Optional<> as you cannot always ensure the right parameter is used. Also, if you need an Integer or Long just use that data type to avoid casting types later on in the DAO.

@RequestMapping(value="/data", method = RequestMethod.GET)
public @ResponseBody
Item getItem(@RequestParam("itemid") Optional<Integer> itemid) { 
    if( itemid.isPresent()){
         Item i = itemDao.findOne(itemid.get());              
         return i;
     } else ....
}

How to save an HTML5 Canvas as an image on a server?

I just made an imageCrop and Upload feature with

https://www.npmjs.com/package/react-image-crop

to get the ImagePreview ( the cropped image rendering in a canvas)

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95);

I prefer sending data in blob with content type image/jpeg rather than toDataURL ( a huge base64 string`

My implementation for uploading to Azure Blob using SAS URL

axios.post(azure_sas_url, image_in_blob, {
   headers: {
      'x-ms-blob-type': 'BlockBlob',
      'Content-Type': 'image/jpeg'
   }
})

Check if datetime instance falls in between other two datetime objects

You can, use:

if (date >= startDate && date<= EndDate) { return true; }

cleanup php session files

# Every 30 minutes, not on the hour<br>
# Grabs maxlifetime directly from \`php -i\`<br>
# doesn't care if /var/lib/php5 exists, errs go to /dev/null<br>

09,39 * * * *   find /var/lib/php5/ -type f -cmin +$(echo "\`php -i|grep -i session.gc_maxlifetime|cut -d' ' -f3\` / 60" | bc) -exec rm -f {} \\; >/dev/null 2>&1

The Breakdown: Only files: find /var/lib/php5/ -type f
Older than minutes: -cmin
Get php settings: $(echo "`php -i|grep -i session.gc_maxlifetime
Do the math: |cut -d' ' -f3` / 60" | bc)
RM matching files: -exec rm -f {} \;

What are the -Xms and -Xmx parameters when starting JVM?

-Xms initial heap size for the startup, however, during the working process the heap size can be less than -Xms due to users' inactivity or GC iterations. This is not a minimal required heap size.

-Xmx maximal heap size

Populate XDocument from String

How about this...?

TextReader tr = new StringReader("<Root>Content</Root>");
XDocument doc = XDocument.Load(tr);
Console.WriteLine(doc);

This was taken from the MSDN docs for XDocument.Load, found here...

http://msdn.microsoft.com/en-us/library/bb299692.aspx

How to change context root of a dynamic web project in Eclipse?

If the project is maven, change the "finalName" in pom.xml and Update Project as Maven.This worked for me.

Difference between frontend, backend, and middleware in web development

Here is a real world example which shows front/mid/back end.

General description:

  • Frontend is responsible for presenting data to user. Please note interesting quirk that you may have two different front ends associated with single backend
  • Backend provides business logic/data persistence.
  • Middleware (activemq in the picture) is responsible for system to system. integration between backends. Usually it is installed as separate application enter image description here

Overlapping:

It is possible to have overlapping between frontend and backend. This usually leaads to long-term issues with application maintenance and scalability. Fairly common in legacy applications.

Most modern technology stacks encourage developers to have strict separation. For example in the picture you can see that backend of the first system has rest web service which is a clear separation line.

Bottlenecks

Most bottlenecks in large are caused by database/network. Databases are located in backend. As for network issues every connection goes through netowrk, so every connection has potential for being slow. With good application design these issues are avoidable to large extend.

How do I convert a double into a string in C++?

The Standard C++11 way (if you don't care about the output format):

#include <string>

auto str = std::to_string(42.5); 

to_string is a new library function introduced in N1803 (r0), N1982 (r1) and N2408 (r2) "Simple Numeric Access". There are also the stod function to perform the reverse operation.

If you do want to have a different output format than "%f", use the snprintf or ostringstream methods as illustrated in other answers.

Which is more efficient, a for-each loop, or an iterator?

The foreach underhood is creating the iterator, calling hasNext() and calling next() to get the value; The issue with the performance comes only if you are using something that implements the RandomomAccess.

for (Iterator<CustomObj> iter = customList.iterator(); iter.hasNext()){
   CustomObj custObj = iter.next();
   ....
}

Performance issues with the iterator-based loop is because it is:

  1. allocating an object even if the list is empty (Iterator<CustomObj> iter = customList.iterator(););
  2. iter.hasNext() during every iteration of the loop there is an invokeInterface virtual call (go through all the classes, then do method table lookup before the jump).
  3. the implementation of the iterator has to do at least 2 fields lookup in order to make hasNext() call figure the value: #1 get current count and #2 get total count
  4. inside the body loop, there is another invokeInterface virtual call iter.next(so: go through all the classes and do method table lookup before the jump) and as well has to do fields lookup: #1 get the index and #2 get the reference to the array to do the offset into it (in every iteration).

A potential optimiziation is to switch to an index iteration with the cached size lookup:

for(int x = 0, size = customList.size(); x < size; x++){
  CustomObj custObj = customList.get(x);
  ...
}

Here we have:

  1. one invokeInterface virtual method call customList.size() on the initial creation of the for loop to get the size
  2. the get method call customList.get(x) during the body for loop, which is a field lookup to the array and then can do the offset into the array

We reduced a ton of method calls, field lookups. This you don't want to do with LinkedList or with something that is not a RandomAccess collection obj, otherwise the customList.get(x) is gonna turn into something that has to traverse the LinkedList on every iteration.

This is perfect when you know that is any RandomAccess based list collection.

Java: how to use UrlConnection to post request with authorization?

A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead.

Below is the code to do that,

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty ("Authorization", encodedCredentials);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(data);
    writer.flush();
    String line;
    BufferedReader reader = new BufferedReader(new 
                                     InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    writer.close();
    reader.close();

Change URLConnection to HttpURLConnection, to make it POST request.

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

Suggestion (...in comments):

You might need to set these properties too,

conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );

Collectors.toMap() keyMapper -- more succinct expression?

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
roster
    .stream()
    .collect(
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)
    );