Programs & Examples On #Asp.net mvc routing

Questions about routing within ASP.NET (including MVC).

Set "Homepage" in Asp.Net MVC

I tried the answer but it didn't worked for me. This is what i ended up doing:

Create a new controller DefaultController. In index action, i wrote one line redirect:

return Redirect("~/Default.aspx")

In RouteConfig.cs, change controller="Default" for the route.

 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
        );

ASP.NET MVC - Extract parameter of an URL

Update

RouteData.Values["id"] + Request.Url.Query

Will match all your examples


It is not entirely clear what you are trying to achieve. MVC passes URL parameters for you through model binding.

public class CustomerController : Controller {

  public ActionResult Edit(int id) {

    int customerId = id //the id in the URL

    return View();
  }

}


public class ProductController : Controller {

  public ActionResult Edit(int id, bool allowed) { 

    int productId = id; // the id in the URL
    bool isAllowed = allowed  // the ?allowed=true in the URL

    return View();
  }

}

Adding a route mapping to your global.asax.cs file before the default will handle the /administration/ part. Or you might want to look into MVC Areas.

routes.MapRoute(
  "Admin", // Route name
  "Administration/{controller}/{action}/{id}", // URL with parameters
  new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

If it's the raw URL data you are after then you can use one of the various URL and Request properties available in your controller action

string url = Request.RawUrl;
string query= Request.Url.Query;
string isAllowed= Request.QueryString["allowed"];

It sounds like Request.Url.PathAndQuery could be what you want.

If you want access to the raw posted data you can use

string isAllowed = Request.Params["allowed"];
string id = RouteData.Values["id"];

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

I hate answering my own question, but @Matt Bodily put me on the right track.

The @Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)

Note: , null is significant in this case, to match the right signature.

Documentation: @Html.ActionLink (LinkExtensions.ActionLink)

Documentation for this particular overload:

LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)

It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.

Still marking Matt's response as the answer.

Edit: Found yet another HTML helper to solve this:

@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })

The view 'Index' or its master was not found.

If You can get this error even with all the correct MapRoutes in your area registration and all other basic configurations are fine.

This is the situation:

I have used below mentioned code from Jquery file to post back data and then load a view from controller action method.

$.post("/Customers/ReturnRetailOnlySales", {petKey: '<%: Model.PetKey %>'}); 

Above jQuery code I didn't mentioned success callback function. What was happened there is after finishing a post back scenario on action method, without routing to my expected view it came back to Jquery side and gave view not found error as above.

Then I gave a solution like below and its working without any problem.

 $.post("/Customers/ReturnRetailOnlySales", {petKey: '<%: Model.PetKey %>'},
      function (data) {
 var url = Sys.Url.route('PetDetail', { action: "ReturnRetailOnlySalesItems", controller: "Customers",petKey: '<%: Model.PetKey %>'});
 window.location = url;});   

Note: I sent my request inside the success callback function to my expected views action method.Then view engine found a relevant area's view file and load correctly.

Routing for custom ASP.NET MVC 404 Error page

Source

NotFoundMVC - Provides a user-friendly 404 page whenever a controller, action or route is not found in your ASP.NET MVC3 application. A view called NotFound is rendered instead of the default ASP.NET error page.

You can add this plugin via nuget using: Install-Package NotFoundMvc

NotFoundMvc automatically installs itself during web application start-up. It handles all the different ways a 404 HttpException is usually thrown by ASP.NET MVC. This includes a missing controller, action and route.

Step by Step Installation Guide :

1 - Right click on your Project and Select Manage Nuget Packages...

2 - Search for NotFoundMvc and install it. enter image description here

3 - Once the installation has be completed, two files will be added to your project. As shown in the screenshots below.

enter image description here

4 - Open the newly added NotFound.cshtml present at Views/Shared and modify it at your will. Now run the application and type in an incorrect url, and you will be greeted with a User friendly 404 page.

enter image description here

No more, will users get errors message like Server Error in '/' Application. The resource cannot be found.

Hope this helps :)

P.S : Kudos to Andrew Davey for making such an awesome plugin.

npm install hangs

I was having the same problem. I tried a

npm config set registry http://registry.npmjs.org/

to turn off https. I also tried

npm set progress=false 

to turn off the progress bar (it has been reported to slow down downloads).

The problem was with my network driver. I just needed to reboot and the lag went away.

Excel VBA to Export Selected Sheets to PDF

Once you have Selected a group of sheets, you can use Selection

Consider:

Sub luxation()
    ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
    Selection.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:="C:\TestFolder\temp.pdf", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub

EDIT#1:

Further testing has reveled that this technique depends on the group of cells selected on each worksheet. To get a comprehensive output, use something like:

Sub Macro1()

   Sheets("Sheet1").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet2").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet3").Activate
   ActiveSheet.UsedRange.Select

   ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
   Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
      "C:\Users\James\Desktop\pdfmaker.pdf", Quality:=xlQualityStandard, _
      IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
      True
End Sub

UnicodeDecodeError, invalid continuation byte

In binary, 0xE9 looks like 1110 1001. If you read about UTF-8 on Wikipedia, you’ll see that such a byte must be followed by two of the form 10xx xxxx. So, for example:

>>> b'\xe9\x80\x80'.decode('utf-8')
u'\u9000'

But that’s just the mechanical cause of the exception. In this case, you have a string that is almost certainly encoded in latin 1. You can see how UTF-8 and latin 1 look different:

>>> u'\xe9'.encode('utf-8')
b'\xc3\xa9'
>>> u'\xe9'.encode('latin-1')
b'\xe9'

(Note, I'm using a mix of Python 2 and 3 representation here. The input is valid in any version of Python, but your Python interpreter is unlikely to actually show both unicode and byte strings in this way.)

Cell Style Alignment on a range

  ExcelApp.Sheets[1].Range[ExcelApp.Sheets[1].Cells[1, 1], ExcelApp.Sheets[1].Cells[70, 15]].Cells.HorizontalAlignment =
                 Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

This works fine for me.

Find all table names with column name?

You could do this:

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;

Reference:

Intent from Fragment to Activity

in your receiving intent use as

Intent intent = getActivity().getIntent();
        ((TextView)view.findViewById(R.id.hello)).setText(intent.getStringExtra("Hello"));

and in your send intent

Intent intent = new Intent(getActivity(),Main2Activity.class);
        intent.putExtra("Hello","Nisar");
        getActivity().startActivity(intent);

remember both are in fragments

How do I overload the [] operator in C#

The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.

For example, in your case where an int is the key or index:

public int this[int index]
{
    get => GetValue(index);
}

You can also add a set accessor so that the indexer becomes read and write rather than just read-only.

public int this[int index]
{
    get => GetValue(index);
    set => SetValue(index, value);
}

If you want to index using a different type, you just change the signature of the indexer.

public int this[string index]
...

window.open with target "_blank" in Chrome

window.open(skey, "_blank", "toolbar=1, scrollbars=1, resizable=1, width=" + 1015 + ", height=" + 800);

EXCEL VBA Check if entry is empty or not 'space'

You can use the following code to check if a textbox object is null/empty

'Checks if the box is null

If Me.TextBox & "" <> "" Then

        'Enter Code here...

End if

"The operation is not valid for the state of the transaction" error and transaction scope

I've encountered this error when my Transaction is nested within another. Is it possible that the stored procedure declares its own transaction or that the calling function declares one?

Listing all extras of an Intent

The get(String key) method of Bundle returns an Object. Your best bet is to spin over the key set calling get(String) on each key and using toString() on the Object to output them. This will work best for primitives, but you may run into issues with Objects that do not implement a toString().

Asking the user for input until they give a valid response

You can always apply simple if-else logic and add one more if logic to your code along with a for loop.

while True:
     age = int(input("Please enter your age: "))
     if (age >= 18)  : 
         print("You are able to vote in the United States!")
     if (age < 18) & (age > 0):
         print("You are not able to vote in the United States.")
     else:
         print("Wrong characters, the input must be numeric")
         continue

This will be an infinite loo and you would be asked to enter the age, indefinitely.

Count items in a folder with PowerShell

To count the number of a specific filetype in a folder. The example is to count mp3 files on F: drive.

( Get-ChildItme F: -Filter *.mp3 - Recurse | measure ).Count

Tested in 6.2.3, but should work >4.

Check if application is on its first run

The following is an example of using SharedPreferences to achieve a 'forWhat' check.

    preferences = PreferenceManager.getDefaultSharedPreferences(context);
    preferencesEditor = preferences.edit();
public static boolean isFirstRun(String forWhat) {
    if (preferences.getBoolean(forWhat, true)) {
        preferencesEditor.putBoolean(forWhat, false).commit();
        return true;
    } else {
        return false;
    }
}

Regular expressions in C: examples?

While the answer above is good, I recommend using PCRE2. This means you can literally use all the regex examples out there now and not have to translate from some ancient regex.

I made an answer for this already, but I think it can help here too..

Regex In C To Search For Credit Card Numbers

// YOU MUST SPECIFY THE UNIT WIDTH BEFORE THE INCLUDE OF THE pcre.h

#define PCRE2_CODE_UNIT_WIDTH 8
#include <stdio.h>
#include <string.h>
#include <pcre2.h>
#include <stdbool.h>

int main(){

bool Debug = true;
bool Found = false;
pcre2_code *re;
PCRE2_SPTR pattern;
PCRE2_SPTR subject;
int errornumber;
int i;
int rc;
PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector;
size_t subject_length;
pcre2_match_data *match_data;


char * RegexStr = "(?:\\D|^)(5[1-5][0-9]{2}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4})(?:\\D|$)";
char * source = "5111 2222 3333 4444";

pattern = (PCRE2_SPTR)RegexStr;// <<<<< This is where you pass your REGEX 
subject = (PCRE2_SPTR)source;// <<<<< This is where you pass your bufer that will be checked. 
subject_length = strlen((char *)subject);




  re = pcre2_compile(
  pattern,               /* the pattern */
  PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
  0,                     /* default options */
  &errornumber,          /* for error number */
  &erroroffset,          /* for error offset */
  NULL);                 /* use default compile context */

/* Compilation failed: print the error message and exit. */
if (re == NULL)
  {
  PCRE2_UCHAR buffer[256];
  pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
  printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,buffer);
  return 1;
  }


match_data = pcre2_match_data_create_from_pattern(re, NULL);

rc = pcre2_match(
  re,
  subject,              /* the subject string */
  subject_length,       /* the length of the subject */
  0,                    /* start at offset 0 in the subject */
  0,                    /* default options */
  match_data,           /* block for storing the result */
  NULL);

if (rc < 0)
  {
  switch(rc)
    {
    case PCRE2_ERROR_NOMATCH: //printf("No match\n"); //
    pcre2_match_data_free(match_data);
    pcre2_code_free(re);
    Found = 0;
    return Found;
    //  break;
    /*
    Handle other special cases if you like
    */
    default: printf("Matching error %d\n", rc); //break;
    }
  pcre2_match_data_free(match_data);   /* Release memory used for the match */
  pcre2_code_free(re);
  Found = 0;                /* data and the compiled pattern. */
  return Found;
  }


if (Debug){
ovector = pcre2_get_ovector_pointer(match_data);
printf("Match succeeded at offset %d\n", (int)ovector[0]);

if (rc == 0)
  printf("ovector was not big enough for all the captured substrings\n");


if (ovector[0] > ovector[1])
  {
  printf("\\K was used in an assertion to set the match start after its end.\n"
    "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
      (char *)(subject + ovector[1]));
  printf("Run abandoned\n");
  pcre2_match_data_free(match_data);
  pcre2_code_free(re);
  return 0;
}

for (i = 0; i < rc; i++)
  {
  PCRE2_SPTR substring_start = subject + ovector[2*i];
  size_t substring_length = ovector[2*i+1] - ovector[2*i];
  printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
  }
}

else{
  if(rc > 0){
    Found = true;

    } 
} 
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return Found;

}

Install PCRE using:

wget https://ftp.pcre.org/pub/pcre/pcre2-10.31.zip
make 
sudo make install 
sudo ldconfig

Compile using :

gcc foo.c -lpcre2-8 -o foo

Check my answer for more details.

Eclipse can't find / load main class

I have solved the issue following way:

Go to Run Configuration (Right Click on Java File->Run->Run Configuration).

Go to ClassPath Tab: Click on Advanced -> Add Folders -> Add bin directory (which has class file in it for Java source code)

Re run the code, now it will solve the issue. It worked for me

RuntimeError on windows trying python multiprocessing

Though the earlier answers are correct, there's a small complication it would help to remark on.

In case your main module imports another module in which global variables or class member variables are defined and initialized to (or using) some new objects, you may have to condition that import in the same way:

if __name__ ==  '__main__':
  import my_module

Remove .php extension with .htaccess

The following code works fine for me:

RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

HTML <sup /> tag affecting line height, how to make it consistent?

Specially use this on newsletter -

<sup style="font-size:9px; line-height:8px;">&reg;</sup>

How to add include and lib paths to configure/make cycle?

This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf

Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.

After successfully running autogen.sh/configure, compile with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make

The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.

I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.

How can I increment a char?

def doubleChar(str):
    result = ''
    for char in str:
        result += char * 2
    return result

print(doubleChar("amar"))

output:

aammaarr

How do I create a SQL table under a different schema?

The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.

USE [DBName] 
GO 
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema] 
GO

Android, How to create option Menu

import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

public class AndroidWalkthroughApp2 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // show menu when menu button is pressed
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // display a message when a button was pressed
        String message = "";
        if (item.getItemId() == R.id.option1) {
            message = "You selected option 1!";
        }
        else if (item.getItemId() == R.id.option2) {
            message = "You selected option 2!";
        }
        else {
            message = "Why would you select that!?";
        }

        // show message via toast
        Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
        toast.show();

        return true;
    }
}

Sort matrix according to first column in R

Be aware that if you want to have values in the reverse order, you can easily do so:

> example = matrix(c(1,1,1,4,3,3,2,349,393,392,459,49,32,94), ncol = 2)
> example[order(example[,1], decreasing = TRUE),]
     [,1] [,2]
[1,]    4  459
[2,]    3   49
[3,]    3   32
[4,]    2   94
[5,]    1  349
[6,]    1  393
[7,]    1  392

Ascending and Descending Number Order in java

You can sort the array first, and then loop through it twice, once in both directions:

Arrays.sort(arr); 
System.out.print("Numbers in Ascending Order:" ); 
for(int i = 0; i < arr.length; i++){ 
  System.out.print( " " + arr[i]); 
} 
System.out.print("Numbers in Descending Order: " ); 
for(int i = arr.length - 1; i >= 0; i--){ 
  System.out.print( " " + arr[i]); 
} 

How to use __doPostBack()

I'd just like to add something to this post for asp:button. I've tried clientId and it doesn't seem to work for me:

__doPostBack('<%= btn.ClientID%>', '');

However, getting the UniqueId seems to post back to the server, like below:

__doPostBack('<%= btn.UniqueID%>', '');

This might help someone else in future, hence posting this.

how to convert current date to YYYY-MM-DD format with angular 2

Try this below code it is also works well in angular 2

<span>{{current_date | date: 'yyyy-MM-dd'}}</span>

Simple linked list in C++

You should take reference of a head pointer. Otherwise the pointer modification is not visible outside of the function.

void addNode(struct Node *&head, int n){
    struct Node *NewNode = new Node;
 NewNode-> x = n;
 NewNode -> next = head;
 head = NewNode;
}

How do I get the current absolute URL in Ruby on Rails?

To get the absolute URL which means that the from the root it can be displayed like this

<%= link_to 'Edit', edit_user_url(user) %>

The users_url helper generates a URL that includes the protocol and host name. The users_path helper generates only the path portion.

users_url: http://localhost/users
users_path: /users

Javascript | Set all values of an array

The ES6 approach is very clean. So first you initialize an array of x length, and then call the fill method on it.

let arr = new Array(3).fill(9)

this will create an array with 3 elements like:

[9, 9, 9]

How to make bootstrap 3 fluid layout without horizontal scrollbar

I ran in to the same problem (wanting a fluid layout) but wanted to keep the responsive options with rearranging columns and so on for smaller screens and ended up with a small change to in variables.less:

// Large screen / wide desktop  (last row of file)
@container-lg-desktop:        100%; //((1140px + @grid-gutter-width));

This value is used once in grid.less and sets

@media (min-width: @screen-lg-desktop) {
  .container {
    max-width: @container-lg-desktop;
  }
  ....
}

The result is that over 1200px the grid is fluid (without horizontal scrollbars). Below that the normal responsive rules apply. You can of course set this to other media queries as well just as easily.

If you do not want to edit and compile .less yourself you could override the maxwidth in your own style sheet similair to below:

@media (min-width: 1200px) {  /* or min-width: wherever-you-want-your-fluid-breakpoint */
  body .container {
    max-width: 100%;
  }
}

All this assumes you use the normal Bootstrap grid syntax, including container, like below:

<div class="container">
  <div class="row" >
    <div class="col-md-6">.col-md-6</div>
    <div class="col-md-6">.col-md-6</div>
  </div>
</div>

Hope this helps!

How to Detect Browser Back Button event - Cross Browser

I was able to use some of the answers in this thread and others to get it working in IE and Chrome/Edge. history.pushState for me wasn't supported in IE11.

if (history.pushState) {
    //Chrome and modern browsers
    history.pushState(null, document.title, location.href);
    window.addEventListener('popstate', function (event) {
        history.pushState(null, document.title, location.href);
    });
}
else {
    //IE
    history.forward();
}

Link to download apache http server for 64bit windows.

An unofficial 64-bit Windows build is available from Apache Lounge.

how to check for special characters php

<?php

$string = 'foo';

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
{
    // one or more of the 'special characters' found in $string
}

Is it possible to Turn page programmatically in UIPageViewController?

For single page, I just edited the answer of @Jack Humphries

-(void)viewDidLoad
{
  counter = 0;
}
-(IBAction)buttonClick:(id)sender
{
  counter++;
  DataViewController *secondVC = [self.modelController viewControllerAtIndex:counter storyboard:self.storyboard];
  NSArray *viewControllers = nil;          
  viewControllers = [NSArray arrayWithObjects:secondVC, nil];          
  [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
}

How to send and receive JSON data from a restful webservice using Jersey API

Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.

@Path("/hello")
public class Hello {

  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {

    String input = (String) inputJsonObj.get("input");
    String output = "The input you sent is :" + input;
    JSONObject outputJsonObj = new JSONObject();
    outputJsonObj.put("output", output);

    return outputJsonObj;
  }
}

And, your client code should look like this:

  ClientConfig config = new DefaultClientConfig();
  Client client = Client.create(config);
  client.addFilter(new LoggingFilter());
  WebResource service = client.resource(getBaseURI());
  JSONObject inputJsonObj = new JSONObject();
  inputJsonObj.put("input", "Value");
  System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));

ArrayBuffer to base64 encoded string

My recommendation for this is to NOT use native btoa strategies—as they don't correctly encode all ArrayBuffer's…

rewrite the DOMs atob() and btoa()

Since DOMStrings are 16-bit-encoded strings, in most browsers calling window.btoa on a Unicode string will cause a Character Out Of Range exception if a character exceeds the range of a 8-bit ASCII-encoded character.

While I have never encountered this exact error, I have found that many of the ArrayBuffer's I have tried to encode have encoded incorrectly.

I would either use MDN recommendation or gist.

How do I create a shortcut via command-line in Windows?

Cannot be done with pure batch.Check the shortcutJS.bat - it is a jscript/bat hybrid and should be used with .bat extension:

call shortcutJS.bat -linkfile "%~n0.lnk" -target  "%~f0" -linkarguments "some arguments"

With -help you can check the other options (you can set icon , admin permissions and etc.)

View stored procedure/function definition in MySQL

SHOW CREATE PROCEDURE <name>

Returns the text of a previously defined stored procedure that was created using the CREATE PROCEDURE statement. Swap PROCEDURE for FUNCTION for a stored function.

How do I bind the enter key to a function in tkinter?

Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")
root.bind('<Return>', func)

def onclick():
    print("You clicked the button")

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Then you just have tweak things a little when making both the button click and hitting Return call the same function--because the command function needs to be a function that takes no arguments, whereas the bind function needs to be a function that takes one argument(the event object):

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event=None):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Or, you can just forgo using the button's command argument and instead use bind() to attach the onclick function to the button, which means the function needs to take one argument--just like with Return:

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me")
button.bind('<Button-1>', onclick)
button.pack()

root.mainloop()

Here it is in a class setting:

import tkinter as tk

class Application(tk.Frame):
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("300x200")

        tk.Frame.__init__(self, self.root)
        self.create_widgets()

    def create_widgets(self):
        self.root.bind('<Return>', self.parse)
        self.grid()

        self.submit = tk.Button(self, text="Submit")
        self.submit.bind('<Button-1>', self.parse)
        self.submit.grid()

    def parse(self, event):
        print("You clicked?")

    def start(self):
        self.root.mainloop()


Application().start()

How to run Gradle from the command line on Mac bash

Also, if you don't have the gradlew file in your current directory:

You can install gradle with homebrew with the following command:

$ brew install gradle

As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):

$ gradle test 

PHP: date function to get month of the current date

as date_format uses the same format as date ( http://www.php.net/manual/en/function.date.php ) the "Numeric representation of a month, without leading zeros" is a lowercase n .. so

echo date('n'); // "9"

How do I convert a String to an int in Java?

import java.util.*;

public class strToint {

    public static void main(String[] args) {

        String str = "123";
        byte barr[] = str.getBytes();

        System.out.println(Arrays.toString(barr));
        int result = 0;

        for(int i = 0; i < barr.length; i++) {
            //System.out.print(barr[i]+" ");
            int ii = barr[i];
            char a = (char) ii;
            int no = Character.getNumericValue(a);
            result = result * 10 + no;
            System.out.println(result);
        }

        System.out.println("result:"+result);
    }
}

Why write <script type="text/javascript"> when the mime type is set by the server?

Because, at least in HTML 4.01 and XHTML 1(.1), the type attribute for <script> elements is required.

In HTML 5, type is no longer required.

In fact, while you should use text/javascript in your HTML source, many servers will send the file with Content-type: application/javascript. Read more about these MIME types in RFC 4329.

Notice the difference between RFC 4329, that marked text/javascript as obsolete and recommending the use of application/javascript, and the reality in which some browsers freak out on <script> elements containing type="application/javascript" (in HTML source, not the HTTP Content-type header of the file that gets send). Recently, there was a discussion on the WHATWG mailing list about this discrepancy (HTML 5's type defaults to text/javascript), read these messages with subject Will you consider about RFC 4329?

NSURLConnection Using iOS Swift

Check Below Codes :

1. SynchronousRequest

Swift 1.2

    let urlPath: String = "YOUR_URL_HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)
    var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
    var err: NSError
    println(response)
    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary
    println("Synchronous\(jsonResult)")

Swift 2.0 +

let urlPath: String = "YOUR_URL_HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSURLRequest = NSURLRequest(URL: url)
    let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil


    do{

        let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)

            print(response)
            do {
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
                    print("Synchronous\(jsonResult)")
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }



    }catch let error as NSError
    {
         print(error.localizedDescription)
    }

2. AsynchonousRequest

Swift 1.2

let urlPath: String = "YOUR_URL_HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)
    let queue:NSOperationQueue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var err: NSError
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("Asynchronous\(jsonResult)")
       })

Swift 2.0 +

let urlPath: String = "YOUR_URL_HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSURLRequest = NSURLRequest(URL: url)
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

3. As usual URL connection

Swift 1.2

    var dataVal = NSMutableData()
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
    connection.start()

Then

 func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.dataVal?.appendData(data)
}


func connectionDidFinishLoading(connection: NSURLConnection!)
{
    var error: NSErrorPointer=nil

    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary

    println(jsonResult)



}

Swift 2.0 +

   var dataVal = NSMutableData()
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
    connection.start()

Then

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    dataVal.appendData(data)
}


func connectionDidFinishLoading(connection: NSURLConnection!)
{

    do {
        if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
            print(jsonResult)
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }

}

4. Asynchronous POST Request

Swift 1.2

    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
     var stringPost="deviceToken=123456" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in


        var err: NSError

        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")


        })

Swift 2.0 +

let urlPath: String = "YOUR URL HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
    let stringPost="deviceToken=123456" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

5. Asynchronous GET Request

Swift 1.2

    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "GET"
    request1.timeoutInterval = 60
    let queue:NSOperationQueue = NSOperationQueue()

     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in


        var err: NSError

        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")


        })

Swift 2.0 +

let urlPath: String = "YOUR URL HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "GET"
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

6. Image(File) Upload

Swift 2.0 +

  let mainURL = "YOUR_URL_HERE"

    let url = NSURL(string: mainURL)
    let request = NSMutableURLRequest(URL: url!)
    let boundary = "78876565564454554547676"
    request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


    request.HTTPMethod = "POST" // POST OR PUT What you want
    let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)

    let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)





    var body = NSMutableData()

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    // Append your parameters

    body.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


    // Append your Image/File Data

    var imageNameval = "HELLO.jpg"

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(imageData!)
    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    request.HTTPBody = body




    let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

        if error != nil {

            //handle error


        }
        else {




            let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!
            print("Response:\(outputString)")


        }
    }
    dataTask.resume()

7. GET,POST,Etc Swift 3.0 +

let request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE" ,param: param))!,
    cachePolicy: .useProtocolCachePolicy,
    timeoutInterval:60)
request.httpMethod = "POST" // POST ,GET, PUT What you want 

let session = URLSession.shared



  let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in

do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

    }
    dataTask.resume()

CSS @media print issues with background-color;

There is another trick you can do without activating the print border option mentioned in other posts. Since borders are printed you can simulate solid background-colors with this hack:

.your-background:before {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  z-index: -1;
  border-bottom: 1000px solid #eee; /* Make it fit your needs */
}

Activate it by adding the class to your element:

<table>
  <tr>
    <td class="your-background">&nbsp;</td>
    <td class="your-background">&nbsp;</td>
    <td class="your-background">&nbsp;</td>
  </tr>
</table>

Although this needs some extra code and some extra care to make background-colors visible, it is yet the only solution known to me.

Notice this hack won't work on elements other than display: block; or display: table-cell;, so for example <table class="your-background"> and <tr class="your-background"> won't work.

We use this to get background colors in all browsers (still, IE9+ required).

How to convert float to varchar in SQL Server

Convert into an integer first and then into a string:

cast((convert(int,b.tax_id)) as varchar(20))

How to overload __init__ method based on argument type?

Excellent question. I've tackled this problem as well, and while I agree that "factories" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:

Here's a sample (this is a read method and not a constructor, but the idea is the same):

def read(self, str=None, filename=None, addr=0):
    """ Read binary data and return a store object. The data
        store is also saved in the interal 'data' attribute.

        The data can either be taken from a string (str 
        argument) or a file (provide a filename, which will 
        be read in binary mode). If both are provided, the str 
        will be used. If neither is provided, an ArgumentError 
        is raised.
    """
    if str is None:
        if filename is None:
            raise ArgumentError('Please supply a string or a filename')

        file = open(filename, 'rb')
        str = file.read()
        file.close()
    ...
    ... # rest of code

The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:

obj.read(filename="blob.txt")

And to read it from a string, I say:

obj.read(str="\x34\x55")

This way the user has just a single method to call. Handling it inside, as you saw, is not overly complex

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

StreamWriter is available for NET 1.1. and for the Compact framework. Just open the file and apply the ToString to your StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.Append(......);

    StreamWriter sw = new StreamWriter("\\hereIAm.txt", true);
    sw.Write(sb.ToString());
    sw.Close();

Also, note that you say that you want to append debug messages to the file (like a log). In this case, the correct constructor for StreamWriter is the one that accepts an append boolean flag. If true then it tries to append to an existing file or create a new one if it doesn't exists.

Generating random numbers with normal distribution in Excel

Rand() does generate a uniform distribution of random numbers between 0 and 1, but the norminv (or norm.inv) function is taking the uniform distributed Rand() as an input to generate the normally distributed sample set.

Using LIKE in an Oracle IN clause

A REGEXP_LIKE will do a case-insensitive regexp search.

select * from Users where Regexp_Like (User_Name, 'karl|anders|leif','i')

This will be executed as a full table scan - just as the LIKE or solution, so the performance will be really bad if the table is not small. If it's not used often at all, it might be ok.

If you need some kind of performance, you will need Oracle Text (or some external indexer).

To get substring indexing with Oracle Text you will need a CONTEXT index. It's a bit involved as it's made for indexing large documents and text using a lot of smarts. If you have particular needs, such as substring searches in numbers and all words (including "the" "an" "a", spaces, etc) , you need to create custom lexers to remove some of the smart stuff...

If you insert a lot of data, Oracle Text will not make things faster, especially if you need the index to be updated within the transactions and not periodically.

JSON serialization/deserialization in ASP.Net Core

.net core

using System.Text.Json;

To serialize

var jsonStr = JsonSerializer.Serialize(MyObject)

Deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out This Microsoft side

convert string into array of integers

us the split function:

var splitresult = "14 2".split(" ");

SQL SELECT WHERE field contains words

best way is making full-text index on a column in table and use contain instead of LIKE

SELECT * FROM MyTable WHERE 
contains(Column1 , N'word1' )
AND contains(Column1 , N'word2' )
AND contains(Column1 , N'word3' )

When to catch java.lang.Error?

An Error usually shouldn't be caught, as it indicates an abnormal condition that should never occur.

From the Java API Specification for the Error class:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. [...]

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

As the specification mentions, an Error is only thrown in circumstances that are Chances are, when an Error occurs, there is very little the application can do, and in some circumstances, the Java Virtual Machine itself may be in an unstable state (such as VirtualMachineError)

Although an Error is a subclass of Throwable which means that it can be caught by a try-catch clause, but it probably isn't really needed, as the application will be in an abnormal state when an Error is thrown by the JVM.

There's also a short section on this topic in Section 11.5 The Exception Hierarchy of the Java Language Specification, 2nd Edition.

Can I change the Android startActivity() transition animation?

See themes on android: http://developer.android.com/guide/topics/ui/themes.html.

Under themes.xml there should be android:windowAnimationStyle where you can see the declaration of the style in styles.xml.

Example implementation:

<style name="AppTheme" parent="...">

    ...

    <item name="android:windowAnimationStyle">@style/WindowAnimationStyle</item>

</style>

<style name="WindowAnimationStyle">
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>

Multiple github accounts on the same computer?

Beside of creating multiple SSH Keys for multiple accounts you can also consider to add collaborators on each project using the same account emails and store the password permanently.

#this store the password permanently
$ git config --global credential.helper wincred

I have setup multiple accounts with different emails then put the same user and email on each account as one of the collaborators. By this way I can access to all account without adding SSH Key, or switching to another username, and email for the authentication.

Python, Pandas : write content of DataFrame into text File

The current best way to do this is to use df.to_string() :

with open(writePath, 'a') as f:
    f.write(
        df.to_string(header = False, index = False)
    )

Will output the following

18 55 1 70   
18 55 2 67 
18 57 2 75     
18 58 1 35  
19 54 2 70 

This method also lets you easily choose which columns to print with the columns attribute, lets you keep the column, index labels if you wish, and has other attributes for spacing ect.

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

android View not attached to window manager

when you declare activity in the manifest you need android:configChanges="orientation"

example:

<activity android:theme="@android:style/Theme.Light.NoTitleBar" android:configChanges="orientation"  android:label="traducción" android:name=".PantallaTraductorAppActivity"></activity>

insert data from one table to another in mysql

You can use INSERT...SELECT syntax. Note that you can quote '1' directly in the SELECT part.

INSERT INTO mt_magazine_subscription ( 
      magazine_subscription_id, 
      subscription_name, 
      magazine_id, 
      status ) 
SELECT magazine_subscription_id, 
       subscription_name, 
       magazine_id, 
       '1'
FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC 

Remove Rows From Data Frame where a Row matches a String

if you wish to using dplyr, for to remove row "Foo":

df %>%
 filter(!C=="Foo")

How do I check that a number is float or integer?

This maybe isn't as performant as the % answer, which prevents you from having to convert to a string first, but I haven't seen anyone post it yet, so here's another option that should work fine:

function isInteger(num) {
    return num.toString().indexOf('.') === -1;
}

Pass Multiple Parameters to jQuery ajax call

I successfully passed multiple parameters using json

data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + "'," + "'tempdata':'" +"myvalue" + "'}",

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

How to find the width of a div using vanilla JavaScript?

The correct way of getting computed style is waiting till page is rendered. It can be done in the following manner. Pay attention to timeout on getting auto values.

function getStyleInfo() {
    setTimeout(function() {
        const style = window.getComputedStyle(document.getElementById('__root__'));
        if (style.height == 'auto') {
            getStyleInfo();
        }
        // IF we got here we can do actual business logic staff
        console.log(style.height, style.width);
    }, 100);
};

window.onload=function() { getStyleInfo(); };

If you use just

window.onload=function() {
    var computedStyle = window.getComputedStyle(document.getElementById('__root__'));
}

you can get auto values for width and height because browsers does not render till full load is performed.

What does the "+" (plus sign) CSS selector mean?

p+p{
//styling the code
}

p+p{
} simply mean find all the adjacent/sibling paragraphs with respect to first paragraph in DOM body.

    <div>
    <input type="text" placeholder="something">
    <p>This is first paragraph</p>
    <button>Button </button>
    <p> This is second paragraph</p>
    <p>This is third paragraph</p>
    </div>

    Styling part 
    <style type="text/css">
        p+p{
            color: red;
            font-weight: bolder;
        }
    </style>

   It will style all sibling paragraph with red color.

final output look like this

enter image description here

CRON job to run on the last day of the month

For AWS Cloudwatch cron implementation (Scheduling Lambdas, etc..) this works:

55 23 L * ? *

Running at 11:55pm on the last day of each month.

How to get the list of all installed color schemes in Vim?

If you have your vim compiled with +menu, you can follow menus with the :help of console-menu. From there, you can navigate to Edit.Color\ Scheme to get the same list as with in gvim.

Other method is to use a cool script ScrollColors that previews the colorschemes while you scroll the schemes with j/k.

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

MSBUILD : error MSB1008: Only one project can be specified

Yet another cause and solution to this: Check that you didn't put a space in the wrong place, i.e. in parameters; mine was dotnet -c Release - o /home/some/path (note the space between - and o), I kept looking at the path itself, which was correct and threw me off. Hope that helps! (this was in Bash though it should also apply to Windows)

SQL Error: 0, SQLState: 08S01 Communications link failure

The communication link between the driver and the data source to which the driver was attempting to connect failed before the function completed processing. So usually its a network error. This could be caused by packet drops or badly configured Firewall/Switch.

Select multiple images from android gallery

Define these variables in the class:

int PICK_IMAGE_MULTIPLE = 1; 
String imageEncoded;    
List<String> imagesEncodedList;

Let's Assume that onClick on a button it should open gallery to select images

 Intent intent = new Intent();
 intent.setType("image/*");
 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
 intent.setAction(Intent.ACTION_GET_CONTENT);
 startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);

Then you should override onActivityResult Method

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {
        // When an Image is picked
        if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
                    && null != data) {
            // Get the Image from data

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            imagesEncodedList = new ArrayList<String>();
            if(data.getData()!=null){

                Uri mImageUri=data.getData();

                // Get the cursor
                Cursor cursor = getContentResolver().query(mImageUri,
                            filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imageEncoded  = cursor.getString(columnIndex);
                cursor.close();

            } else {
                if (data.getClipData() != null) {
                    ClipData mClipData = data.getClipData();
                    ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                    for (int i = 0; i < mClipData.getItemCount(); i++) {

                        ClipData.Item item = mClipData.getItemAt(i);
                        Uri uri = item.getUri();
                        mArrayUri.add(uri);
                        // Get the cursor
                        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                        // Move to first row
                        cursor.moveToFirst();

                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        imageEncoded  = cursor.getString(columnIndex);
                        imagesEncodedList.add(imageEncoded);
                        cursor.close();

                    }
                    Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
                }
            }
        } else {
            Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
    }

    super.onActivityResult(requestCode, resultCode, data);
}

NOTE THAT: the gallery doesn't give you the ability to select multi-images so we here open all images studio that you can select multi-images from them. and don't forget to add the permissions to your manifest

VERY IMPORTANT: getData(); to get one single image and I've stored it here in imageEncoded String if the user select multi-images then they should be stored in the list

So you have to check which is null to use the other

Wish you have a nice try and to others

How to set up a cron job to run an executable every hour?

You can also use @hourly instant of 0 * * * *

Where can I find the Java SDK in Linux after installing it?

This is the best way which worked for me Execute this Command:-

$(dirname $(readlink $(which javac)))/java_home

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

The regular UITableViewCell works well to position things but the cell.imageView doesn't seem to behave like you want it to. I found that it's simple enough to get the UITableViewCell to lay out properly by first giving the cell.imageView a properly sized image like

// Putting in a blank image to make sure text always pushed to the side.
UIGraphicsBeginImageContextWithOptions(CGSizeMake(kGroupImageDimension, kGroupImageDimension), NO, 0.0);
UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cell.imageView.image = blank;

Then you can just connect up your own properly working UIImageView with

// The cell.imageView increases in size to accomodate the image given it.
// We don't want this behaviour so we just attached a view on top of cell.imageView.
// This gives us the positioning of the cell.imageView without the sizing
// behaviour.
UIImageView *anImageView = nil;
NSArray *subviews = [cell.imageView subviews];
if ([subviews count] == 0)
{
    anImageView = [[UIImageView alloc] init];
    anImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [cell.imageView addSubview:anImageView];

    NSLayoutConstraint *aConstraint = [NSLayoutConstraint constraintWithItem:anImageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:cell.imageView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
    [cell.imageView addConstraint:aConstraint];

    aConstraint = [NSLayoutConstraint constraintWithItem:anImageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:cell.imageView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];
    [cell.imageView addConstraint:aConstraint];

    aConstraint = [NSLayoutConstraint constraintWithItem:anImageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:kGroupImageDimension];
    [cell.imageView addConstraint:aConstraint];

    aConstraint = [NSLayoutConstraint constraintWithItem:anImageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:kGroupImageDimension];
    [cell.imageView addConstraint:aConstraint];
}
else
{
    anImageView = [subviews firstObject];
}

Set the image on anImageView and it will do what you expect a UIImageView to do. Be the size you want it regardless of the image you give it. This should go in tableView:cellForRowAtIndexPath:

Why is __dirname not defined in node REPL?

Building on the existing answers here, you could define this in your REPL:

__dirname = path.resolve(path.dirname(''));

Or:

__dirname = path.resolve();

If no path segments are passed, path.resolve() will return the absolute path of the current working directory.


Or @Jthorpe's alternatives:

__dirname = process.cwd();
__dirname = fs.realpathSync('.');
__dirname = process.env.PWD

PostgreSQL: How to make "case-insensitive" query

You could also use POSIX regular expressions, like

SELECT id FROM groups where name ~* 'administrator'

SELECT 'asd' ~* 'AsD' returns t

Creating a jQuery object from a big HTML-string

I use the following for my HTML templates:

$(".main").empty();

var _template = '<p id="myelement">Your HTML Code</p>';
var template = $.parseHTML(_template);
var final = $(template).find("#myelement");

$(".main").append(final.html());

Note: Assuming if you are using jQuery

Special characters like @ and & in cURL POST data

Double quote (" ") the entire URL .It works.

curl "http://www.mysite.com?name=john&passwd=@31&3*J"

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

Problem

I had a similar problem using axes. The class parameter is frameon but the kwarg is frame_on. axes_api
>>> plt.gca().set(frameon=False)
AttributeError: Unknown property frameon

Solution

frame_on

Example

data = range(100)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(data)
#ax.set(frameon=False)  # Old
ax.set(frame_on=False)  # New
plt.show()

Listview Scroll to the end of the list after updating the list

The simplest solution is :

    listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
    listView.setStackFromBottom(true);

How to resolve cURL Error (7): couldn't connect to host?

This issue can also be caused by making curl calls to https when it is not configured on the remote device. Calling over http can resolve this problem in these situations, at least until you configure ssl on the remote.

How to get Spinner selected item value to string?

Try this:

String text = mySpinner.getSelectedItem().toString();

Like this you can get value for different Spinners.

Variable number of arguments in C++?

You probably shouldn't, and you can probably do what you want to do in a safer and simpler way. Technically to use variable number of arguments in C you include stdarg.h. From that you'll get the va_list type as well as three functions that operate on it called va_start(), va_arg() and va_end().

#include<stdarg.h>

int maxof(int n_args, ...)
{
    va_list ap;
    va_start(ap, n_args);
    int max = va_arg(ap, int);
    for(int i = 2; i <= n_args; i++) {
        int a = va_arg(ap, int);
        if(a > max) max = a;
    }
    va_end(ap);
    return max;
}

If you ask me, this is a mess. It looks bad, it's unsafe, and it's full of technical details that have nothing to do with what you're conceptually trying to achieve. Instead, consider using overloading or inheritance/polymorphism, builder pattern (as in operator<<() in streams) or default arguments etc. These are all safer: the compiler gets to know more about what you're trying to do so there are more occasions it can stop you before you blow your leg off.

What is the apply function in Scala?

It comes from the idea that you often want to apply something to an object. The more accurate example is the one of factories. When you have a factory, you want to apply parameter to it to create an object.

Scala guys thought that, as it occurs in many situation, it could be nice to have a shortcut to call apply. Thus when you give parameters directly to an object, it's desugared as if you pass these parameters to the apply function of that object:

class MyAdder(x: Int) {
  def apply(y: Int) = x + y
}

val adder = new MyAdder(2)
val result = adder(4) // equivalent to x.apply(4)

It's often use in companion object, to provide a nice factory method for a class or a trait, here is an example:

trait A {
  val x: Int
  def myComplexStrategy: Int
}

object A {
  def apply(x: Int): A = new MyA(x)

  private class MyA(val x: Int) extends A {
    val myComplexStrategy = 42
  }
}

From the scala standard library, you might look at how scala.collection.Seq is implemented: Seq is a trait, thus new Seq(1, 2) won't compile but thanks to companion object and apply, you can call Seq(1, 2) and the implementation is chosen by the companion object.

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

multipart/form-data

Note. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.

Please consult the appendix for information about security issues for forms.

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

The content type "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of "multipart/form-data" is available at the [IANA] registry.

A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.

As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.

application/x-www-form-urlencoded

This is the default content type. Forms submitted with this content type must be encoded as follows:

Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value by=' and name/value pairs are separated from each other by `&'.

application/x-www-form-urlencoded the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

SQL WHERE ID IN (id1, id2, ..., idn)

First option is definitely the best option.

SELECT * FROM TABLE WHERE ID IN (id1, id2, ..., idn)

However considering that the list of ids is very huge, say millions, you should consider chunk sizes like below:

  • Divide you list of Ids into chunks of fixed number, say 100
  • Chunk size should be decided based upon the memory size of your server
  • Suppose you have 10000 Ids, you will have 10000/100 = 100 chunks
  • Process one chunk at a time resulting in 100 database calls for select

Why should you divide into chunks?

You will never get memory overflow exception which is very common in scenarios like yours. You will have optimized number of database calls resulting in better performance.

It has always worked like charm for me. Hope it would work for my fellow developers as well :)

How do I create a datetime in Python from milliseconds?

Just convert it to timestamp

datetime.datetime.fromtimestamp(ms/1000.0)

How to get week number of the month from the date in sql server 2008

Logic here works as well 4.3 weeks in every month. Take that from the DATEPART(WEEK) on every month but January. Just another way of looking at things. This would also account for months where there is a 5th week

DECLARE @date VARCHAR(10)
SET @date = '7/27/2019'

SELECT CEILING(DATEPART(WEEK,@date)-((DATEPART(MONTH,@date)-1)*4.3333)) 'Week of Month'

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

These steps really help me:

Step 1: Create a directory in android/app/src/main/assets

Linux command: mkdir android/app/src/main/assets

Step 2: Rename index.android.js (in root directory) to index.js (Maybe there is an index.js file in which case you do not need to rename it) then run the following command:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

Step 3: Build your APK: react-native run-android

Please use index.js in latest version.

Enjoy :)

Find closing HTML tag in Sublime Text

It's built in from Sublime Editor 2 at least. Just press the following and it balances the HTML-tag

Shortcut (Mac): Shift + Command + A

Shortcut (Windows): Control + Alt + A

How to remove all subviews of a view in Swift?

did you try something like

for o : AnyObject in self.subviews {
     if let v = o as? NSView {
         v.removeFromSuperview()
     }
}

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

I've recently created simpler abstraction called wait.for to call async functions in sync mode (based on node-fibers). There is also a version based on upcoming ES6 Generators.

https://github.com/luciotato/waitfor

Using wait.for, you can call any standard nodejs async function, as if it were a sync function, without blocking node's event loop.

You can code sequentially when you need it, which is, (I'm guessing) perfect to simplify your scripts for personal use.

using wait.for your code will be:

require('waitfor')

..in a fiber..
//start-of-code
console.log('Welcome to My Console,');
wait.miliseconds(10*1000); //defined in waitfor/paralell-tests.js - DOES NOT BLOCK
console.log('Blah blah blah blah extra-blah');
//endcode. 

Also any async function can be called in Sync mode. Check the examples.

Naming threads and thread-pools of ExecutorService

Based on few of the comments above, difference is I just used lambda

Executors.newFixedThreadPool(10, r -> new Thread(r, "my-threads-%d"))

Getters \ setters for dummies

You'd use them for instance to implement computed properties.

For example:

function Circle(radius) {
    this.radius = radius;
}

Object.defineProperty(Circle.prototype, 'circumference', {
    get: function() { return 2*Math.PI*this.radius; }
});

Object.defineProperty(Circle.prototype, 'area', {
    get: function() { return Math.PI*this.radius*this.radius; }
});

c = new Circle(10);
console.log(c.area); // Should output 314.159
console.log(c.circumference); // Should output 62.832

(CodePen)

tmux set -g mouse-mode on doesn't work

As @Graham42 said, from version 2.1 mouse options has been renamed but you can use the mouse with any version of tmux adding this to your ~/.tmux.conf:

Bash shells:

is_pre_2_1="[[ $(tmux -V | cut -d' ' -f2) < 2.1 ]] && echo true || echo false"
if-shell "$is_pre_2_1" "setw -g mode-mouse on; set -g mouse-resize-pane on;\
      set -g mouse-select-pane on; set -g mouse-select-window on" "set -g mouse on"

Sh (Bourne shell) shells:

is_pre_2_1="tmux -V | cut -d' ' -f2 | awk '{print ($0 < 2.1) ? "true" : "false"}'"
if-shell "$is_pre_2_1" "setw -g mode-mouse on; set -g mouse-resize-pane on;\
      set -g mouse-select-pane on; set -g mouse-select-window on" "set -g mouse on"

Hope this helps

What happens to C# Dictionary<int, int> lookup if the key does not exist?

int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;

If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.

Hope, this code helps you.

python: sys is not defined

Move import sys outside of the try-except block:

import sys
try:
    # ...
except ImportError:
    # ...

If any of the imports before the import sys line fails, the rest of the block is not executed, and sys is never imported. Instead, execution jumps to the exception handling block, where you then try to access a non-existing name.

sys is a built-in module anyway, it is always present as it holds the data structures to track imports; if importing sys fails, you have bigger problems on your hand (as that would indicate that all module importing is broken).

Barcode scanner for mobile phone for Website in form

Check this out: http://qrdroid.com/web-masters.php

You can create a link in your web form, something like:

http://qrdroid.com/scan?q=http://www.your-site.com/your-form.php?code={CODE}

When somebody clicks that link, an app to scan the code will be opened. After the user scans the code, http://www.your-site.com/your-form.php?code={CODE} will be automatically called. You can then make your-form.php read the parameter code to prepopulate the field.

Maven plugin not using Eclipse's proxy settings

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">

     <proxies>
       <proxy>
          <active>true</active>
          <protocol>http</protocol>
          <host>proxy.somewhere.com</host>
          <port>8080</port>
          <username>proxyuser</username>
          <password>somepassword</password>
          <nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
        </proxy>
      </proxies>

    </settings>

Window > Preferences > Maven > User Settings

enter image description here

Xcode - Warning: Implicit declaration of function is invalid in C99

The compiler wants to know the function before it can use it

just declare the function before you call it

#include <stdio.h>

int Fibonacci(int number); //now the compiler knows, what the signature looks like. this is all it needs for now

int main(int argc, const char * argv[])
{
    int input;
    printf("Please give me a number : ");
    scanf("%d", &input);
    getchar();
    printf("The fibonacci number of %d is : %d", input, Fibonacci(input)); //!!!

}/* main */

int Fibonacci(int number)
{
//…

File uploading with Express 4.0: req.files undefined

multer is a middleware which handles “multipart/form-data” and magically & makes the uploaded files and form data available to us in request as request.files and request.body.

installing multer :- npm install multer --save

in .html file:-

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="hidden" name="msgtype" value="2"/>
    <input type="file" name="avatar" />
    <input type="submit" value="Upload" />
</form>

in .js file:-

var express = require('express');
var multer = require('multer');
var app = express();
var server = require('http').createServer(app);
var port = process.env.PORT || 3000;
var upload = multer({ dest: 'uploads/' });

app.use(function (req, res, next) {
  console.log(req.files); // JSON Object
  next();
});

server.listen(port, function () {
  console.log('Server successfully running at:-', port);
});

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/public/file-upload.html');
})

app.post('/upload', upload.single('avatar'),  function(req, res) {
  console.log(req.files); // JSON Object
});

Hope this helps!

Get button click inside UITableViewCell

CustomTableCell.h is a UITableViewCell:

@property (weak, nonatomic) IBOutlet UIButton *action1Button;
@property (weak, nonatomic) IBOutlet UIButton *action2Button;

MyVC.m after imports:

@interface MYTapGestureRecognizer : UITapGestureRecognizer
@property (nonatomic) NSInteger dataint;
@end

Inside "cellForRowAtIndexPath" in MyVC.m:

//CustomTableCell 
CustomTableCell *cell = (CustomTableCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

//Set title buttons
[cell.action1Button setTitle:[NSString stringWithString:NSLocalizedString(@"action1", nil)] forState:UIControlStateNormal];
[cell.action2Button setTitle:[NSString stringWithString:NSLocalizedString(@"action2", nil)] forState:UIControlStateNormal];

//Set visibility buttons
[cell.action1Button setHidden:FALSE];
[cell.action2Button setHidden:FALSE];

//Do 1 action
[cell.action1Button addTarget:self action:@selector(do1Action :) forControlEvents:UIControlEventTouchUpInside];

//Do 2 action
MYTapGestureRecognizer *action2Tap = [[MYTapGestureRecognizer alloc] initWithTarget:self action:@selector(do2Action :)];
cancelTap.numberOfTapsRequired = 1;
cancelTap.dataint = indexPath.row;
[cell.action2Button setUserInteractionEnabled:YES];
[cell.action2Button addGestureRecognizer:action2Tap];

MyVC.m:

-(void)do1Action :(id)sender{
//do some action that is not necessary fr data
}

-(void)do2Action :(UITapGestureRecognizer *)tapRecognizer{
MYTapGestureRecognizer *tap = (MYTapGestureRecognizer *)tapRecognizer;
numberTag = tap.dataint;
FriendRequest *fr = [_list objectAtIndex:numberTag];

//connect with a WS o do some action with fr data

//actualize list in tableView
 [self.myTableView reloadData];
}

Unable to auto-detect email address

Try the following steps,

  1. Open command prompt and then run
  2. git config --global user.email "[email protected]" // put your email address press enter
  3. git config --global user.name "YOUR NAME" // put your name

Default keystore file does not exist?

For Mac Users: The debug.keystore file exists in ~/.android directory. Sometimes, due to the relative path, the above mentioned error keeps on popping up.

$_SERVER['HTTP_REFERER'] missing

SOLUTION

As stated by others very well, HTTP_REFERER is set by the local machine of the user, specifically the browser, which means it's not reliable for security. However, this still is entirely the way in which Google Analytics monitors where you're getting your visitors from, so, it can actually be useful to check, exclude, include, etc..

If you think you should see an HTTP_REFERER and do not, add this to your PHP code, preferably at the top:

ini_set('session.referer_check', 'TRUE');

A more appropriate long-term solution, of course, is to actually update your php.ini or equivalent file. This is a nice and quick way of verifying, though.

TESTING

Run print($_SERVER['HTTP_REFERER']); on your site, go to google.com, inspect some text, edit it to be <a href="https://example.com">LINK!</a>, apply the change, then click the link. If it works, all is well and running precisely!

But maybe $_SERVER is wrong, or the test above says it's broken. Update your page with this, and then test again...

<script type="text/javascript">
    console.log("REFER!" + document.referrer + "|" + location.referrer + "|");
</script>

USES

I use HTTP REFERER to block spam sites in GoogleAnalytics. Below is a graph focusing on one particular website's referrals. From 0 to 44 in one day, it wasn't caused by real users. It was caused by a botted site trying to get my attention to buy their services. But it just started because php.ini was updated to ignore the referer, which meant these spam, junk garbage sites were not getting their appropriate ERROR 403, "Access Denied."

sql like operator to get the numbers only

You can try this

ISNUMERIC (Transact-SQL)

ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.

DECLARE @Table TABLE(
        Col VARCHAR(50)
)

INSERT INTO @Table SELECT 'ABC' 
INSERT INTO @Table SELECT 'Italy' 
INSERT INTO @Table SELECT 'Apple' 
INSERT INTO @Table SELECT '234.62' 
INSERT INTO @Table SELECT '2:234:43:22' 
INSERT INTO @Table SELECT 'France' 
INSERT INTO @Table SELECT '6435.23'
INSERT INTO @Table SELECT '2' 
INSERT INTO @Table SELECT 'Lions'

SELECT  *
FROM    @Table
WHERE   ISNUMERIC(Col) = 1

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

Encrypt and decrypt a String in java

Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.

I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.

If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.

jQuery form input select by id

You can just target the id directly:

var value = $('#b').val();

If you have more than one element with that id in the same page, it won't work properly anyway. You have to make sure that the id is unique.

If you actually are using the code for different pages, and only want to find the element on those pages where the id:s are nested, you can just use the descendant operator, i.e. space:

var value = $('#a #b').val();

How to pass an event object to a function in Javascript?

I would change your binding to be:

<button type="button" value="click me" onclick="check_me" />

I would then change your check_me() function declaration to be:

function check_me() {   
  //event.preventDefault();
  var hello = document.myForm.username.value;
  var err = '';

  if(hello == '' || hello == null) {
    err = 'User name required';
  }

  if(err != '') { 
     alert(err); 
     $('username').focus(); 
     event.preventDefault(); 
   } else { 
    return true; }
}

How to read multiple Integer values from a single line of input in Java?

Java 8

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int arr[] = Arrays.stream(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();

Difference between session affinity and sticky session?

I've seen those terms used interchangeably, but there are different ways of implementing it:

  1. Send a cookie on the first response and then look for it on subsequent ones. The cookie says which real server to send to.
    Bad if you have to support cookie-less browsers
  2. Partition based on the requester's IP address.
    Bad if it isn't static or if many come in through the same proxy.
  3. If you authenticate users, partition based on user name (it has to be an HTTP supported authentication mode to do this).
  4. Don't require state.
    Let clients hit any server (send state to the client and have them send it back)
    This is not a sticky session, it's a way to avoid having to do it.

I would suspect that sticky might refer to the cookie way, and that affinity might refer to #2 and #3 in some contexts, but that's not how I have seen it used (or use it myself)

Echo equivalent in PowerShell for script testing

PowerShell has aliases for several common commands like echo. Type the following in PowerShell:

Get-Alias echo

to get a response:

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           echo -> Write-Output

Even Get-Alias has an alias gal -> Get-Alias. You could write gal echo to get the alias for echo.

gal echo

Other aliases are listed here: https://docs.microsoft.com/en-us/powershell/scripting/learn/using-familiar-command-names?view=powershell-6

cat dir mount rm cd echo move rmdir chdir erase popd sleep clear h ps sort cls history pushd tee copy kill pwd type del lp r write diff ls ren

How to change Screen buffer size in Windows Command Prompt from batch script

Below is a very simple VB.NET program that will do what you want.

It will set the buffer to 100 chars wide by 1000 chars high. It then sets the width of the window to match the buffer size.

Module ConsoleBuffer
  Sub Main()
    Console.WindowWidth = 100
    Console.BufferWidth = 100
    Console.BufferHeight = 1000
  End Sub
End Module

UPDATE

I modified the code to first set Console.WindowWidth and then set Console.BufferWidth because if you try to set Console.BufferWidth to a value less than the current Console.WindowWidth the program will throw an exception.

This is only a sample...you should add code to handle command line parameters and error handling.

How To Get Selected Value From UIPickerView

You can get it in the following manner:

NSInteger row;
NSArray *repeatPickerData;
UIPickerView *repeatPickerView;

row = [repeatPickerView selectedRowInComponent:0];
self.strPrintRepeat = [repeatPickerData objectAtIndex:row];

How to enable bulk permission in SQL Server

If you get an error saying "Cannot Bulk load file because you don't have access right"

First make sure the path and file name you have given are correct.

then try giving the bulkadmin role to the user. To do so follow the steps :- In Object Explorer -> Security -> Logins -> Select the user (right click) -> Properties -> Server Roles -> check the bulkadmin checkbox -> OK.

This worked for me.

What's the best three-way merge tool?

The summary is that I found ECMerge to be a great, though commercial product. http://www.elliecomputing.com/products/merge_overview.asp

enter image description here

I also agree with MrTelly that Ultracompare is very good. One nice feature is that it will compare RTF and Word docs, which is handy when you end up programming in word with the sales guys and they don't manage their docs correctly.

What are Unwind segues for and how do you use them?

As far as how to use unwind segues in StoryBoard...

Step 1)

Go to the code for the view controller that you wish to unwind to and add this:

Objective-C

- (IBAction)unwindToViewControllerNameHere:(UIStoryboardSegue *)segue {
    //nothing goes here
}

Be sure to also declare this method in your .h file in Obj-C

Swift

@IBAction func unwindToViewControllerNameHere(segue: UIStoryboardSegue) {
    //nothing goes here
}

Step 2)

In storyboard, go to the view that you want to unwind from and simply drag a segue from your button or whatever up to the little orange "EXIT" icon at the top right of your source view.

enter image description here

There should now be an option to connect to "- unwindToViewControllerNameHere"

That's it, your segue will unwind when your button is tapped.

How do I view cookies in Internet Explorer 11 using Developer Tools

Update 2018 for Microsoft Edge Developer Tools

The Dev Tools in Edge finally added support for managing and browsing cookies.

Note: Even if you are testing and supporting IE targets, you mine as well do the heavy lifting of your browser compatibility testing by leveraging the new tooling in Edge, and defer checking in IE 11 (etc) for the last leg.

Debugger Panel > Cookies Manager

Debugger Tab

Network Panel > Request Details > Cookies

Network Tab

The benefit, of course, to the debugger tab is you don't have to hunt and peck for individual cookies across multiple different and historical requests.

Tomcat won't stop or restart

Make sure Tomcat is not currently running and the PID file is removed. Them you should start Tomcat successfully.

If you start fresh then:

  1. Create setenv.sh file in <CATALINA_HOME>/bin.
  2. In it I set CATALINA_PID=/tmp/tomcat.pid (or other directory of your choice) so you have more control over the Tomcat process.

Then to start Tomcat find catalina.sh in <CATALINA_HOME>/bin and execute:

./catalina.sh start

and to stop it run:

./catalina.sh stop 10 -force

From catalina.sh script's doc:

./catalina.sh

Usage: catalina.sh ( commands ... )
commands:

start             Start Catalina in a separate window
stop              Stop Catalina, waiting up to 5 seconds for the process to end
stop n            Stop Catalina, waiting up to n seconds for the process to end
stop -force       Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running
stop n -force     Stop Catalina, wait up to n seconds and then use kill -KILL if still running

Note: If you want to use -force flag then setting CATALINA_PID is mandatory.

How to Convert the value in DataTable into a string array in c#

If that's all what you want to do, you don't need to convert it into an array. You can just access it as:

string myData=yourDataTable.Rows[0][1].ToString();//Gives you USA

How do you dismiss the keyboard when editing a UITextField

If you connect the DidEndOnExit event of the text field to an action (IBAction) in InterfaceBuilder, it will be messaged when the user dismisses the keyboard (with the return key) and the sender will be a reference to the UITextField that fired the event.

For example:

-(IBAction)userDoneEnteringText:(id)sender
{
    UITextField theField = (UITextField*)sender;
    // do whatever you want with this text field
}

Then, in InterfaceBuilder, link the DidEndOnExit event of the text field to this action on your controller (or whatever you're using to link events from the UI). Whenever the user enters text and dismisses the text field, the controller will be sent this message.

Float a DIV on top of another DIV

What about:

.close-image{
    display:block;
    cursor:pointer;
    z-index:3;
    position:absolute;
    top:0;
    right:0;
}

Is that the desired result?

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

This is possible with a bit of format conversion.

To extract the private key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa

To convert the private key to a public key:

openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8

To extract the public key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

Swift 3.0:

let userInterface = UIDevice.current.userInterfaceIdiom

if(userInterface == .pad){
    //iPads
}else if(userInterface == .phone){
    //iPhone
}else if(userInterface == .carPlay){
    //CarPlay
}else if(userInterface == .tv){
    //AppleTV
}

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

This excellent answer explains very well what is happening and provides a solution. I would like to add another solution that might be suitable in similar cases: using the query method:

result = result.query("(var > 0.25) or (var < -0.25)")

See also http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-query.

(Some tests with a dataframe I'm currently working with suggest that this method is a bit slower than using the bitwise operators on series of booleans: 2 ms vs. 870 µs)

A piece of warning: At least one situation where this is not straightforward is when column names happen to be python expressions. I had columns named WT_38hph_IP_2, WT_38hph_input_2 and log2(WT_38hph_IP_2/WT_38hph_input_2) and wanted to perform the following query: "(log2(WT_38hph_IP_2/WT_38hph_input_2) > 1) and (WT_38hph_IP_2 > 20)"

I obtained the following exception cascade:

  • KeyError: 'log2'
  • UndefinedVariableError: name 'log2' is not defined
  • ValueError: "log2" is not a supported function

I guess this happened because the query parser was trying to make something from the first two columns instead of identifying the expression with the name of the third column.

A possible workaround is proposed here.

Move all files except one

I would go with the traditional find & xargs way:

find ~/Linux/Old -maxdepth 1 -mindepth 1 -not -name Tux.png -print0 | 
    xargs -0 mv -t ~/Linux/New

-maxdepth 1 makes it not search recursively. If you only care about files, you can say -type f. -mindepth 1 makes it not include the ~/Linux/Old path itself into the result. Works with any filenames, including with those that contain embedded newlines.

One comment notes that the mv -t option is a probably GNU extension. For systems that don't have it

find ~/Linux/Old -maxdepth 1 -mindepth 1 -not -name Tux.png \
    -exec mv '{}' ~/Linux/New \;

PostgreSQL, checking date relative to "today"

I think this will do it:

SELECT * FROM MyTable WHERE mydate > now()::date - 365;

Git fetch remote branch

If you have a repository that was cloned with --depth 1 then many of the commands that were listed will not work. For example, see here

% git clone --depth 1 https://github.com/repo/code
Cloning into 'code'...
cd code
remote: Counting objects: 1778, done.
remote: Compressing objects: 100% (1105/1105), done.
remote: Total 1778 (delta 87), reused 1390 (delta 58), pack-reused 0
Receiving objects: 100% (1778/1778), 5.54 MiB | 4.33 MiB/s, done.
Resolving deltas: 100% (87/87), done.
Checking connectivity... done.
Checking out files: 100% (1215/1215), done.
% cd code
% git checkout other_branch
error: pathspec 'other_branch' did not match any file(s) known to git.
% git fetch origin other_branch
remote: Counting objects: 47289, done.
remote: Compressing objects: 100% (15906/15906), done.
remote: Total 47289 (delta 30151), reused 46699 (delta 29570), pack-reused 0
Receiving objects: 100% (47289/47289), 31.03 MiB | 5.70 MiB/s, done.
Resolving deltas: 100% (30151/30151), completed with 362 local objects.
From https://github.com/repo/code
 * branch            other_branch-> FETCH_HEAD
% git checkout other_branch
error: pathspec 'other_branch' did not match any file(s) known to git.
%

In this case I would reclone the repository, but perhaps there are other techniques e.g. git shallow clone (clone --depth) misses remote branches

ADB Driver and Windows 8.1

I had the following problem:
I had a Android phone without drivers, and it could not be recognized by the Windows 8.1. Neither as phone, neither as USB storage device.

I searched Device manager.
I opened Device manager, I right click on Android Phone->Android Composite Interface.
I selected "Update Driver Software"
I choose "Browse My Computer for Driver Software"
Then I choose "Let me pick from a list of devices"
I selected "USB Composite Device"

A new USB device is added to the list, and I can connect to my phone using adb and Android SDK.

Also I can use the phone as storage device.
Good luck

How do I prevent a Gateway Timeout with FastCGI on Nginx

If you use unicorn.

Look at top on your server. Unicorn likely is using 100% of CPU right now. There are several reasons of this problem.

  • You should check your HTTP requests, some of their can be very hard.

  • Check unicorn's version. May be you've updated it recently, and something was broken.

Remove duplicates in the list using linq

Use Distinct() but keep in mind that it uses the default equality comparer to compare values, so if you want anything beyond that you need to implement your own comparer.

Please see http://msdn.microsoft.com/en-us/library/bb348436.aspx for an example.

How to Import .bson file format on mongodb

mongorestore -d db_name /path/

make sure you run this query in bin folder of mongoDb

C:\Program Files\MongoDB\Server\4.2\bin -

then run this above command.

Downloading a file from spring controllers

With Spring 3.0 you can use the HttpEntity return object. If you use this, then your controller does not need a HttpServletResponse object, and therefore it is easier to test. Except this, this answer is relative equals to the one of Infeligo.

If the return value of your pdf framework is an byte array (read the second part of my answer for other return values) :

@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
                 @PathVariable("fileName") String fileName) throws IOException {

    byte[] documentBody = this.pdfFramework.createPdf(filename);

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
                   "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(documentBody.length);

    return new HttpEntity<byte[]>(documentBody, header);
}

If the return type of your PDF Framework (documentBbody) is not already a byte array (and also no ByteArrayInputStream) then it would been wise NOT to make it a byte array first. Instead it is better to use:

example with FileSystemResource:

@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
                 @PathVariable("fileName") String fileName) throws IOException {

    File document = this.pdfFramework.createPdf(filename);

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
                   "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(document.length());

    return new HttpEntity<byte[]>(new FileSystemResource(document),
                                  header);
}

Reference member variables as class members

It's called dependency injection via constructor injection: class A gets the dependency as an argument to its constructor and saves the reference to dependent class as a private variable.

There's an interesting introduction on wikipedia.

For const-correctness I'd write:

using T = int;

class A
{
public:
  A(const T &thing) : m_thing(thing) {}
  // ...

private:
   const T &m_thing;
};

but a problem with this class is that it accepts references to temporary objects:

T t;
A a1{t};    // this is ok, but...

A a2{T()};  // ... this is BAD.

It's better to add (requires C++11 at least):

class A
{
public:
  A(const T &thing) : m_thing(thing) {}
  A(const T &&) = delete;  // prevents rvalue binding
  // ...

private:
  const T &m_thing;
};

Anyway if you change the constructor:

class A
{
public:
  A(const T *thing) : m_thing(*thing) { assert(thing); }
  // ...

private:
   const T &m_thing;
};

it's pretty much guaranteed that you won't have a pointer to a temporary.

Also, since the constructor takes a pointer, it's clearer to users of A that they need to pay attention to the lifetime of the object they pass.


Somewhat related topics are:

Converting JSON to XML in Java

If you want to replace any node value you can do like this

JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
xml.replace("old value", "new value");

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')

What exactly does numpy.exp() do?

The exponential function is e^x where e is a mathematical constant called Euler's number, approximately 2.718281. This value has a close mathematical relationship with pi and the slope of the curve e^x is equal to its value at every point. np.exp() calculates e^x for each value of x in your input array.

TypeError: 'int' object is not subscriptable

If you want to sum the digit of a number, one way to do it is using sum() + a generator expression:

sum(int(i) for i in str(155))

I modified a little your code using sum(), maybe you want to take a look at it:

birthday = raw_input("When is your birthday(mm/dd/yyyy)? ")
summ = sum(int(i) for i in birthday[0:2])
sumd = sum(int(i) for i in birthday[3:5])
sumy = sum(int(i) for i in birthday[6:10])
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumln = sum(int(c) for c in str(sumall)))
print "Your lucky number is", sumln

INSERT IF NOT EXISTS ELSE UPDATE?

You should use the INSERT OR IGNORE command followed by an UPDATE command: In the following example name is a primary key:

INSERT OR IGNORE INTO my_table (name, age) VALUES ('Karen', 34)
UPDATE my_table SET age = 34 WHERE name='Karen'

The first command will insert the record. If the record exists, it will ignore the error caused by the conflict with an existing primary key.

The second command will update the record (which now definitely exists)

From ND to 1D arrays

One of the simplest way is to use flatten(), like this example :

 import numpy as np

 batch_y =train_output.iloc[sample, :]
 batch_y = np.array(batch_y).flatten()

My array it was like this :

    0
0   6
1   6
2   5
3   4
4   3
.
.
.

After using flatten():

array([6, 6, 5, ..., 5, 3, 6])

It's also the solution of errors of this type :

Cannot feed value of shape (100, 1) for Tensor 'input/Y:0', which has shape '(?,)' 

Execute command on all files in a directory

I'm doing this on my raspberry pi from the command line by running:

for i in *;do omxplayer "$i";done

span with onclick event inside a tag

Fnd the answer.

I have use some styles inorder to achive this.

<span 
   class="pseudolink" 
   onclick="location='https://jsfiddle.net/'">
Go TO URL
</span>

.pseudolink { 
   color:blue; 
   text-decoration:underline; 
   cursor:pointer; 
   }

https://jsfiddle.net/mafais/bys46d5w/

Git: How to update/checkout a single file from remote origin master?

Following code worked for me:

     git fetch
     git checkout <branch from which file needs to be fetched> <filepath> 

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was having the same problem. It seems that passing Me.ComboBox1.Value as an argument for the Vlookup function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.

Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False) 

Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>).

So it would end up being

Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False) 

Strange as it may sound, it works for me.

Hope this helps.

Java reverse an int value without using array

public static int reverse(int x) {
    int tmp = x;
    int oct = 0;
    int res = 0;
    while (true) {
        oct = tmp % 10;
        tmp = tmp / 10;
        res = (res+oct)*10;
        if ((tmp/10) == 0) {
            res = res+tmp;
            return res;
        }
    }
}

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

Generic

C code. Using 1 byte input data num as example.

    unsigned char num = 0xaa;   // 1010 1010 (aa) -> 0101 0101 (55)
    int s = sizeof(num) * 8;    // get number of bits
    int i, x, y, p;
    int var = 0;                // make var data type to be equal or larger than num

    for (i = 0; i < (s / 2); i++) {
        // extract bit on the left, from MSB
        p = s - i - 1;
        x = num & (1 << p);
        x = x >> p;
        printf("x: %d\n", x);

        // extract bit on the right, from LSB
        y = num & (1 << i);
        y = y >> i;
        printf("y: %d\n", y);

        var = var | (x << i);       // apply x
        var = var | (y << p);       // apply y
    }

    printf("new: 0x%x\n", new);

What's the difference between equal?, eql?, ===, and ==?

I would like to expand on the === operator.

=== is not an equality operator!

Not.

Let's get that point really across.

You might be familiar with === as an equality operator in Javascript and PHP, but this just not an equality operator in Ruby and has fundamentally different semantics.

So what does === do?

=== is the pattern matching operator!

  • === matches regular expressions
  • === checks range membership
  • === checks being instance of a class
  • === calls lambda expressions
  • === sometimes checks equality, but mostly it does not

So how does this madness make sense?

  • Enumerable#grep uses === internally
  • case when statements use === internally
  • Fun fact, rescue uses === internally

That is why you can use regular expressions and classes and ranges and even lambda expressions in a case when statement.

Some examples

case value
when /regexp/
  # value matches this regexp
when 4..10
  # value is in range
when MyClass
  # value is an instance of class
when ->(value) { ... }
  # lambda expression returns true
when a, b, c, d
  # value matches one of a through d with `===`
when *array
  # value matches an element in array with `===`
when x
  # values is equal to x unless x is one of the above
end

All these example work with pattern === value too, as well as with grep method.

arr = ['the', 'quick', 'brown', 'fox', 1, 1, 2, 3, 5, 8, 13]
arr.grep(/[qx]/)                                                                                                                            
# => ["quick", "fox"]
arr.grep(4..10)
# => [5, 8]
arr.grep(String)
# => ["the", "quick", "brown", "fox"]
arr.grep(1)
# => [1, 1]

How to configure postgresql for the first time?

EDIT: Warning: Please, read the answer posted by Evan Carroll. It seems that this solution is not safe and not recommended.

This worked for me in the standard Ubuntu 14.04 64 bits installation.

I followed the instructions, with small modifications, that I found in http://suite.opengeo.org/4.1/dataadmin/pgGettingStarted/firstconnect.html

  1. Install postgreSQL (if not already in your machine):

sudo apt-get install postgresql

  1. Run psql using the postgres user

sudo –u postgres psql postgres

  1. Set a new password for the postgres user:

\password postgres

  1. Exit psql

\q

  1. Edit /etc/postgresql/9.3/main/pg_hba.conf and change:

#Database administrative login by Unix domain socket local all postgres peer

To:

#Database administrative login by Unix domain socket local all postgres md5

  1. Restart postgreSQL:

sudo service postgresql restart

  1. Create a new database

sudo –u postgres createdb mytestdb

  1. Run psql with the postgres user again:

psql –U postgres –W

  1. List the existing databases (your new database should be there now):

\l

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

In my case use VS 2013, and It's not support MVC 3 natively (even of you change ./Views/web.config): https://stackoverflow.com/a/28155567/1536197

How to clear PermGen space Error in tomcat

I'm running tomcat7 on CentOS 6.6. I tried creating a new /usr/share/tomcat/bin/setenv.sh file and setting both JAVA_OPTS and CATALINA_OPTS. But tomcat wouldn't pick up the values on restart. When I put the following line into /etc/tomcat/tomcat.conf:

CATALINA_OPTS="-Xms128m -Xmx1024m -XX:MaxPermSize=1024m"

tomcat did pick up the new environment variable. I verified this by running

ps aux | grep tomcat

and seeing the new settings in the output. This took a long time to diagnose and I didn't see anyone else suggesting this, so I thought I'd throw it out to the internet community.

Connection Strings for Entity Framework

To enable the same edmx to access multiple databases and database providers and vise versa I use the following technique:

1) Define a ConnectionManager:

public static class ConnectionManager
{
    public static string GetConnectionString(string modelName)
    {
        var resourceAssembly = Assembly.GetCallingAssembly();

        var resources = resourceAssembly.GetManifestResourceNames();

        if (!resources.Contains(modelName + ".csdl")
            || !resources.Contains(modelName + ".ssdl")
            || !resources.Contains(modelName + ".msl"))
        {
            throw new ApplicationException(
                    "Could not find connection resources required by assembly: "
                    + System.Reflection.Assembly.GetCallingAssembly().FullName);
        }

        var provider = System.Configuration.ConfigurationManager.AppSettings.Get(
                        "MyModelUnitOfWorkProvider");

        var providerConnectionString = System.Configuration.ConfigurationManager.AppSettings.Get(
                        "MyModelUnitOfWorkConnectionString");

        string ssdlText;

        using (var ssdlInput = resourceAssembly.GetManifestResourceStream(modelName + ".ssdl"))
        {
            using (var textReader = new StreamReader(ssdlInput))
            {
                ssdlText = textReader.ReadToEnd();
            }
        }

        var token = "Provider=\"";
        var start = ssdlText.IndexOf(token);
        var end = ssdlText.IndexOf('"', start + token.Length);
        var oldProvider = ssdlText.Substring(start, end + 1 - start);

        ssdlText = ssdlText.Replace(oldProvider, "Provider=\"" + provider + "\"");

        var tempDir = Environment.GetEnvironmentVariable("TEMP") + '\\' + resourceAssembly.GetName().Name;
        Directory.CreateDirectory(tempDir);

        var ssdlOutputPath = tempDir + '\\' + Guid.NewGuid() + ".ssdl";

        using (var outputFile = new FileStream(ssdlOutputPath, FileMode.Create))
        {
            using (var outputStream = new StreamWriter(outputFile))
            {
                outputStream.Write(ssdlText);
            }
        }

        var eBuilder = new EntityConnectionStringBuilder
        {
            Provider = provider,

            Metadata = "res://*/" + modelName + ".csdl"
                        + "|" + ssdlOutputPath
                        + "|res://*/" + modelName + ".msl",

            ProviderConnectionString = providerConnectionString
        };

        return eBuilder.ToString();
    }
}

2) Modify the T4 that creates your ObjectContext so that it will use the ConnectionManager:

public partial class MyModelUnitOfWork : ObjectContext
{
    public const string ContainerName = "MyModelUnitOfWork";
    public static readonly string ConnectionString
        = ConnectionManager.GetConnectionString("MyModel");

3) Add the following lines to App.Config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="MyModelUnitOfWork" connectionString=... />
  </connectionStrings>
  <appSettings>
    <add key="MyModelUnitOfWorkConnectionString" value="data source=MyPc\SqlExpress;initial catalog=MyDB;integrated security=True;multipleactiveresultsets=True" />
    <add key="MyModelUnitOfWorkProvider" value="System.Data.SqlClient" />
  </appSettings>
</configuration>

The ConnectionManager will replace the ConnectionString and Provider to what ever is in the App.Config.

You can use the same ConnectionManager for all ObjectContexts (so they all read the same settings from App.Config), or edit the T4 so it creates one ConnectionManager for each (in its own namespace), so that each reads separate settings.

Dynamically add event listener

Renderer has been deprecated in Angular 4.0.0-rc.1, read the update below

The angular2 way is to use listen or listenGlobal from Renderer

For example, if you want to add a click event to a Component, you have to use Renderer and ElementRef (this gives you as well the option to use ViewChild, or anything that retrieves the nativeElement)

constructor(elementRef: ElementRef, renderer: Renderer) {

    // Listen to click events in the component
    renderer.listen(elementRef.nativeElement, 'click', (event) => {
      // Do something with 'event'
    })
);

You can use listenGlobal that will give you access to document, body, etc.

renderer.listenGlobal('document', 'click', (event) => {
  // Do something with 'event'
});

Note that since beta.2 both listen and listenGlobal return a function to remove the listener (see breaking changes section from changelog for beta.2). This is to avoid memory leaks in big applications (see #6686).

So to remove the listener we added dynamically we must assign listen or listenGlobal to a variable that will hold the function returned, and then we execute it.

// listenFunc will hold the function returned by "renderer.listen"
listenFunc: Function;

// globalListenFunc will hold the function returned by "renderer.listenGlobal"
globalListenFunc: Function;

constructor(elementRef: ElementRef, renderer: Renderer) {
    
    // We cache the function "listen" returns
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        // Do something with 'event'
    });

    // We cache the function "listenGlobal" returns
    this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
        // Do something with 'event'
    });
}

ngOnDestroy() {
    // We execute both functions to remove the respectives listeners

    // Removes "listen" listener
    this.listenFunc();
    
    // Removs "listenGlobal" listener
    this.globalListenFunc();
}

Here's a plnkr with an example working. The example contains the usage of listen and listenGlobal.

Using RendererV2 with Angular 4.0.0-rc.1+ (Renderer2 since 4.0.0-rc.3)

  • 25/02/2017: Renderer has been deprecated, now we should use RendererV2 (see line below). See the commit.

  • 10/03/2017: RendererV2 was renamed to Renderer2. See the breaking changes.

RendererV2 has no more listenGlobal function for global events (document, body, window). It only has a listen function which achieves both functionalities.

For reference, I'm copy & pasting the source code of the DOM Renderer implementation since it may change (yes, it's angular!).

listen(target: 'window'|'document'|'body'|any, event: string, callback: (event: any) => boolean):
      () => void {
    if (typeof target === 'string') {
      return <() => void>this.eventManager.addGlobalEventListener(
          target, event, decoratePreventDefault(callback));
    }
    return <() => void>this.eventManager.addEventListener(
               target, event, decoratePreventDefault(callback)) as() => void;
  }

As you can see, now it verifies if we're passing a string (document, body or window), in which case it will use an internal addGlobalEventListener function. In any other case, when we pass an element (nativeElement) it will use a simple addEventListener

To remove the listener it's the same as it was with Renderer in angular 2.x. listen returns a function, then call that function.

Example

// Add listeners
let global = this.renderer.listen('document', 'click', (evt) => {
  console.log('Clicking the document', evt);
})

let simple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
  console.log('Clicking the button', evt);
});

// Remove listeners
global();
simple();

plnkr with Angular 4.0.0-rc.1 using RendererV2

plnkr with Angular 4.0.0-rc.3 using Renderer2

bower command not found

I am almost sure you are not actually getting it installed correctly. Since you are trying to install it globally, you will need to run it with sudo:

sudo npm install -g bower

MySQLi count(*) always returns 1

Always try to do an associative fetch, that way you can easy get what you want in multiple case result

Here's an example

$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";

Eclipse Java error: This selection cannot be launched and there are no recent launches

It happens when sometimes we copy or import the project from somewhere. The source folder is a big thing to concern about.

One simple technique is, create a new project, inside the source folder, create a new class and paste the content over there.

It will work...

Hope it helps.

How do I combine 2 javascript variables into a string

ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:

// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);

// => "Yo, Brendan!"

var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);

//=> JavaScript first appeared 20 years ago. Crazy!

Markdown open a new window link

You can edit the generated markup and add

target = "_blank"

Setting Inheritance and Propagation flags with set-acl and powershell

Here's some succinct Powershell code to apply new permissions to a folder by modifying it's existing ACL (Access Control List).

# Get the ACL for an existing folder
$existingAcl = Get-Acl -Path 'C:\DemoFolder'

# Set the permissions that you want to apply to the folder
$permissions = $env:username, 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'

# Create a new FileSystemAccessRule object
$rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions

# Modify the existing ACL to include the new rule
$existingAcl.SetAccessRule($rule)

# Apply the modified access rule to the folder
$existingAcl | Set-Acl -Path 'C:\DemoFolder'

Each of the values in the $permissions variable list pertain to the parameters of this constructor for the FileSystemAccessRule class.

Courtesy of this page.

Jaxb, Class has two properties of the same name

These are the two properties JAXB is looking at.

public java.util.List testjaxp.ModeleREP.getTimeSeries()  

and

protected java.util.List testjaxp.ModeleREP.timeSeries

This can be avoided by using JAXB annotation at get method just like mentioned below.

@XmlElement(name="TimeSeries"))  
public java.util.List testjaxp.ModeleREP.getTimeSeries()

How to solve SyntaxError on autogenerated manage.py?

I had same problem and could solve it. It is related to the version of Django you've installed, some of them are not supported by python 2.7. If you have installed Django with pip, it means that you are installing the latest version of that which probably is not supported in python 2.7, You can get more information about it here. I would suggest to python 3 or specify the version of Django during installing (which is 1.11 for python 2.7).

MySQL Server has gone away when importing large sql file

I am doing some large calculations which involves the mysql connection to stay long time and with heavy data. i was facing this "Mysql go away issue". So i tried t optimize the queries but that doen't helped me then i increased the mysql variables limit which is set to a lower value by default.

wait_timeout max_allowed_packet

To the limit what ever suits to you it should be the Any Number * 1024(Bytes). you can login to terminal using 'mysql -u username - p' command and can check and change for these variable limits.

how to make a html iframe 100% width and height?

this code probable help you .

<iframe src="" onload="this.width=screen.width;this.height=screen.height;">

How to launch a Google Chrome Tab with specific URL using C#

UPDATE: Please see Dylan's or d.c's anwer for a little easier (and more stable) solution, which does not rely on Chrome beeing installed in LocalAppData!


Even if I agree with Daniel Hilgarth to open a new tab in chrome you just need to execute chrome.exe with your URL as the argument:

Process.Start(@"%AppData%\..\Local\Google\Chrome\Application\chrome.exe", 
              "http:\\www.YourUrl.com");

XCOPY switch to create specified directory if it doesn't exist?

I tried this on the command.it is working for me.

if "$(OutDir)"=="bin\Debug\"  goto Visual
:TFSBuild
goto exit
:Visual
xcopy /y "$(TargetPath)$(TargetName).dll" "$(ProjectDir)..\Demo"
xcopy /y "$(TargetDir)$(TargetName).pdb" "$(ProjectDir)..\Demo"
goto exit
:exit

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

Find out whether radio button is checked with JQuery?

dynamic generated Radio Button Check radio get value

$("input:radio[name=radiobuttonname:checked").val();

On change dynamic Radio button

$('input[name^="radioname"]').change(function () {if (this.value == 2) { }else{}});

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

For me, this was an issue with cyclic dependencies.

IOW, module A required module B, and module B required module A.

So in module B, require('./A') is an empty object rather than a function.

How to deal with cyclic dependencies in Node.js

SQLException: No suitable driver found for jdbc:derby://localhost:1527

The JDBC DriverManager can't find any suitable Driver for the given connection URL. Either the JDBC driver isn't loaded at all before connecting the DB, or the connection URL is wrong. Since the connection URL looks fine, I bet that the driver isn't loaded at all. You need to load the driver during application's startup before connecting the DB. For Apache Derby, the driver class name is org.apache.derby.jdbc.ClientDriver. So:

Class.forName("org.apache.derby.jdbc.ClientDriver");

How to set shape's opacity?

In general you just have to define a slightly transparent color when creating the shape.

You can achieve that by setting the colors alpha channel.

#FF000000 will get you a solid black whereas #00000000 will get you a 100% transparent black (well it isn't black anymore obviously).

The color scheme is like this #AARRGGBB there A stands for alpha channel, R stands for red, G for green and B for blue.

The same thing applies if you set the color in Java. There it will only look like 0xFF000000.

UPDATE

In your case you'd have to add a solid node. Like below.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/shape_my">
    <stroke android:width="4dp" android:color="#636161" />
    <padding android:left="20dp"
        android:top="20dp"
        android:right="20dp"
        android:bottom="20dp" />
    <corners android:radius="24dp" />
    <solid android:color="#88000000" />
</shape>

The color here is a half transparent black.

Access event to call preventdefault from custom function originating from onclick attribute of tag

Add a unique class to the links and a javascript that prevents default on links with this class:

<a href="#" class="prevent-default" 
   onclick="$('.comment .hidden').toggle();">Show comments</a>

<script>
  $(document).ready(function(){

    $("a.prevent-default").click(function(event) {
         event.preventDefault(); 
          });
  });
</script>

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

It should be noted that primitive types must have a value. If you used Objects (ie Integer), you could initialize value to null and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

angularjs make a simple countdown

You probably didn't declare your module correctly, or you put the function before the module is declared (safe rule is to put angular module after the body, once all the page is loaded). Since you're using angularjs, then you should use $interval (angularjs equivalence to setInterval which is a windows service).

Here is a working solution:

_x000D_
_x000D_
angular.module('count', [])_x000D_
  .controller('countController', function($scope, $interval) {_x000D_
    $scope.countDown = 10;_x000D_
    $interval(function() {_x000D_
      console.log($scope.countDown--);_x000D_
    }, 1000, $scope.countDown);_x000D_
  });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.1/angular.min.js"></script>_x000D_
_x000D_
_x000D_
<body>_x000D_
  <div ng-app="count" ng-controller="countController"> {{countDown}} </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Note: it stops at 0 in the html view, but at 1 in the console.log, can you figure out why? ;)

return error message with actionResult

You need to return a view which has a friendly error message to the user

catch (Exception ex)
{
   // to do :log error
   return View("Error");
}

You should not be showing the internal details of your exception(like exception stacktrace etc) to the user. You should be logging the relevant information to your error log so that you can go through it and fix the issue.

If your request is an ajax request, You may return a JSON response with a proper status flag which client can evaluate and do further actions

[HttpPost]
public ActionResult Create(CustomerVM model)
{
  try
  {
   //save customer
    return Json(new { status="success",message="customer created"});
  }
  catch(Exception ex)
  {
    //to do: log error
   return Json(new { status="error",message="error creating customer"});
  }
} 

If you want to show the error in the form user submitted, You may use ModelState.AddModelError method along with the Html helper methods like Html.ValidationSummary etc to show the error to the user in the form he submitted.

Java converting int to hex and back again

int val = -32768;
String hex = Integer.toHexString(val);

int parsedResult = (int) Long.parseLong(hex, 16);
System.out.println(parsedResult);

That's how you can do it.

The reason why it doesn't work your way: Integer.parseInt takes a signed int, while toHexString produces an unsigned result. So if you insert something higher than 0x7FFFFFF, an error will be thrown automatically. If you parse it as long instead, it will still be signed. But when you cast it back to int, it will overflow to the correct value.

Div with horizontal scrolling only

try this:

HTML:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
</div>

CSS:

.container {
  width: 200px;
  height: 100px;
  display: flex;
  overflow-x: auto;
}

.item {
  width: 100px;
  flex-shrink: 0;
  height: 100px;
}

The white-space: nowrap; property dont let you wrap text. Just see here for an example: https://codepen.io/oezkany/pen/YoVgYK

What is the difference between a strongly typed language and a statically typed language?

Answer is already given above. Trying to differentiate between strong vs week and static vs dynamic concept.

What is Strongly typed VS Weakly typed?

Strongly Typed: Will not be automatically converted from one type to another

In Go or Python like strongly typed languages "2" + 8 will raise a type error, because they don't allow for "type coercion".

Weakly (loosely) Typed: Will be automatically converted to one type to another: Weakly typed languages like JavaScript or Perl won't throw an error and in this case JavaScript will results '28' and perl will result 10.

Perl Example:

my $a = "2" + 8;
print $a,"\n";

Save it to main.pl and run perl main.pl and you will get output 10.

What is Static VS Dynamic type?

In programming, programmer define static typing and dynamic typing with respect to the point at which the variable types are checked. Static typed languages are those in which type checking is done at compile-time, whereas dynamic typed languages are those in which type checking is done at run-time.

  • Static: Types checked before run-time
  • Dynamic: Types checked on the fly, during execution

What is this means?

In Go it checks typed before run-time (static check). This mean it not only translates and type-checks code it’s executing, but it will scan through all the code and type error would be thrown before the code is even run. For example,

package main

import "fmt"

func foo(a int) {
    if (a > 0) {
        fmt.Println("I am feeling lucky (maybe).")
    } else {
        fmt.Println("2" + 8)
    }
}

func main() {
    foo(2)
}

Save this file in main.go and run it, you will get compilation failed message for this.

go run main.go
# command-line-arguments
./main.go:9:25: cannot convert "2" (type untyped string) to type int
./main.go:9:25: invalid operation: "2" + 8 (mismatched types string and int)

But this case is not valid for Python. For example following block of code will execute for first foo(2) call and will fail for second foo(0) call. It's because Python is dynamically typed, it only translates and type-checks code it’s executing on. The else block never executes for foo(2), so "2" + 8 is never even looked at and for foo(0) call it will try to execute that block and failed.

def foo(a):
    if a > 0:
        print 'I am feeling lucky.'
    else:
        print "2" + 8
foo(2)
foo(0)

You will see following output

python main.py
I am feeling lucky.
Traceback (most recent call last):
  File "pyth.py", line 7, in <module>
    foo(0)
  File "pyth.py", line 5, in foo
    print "2" + 8
TypeError: cannot concatenate 'str' and 'int' objects

Android Google Maps API V2 Zoom to Current Location

This is working Current Location with zoom for Google Map V2

 double lat= location.getLatitude();
 double lng = location.getLongitude();
 LatLng ll = new LatLng(lat, lng);
 googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));

Create new user in MySQL and give it full access to one database

The below command will work if you want create a new user give him all the access to a specific database(not all databases in your Mysql) on your localhost.

GRANT ALL PRIVILEGES ON test_database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

This will grant all privileges to one database test_database (in your case dbTest) to that user on localhost.

Check what permissions that above command issued to that user by running the below command.

SHOW GRANTS FOR 'user'@'localhost'

Just in case, if you want to limit the user access to only one single table

GRANT ALL ON mydb.table_name TO 'someuser'@'host';

Read .doc file with python

One can use the textract library. It take care of both "doc" as well as "docx"

import textract
text = textract.process("path/to/file.extension")

You can even use 'antiword' (sudo apt-get install antiword) and then convert doc to first into docx and then read through docx2txt.

antiword filename.doc > filename.docx

Ultimately, textract in the backend is using antiword.

Check if not nil and not empty in Rails shortcut?

You can use .present? which comes included with ActiveSupport.

@city = @user.city.present?
# etc ...

You could even write it like this

def show
  %w(city state bio contact twitter mail).each do |attr|
    instance_variable_set "@#{attr}", @user[attr].present?
  end
end

It's worth noting that if you want to test if something is blank, you can use .blank? (this is the opposite of .present?)

Also, don't use foo == nil. Use foo.nil? instead.

How to link to part of the same document in Markdown?

Some more spins on the <a name=""> trick:

<a id="a-link"></a> Title
------

#### <a id="a-link"></a> Title (when you wanna control the h{N} with #'s)

Query to list all stored procedures

If you are using SQL Server 2005 the following will work:

select *
  from sys.procedures
 where is_ms_shipped = 0

Assigning multiple styles on an HTML element

In HTML the style tag has the following syntax:

style="property1:value1;property2:value2"

so in your case:

<h2 style="text-align:center;font-family:tahoma">TITLE</h2>

Hope this helps.

Manually adding a Userscript to Google Chrome

Update 2016: seems to be working again.

Update August 2014: No longer works as of recent Chrome versions.


Yeah, the new state of affairs sucks. Fortunately it's not so hard as the other answers imply.

  1. Browse in Chrome to chrome://extensions
  2. Drag the .user.js file into that page.

Voila. You can also drag files from the downloads footer bar to the extensions tab.

Chrome will automatically create a manifest.json file in the extensions directory that Brock documented.

<3 Freedom.

Creation timestamp and last update timestamp with Hibernate and MySQL

If you are using the JPA annotations, you can use @PrePersist and @PreUpdate event hooks do this:

@Entity
@Table(name = "entities")    
public class Entity {
  ...

  private Date created;
  private Date updated;

  @PrePersist
  protected void onCreate() {
    created = new Date();
  }

  @PreUpdate
  protected void onUpdate() {
    updated = new Date();
  }
}

or you can use the @EntityListener annotation on the class and place the event code in an external class.

How to split data into 3 sets (train, validation and test)?

def train_val_test_split(X, y, train_size, val_size, test_size):
    X_train_val, X_test, y_train_val, y_test = train_test_split(X, y, test_size = test_size)
    relative_train_size = train_size / (val_size + train_size)
    X_train, X_val, y_train, y_val = train_test_split(X_train_val, y_train_val,
                                                      train_size = relative_train_size, test_size = 1-relative_train_size)
    return X_train, X_val, X_test, y_train, y_val, y_test

Here we split data 2 times with sklearn's train_test_split

View google chrome's cached pictures

This page contains all the cached urls

chrome://cache

Unfortunately to actually see the file you have to select everything on the page and paste it in this tool: http://www.sensefulsolutions.com/2012/01/viewing-chrome-cache-easy-way.html

How do I truncate a .NET string?

As an addition to the possibilities discussed above I'd like to share my solution. It's an extension method that allows null (returns string.Empty) also there is a second .Truncate() for using it with an ellipsis. Beware, it's not performance optimized.

public static string Truncate(this string value, int maxLength) =>
    (value ?? string.Empty).Substring(0, (value?.Length ?? 0) <= (maxLength < 0 ? 0 : maxLength) ? (value?.Length ?? 0) : (maxLength < 0 ? 0 : maxLength));
public static string Truncate(this string value, int maxLength, string ellipsis) =>
    string.Concat(value.Truncate(maxLength - (((value?.Length ?? 0) > maxLength ? ellipsis : null)?.Length ?? 0)), ((value?.Length ?? 0) > maxLength ? ellipsis : null)).Truncate(maxLength);

Can I change a column from NOT NULL to NULL without dropping it?

ALTER TABLE myTable ALTER COLUMN myColumn {DataType} NULL

where {DataType} is the current data type of that column (For example int or varchar(10))

How do function pointers in C work?

Since function pointers are often typed callbacks, you might want to have a look at type safe callbacks. The same applies to entry points, etc of functions that are not callbacks.

C is quite fickle and forgiving at the same time :)

d3 add text to circle

Here's a way that I consider easier: The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre.

const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ]

const nodeElems = svg.append('g')
.selectAll('circle')
.data(nodes)
.enter().append('circle')
.attr('r',radius)
.attr('fill', getNodeColor)

const textElems = svg.append('g')
.selectAll('text')
.data(nodes)
.enter().append('text')
.text(node => node.label)
.attr('font-size',8)//font size
.attr('dx', -10)//positions text towards the left of the center of the circle
.attr('dy',4)

Read a plain text file with php

$file="./doc.txt";
$doc=file_get_contents($file);

$line=explode("\n",$doc);
foreach($line as $newline){
    echo '<h3 style="color:#453288">'.$newline.'</h3><br>';

}

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

I am assuming what you are trying to achieve is to insert a line after the first few lines of of a textfile.

head -n10 file.txt >> newfile.txt
echo "your line >> newfile.txt
tail -n +10 file.txt >> newfile.txt

If you don't want to rest of the lines from the file, just skip the tail part.

convert date string to mysql datetime field

I assume we are talking about doing this in Bash?

I like to use sed to load the date values into an array so I can break down each field and do whatever I want with it. The following example assumes and input format of mm/dd/yyyy...

DATE=$2
DATE_ARRAY=(`echo $DATE | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
LOAD_DATE=$YEAR$MONTH$DAY

you also may want to read up on the date command in linux. It can be very useful: http://unixhelp.ed.ac.uk/CGI/man-cgi?date

Hope that helps... :)

-Ryan