Programs & Examples On #Luntbuild

Luntbuild is a build automation and management tool.

Select SQL results grouped by weeks

This should do it for you:

Declare @DatePeriod datetime

Set @DatePeriod = '2011-05-30'

Select  ProductName,
        IsNull([1],0) as 'Week 1',
        IsNull([2],0) as 'Week 2',
        IsNull([3],0) as 'Week 3',
        IsNull([4],0) as 'Week 4',
        IsNull([5], 0) as 'Week 5'

From 
(
Select  ProductName,
        DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, InputDate), 0), InputDate) +1 as [Weeks],
        Sale as 'Sale'

From dbo.YourTable
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, InputDate)= DatePart(Month, @DatePeriod)
)p 
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv

It will calculate the week number relative to the month. So instead of week 20 for the year it will be week 2. The @DatePeriod variable is used to fetch only rows relative to the month (in this example only for the month of May)

Output using my sample data:

enter image description here

cleanup php session files

You can create script /etc/cron.hourly/php and put there:

#!/bin/bash

max=24
tmpdir=/tmp

nice find ${tmpdir} -type f -name 'sess_*' -mmin +${max} -delete

Then make the script executable (chmod +x).

Now every hour will be deleted all session files with data modified more than 24 minutes ago.

MySQL OPTIMIZE all tables?

You can use mysqlcheck to do this at the command line.

One database:

mysqlcheck -o <db_schema_name>

All databases:

mysqlcheck -o --all-databases

Python unexpected EOF while parsing

Indent it! first. That would take care of your SyntaxError.

Apart from that there are couple of other problems in your program.

  • Use raw_input when you want accept string as an input. input takes only Python expressions and it does an eval on them.

  • You are using certain 8bit characters in your script like . You might need to define the encoding at the top of your script using # -*- coding:latin-1 -*- line commonly called as coding-cookie.

  • Also, while doing str comparison, normalize the strings and compare. (people using lower() it) This helps in giving little flexibility with user input.

  • I also think that reading Python tutorial might helpful to you. :)

Sample Code

#-*- coding: latin1 -*-

while 1:
    date=raw_input("Example: March 21 | What is the date? ")
    if date.lower() == "march 21":

    ....

How to use executables from a package installed locally in node_modules?

In case you are using fish shell and do not want to add to $path for security reason. We can add the below function to run local node executables.

### run executables in node_module/.bin directory
function n 
  set -l npmbin (npm bin)   
  set -l argvCount (count $argv)
  switch $argvCount
    case 0
      echo please specify the local node executable as 1st argument
    case 1
      # for one argument, we can eval directly 
      eval $npmbin/$argv
    case '*'
      set --local executable $argv[1]
      # for 2 or more arguments we cannot append directly after the $npmbin/ since the fish will apply each array element after the the start string: $npmbin/arg1 $npmbin/arg2... 
      # This is just how fish interoperate array. 
      set --erase argv[1]
      eval $npmbin/$executable $argv 
  end
end

Now you can run thing like:

n coffee

or more arguments like:

n browser-sync --version

Note, if you are bash user, then @Bob9630 answers is the way to go by leveraging bash's $@, which is not available in fishshell.

CSS Div width percentage and padding without breaking layout

You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.

An example:

width: calc((100%) - (32px))

Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.

_x000D_
_x000D_
.outer {_x000D_
  width: 200px;_x000D_
  height: 120px;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  height: 40px;_x000D_
  top: 30px;_x000D_
  position: relative;_x000D_
  padding: 16px;_x000D_
  background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
  width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
  <div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
  <div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to read until EOF from cin in C++

The only way you can read a variable amount of data from stdin is using loops. I've always found that the std::getline() function works very well:

std::string line;
while (std::getline(std::cin, line))
{
    std::cout << line << std::endl;
}

By default getline() reads until a newline. You can specify an alternative termination character, but EOF is not itself a character so you cannot simply make one call to getline().

What is class="mb-0" in Bootstrap 4?

Bootstrap has predefined classes that we use for styling. If you are familiar with CSS, you'd know what padding, margin and spacing etc. are.

mb-0 = margin-bottom:0;

OK now moving a little further in knowledge, bootstrap has more classes for margin including:

mt- = margin-top
mb- = margin-bottom
ml- = margin-left
mr- = margin-right
my- = it sets margin-left and margin-right at the same time on y axes
mX- = it sets margin-bottom and margin-top at the same time on X axes

This and much more is explained here https://getbootstrap.com/docs/5.0/utilities/spacing/ The best way to learn is through https://getbootstrap.com site itself. It explains a lot obout its built in classes.

How to get the first element of the List or Set?

This is not an exact answer to this question, but in case the objects should be sorted SortedSet has a first() method:

SortedSet<String> sortedSet = new TreeSet<String>();
sortedSet.add("2");
sortedSet.add("1");
sortedSet.add("3");
String first = sortedSet.first(); //first="1"

The sorted objects must implement the Comparable interface (like String does)

Given URL is not permitted by the application configuration

Sometimes this error occurs for old javascript sdk. If you save locally javascript file. Update it. I prefer to load it form the facebook server all the time.

Creating a segue programmatically

You have to link your code to the UIStoryboard that you're using. Make sure you go into YourViewController in your UIStoryboard, click on the border around it, and then set its identifier field to a NSString that you call in your code.

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" 
                                                     bundle:nil];
YourViewController *yourViewController = 
 (YourViewController *)
  [storyboard instantiateViewControllerWithIdentifier:@"yourViewControllerID"];
[self.navigationController pushViewController:yourViewController animated:YES];

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

KOUT[i] is a single element of a list. But you are assigning a list to this element. your func is generating a list.

Passing in class names to react components

With React 16.6.3 and @Material UI 3.5.1, I am using arrays in className like className={[classes.tableCell, classes.capitalize]}

Try something like the following in your case.

class Pill extends React.Component {
    render() {
        return (
           <button className={['pill', this.props.styleName]}>{this.props.children}</button>
        );
    }
}

Two values from one input in python?

The Python way to map

printf("Enter two numbers here: ");
scanf("%d %d", &var1, &var2)

would be

var1, var2 = raw_input("Enter two numbers here: ").split()

Note that we don't have to explicitly specify split(' ') because split() uses any whitespace characters as delimiter as default. That means if we simply called split() then the user could have separated the numbers using tabs, if he really wanted, and also spaces.,

Python has dynamic typing so there is no need to specify %d. However, if you ran the above then var1 and var2 would be both Strings. You can convert them to int using another line

var1, var2 = [int(var1), int(var2)]

Or you could use list comprehension

var1, var2 = [int(x) for x in [var1, var2]]

To sum it up, you could have done the whole thing with this one-liner:

# Python 3
var1, var2 = [int(x) for x in input("Enter two numbers here: ").split()]

# Python 2
var1, var2 = [int(x) for x in raw_input("Enter two numbers here: ").split()]

Java: splitting the filename into a base and extension

Source: http://www.java2s.com/Code/Java/File-Input-Output/Getextensionpathandfilename.htm

such an utility class :

class Filename {
  private String fullPath;
  private char pathSeparator, extensionSeparator;

  public Filename(String str, char sep, char ext) {
    fullPath = str;
    pathSeparator = sep;
    extensionSeparator = ext;
  }

  public String extension() {
    int dot = fullPath.lastIndexOf(extensionSeparator);
    return fullPath.substring(dot + 1);
  }

  public String filename() { // gets filename without extension
    int dot = fullPath.lastIndexOf(extensionSeparator);
    int sep = fullPath.lastIndexOf(pathSeparator);
    return fullPath.substring(sep + 1, dot);
  }

  public String path() {
    int sep = fullPath.lastIndexOf(pathSeparator);
    return fullPath.substring(0, sep);
  }
}

usage:

public class FilenameDemo {
  public static void main(String[] args) {
    final String FPATH = "/home/mem/index.html";
    Filename myHomePage = new Filename(FPATH, '/', '.');
    System.out.println("Extension = " + myHomePage.extension());
    System.out.println("Filename = " + myHomePage.filename());
    System.out.println("Path = " + myHomePage.path());
  }
}

How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'

using OR if you have multiple keywords.

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

This was a bug fixed in version 4.3.11 https://hibernate.atlassian.net/browse/HHH-2851

EDIT: Best way to execute a native query is still to use NamedParameterJdbcTemplate It allows you need to retrieve a result that is not a managed entity ; you can use a RowMapper and even a Map of named parameters!

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

@Autowired
public void setDataSource(DataSource dataSource) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}

final List<Long> resultList = namedParameterJdbcTemplate.query(query, 
            mapOfNamedParamters, 
            new RowMapper<Long>() {
        @Override
        public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getLong(1);
        }
    });

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

Here is some SQL that actually make sense:

SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL

Simple is always better.

Determine which element the mouse pointer is on top of in JavaScript

In newer browsers, you could do the following:

document.querySelectorAll( ":hover" );

That'll give you a NodeList of items that the mouse is currently over in document order. The last element in the NodeList is the most specific, each preceding one should be a parent, grandparent, and so on.

How to clear File Input

Another solution if you want to be certain that this is cross-browser capable is to remove() the tag and then append() or prepend() or in some other way re-add a new instance of the input tag with the same attributes.

<form method="POST" enctype="multipart/form-data">
<label for="fileinput">
 <input type="file" name="fileinput" id="fileinput" />
</label>
</form>

$("#fileinput").remove();
$("<input>")
  .attr({
    type: 'file',
    id: 'fileinput',
    name: 'fileinput'
    })
  .appendTo($("label[for='fileinput']"));

AngularJS - pass function to directive

Perhaps I am missing something, but although the other solutions do call the parent scope function there is no ability to pass arguments from directive code, this is because the update-fn is calling updateFn() with fixed parameters, in for example {msg: "Hello World"}. A slight change allows the directive to pass arguments, which I would think is far more useful.

<test color1="color1" update-fn="updateFn"></test>

Note the HTML is passing a function reference, i.e., without () brackets.

JS

var app = angular.module('dr', []);

app.controller("testCtrl", function($scope) {
    $scope.color1 = "color";
    $scope.updateFn = function(msg) {        
        alert(msg);
    }
});

app.directive('test', function() {
    return {
        restrict: 'E',
        scope: {
            color1: '=',
            updateFn: '&'
        },
        // object is passed while making the call
        template: "<button ng-click='callUpdate()'>
            Click</button>",
        replace: true,        
        link: function(scope, elm, attrs) {       
          scope.callUpdate = function() {
            scope.updateFn()("Directive Args");
          }
        }
    }
});

So in the above, the HTML is calling local scope callUpdate function, which then 'fetches' the updateFn from the parent scope and calls the returned function with parameters that the directive can generate.

http://jsfiddle.net/mygknek2/

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

Your annotations look fine. Here are the things to check:

  • make sure the annotation is javax.persistence.Entity, and not org.hibernate.annotations.Entity. The former makes the entity detectable. The latter is just an addition.

  • if you are manually listing your entities (in persistence.xml, in hibernate.cfg.xml, or when configuring your session factory), then make sure you have also listed the ScopeTopic entity

  • make sure you don't have multiple ScopeTopic classes in different packages, and you've imported the wrong one.

grep without showing path/file:line

From the man page:

-h, --no-filename
    Suppress the prefixing of file names on output. This is the default when there
    is only one file (or only standard input) to search.

insert a NOT NULL column to an existing table

ALTER TABLE `MY_TABLE` ADD COLUMN `STAGE` INTEGER UNSIGNED NOT NULL AFTER `PREV_COLUMN`;

How to group by week in MySQL?

If you need the "week ending" date this will work as well. This will count the number of records for each week. Example: If three work orders were created between (inclusive) 1/2/2010 and 1/8/2010 and 5 were created between (inclusive) 1/9/2010 and 1/16/2010 this would return:

3 1/8/2010
5 1/16/2010

I had to use the extra DATE() function to truncate my datetime field.

SELECT COUNT(*), DATE_ADD( DATE(wo.date_created), INTERVAL (7 - DAYOFWEEK( wo.date_created )) DAY) week_ending
FROM work_order wo
GROUP BY week_ending;

Taking the record with the max date

If date and col_date are the same columns you should simply do:

SELECT A, MAX(date) FROM t GROUP BY A

Why not use:

WITH x AS ( SELECT A, MAX(col_date) m FROM TABLENAME )
SELECT A, date FROM TABLENAME t JOIN x ON x.A = t.A AND x.m = t.col_date

Otherwise:

SELECT A, FIRST_VALUE(date) KEEP(dense_rank FIRST ORDER BY col_date DESC)
  FROM TABLENAME
 GROUP BY A

How to loop through key/value object in Javascript?

Something like this:

setUsers = function (data) {
    for (k in data) {
        user[k] = data[k];
    }
}

Send JSON via POST in C# and Receive the JSON returned?

Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:

// ...

string payload = JsonConvert.SerializeObject(new
{
    agent = new
    {
        name    = "Agent Name",
        version = 1,
    },

    username = "username",
    password = "password",
    token    = "xxxxx",
});

var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(uri, content);

// ...

how to open popup window using jsp or jquery?

Can be done with in jquery-

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css" />
    <script>
    $(function() {
    $( "#dialog" ).dialog();
    });
    </script>

    <div id="dialog" title="Basic dialog">
    //your form layout
    </div>

Pivoting rows into columns dynamically in Oracle

First of all, dynamically pivot using pivot xml again needs to be parsed. We have another way of doing this by storing the column names in a variable and passing them in the dynamic sql as below.

Consider we have a table like below.

enter image description here

If we need to show the values in the column YR as column names and the values in those columns from QTY, then we can use the below code.

declare
  sqlqry clob;
  cols clob;
begin
  select listagg('''' || YR || ''' as "' || YR || '"', ',') within group (order by YR)
  into   cols
  from   (select distinct YR from EMPLOYEE);


  sqlqry :=
  '      
  select * from
  (
      select *
      from EMPLOYEE
  )
  pivot
  (
    MIN(QTY) for YR in (' || cols  || ')
  )';

  execute immediate sqlqry;
end;
/

RESULT

enter image description here

What is the equivalent of ngShow and ngHide in Angular 2+?

I find myself in the same situation with the difference than in my case the element was a flex container.If is not your case an easy work around could be

[style.display]="!isLoading ? 'block' : 'none'"

in my case due to the fact that a lot of browsers that we support still need the vendor prefix to avoid problems i went for another easy solution

[class.is-loading]="isLoading"

where then the CSS is simple as

&.is-loading { display: none } 

to leave then the displayed state handled by the default class.

Can I change the Android startActivity() transition animation?

In the same statement in which you execute finish(), execute your animation there too. Then, in the new activity, run another animation. See this code:

fadein.xml

<set xmlns:android="http://schemas.android.com/apk/res/android" 
     android:fillAfter="true">
     <alpha android:fromAlpha="1.0" 
            android:toAlpha="0.0"
            android:duration="500"/> //Time in milliseconds
</set>

In your finish-class

private void finishTask() {
    if("blabbla".equals("blablabla"){
        finish();
        runFadeInAnimation();
    }
}

private void runFadeInAnimation() {
    Animation a = AnimationUtils.loadAnimation(this, R.anim.fadein);
    a.reset();
    LinearLayout ll = (LinearLayout) findViewById(R.id.yourviewhere);
    ll.clearAnimation();
    ll.startAnimation(a);   
}

fadeout.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
           android:fillAfter="true">
  <alpha android:fromAlpha="0.0"
         android:toAlpha="1.0"
         android:duration="500"/>
</set>

In your new Activity-class you create a similiar method like the runFadeAnimation I wrote and then you run it in onCreate and don't forget to change the resources id to fadeout.

Center Plot title in ggplot2

The ggeasy package has a function called easy_center_title() to do just that. I find it much more appealing than theme(plot.title = element_text(hjust = 0.5)) and it's so much easier to remember.

ggplot(data = dat, aes(time, total_bill, fill = time)) + 
  geom_bar(colour = "black", fill = "#DD8888", width = .8, stat = "identity") + 
  guides(fill = FALSE) +
  xlab("Time of day") +
  ylab("Total bill") +
  ggtitle("Average bill for 2 people") +
  ggeasy::easy_center_title()

enter image description here

Note that as of writing this answer you will need to install the development version of ggeasy from GitHub to use easy_center_title(). You can do so by running remotes::install_github("jonocarroll/ggeasy").

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

How to make a node.js application run permanently?

Try pm2 to make your application run forever.

npm install -g pm2

and then use

pm2 start server.js

to list and stop apps, use commnds

pm2 list

pm2 stop 0

Serializing/deserializing with memory stream

BinaryFormatter may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.

If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer or XmlSerializer.

Empty ArrayList equals null

No, because it contains items there must be an instance of it. Its items being null is irrelevant, so the statment ((arrayList) != null) == true

Multiple arguments to function called by pthread_create()?

I have the same question as the original poster, Michael.

However I have tried to apply the answers submitted for the original code without success

After some trial and error, here is my version of the code that works (or at least works for me!). And if you look closely, you will note that it is different to the earlier solutions posted.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct arg_struct
{
   int arg1;
   int arg2;
} *args;

void *print_the_arguments(void *arguments)
{
   struct arg_struct *args = arguments;
   printf("Thread\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   pthread_exit(NULL);
   return NULL;
}

int main()
{
   pthread_t some_thread;
   args = malloc(sizeof(struct arg_struct) * 1);

   args->arg1 = 5;
   args->arg2 = 7;

   printf("Before\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   printf("\n");


   if (pthread_create(&some_thread, NULL, &print_the_arguments, args) != 0)
   {
      printf("Uh-oh!\n");
      return -1;
   }

   return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}

How to compare a local git branch with its remote branch?

If you use TortoiseGit (it provides GUI for Git), you can right click your Git repo folder then click Git Sync.

You can select your branches to compare if not selected. Than you can view differences commit. You can also right click any commit then Compare with previous revision to view differences side by side.tortoise git sync to compare remote and local branch

org.hibernate.MappingException: Unknown entity

you should add all the entity files in the .addAnnotatedClass(Class) method, if the class needs to be auto discovered.

use this link, it might help..

http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/cfg/AnnotationConfiguration.html

Browser Caching of CSS files

Your file will probably be cached - but it depends...

Different browsers have slightly different behaviors - most noticeably when dealing with ambiguous/limited caching headers emanating from the server. If you send a clear signal, the browsers obey, virtually all of the time.

The greatest variance by far, is in the default caching configuration of different web servers and application servers.

Some (e.g. Apache) are likely to serve known static file types with HTTP headers encouraging the browser to cache them, while other servers may send no-cache commands with every response - regardless of filetype.

...

So, first off, read some of the excellent HTTP caching tutorials out there. HTTP Caching & Cache-Busting for Content Publishers was a real eye opener for me :-)

Next install and fiddle around with Firebug and the Live HTTP Headers add-on , to find out which headers your server is actually sending.

Then read your web server docs to find out how to tweak them to perfection (or talk your sysadmin into doing it for you).

...

As to what happens when the browser is restarted, it depends on the browser and the user configuration.

As a rule of thumb, expect the browser to be more likely to check in with the server after each restart, to see if anything has changed (see If-Last-Modified and If-None-Match).

If you configure your server correctly, it should be able to return a super-short 304 Not Modified (costing very little bandwidth) and after that the browser will use the cache as normal.

How to force C# .net app to run only one instance in Windows?

I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded

using System.Threading;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   bool createdNew = true;
   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
   {
      if (createdNew)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
      else
      {
         Process current = Process.GetCurrentProcess();
         foreach (Process process in Process.GetProcessesByName(current.ProcessName))
         {
            if (process.Id != current.Id)
            {
               SetForegroundWindow(process.MainWindowHandle);
               break;
            }
         }
      }
   }
}

Jquery change background color

This is how it should be:

Code:

$(function(){
  $("button").mouseover(function(){
    var $p = $("#P44");
    $p.stop()
      .css("background-color","yellow")
      .hide(1500, function() {
          $p.css("background-color","red")
            .show(1500);
      });
  });
});

Demo: http://jsfiddle.net/p7w9W/2/

Explanation:

You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p> there you shouldn't include a class in your selector.

I also enhanced your code (caching of the jQuery object, chaining, etc.)

Update: As suggested by VKolev the color is now changing when the item is hidden.

Find the host name and port using PSQL commands

select inet_server_addr( ), inet_server_port( );

Multiple separate IF conditions in SQL Server

Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.

As a beginner in SQL I find that when using a BEGIN and END SSMS usually adds a squiggly line with incorrect syntax near 'END' to END, simply because there's no content in between yet. If you're just setting up BEGIN and END to get started and add the actual query later, then simply add a bogus PRINT statement so SSMS stops bothering you.

For example:

IF (1=1)
BEGIN
  PRINT 'BOGUS'
END

The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:

IF (1=1)
BEGIN
END

localhost refused to connect Error in visual studio

I had the same problem. Deleting .vs folder (including all contents, folder might be hidden) worked for me.

How to merge two json string in Python?

What do you mean by merging? JSON objects are key-value data structure. What would be a key and a value in this case? I think you need to create new directory and populate it with old data:

d = {}
d["new_key"] = jsonStringA[<key_that_you_did_not_mention_here>] + \ 
               jsonStringB["timestamp_in_ms"]

Merging method is obviously up to you.

Linux: command to open URL in default browser

For opening a URL in the browser through the terminal, CentOS 7 users can use gio open command. For example, if you want to open google.com then gio open https://www.google.com will open google.com URL in the browser.

xdg-open https://www.google.com will also work but this tool has been deprecated, Use gio open instead. I prefer this as this is the easiest way to open a URL using a command from the terminal.

Can I call a base class's virtual function if I'm overriding it?

Sometimes you need to call the base class' implementation, when you aren't in the derived function...It still works:

struct Base
{
    virtual int Foo()
    {
        return -1;
    }
};

struct Derived : public Base
{
    virtual int Foo()
    {
        return -2;
    }
};

int main(int argc, char* argv[])
{
    Base *x = new Derived;

    ASSERT(-2 == x->Foo());

    //syntax is trippy but it works
    ASSERT(-1 == x->Base::Foo());

    return 0;
}

bundle install fails with SSL certificate verification error

To note, if you're grabbing gems from a source which SSL cert is trusted by an internal certificate authority (or you are connecting to an external source through a company web proxy with SSL inspection), point your SSL_CERT_FILE env variable to your certificate chain. This most likely just requires exporting your root certificate from your certificate store (System Keychain on macOS) to an accessible location from your shell i.e.:

export SSL_CERT_FILE=~/RootCert.pem

PHP regular expression - filter number only

To remove anything that is not a number:

$output = preg_replace('/[^0-9]/', '', $input);

Explanation:

  • [0-9] matches any number between 0 and 9 inclusively.
  • ^ negates a [] pattern.
  • So, [^0-9] matches anything that is not a number, and since we're using preg_replace, they will be replaced by nothing '' (second argument of preg_replace).

Non-recursive depth first search algorithm

Using Stack, here are the steps to follow: Push the first vertex on the stack then,

  1. If possible, visit an adjacent unvisited vertex, mark it, and push it on the stack.
  2. If you can’t follow step 1, then, if possible, pop a vertex off the stack.
  3. If you can’t follow step 1 or step 2, you’re done.

Here's the Java program following the above steps:

public void searchDepthFirst() {
    // begin at vertex 0
    vertexList[0].wasVisited = true;
    displayVertex(0);
    stack.push(0);
    while (!stack.isEmpty()) {
        int adjacentVertex = getAdjacentUnvisitedVertex(stack.peek());
        // if no such vertex
        if (adjacentVertex == -1) {
            stack.pop();
        } else {
            vertexList[adjacentVertex].wasVisited = true;
            // Do something
            stack.push(adjacentVertex);
        }
    }
    // stack is empty, so we're done, reset flags
    for (int j = 0; j < nVerts; j++)
            vertexList[j].wasVisited = false;
}

How to delete an SVN project from SVN repository

Disposing of a Working Copy

Subversion doesn't track either the state or the existence of working copies on the server, so there's no server overhead to keeping working copies around. Likewise, there's no need to let the server know that you're going to delete a working copy.

If you're likely to use a working copy again, there's nothing wrong with just leaving it on disk until you're ready to use it again, at which point all it takes is an svn update to bring it up to date and ready for use.

However, if you're definitely not going to use a working copy again, you can safely delete the entire thing using whatever directory removal capabilities your operating system offers. We recommend that before you do so you run svn status and review any files listed in its output that are prefixed with a ? to make certain that they're not of importance.

from: http://svnbook.red-bean.com/en/1.7/svn.tour.cleanup.html

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

First go to Wamp->Apache->Service->Test Port 80

If its being user by Microsoft HTTPAPI / 2.0

Then the solution is to manually stop the service named web deployment agent service

If you have Microsoft Sql Server installed, even though the IIS service is disabled, it keeps a web service named httpapi2.0 running.

How to return a value from pthread threads in C?

You are returning the address of a local variable, which no longer exists when the thread function exits. In any case, why call pthread_exit? why not simply return a value from the thread function?

void *myThread()
{
   return (void *) 42;
}

and then in main:

printf("%d\n",(int)status);   

If you need to return a complicated value such a structure, it's probably easiest to allocate it dynamically via malloc() and return a pointer. Of course, the code that initiated the thread will then be responsible for freeing the memory.

Javascript to convert UTC to local time

Try:

var date = new Date('2012-11-29 17:00:34 UTC');
date.toString();

GIT vs. Perforce- Two VCS will enter... one will leave

The Perl 5 interpreter source code is currently going through the throes of converting from Perforce to git. Maybe Sam Vilain’s git-p4raw importer is of interest.

In any case, one of the major wins you’re going to have over every centralised VCS and most distributed ones also is raw, blistering speed. You can’t imagine how liberating it is to have the entire project history at hand, mere fractions of fractions of a second away, until you have experienced it. Even generating a commit log of the whole project history that includes a full diff for each commit can be measured in fractions of a second. Git is so fast your hat will fly off. VCSs that have to roundtrip over the network simply have no chance of competing, not even over a Gigabit Ethernet link.

Also, git makes it very easy to be carefully selective when making commits, thereby allowing changes in your working copy (or even within a single file) to be spread out over multiple commits – and across different branches if you need that. This allows you to make fewer mental notes while working – you don’t need to plan out your work so carefully, deciding up front what set of changes you’ll commit and making sure to postpone anything else. You can just make any changes you want as they occur to you, and still untangle them – nearly always quite easily – when it’s time to commit. The stash can be a very big help here.

I have found that together, these facts cause me to naturally make many more and much more focused commits than before I used git. This in turn not only makes your history generally more useful, but is particularly beneficial for value-add tools such as git bisect.

I’m sure there are more things I can’t think of right now. One problem with the proposition of selling your team on git is that many benefits are interrelated and play off each other, as I hinted at above, such that it is hard to simply look at a list of features and benefits of git and infer how they are going to change your workflow, and which changes are going to be bonafide improvements. You need to take this into account, and you also need to explicitly point it out.

How does Task<int> become an int?

No requires converting the Task to int. Simply Use The Task Result.

int taskResult = AccessTheWebAndDouble().Result;

public async Task<int> AccessTheWebAndDouble()
{
    int task = AccessTheWeb();
    return task;
}

It will return the value if available otherwise it return 0.

Oracle: is there a tool to trace queries, like Profiler for sql server?

You can use The Oracle Enterprise Manager to monitor the active sessions, with the query that is being executed, its execution plan, locks, some statistics and even a progress bar for the longer tasks.

See: http://download.oracle.com/docs/cd/B10501_01/em.920/a96674/db_admin.htm#1013955

Go to Instance -> sessions and watch the SQL Tab of each session.

There are other ways. Enterprise manager just puts with pretty colors what is already available in specials views like those documented here: http://www.oracle.com/pls/db92/db92.catalog_views?remark=homepage

And, of course you can also use Explain PLAN FOR, TRACE tool and tons of other ways of instrumentalization. There are some reports in the enterprise manager for the top most expensive SQL Queries. You can also search recent queries kept on the cache.

Twitter Bootstrap 3: how to use media queries?

Use media queries for IE;

@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) 
and (orientation : landscape) and (-ms-high-contrast: none), (-ms-high-contrast: active) {
}
@media only screen 
and (min-device-width : 360px) 
and (max-device-width : 640px) 
and (orientation : portrait) and (-ms-high-contrast: none), (-ms-high-contrast: active) {
}

How to use the unsigned Integer in Java 8 and Java 9?

Per the documentation you posted, and this blog post - there's no difference when declaring the primitive between an unsigned int/long and a signed one. The "new support" is the addition of the static methods in the Integer and Long classes, e.g. Integer.divideUnsigned. If you're not using those methods, your "unsigned" long above 2^63-1 is just a plain old long with a negative value.

From a quick skim, it doesn't look like there's a way to declare integer constants in the range outside of +/- 2^31-1, or +/- 2^63-1 for longs. You would have to manually compute the negative value corresponding to your out-of-range positive value.

jQuery change method on input type="file"

is the ajax uploader refreshing your input element? if so you should consider using .live() method.

 $('#imageFile').live('change', function(){ uploadFile(); });

update:

from jQuery 1.7+ you should use now .on()

 $(parent_element_selector_here or document ).on('change','#imageFile' , function(){ uploadFile(); });

Initialize Array of Objects using NSArray

NSMutableArray *persons = [NSMutableArray array];
for (int i = 0; i < myPersonsCount; i++) {
   [persons addObject:[[Person alloc] init]];
}
NSArray *arrayOfPersons = [NSArray arrayWithArray:persons]; // if you want immutable array

also you can reach this without using NSMutableArray:

NSArray *persons = [NSArray array];
for (int i = 0; i < myPersonsCount; i++) {
   persons = [persons arrayByAddingObject:[[Person alloc] init]];
}

One more thing - it's valid for ARC enabled environment, if you going to use it without ARC don't forget to add autoreleased objects into array!

[persons addObject:[[[Person alloc] init] autorelease];

Check if a string within a list contains a specific string with Linq

Thast should be easy enough

if( myList.Any( s => s.Contains(stringToCheck))){
  //do your stuff here
}

How to test if a string is JSON or not?

when using jQuery $.ajax() the response will have the responseJSON property if the response was JSON, this could be checked like this:

if (xhr.hasOwnProperty('responseJSON')) {}

How do I get the different parts of a Flask request's url?

another example:

request:

curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y

then:

request.method:              GET
request.url:                 http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url:            http://127.0.0.1:5000/alert/dingding/test
request.url_charset:         utf-8
request.url_root:            http://127.0.0.1:5000/
str(request.url_rule):       /alert/dingding/test
request.host_url:            http://127.0.0.1:5000/
request.host:                127.0.0.1:5000
request.script_root:
request.path:                /alert/dingding/test
request.full_path:           /alert/dingding/test?x=y

request.args:                ImmutableMultiDict([('x', 'y')])
request.args.get('x'):       y

Download a file with Android, and showing the progress in a ProgressDialog

Use Android Query library, very cool indeed.You can change it to use ProgressDialog as you see in other examples, this one will show progress view from your layout and hide it after completion.

File target = new File(new File(Environment.getExternalStorageDirectory(), "ApplicationName"), "tmp.pdf");
new AQuery(this).progress(R.id.progress_view).download(_competition.qualificationScoreCardsPdf(), target, new AjaxCallback<File>() {
    public void callback(String url, File file, AjaxStatus status) {
        if (file != null) {
            // do something with file  
        } 
    }
});

Checking for an empty field with MySQL

If you want to find all records that are not NULL, and either empty or have any number of spaces, this will work:

LIKE '%\ '

Make sure that there's a space after the backslash. More info here: http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html

How to auto-size an iFrame?

On any other element, I would use the scrollHeight of the DOM object and set the height accordingly. I don't know if this would work on an iframe (because they're a bit kooky about everything) but it's certainly worth a try.

Edit: Having had a look around, the popular consensus is setting the height from within the iframe using the offsetHeight:

function setHeight() {
    parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px';
}

And attach that to run with the iframe-body's onLoad event.

Detecting when Iframe content has loaded (Cross browser)

For anyone using Ember, this should work as expected:

<iframe onLoad={{action 'actionName'}}  frameborder='0' src={{iframeSrc}} />

Insert json file into mongodb

mongoimport --jsonArray  -d DatabaseN -c collectionName /filePath/filename.json

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

Calculate the display width of a string in Java

If you just want to use AWT, then use Graphics.getFontMetrics (optionally specifying the font, for a non-default one) to get a FontMetrics and then FontMetrics.stringWidth to find the width for the specified string.

For example, if you have a Graphics variable called g, you'd use:

int width = g.getFontMetrics().stringWidth(text);

For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.

How can I discard remote changes and mark a file as "resolved"?

Make sure of the conflict origin: if it is the result of a git merge, see Brian Campbell's answer.

But if is the result of a git rebase, in order to discard remote (their) changes and use local changes, you would have to do a:

git checkout --theirs -- .

See "Why is the meaning of “ours” and “theirs” reversed"" to see how ours and theirs are swapped during a rebase (because the upstream branch is checked out).

How to list records with date from the last 10 days?

you can use between too:

SELECT Table.date
  FROM Table 
  WHERE date between current_date and current_date - interval '10 day';

Python - Join with newline

You have to print it:

In [22]: "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
Out[22]: 'I\nwould\nexpect\nmultiple\nlines'

In [23]: print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

Carriage return and Line feed... Are both required in C#?

A carriage return \r moves the cursor to the beginning of the current line. A newline \n causes a drop to the next line and possibly the beginning of the next line; That's the platform dependent part that Alexei notes above (on a *nix system \n gives you both a carriage return and a newline, in windows it doesn't)

What you use depends on what you're trying to do. If I wanted to make a little spinning thing on a console I would do str = "|\r/\r-\r\\\r"; for example.

Importing xsd into wsdl

import vs. include

The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import statement with an include statement).

Another area of confusion is how to specify the location or path of the included .xsd file: An XSD import statement has an optional attribute named schemaLocation but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.

When you do chose to use an external .xsd file for your WSDL, the schemaLocation attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:

WSDL:

xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>

XSD:

<xsd:schema targetNamespace="urn:listing3"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xmlbeans-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>generate-sources-xmlbeans</id>
      <phase>generate-sources</phase>
      <goals>
    <goal>xmlbeans</goal>
      </goals>
    </execution>
  </executions>
  <version>2.3.3</version>
  <inherited>true</inherited>
  <configuration>
    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
  </configuration>
</plugin>

You can read more on this in this great IBM article. It has typos such as xsd:import instead of xs:import but otherwise it's fine.

Measure the time it takes to execute a t-sql query

DECLARE @StartTime datetime
DECLARE @EndTime datetime
SELECT @StartTime=GETDATE() 

 -- Write Your Query


SELECT @EndTime=GETDATE()

--This will return execution time of your query
SELECT DATEDIFF(MS,@StartTime,@EndTime) AS [Duration in millisecs]

You can also See this solution

How to trim whitespace from a Bash variable?

This is what I did and worked out perfect and so simple:

the_string="        test"
the_string=`echo $the_string`
echo "$the_string"

Output:

test

What is the current choice for doing RPC in Python?

There are some attempts at making SOAP work with python, but I haven't tested it much so I can't say if it is good or not.

SOAPy is one example.

Not receiving Google OAuth refresh token

Rich Sutton's answer finally worked for me, after I realized that adding access_type=offline is done on the front end client's request for an authorization code, not the back end request that exchanges that code for an access_token. I've added a comment to his answer and this link at Google for more info about refreshing tokens.

P.S. If you are using Satellizer, here is how to add that option to the $authProvider.google in AngularJS.

PHP read and write JSON from file

The clue is in the error message - if you look at the documentation for json_decode note that it can take a second param, which controls whether it returns an array or an object - it defaults to object.

So change your call to

$json = json_decode(file_get_contents($file), true);

And it'll return an associative array and your code should work fine.

Performance differences between ArrayList and LinkedList

I want to add an additional piece of information her about the difference in performance.

We already know that due to the fact that ArrayList implementation is backed by an Object[] it's supports random access and dynamic resizing and LinkedList implementation uses references to head and tail to navigate it. It has no random access capabilities, but it supports dynamic resizing as well.

The first thing is that with an ArrayList, you can immediately access the index, whereas with a LinkedList, you have iterate down the object chain.

Secondly, inserting into ArrayList is generally slower because it has to grow once you hit its boundaries. It will have to create a new bigger array, and copy data from the original one.

But the interesting thing is that when you create an ArrayList that is already huge enough to fit all your inserts it will obviously not involve any array copying operations. Adding to it will be even faster than with LinkedList because LinkedList will have to deal with its pointers, while huge ArrayList just sets value at given index.

enter image description here

Check out for more ArrayList and LinkedList differences.

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Adding java.util.list will resolve your problem because List interface which you are trying to use is part of java.util.list package.

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

Following is the solution which worked for me. The files which I updated are as follows:

  1. config.xml (Full Path: /config.xml)
  2. network_security_config.xml (Full Path: /resources/android/xml/network_security_config.xml)

Changes in the corresponding files are as follows:

1. config.xml

I have added <application android:usesCleartextTraffic="true" /> tag within <edit-config> tag in the config.xml file

<platform name="android">
    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
        <application android:usesCleartextTraffic="true" />
        <application android:networkSecurityConfig="@xml/network_security_config" />
    </edit-config>
    ...
<platform name="android">

2. network_security_config.xml

In this file I have added 2 <domain> tag within <domain-config> tag, the main domain and a sub domain as per my project requirement

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">mywebsite.in</domain>
        <domain includeSubdomains="true">api.mywebsite.in</domain>
    </domain-config>
</network-security-config>

Thanks @Ashutosh for the providing the help.

Hope it helps.

Java HTTP Client Request with defined timeout

Op later stated they were using Apache Commons HttpClient 3.0.1

 HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        client.getHttpConnectionManager().getParams().setSoTimeout(5000);

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

In PostgreSQL, the default limit is 63 characters. Because index names must be unique it's nice to have a little convention. I use (I tweaked the example to explain more complex constructions):

def change
  add_index :studies, [:professor_id, :user_id], name: :idx_study_professor_user
end

The normal index would have been:

:index_studies_on_professor_id_and_user_id

The logic would be:

  • index becomes idx
  • Singular table name
  • No joining words
  • No _id
  • Alphabetical order

Which usually does the job.

Removing border from table cells

<style type="text/css">
table {
  border:1px solid black;
}
</style>

React Native Error: ENOSPC: System limit for number of file watchers reached

Late answer, and there are many good answers already.

In case you want a simple script to check if the maximum file watches is big enough, and if not, increase the limit, here it is:

#!/usr/bin/env bash

let current_watches=`sysctl -n fs.inotify.max_user_watches`

if (( current_watches < 80000 ))
then
  echo "Current max_user_watches ${current_watches} is less than 80000."
else
  echo "Current max_user_watches ${current_watches} is already equal to or greater than 80000."
  exit 0
fi

if sudo sysctl -w fs.inotify.max_user_watches=80000 && sudo sysctl -p && echo fs.inotify.max_user_watches=80000 | sudo tee /etc/sysctl.d/10-user-watches.conf
then
  echo "max_user_watches changed to 80000."
else
  echo "Could not change max_user_watches."
  exit 1
fi

The script increases the limit to 80000, but feel free to set a limit that you want.

Regex doesn't work in String.matches()

Used

String[] words = {"{apf","hum_","dkoe","12f"};
    for(String s:words)
    {
        if(s.matches("[a-z]+"))
        {
            System.out.println(s);
        }
    }

Scanner is skipping nextLine() after using next() or nextFoo()?

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        scan.nextLine();
        double d = scan.nextDouble();
        scan.nextLine();
        String s = scan.nextLine();

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }

Facebook OAuth "The domain of this URL isn't included in the app's domain"

In my case, things i had to do is only enabling the Embedded Browser OAuth Login

enter image description here

How to create an Oracle sequence starting with max value from a table?

DECLARE
    v_max NUMBER;
BEGIN
    SELECT (NVL (MAX (<COLUMN_NAME>), 0) + 1) INTO v_max FROM <TABLE_NAME>;
    EXECUTE IMMEDIATE 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || v_max || ' NOCYCLE CACHE 20 NOORDER';
END;

How can you profile a Python script?

The python wiki is a great page for profiling resources: http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Profiling_Code

as is the python docs: http://docs.python.org/library/profile.html

as shown by Chris Lawlor cProfile is a great tool and can easily be used to print to the screen:

python -m cProfile -s time mine.py <args>

or to file:

python -m cProfile -o output.file mine.py <args>

PS> If you are using Ubuntu, make sure to install python-profile

apt-get install python-profiler 

If you output to file you can get nice visualizations using the following tools

PyCallGraph : a tool to create call graph images
install:

 pip install pycallgraph

run:

 pycallgraph mine.py args

view:

 gimp pycallgraph.png

You can use whatever you like to view the png file, I used gimp
Unfortunately I often get

dot: graph is too large for cairo-renderer bitmaps. Scaling by 0.257079 to fit

which makes my images unusably small. So I generally create svg files:

pycallgraph -f svg -o pycallgraph.svg mine.py <args>

PS> make sure to install graphviz (which provides the dot program):

pip install graphviz

Alternative Graphing using gprof2dot via @maxy / @quodlibetor :

pip install gprof2dot
python -m cProfile -o profile.pstats mine.py
gprof2dot -f pstats profile.pstats | dot -Tsvg -o mine.svg

PHP - Indirect modification of overloaded property

Though I am very late in this discussion, I thought this may be useful for some one in future.

I had faced similar situation. The easiest workaround for those who doesn't mind unsetting and resetting the variable is to do so. I am pretty sure the reason why this is not working is clear from the other answers and from the php.net manual. The simplest workaround worked for me is

Assumption:

  1. $object is the object with overloaded __get and __set from the base class, which I am not in the freedom to modify.
  2. shippingData is the array I want to modify a field of for e.g. :- phone_number

 

// First store the array in a local variable.
$tempShippingData = $object->shippingData;

unset($object->shippingData);

$tempShippingData['phone_number'] = '888-666-0000' // what ever the value you want to set

$object->shippingData = $tempShippingData; // this will again call the __set and set the array variable

unset($tempShippingData);

Note: this solution is one of the quick workaround possible to solve the problem and get the variable copied. If the array is too humungous, it may be good to force rewrite the __get method to return a reference rather expensive copying of big arrays.

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

Are you sure your newline is not CHR(13) + CHR(10), in which case, you are ending up with CHR(13) + '_', which might still look like a newline?

Try REPLACE(col_name, CHR(13) + CHR(10), '')

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

To get ride of all Unnamed columns, you can also use regex such as df.drop(df.filter(regex="Unname"),axis=1, inplace=True)

HTML form submit to PHP script

Here is what I find works

  1. Set a form name
  2. Use a default select option, for example...

    <option value="-1" selected>Please Select</option>

So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.

  1. Try to use HTML5 attributes now they are supported.

This input

<input type="submit">

should be

<input name="Submit" type="submit" value="Submit">

whenever I use a form that fails, it is a failure due to the difference in calling the button name submit and name as Submit.

You should also set your enctype attribute for your form as forms fail on my web host if it's not set.

Disable automatic sorting on the first column when using jQuery DataTables

Add

"aaSorting": []

And check if default value is not null only set sortable column then

if ($('#table').DataTable().order().length == 1) {
    d.SortColumn = $('#table').DataTable().order()[0][0];
    d.SortOrder = $('#table').DataTable().order()[0][1];
}

What is Model in ModelAndView from Spring MVC?

It is all explained by the javadoc for the constructor. It is a convenience constructor that populates the model with one attribute / value pair.

So ...

   new ModelAndView(view, name, value);

is equivalent to:

   Map model = ...
   model.put(name, value);
   new ModelAndView(view, model);

Displaying Windows command prompt output and redirecting it to a file

Here's a sample of what I've used based on one of the other answers

@echo off
REM SOME CODE
set __ERROR_LOG=c:\errors.txt
REM set __IPADDRESS=x.x.x.x

REM Test a variable
if not defined __IPADDRESS (
     REM Call function with some data and terminate
     call :TEE %DATE%,%TIME%,IP ADDRESS IS NOT DEFINED
     goto :EOF
)

REM If test happens to be successful, TEE out a message and end script.
call :TEE Script Ended Successful
goto :EOF


REM THE TEE FUNCTION
:TEE
for /f "tokens=*" %%Z in ("%*") do (
     >  CON ECHO.%%Z
     >> "%__ERROR_LOG%" ECHO.%%Z
     goto :EOF
)

What is the difference between Sublime text and Github's Atom

Atom has been created by Github and it includes "git awareness". That is a feature I like quite a lot:

enter image description here

Also it highlights the files in the git tree that have changed with different colours depending on their commit status:

enter image description here

Build query string for System.Net.HttpClient get

Thanks to "Darin Dimitrov", This is the extension methods.

 public static partial class Ext
{
    public static Uri GetUriWithparameters(this Uri uri,Dictionary<string,string> queryParams = null,int port = -1)
    {
        var builder = new UriBuilder(uri);
        builder.Port = port;
        if(null != queryParams && 0 < queryParams.Count)
        {
            var query = HttpUtility.ParseQueryString(builder.Query);
            foreach(var item in queryParams)
            {
                query[item.Key] = item.Value;
            }
            builder.Query = query.ToString();
        }
        return builder.Uri;
    }

    public static string GetUriWithparameters(string uri,Dictionary<string,string> queryParams = null,int port = -1)
    {
        var builder = new UriBuilder(uri);
        builder.Port = port;
        if(null != queryParams && 0 < queryParams.Count)
        {
            var query = HttpUtility.ParseQueryString(builder.Query);
            foreach(var item in queryParams)
            {
                query[item.Key] = item.Value;
            }
            builder.Query = query.ToString();
        }
        return builder.Uri.ToString();
    }
}

How do I create a local database inside of Microsoft SQL Server 2014?

install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB

Sharing link on WhatsApp from mobile website (not application) for Android

LATEST UPDATE

Now you can use the latest API from whatsapp https://wa.me/ without worrying about the user agent, the API will do the user agent handling.

Share pre-filled text with contact selection option in respective whatsapp client (Android / iOS / Webapp):

https://wa.me/?text=urlencodedtext

Open Chat Dialog for a particular whatsapp user in respective whatsapp client (Android / iOS / Webapp):

https://wa.me/whatsappphonenumber

Share pre-filled text with a particular user (Combine above two):

https://wa.me/whatsappphonenumber/?text=urlencodedtext

Note : whatsappphonenumber should be full phone number in international format. Omit any zeroes, brackets or dashes when adding the phone number in international format.

For official documentation visit https://faq.whatsapp.com/en/general/26000030

Has an event handler already been added?

I recently came to a similar situation where I needed to register a handler for an event only once. I found that you can safely unregister first, and then register again, even if the handler is not registered at all:

myClass.MyEvent -= MyHandler;
myClass.MyEvent += MyHandler;

Note that doing this every time you register your handler will ensure that your handler is registered only once. Sounds like a pretty good practice to me :)

jQuery autocomplete with callback ajax json

I used the construction of $.each (data [i], function (key, value) But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: autocomplete form with ajax success

Specify the date format in XMLGregorianCalendar

There isn’t really an ideal conversion, but I would like to supply a couple of options.

java.time

First, you should use LocalDate from java.time, the modern Java date and time API, for parsing and holding your date. Avoid Date and SimpleDateFormat since they have design problems and also are long outdated. The latter in particular is notoriously troublesome.

    DateTimeFormatter originalDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");

    String dateString = "13/06/1983";
    LocalDate date = LocalDate.parse(dateString, originalDateFormatter);
    System.out.println(date);

The output is:

1983-06-13

Do you need to go any further? LocalDate.toString() produces the format you asked about.

Format and parse

Assuming that you do require an XMLGregorianCalendar the first and easy option for converting is:

    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(date.toString());
    System.out.println(xmlDate);

1983-06-13

Formatting to a string and parsing it back feels like a waste to me, but as I said, it’s easy and I don’t think that there are any surprises about the result being as expected.

Pass year, month and day of month individually

    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendarDate(date.getYear(), date.getMonthValue(),
                    date.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED);

The result is the same as before. We need to make explicit that we don’t want a time zone offset (this is what DatatypeConstants.FIELD_UNDEFINED specifies). In case someone is wondering, both LocalDate and XMLGregorianCalendar number months the way humans do, so there is no adding or subtracting 1.

Convert through GregorianCalendar

I only show you this option because I somehow consider it the official way: convert LocalDate to ZonedDateTime, then to GregorianCalendar and finally to XMLGregorianCalendar.

    ZonedDateTime dateTime = date.atStartOfDay(ZoneOffset.UTC);
    GregorianCalendar gregCal = GregorianCalendar.from(dateTime);
    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(gregCal);
    xmlDate.setTime(DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED,
            DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
    xmlDate.setTimezone(DatatypeConstants.FIELD_UNDEFINED);

I like the conversion itself since we neither need to use strings nor need to pass individual fields (with care to do it in the right order). What I don’t like is that we have to pass a time of day and a time zone offset and then wipe out those fields manually afterwards.

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

from jquery $.ajax to angular $http

We can implement ajax request by using http service in AngularJs, which helps to read/load data from remote server.

$http service methods are listed below,

 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

One of the Example:

    $http.get("sample.php")
        .success(function(response) {
            $scope.getting = response.data; // response.data is an array
    }).error(){

        // Error callback will trigger
    });

http://www.drtuts.com/ajax-requests-angularjs/

How to read/process command line arguments?

Pocoo's click is more intuitive, requires less boilerplate, and is at least as powerful as argparse.

The only weakness I've encountered so far is that you can't do much customization to help pages, but that usually isn't a requirement and docopt seems like the clear choice when it is.

Explode string by one or more spaces or tabs

The answers provided by other folks (Ben James) are quite good and I have used them. As user889030 points out, the last array element may be empty. Actually, the first and last array elements can be empty. The code below addresses both issues.

# Split an input string into an array of substrings using any set
# whitespace characters
function explode_whitespace($str) {  
  # Split the input string into an array
  $parts = preg_split('/\s+/', $str);
  # Get the size of the array of substrings
  $sizeParts = sizeof($parts);
  # Check if the last element of the array is a zero-length string
  if ($sizeParts > 0) {
    $lastPart = $parts[$sizeParts-1];
    if ($lastPart == '') {
      array_pop($parts);
      $sizeParts--;
    }
    # Check if the first element of the array is a zero-length string
    if ($sizeParts > 0) {
      $firstPart = $parts[0];
      if ($firstPart == '') 
        array_shift($parts); 
    }
  }
  return $parts;   
}

adb server version doesn't match this client

OS: Ubuntu

There are more than 1 adb are running. Check the current adb:

    which adb
    Expected Output : ANDROID_SDK/platform-tools/adb

Normally the result will be:

    /usr/bin/adb

Delete this older version by:

    cd /urs/bin
    sudo rm adb

What is cURL in PHP?

Php curl class (GET,POST,FILES UPLOAD, SESSIONS, SEND POST JSON, FORCE SELFSIGNED SSL/TLS):

<?php
    // Php curl class
    class Curl {

        public $error;

        function __construct() {}

        function Get($url = "http://hostname.x/api.php?q=jabadoo&txt=gin", $forceSsl = false,$cookie = "", $session = true){
            // $url = $url . "?". http_build_query($data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);        
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){            
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $info = curl_getinfo($ch);
            $res = curl_exec($ch);        
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            }        
        }

        function GetArray($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $forceSsl = false, $cookie = "", $session = true){
            $url = $url . "?". http_build_query($data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $info = curl_getinfo($ch);
            $res = curl_exec($ch);        
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            }        
        }

        function PostJson($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $forceSsl = false, $cookie = "", $session = true){
            $data = json_encode($data);
            $ch = curl_init($url);                                                                      
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);                                                                  
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Authorization: Bearer helo29dasd8asd6asnav7ffa',                                                      
                'Content-Type: application/json',                                                                                
                'Content-Length: ' . strlen($data))                                                                       
            );        
            $res = curl_exec($ch);
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            } 
        }

        function Post($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $files = array('ads/ads0.jpg', 'ads/ads1.jpg'), $forceSsl = false, $cookie = "", $session = true){
            foreach ($files as $k => $v) {
                $f = realpath($v);
                if(file_exists($f)){
                    $fc = new CurlFile($f, mime_content_type($f), basename($f)); 
                    $data["file[".$k."]"] = $fc;
                }
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");        
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // !!!! required as of PHP 5.6.0 for files !!!
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)");
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $res = curl_exec($ch);
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            } 
        }
    }
?>

Example:

<?php
    $urlget = "http://hostname.x/api.php?id=123&user=bax";
    $url = "http://hostname.x/api.php";
    $data = array("name" => "Max", "age" => "36");
    $files = array('ads/ads0.jpg', 'ads/ads1.jpg');

    $curl = new Curl();
    echo $curl->Get($urlget, true, "token=12345");
    echo $curl->GetArray($url, $data, true);
    echo $curl->Post($url, $data, $files, true);
    echo $curl->PostJson($url, $data, true);
?>

Php file: api.php

<?php
    /*
    $Cookie = session_get_cookie_params();
    print_r($Cookie);
    */
    session_set_cookie_params(9000, '/', 'hostname.x', isset($_SERVER["HTTPS"]), true);
    session_start();

    $_SESSION['cnt']++;
    echo "Session count: " . $_SESSION['cnt']. "\r\n";
    echo $json = file_get_contents('php://input');
    $arr = json_decode($json, true);
    echo "<pre>";
    if(!empty($json)){ print_r($arr); }
    if(!empty($_GET)){ print_r($_GET); }
    if(!empty($_POST)){ print_r($_POST); }
    if(!empty($_FILES)){ print_r($_FILES); }
    // request headers
    print_r(getallheaders());
    print_r(apache_response_headers());
    // Fetch a list of headers to be sent.
    // print_r(headers_list());
?>

Moving x-axis to the top of a plot in matplotlib

You want set_ticks_position rather than set_label_position:

ax.xaxis.set_ticks_position('top') # the rest is the same

This gives me:

enter image description here

What's the difference between a 302 and a 307 redirect?

A good example of the 307 Internal Redirect in action is when Google Chrome encounters a HTTP call to a domain it knows as requiring Strict Transport Security.

The browser redirects seamlessly, using the same method as the original call.

HTST 307 Internal Redirect

Nginx location "not equal to" regex

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

Better way to represent array in java properties file

Use YAML files for properties, this supports properties as an array.

Quick glance about YAML:

A superset of JSON, it can do everything JSON can + more

  1. Simple to read
  2. Long properties into multiline values
  3. Supports comments
  4. Properties as Array
  5. YAML Validation

Enter triggers button click

I added a button of type "submit" as first element of the form and made it invisible (width:0;height:0;padding:0;margin:0;border-style:none;font-size:0;). Works like a refresh of the site, i.e. I don't do anything when the button is pressed except that the site is loaded again. For me works fine...

How to apply font anti-alias effects in CSS?

Short answer: You can't.

CSS does not have techniques which affect the rendering of fonts in the browser; only the system can do that.

Obviously, text sharpness can easily be achieved with pixel-dense screens, but if you're using a normal PC that's gonna be hard to achieve.

There are some newer fonts that are smooth but at the sacrifice of it appearing somewhat blurry (look at most of Adobe's fonts, for example). You can also find some smooth-but-blurry-by-design fonts at Google Fonts, however.

There are some new CSS3 techniques for font rendering and text effects though the consistency, performance, and reliability of these techniques vary so largely to the point where you generally shouldn't rely on them too much.

Can't compare naive and aware datetime.now() <= challenge.datetime_end

datetime.datetime.now is not timezone aware.

Django comes with a helper for this, which requires pytz

from django.utils import timezone
now = timezone.now()

You should be able to compare now to challenge.datetime_start

How to force keyboard with numbers in mobile website in Android

Some browsers igoners sending leading zero to the server when the input type is "number". So I use a mixing of jquery and html to load a numeric keypad and also make sure that the value is sent as a text not as a number:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$(".numberonly").focus(function(){$(this).attr("type","number")});_x000D_
$(".numberonly").blur(function(){$(this).attr("type","text")});_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" class="numberonly">
_x000D_
_x000D_
_x000D_

How do I get the Session Object in Spring?

Indeed you can access the information from the session even when the session is being destroyed on an HttpSessionLisener by doing:

public void sessionDestroyed(HttpSessionEvent hse) {
    SecurityContextImpl sci = (SecurityContextImpl) hse.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
    // be sure to check is not null since for users who just get into the home page but never get authenticated it will be
    if (sci != null) {
        UserDetails cud = (UserDetails) sci.getAuthentication().getPrincipal();
        // do whatever you need here with the UserDetails
    }
 }

or you could also access the information anywhere you have the HttpSession object available like:

SecurityContextImpl sci = (SecurityContextImpl) session().getAttribute("SPRING_SECURITY_CONTEXT");

the last assuming you have something like:

HttpSession sesssion = ...; // can come from request.getSession(false);

Serializing list to JSON

Yes, but then what do you do about the django objects? simple json tends to choke on them.

If the objects are individual model objects (not querysets, e.g.), I have occasionally stored the model object type and the pk, like so:

seralized_dict = simplejson.dumps(my_dict, 
                     default=lambda a: "[%s,%s]" % (str(type(a)), a.pk)
                     )

to de-serialize, you can reconstruct the object referenced with model.objects.get(). This doesn't help if you are interested in the object details at the type the dict is stored, but it's effective if all you need to know is which object was involved.

How to set up default schema name in JPA configuration?

Don't know of JPA property for this either. But you could just add the Hibernate property (assuming you use Hibernate as provider) as

...

<property name="hibernate.default_schema" value="myschema"/>

...

Hibernate should pick that up

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

As per my personal experience Adobe edge is the best tool for HTML5. It's still in preview mode but you will download it free from Adobe site.

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Here is a side note for some that may be searching this thread for an answer to this problem. (Be sure to read cautions at the bottom before implementing this solution.) I was having trouble sending emails for a client to which my MS Office 365 subscription did not have a user or domain for. I was trying to SMTP through my [email protected] 365 account but the .NET mail message was addressed from [email protected]. This is when the "5.7.1 Client does not have permissions" error popped up for me. To remedy, the MailMessage class needed to have the Sender property set to an email address that my supplied SMTP credentials had permission in O365 to "Send As". I chose to use my main account email ([email protected]) as seen in the code below. Keep in mind I could have used ANY email address my O365 account had permission to "send as" (i.e. [email protected], [email protected], etc.)

using System;
using System.Net.Mail;

namespace ConsoleApplication1
{
   class Program
   {
      static void Main(string[] args)
      {
         using (
            MailMessage message = new MailMessage
            {
               To = { new MailAddress("[email protected]", "Recipient 1") },
               Sender = new MailAddress("[email protected]", "Me"),
               From = new MailAddress("[email protected]", "Client"),
               Subject=".net Testing"
               Body="Testing .net emailing",
               IsBodyHtml=true,
            }
         )
         {
            using (
               SmtpClient smtp = new SmtpClient
               {
                  Host = "smtp.office365.com",
                  Port = 587,
                  Credentials = new System.Net.NetworkCredential("[email protected]", "Pa55w0rd"),
                  EnableSsl = true
               }
            )
            {
               try { smtp.Send(message); }
               catch (Exception excp)
               {
                  Console.Write(excp.Message);
                  Console.ReadKey();
               }
            }
         }
      }
   }
}

Please note SmtpClient is only disposable and able to use the Using block in .NET Framework 4
Users of .NET Framework 2 through 3.5 should use SmtpClient as such...

SmtpClient smtp = new SmtpClient
{
   Host = "smtp.office365.com",
   Port = 587,
   Credentials = new System.Net.NetworkCredential("[email protected]", "Pa55w0rd"),
   EnableSsl = true
};
try { smtp.Send(message); }
catch (Exception excp)
{
   Console.Write(excp.Message);
   Console.ReadKey();
}

The resulting email's header will look something like this:

Authentication-Results: spf=none (sender IP is )  
   [email protected];  
Received: from MyPC (192.168.1.1) by  
   BLUPR13MB0036.namprd13.prod.outlook.com (10.161.123.150) with Microsoft SMTP  
   Server (TLS) id 15.1.318.9; Mon, 9 Nov 2015 16:06:58 +0000  
MIME-Version: 1.0  
From: Client <[email protected]>  
Sender: Me <[email protected]>  
To: Recipient 1 <[email protected]>  

-- Be Cautious --
Be aware some mail clients may display the Sender address as a note. For example Outlook will display something along these lines in the Reading Pane's header:

Me <[email protected]> on behalf of Client <[email protected]>

However, so long as the email client the recipient uses isn't total garbage, this shouldn't effect the Reply To address. Reply To should still use the From address. To cover all your bases, you can also utilize the MailMessage.ReplyToList property to afford every opportunity to the client to use the correct reply address.

Also, be aware that some email servers may flat out reject any emails that are Sent On Behalf of another company siting Domain Owner Policy Restrictions. Be sure to test thoroughly and look for any bounce backs. I can tell you that my personal Hotmail (mail.live.com) email account is one that will reject messages I send on behalf of a certain client of mine but others clients go through fine. Although I suspect that it has something to do with my client's domain TXT "spf1" records, I do not have an answer as to why it will reject emails sent on behalf of one domain versus another. Maybe someone who knows can shed some light on the subject?

Simple URL GET/POST function in Python

You could use this to wrap urllib2:

def URLRequest(url, params, method="GET"):
    if method == "POST":
        return urllib2.Request(url, data=urllib.urlencode(params))
    else:
        return urllib2.Request(url + "?" + urllib.urlencode(params))

That will return a Request object that has result data and response codes.

How do I auto size columns through the Excel interop objects?

Have a look at this article, it's not an exact match to your problem, but suits it:

iconv - Detected an illegal character in input string

I found one Solution :

echo iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($string));

use utf8_encode()

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

This worked for me for a format like YYYY.MM.DD-HH.MM.SS.fff. Attempting to make this code capable of accepting any string format will be like reinventing the wheel (i.e. there are functions for all this in Boost.

std::chrono::system_clock::time_point string_to_time_point(const std::string &str)
{
    using namespace std;
    using namespace std::chrono;

    int yyyy, mm, dd, HH, MM, SS, fff;

    char scanf_format[] = "%4d.%2d.%2d-%2d.%2d.%2d.%3d";

    sscanf(str.c_str(), scanf_format, &yyyy, &mm, &dd, &HH, &MM, &SS, &fff);

    tm ttm = tm();
    ttm.tm_year = yyyy - 1900; // Year since 1900
    ttm.tm_mon = mm - 1; // Month since January 
    ttm.tm_mday = dd; // Day of the month [1-31]
    ttm.tm_hour = HH; // Hour of the day [00-23]
    ttm.tm_min = MM;
    ttm.tm_sec = SS;

    time_t ttime_t = mktime(&ttm);

    system_clock::time_point time_point_result = std::chrono::system_clock::from_time_t(ttime_t);

    time_point_result += std::chrono::milliseconds(fff);
    return time_point_result;
}

std::string time_point_to_string(std::chrono::system_clock::time_point &tp)
{
    using namespace std;
    using namespace std::chrono;

    auto ttime_t = system_clock::to_time_t(tp);
    auto tp_sec = system_clock::from_time_t(ttime_t);
    milliseconds ms = duration_cast<milliseconds>(tp - tp_sec);

    std::tm * ttm = localtime(&ttime_t);

    char date_time_format[] = "%Y.%m.%d-%H.%M.%S";

    char time_str[] = "yyyy.mm.dd.HH-MM.SS.fff";

    strftime(time_str, strlen(time_str), date_time_format, ttm);

    string result(time_str);
    result.append(".");
    result.append(to_string(ms.count()));

    return result;
}

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

Vlookup is good if the reference values (column A, sheet 1) are in ascending order. Another option is Index and Match, which can be used no matter the order (As long as the values in column a, sheet 1 are unique)

This is what you would put in column B on sheet 2

=INDEX(Sheet1!A$1:B$6,MATCH(A1,Sheet1!A$1:A$6),2)

Setting Sheet1!A$1:B$6 and Sheet1!A$1:A$6 as named ranges makes it a little more user friendly.

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Auto-increment primary key in SQL tables

for those who are having the issue of it still not letting you save once it is changed according to answer below, do the following:

tools -> options -> designers -> Table and Database Designers -> uncheck "prevent saving changes that require table re-creation" box -> OK

and try to save as it should work now

How to paste into a terminal?

Shift + Insert usually works throughout X11.

How to use a filter in a controller?

AngularJs lets you to use filters inside template or inside Controller, Directive etc..

in template you can use this syntax

{{ variable | MyFilter: ... : ... }}

and inside controller you can use injecting the $filter service

angular.module('MyModule').controller('MyCtrl',function($scope, $filter){
    $filter('MyFilter')(arg1, arg2);
})

If you need more with Demo example here is a link

AngularJs filter examples and demo

Check to see if cURL is installed locally?

To extend the answer above and if the case is you are using XAMPP. In the current version of the xampp you cannot locate the curl_exec in the php.ini, just try using

<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>

and save to your htdocs. Next go to your browser and paste

http://localhost/[your_filename].php

if the result looks like this

array(9) {
  ["version_number"]=>
  int(469760)
  ["age"]=>
  int(3)
  ["features"]=>
  int(266141)
  ["ssl_version_number"]=>
  int(0)
  ["version"]=>
  string(6) "7.43.0"
  ["host"]=>
  string(13) "i386-pc-win32"
  ["ssl_version"]=>
  string(14) "OpenSSL/1.0.2e"
  ["libz_version"]=>
  string(5) "1.2.8"
  ["protocols"]=>
  array(19) {
    [0]=>
    string(4) "dict"
    [1]=>
    string(4) "file"
    [2]=>
    string(3) "ftp"
    [3]=>
    string(4) "ftps"
    [4]=>
    string(6) "gopher"
    [5]=>
    string(4) "http"
    [6]=>
    string(5) "https"
    [7]=>
    string(4) "imap"
    [8]=>
    string(5) "imaps"
    [9]=>
    string(4) "ldap"
    [10]=>
    string(4) "pop3"
    [11]=>
    string(5) "pop3s"
    [12]=>
    string(4) "rtsp"
    [13]=>
    string(3) "scp"
    [14]=>
    string(4) "sftp"
    [15]=>
    string(4) "smtp"
    [16]=>
    string(5) "smtps"
    [17]=>
    string(6) "telnet"
    [18]=>
    string(4) "tftp"
  }
}

curl is enable

String contains another two strings

 class Program {
          static void Main(String[] args) {
             // By using extension methods
             if ( "Hello world".ContainsAll(StringComparison.CurrentCultureIgnoreCase, "Hello", "world") ) 
                Console.WriteLine("Found everything by using an extension method!");
             else 
                Console.WriteLine("I didn't");

             // By using a single method
             if ( ContainsAll("Hello world", StringComparison.CurrentCultureIgnoreCase, "Hello", "world") )
                Console.WriteLine("Found everything by using an ad hoc procedure!");
             else 
                Console.WriteLine("I didn't");

          }

          private static Boolean ContainsAll(String str, StringComparison comparisonType, params String[] values) {
             return values.All(s => s.Equals(s, comparisonType));
          }    
       }

       // Extension method for your convenience
       internal static class Extensiones {
          public static Boolean ContainsAll(this String str, StringComparison comparisonType, params String[] values) {
             return values.All(s => s.Equals(s, comparisonType));
          }
       }

Explicitly set column value to null SQL Developer

If you want to use the GUI... click/double-click the table and select the Data tab. Click in the column value you want to set to (null). Select the value and delete it. Hit the commit button (green check-mark button). It should now be null.

enter image description here

More info here:

How to use the SQL Worksheet in SQL Developer to Insert, Update and Delete Data

Insert multiple rows into single column

I believe this should work for inserting multiple rows:

INSERT INTO Data ( Col1 ) VALUES
('Hello'), ('World'),...

How to increase editor font size?

For WINDOWS users: FILE-->SETTingS-->EDITOR-->FONT.

what is the use of $this->uri->segment(3) in codeigniter pagination

By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure: $product_id = $this->uri->segment(3, 0);

It helps avoid having to write code like this:

[if ($this->uri->segment(3) === FALSE)
{
    $product_id = 0;
}
else
{
    $product_id = $this->uri->segment(3);
}]

How do you format code on save in VS Code

No need to add commands anymore. For those who are new to Visual Studio Code and searching for an easy way to format code on saving, kindly follow the below steps.

  1. Open Settings by pressing [Cmd+,] in Mac or using the below screenshot.

VS Code - Open Settings Command Image

  1. Type 'format' in the search box and enable the option 'Format On Save'.

enter image description here

You are done. Thank you.

Data truncated for column?

In my case it was a table with an ENUM that accepts the days of the week as integers (0 to 6). When inserting the value 0 as an integer I got the error message "Data truncated for column ..." so to fix it I had to cast the integer to a string. So instead of:

$item->day = 0;

I had to do;

$item->day = (string) 0;

It looks silly to cast the zero like that but in my case it was in a Laravel factory, and I had to write it like this:

$factory->define(App\Schedule::class, function (Faker $faker) {
    return [
        'day' => (string) $faker->numberBetween(0, 6),
        //
    ];
});

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

For future readers, one easy way is as follows if they wish to export in bulk using bash,

akshay@ideapad:/tmp$ mysql -u someuser -p test -e "select * from offices"
Enter password: 
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+
| officeCode | city          | phone            | addressLine1             | addressLine2 | state      | country   | postalCode | territory |
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+
| 1          | San Francisco | +1 650 219 4782  | 100 Market Street        | Suite 300    | CA         | USA       | 94080      | NA        |
| 2          | Boston        | +1 215 837 0825  | 1550 Court Place         | Suite 102    | MA         | USA       | 02107      | NA        |
| 3          | NYC           | +1 212 555 3000  | 523 East 53rd Street     | apt. 5A      | NY         | USA       | 10022      | NA        |
| 4          | Paris         | +33 14 723 4404  | 43 Rue Jouffroy D'abbans | NULL         | NULL       | France    | 75017      | EMEA      |
| 5          | Tokyo         | +81 33 224 5000  | 4-1 Kioicho              | NULL         | Chiyoda-Ku | Japan     | 102-8578   | Japan     |
| 6          | Sydney        | +61 2 9264 2451  | 5-11 Wentworth Avenue    | Floor #2     | NULL       | Australia | NSW 2010   | APAC      |
| 7          | London        | +44 20 7877 2041 | 25 Old Broad Street      | Level 7      | NULL       | UK        | EC2N 1HN   | EMEA      |
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+

If you're exporting by non-root user then set permission like below

root@ideapad:/tmp# mysql -u root -p
MariaDB[(none)]> UPDATE mysql.user SET File_priv = 'Y' WHERE user='someuser' AND host='localhost';

Restart or Reload mysqld

akshay@ideapad:/tmp$ sudo su
root@ideapad:/tmp#  systemctl restart mariadb

Sample code snippet

akshay@ideapad:/tmp$ cat test.sh 
#!/usr/bin/env bash

user="someuser"
password="password"
database="test"

mysql -u"$user" -p"$password" "$database" <<EOF
SELECT * 
INTO OUTFILE '/tmp/csvs/offices.csv' 
FIELDS TERMINATED BY '|' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\n'
FROM offices;
EOF

Execute

akshay@ideapad:/tmp$ mkdir -p /tmp/csvs
akshay@ideapad:/tmp$ chmod +x test.sh
akshay@ideapad:/tmp$ ./test.sh 
akshay@ideapad:/tmp$ cat /tmp/csvs/offices.csv 
"1"|"San Francisco"|"+1 650 219 4782"|"100 Market Street"|"Suite 300"|"CA"|"USA"|"94080"|"NA"
"2"|"Boston"|"+1 215 837 0825"|"1550 Court Place"|"Suite 102"|"MA"|"USA"|"02107"|"NA"
"3"|"NYC"|"+1 212 555 3000"|"523 East 53rd Street"|"apt. 5A"|"NY"|"USA"|"10022"|"NA"
"4"|"Paris"|"+33 14 723 4404"|"43 Rue Jouffroy D'abbans"|\N|\N|"France"|"75017"|"EMEA"
"5"|"Tokyo"|"+81 33 224 5000"|"4-1 Kioicho"|\N|"Chiyoda-Ku"|"Japan"|"102-8578"|"Japan"
"6"|"Sydney"|"+61 2 9264 2451"|"5-11 Wentworth Avenue"|"Floor #2"|\N|"Australia"|"NSW 2010"|"APAC"
"7"|"London"|"+44 20 7877 2041"|"25 Old Broad Street"|"Level 7"|\N|"UK"|"EC2N 1HN"|"EMEA"

TortoiseSVN icons overlay not showing after updating to Windows 10

I deleted all my onedrive keys, installed latest preview etc and finally realized that the icons were working all along for some explorer directory views and not others.

In other words, medium, large, extra large, and tiles, but not list or detail. Since I don't want to learn all about how that works, I am just viewing my work directories as tiles for now.

How to stretch div height to fill parent div - CSS

Suppose you have

<body>
  <div id="root" />
</body>

With normal CSS, you can do the following. See a working app https://github.com/onmyway133/Lyrics/blob/master/index.html

#root {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

With flexbox, you can

html, body {
  height: 100%
}
body {
  display: flex;
  align-items: stretch;
}

#root {
  width: 100%
}

How to run multiple SQL commands in a single SQL connection?

Just enable this property in your connection string:

sqb.MultipleActiveResultSets = true;

This property allows one open connection for multiple datareaders.

How do I set up the database.yml file in Rails?

At first I would use http://ruby.railstutorial.org/.

And database.yml is place where you put setup for database your application use - username, password, host - for each database. With new application you dont need to change anything - simply use default sqlite setup.

C# '@' before a String

Prefixing the string with an @ indicates that it should be treated as a literal, i.e. no escaping.

For example if your string contains a path you would typically do this:

string path = "c:\\mypath\\to\\myfile.txt";

The @ allows you to do this:

string path = @"c:\mypath\to\myfile.txt";

Notice the lack of double slashes (escaping)

How to increment a JavaScript variable using a button press event

The purist way to do this would be to add event handlers to the button, instead of mixing behavior with the content (LSM, Layered Semantic Markup)

<input type="button" value="Increment" id="increment"/>

<script type="text/javascript">
    var count = 0;
    // JQuery way
    $('#increment').click(function (e) {
        e.preventDefault();
        count++;
    });
    // YUI way
    YAHOO.util.Event.on('increment', 'click', function (e) {
        YAHOO.util.Event.preventDefault(e);
        count++;
    });
    // Simple way
    document.getElementById('increment').onclick = function (e) {
        count++;
        if (e.preventDefault) {
            e.preventDefault();
        }
        e.returnValue = false;
    };
</script>

Install sbt on ubuntu

My guess is that the directory ~/bin/sbt/bin is not in your PATH.

To execute programs or scripts that are in the current directory you need to prefix the command with ./, as in:

./sbt

This is a security feature in linux, so to prevent overriding of system commands (and other programs) by a malicious party dropping a file in your home directory (for example). Imagine a script called 'ls' that emails your /etc/passwd file to 3rd party before executing the ls command... Or one that executes 'rm -rf .'...

That said, unless you need something specific from the latest source code, you're best off doing what paradigmatic said in his post, and install it from the Typesafe repository.

What is the difference between a definition and a declaration?

Find similar answers here: Technical Interview Questions in C.

A declaration provides a name to the program; a definition provides a unique description of an entity (e.g. type, instance, and function) within the program. Declarations can be repeated in a given scope, it introduces a name in a given scope.

A declaration is a definition unless:

  • Declaration declares a function without specifying its body,
  • Declaration contains an extern specifier and no initializer or function body,
  • Declaration is the declaration of a static class data member without a class definition,
  • Declaration is a class name definition,

A definition is a declaration unless:

  • Definition defines a static class data member,
  • Definition defines a non-inline member function.

Aliases in Windows command prompt

You need to pass the parameters, try this:

doskey np=notepad++.exe $*

Edit (responding to Romonov's comment) Q: Is there any way I can make the command prompt remember so I don't have to run this each time I open a new command prompt?

doskey is a textual command that is interpreted by the command processor (e.g. cmd.exe), it can't know to modify state in some other process (especially one that hasn't started yet).

People that use doskey to setup their initial command shell environments typically use the /K option (often via a shortcut) to run a batch file which does all the common setup (like- set window's title, colors, etc).

cmd.exe /K env.cmd

env.cmd:

title "Foo Bar"
doskey np=notepad++.exe $*
...

When to use "new" and when not to, in C++?

New is always used to allocate dynamic memory, which then has to be freed.

By doing the first option, that memory will be automagically freed when scope is lost.

Point p1 = Point(0,0); //This is if you want to be safe and don't want to keep the memory outside this function.

Point* p2 = new Point(0, 0); //This must be freed manually. with...
delete p2;

NSURLConnection Using iOS Swift

An abbreviated version of your code worked for me,

class Remote: NSObject {

    var data = NSMutableData()

    func connect(query:NSString) {
        var url =  NSURL.URLWithString("http://www.google.com")
        var request = NSURLRequest(URL: url)
        var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
    }


     func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        println("didReceiveResponse")
    }

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

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        println(self.data)
    }


    deinit {
        println("deiniting")
    }
}

This is the code I used in the calling class,

class ViewController: UIViewController {

    var remote = Remote()


    @IBAction func downloadTest(sender : UIButton) {
        remote.connect("/apis")
    }

}

You didn't specify in your question where you had this code,

var remote = Remote()
remote.connect("/apis")

If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.

How to remove all click event handlers using jQuery?

You would use off() to remove an event like so:

$("#saveBtn").off("click");

but this will remove all click events bound to this element. If the function with SaveQuestion is the only event bound then the above will do it. If not do the following:

$("#saveBtn").off("click").click(function() { saveQuestion(id); });

Order data frame rows according to vector with specific order

I prefer to use ***_join in dplyr whenever I need to match data. One possible try for this

left_join(data.frame(name=target),df,by="name")

Note that the input for ***_join require tbls or data.frame

Linq Select Group By

You should try it like this:

var result =
        from priceLog in PriceLogList
        group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
        select new {
            LogDateTime = dateGroup.Key,
            AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
        };

Length of array in function argument

Regarding int main():

According to the Standard, argv points to a NULL-terminated array (of pointers to null-terminated strings). (5.1.2.2.1:1).

That is, argv = (char **){ argv[0], ..., argv[argc - 1], 0 };.

Hence, size calculation is performed by a function which is a trivial modification of strlen().

argc is only there to make argv length calculation O(1).

The count-until-NULL method will NOT work for generic array input. You will need to manually specify size as a second argument.

Java: how to import a jar file from command line

try

java -cp "your_jar.jar:lib/referenced_jar.jar" com.your.main.Main

If you are on windows, you should use ; instead of :

What EXACTLY is meant by "de-referencing a NULL pointer"?

From wiki

A null pointer has a reserved value, often but not necessarily the value zero, indicating that it refers to no object
..

Since a null-valued pointer does not refer to a meaningful object, an attempt to dereference a null pointer usually causes a run-time error.

int val =1;
int *p = NULL;
*p = val; // Whooosh!!!! 

How to get first record in each group using Linq

var res = (from element in list)
      .OrderBy(x => x.F2).AsEnumerable()
      .GroupBy(x => x.F1)
      .Select()

Use .AsEnumerable() after OrderBy()

How to style a disabled checkbox?

Checkboxes (radio buttons and <select>) are OS-level components, not browser-level. You cannot reliably style them in a manner that will be consistent across browsers and operating systems.

Your best bet it to put an overlay on top and style that instead.

How to Compare two strings using a if in a stored procedure in sql server 2008?

You can also try this for match string.

DECLARE @temp1 VARCHAR(1000)
    SET @temp1 = '<li>Error in connecting server.</li>'
DECLARE @temp2 VARCHAR(1000)
    SET @temp2 = '<li>Error in connecting server. connection timeout.</li>'

IF @temp1 like '%Error in connecting server.%' OR @temp1 like '%Error in connecting server. connection timeout.%'
  SELECT 'yes'
ELSE
  SELECT 'no'

remove borders around html input

Try this

#generic_search_button
{
    float: left;
    width: 24px; /*new width*/
    height: 24px; /*new width*/
    border: none !important; /* no border and override any inline styles*/
    margin-top: 7px;
    cursor: pointer;
    background-color: White;
    background-image: url(/Images/search.png);
    background-repeat: no-repeat;
    background-position: center center;
}

I think the image size might be wrong

How ViewBag in ASP.NET MVC works

public dynamic ViewBag
{
    get
    {
        if (_viewBag == null)
        {
            _viewBag = new DynamicViewData(() => ViewData);
        }

        return _viewBag;
    }
}

How to convert color code into media.brush?

For WinRT (Windows Store App)

using Windows.UI;
using Windows.UI.Xaml.Media;

    public static Brush ColorToBrush(string color) // color = "#E7E44D"
    {
        color = color.Replace("#", "");
        if (color.Length == 6)
        {
            return new SolidColorBrush(ColorHelper.FromArgb(255,
                byte.Parse(color.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)));
        }
        else
        {
            return null;
        }
    }

How to disable HTML links

You can use this to disabled the Hyperlink of asp.net or link buttons in html.

$("td > a").attr("disabled", "disabled").on("click", function() {
    return false; 
});

How can I use different certificates on specific connections?

If creating a SSLSocketFactory is not an option, just import the key into the JVM

  1. Retrieve the public key: $openssl s_client -connect dev-server:443, then create a file dev-server.pem that looks like

    -----BEGIN CERTIFICATE----- 
    lklkkkllklklklklllkllklkl
    lklkkkllklklklklllkllklkl
    lklkkkllklk....
    -----END CERTIFICATE-----
    
  2. Import the key: #keytool -import -alias dev-server -keystore $JAVA_HOME/jre/lib/security/cacerts -file dev-server.pem. Password: changeit

  3. Restart JVM

Source: How to solve javax.net.ssl.SSLHandshakeException?

SQL Server Management Studio missing

Try restarting your computer if you just installed SQL Server and there's no choice in the SQL Server Installation Center to install SQL Server Management Studio.

This choice (see image below) only appeared for me after I installed SQL Server, then restarted my computer:

enter image description here

How do I automatically update a timestamp in PostgreSQL

Using 'now()' as default value automatically generates time-stamp.

Get user's current location

Edited

Change freegeoip.net into ipinfo.io

<?php    

function get_client_ip()
{
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    } else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    } else if (isset($_SERVER['HTTP_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    } else if (isset($_SERVER['REMOTE_ADDR'])) {
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    } else {
        $ipaddress = 'UNKNOWN';
    }

    return $ipaddress;
}
$PublicIP = get_client_ip();
$json     = file_get_contents("http://ipinfo.io/$PublicIP/geo");
$json     = json_decode($json, true);
$country  = $json['country'];
$region   = $json['region'];
$city     = $json['city'];
?>

Python, Unicode, and the Windows console

Just enter this code in command line before executing python script:

chcp 65001 & set PYTHONIOENCODING=utf-8

How to redirect output of an already running process

You can also do it using reredirect (https://github.com/jerome-pouiller/reredirect/).

The command bellow redirects the outputs (standard and error) of the process PID to FILE:

reredirect -m FILE PID

The README of reredirect also explains other interesting features: how to restore the original state of the process, how to redirect to another command or to redirect only stdout or stderr.

The tool also provides relink, a script allowing to redirect the outputs to the current terminal:

relink PID
relink PID | grep usefull_content

(reredirect seems to have same features than Dupx described in another answer but, it does not depend on Gdb).

Jenkins could not run git

In case the Jenkins is triggering a build by restricting it to run on a slave or any other server (you may find it in the below setting under 'configure')

enter image description here

then the Path to Git executable should be set as per the 'slave_server_hostname' or any other server where the git commands are executed.

Cannot hide status bar in iOS7

Add method in your view controller.

- (BOOL)prefersStatusBarHidden {
    return YES;
}

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

INSERT INTO eSSLSmartOfficeSource2.[dbo].DeviceLogs  (DeviceId,UserId,LogDate,UpdateFlag) 
SELECT DL1.DeviceId ,DL1.UserId COLLATE DATABASE_DEFAULT,DL1.LogDate 
,0 FROM eSSLSmartOffice.[dbo].DeviceLogs DL1 
WHERE  NOT EXISTS 
(SELECT DL2.DeviceId ,DL2.UserId COLLATE DATABASE_DEFAULT
,DL2.LogDate ,DL2.UpdateFlag 
FROM eSSLSmartOfficeSource2.[dbo].DeviceLogs DL2    
WHERE  DL1.DeviceId =DL2.DeviceId
 and DL1.UserId collate  Latin1_General_CS_AS=DL2.UserId collate  Latin1_General_CS_AS
  and DL1.LogDate =DL2.LogDate )

Center icon in a div - horizontally and vertically

Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:

CSS

#container {
    display: table;
    width: 300px; /* not required, just for example */
    height: 400px; /* not required, just for example */
}

#update {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

HTML

<div id="container">
    <a id="update" href="#">
        <i class="icon-refresh"></i>
    </a>
</div>

JSFiddle

Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell display property works.

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

This seems to be the result you see from Firefox when the server is not configured properly for SSL. Chrome, BTW, just gave a generic "ssl failed" code.

What happens is that the browser sends a SSL handshake when the server is expecting an HTTP request. Server responds with a 400 code and an error message that is much bigger that the handshake message that the browser expects. Hence the FF message.

As we can see from the responses here there are many things that can break the SSL configuration but not stop the server starting or give any hints in error.log.

What I did was systematically check down all the answers until I finally found the right one, right at the bottom.

Here is what I had in the access logs:

rfulton.actrix.co.nz:80 192.168.1.3 - - [09/Oct/2016:13:39:32 +1300] "\x16\x03\x01" 400 0 "-" "-"
rfulton.actrix.co.nz:80 192.168.1.3 - - [09/Oct/2016:13:39:46 +1300] "\x16\x03\x01" 400 0 "-" "-"
rfulton.actrix.co.nz:80 192.168.1.3 - - [09/Oct/2016:13:49:13 +1300] "\x16\x03\x01" 400 0 "-" "-"

Calculating Page Load Time In JavaScript

The answer mentioned by @HaNdTriX is a great, but we are not sure if DOM is completely loaded in the below code:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart; 

This works perfectly when used with onload as:

window.onload = function () {
    var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart; 
    console.log('Page load time is '+ loadTime);
}

Edit 1: Added some context to answer

Note: loadTime is in milliseconds, you can divide by 1000 to get seconds as mentioned by @nycynik

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

Spring uses an special logic for resolving this kind of circular dependencies with singleton beans. But this won't apply to other scopes. There is no elegant way of breaking this circular dependency, but a clumsy option could be this one:

@Component("bean1")
@Scope("view")
public class Bean1 {

    @Autowired
    private Bean2 bean2;

    @PostConstruct
    public void init() {
        bean2.setBean1(this);
    }
}

@Component("bean2")
@Scope("view")
public class Bean2 {

    private Bean1 bean1;

    public void setBean1(Bean1 bean1) {
        this.bean1 = bean1;
    }
}

Anyway, circular dependencies are usually a symptom of bad design. You would think again if there is some better way of defining your class dependencies.

How to format DateTime columns in DataGridView?

If it is a windows form Datagrid, you could use the below code to format the datetime for a column

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss";

EDIT :

Apart from this, if you need the datetime in AM/PM format, you could use the below code

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";

Permutations in JavaScript?

const removeItem = (arr, i) => {
  return arr.slice(0, i).concat(arr.slice(i+1));
}

const makePermutations = (strArr) => {
  const doPermutation = (strArr, pairArr) => {
    return strArr.reduce((result, permutItem, i) => {
      const currentPair = removeItem(pairArr, i);
      const tempResult = currentPair.map((item) => permutItem+item);
      return tempResult.length === 1 ? result.concat(tempResult) :
             result.concat(doPermutation(tempResult, currentPair));
    }, []);
  }
  return strArr.length === 1 ? strArr :
         doPermutation(strArr, strArr);
}


makePermutations(["a", "b", "c", "d"]);
//result: ["abcd", "abdc", "acbd", "acdb", "adbc", "adcb", "bacd", "badc", "bcad", "bcda", "bdac", "bdca", "cabd", "cadb", "cbad", "cbda", "cdab", "cdba", "dabc", "dacb", "dbac", "dbca", "dcab", "dcba"]

Create an ArrayList with multiple object types?

You can just add objects of diffefent "Types" to an instance of ArrayList. No need create an ArrayList. Have a look at the below example, You will get below output:

Beginning....
Contents of array: [String, 1]
Size of the list: 2
This is not an Integer String
This is an Integer 1

package com.viswa.examples.programs;

import java.util.ArrayList;
import java.util.Arrays;

public class VarArrayListDemo {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        System.out.println(" Beginning....");

        ArrayList varTypeArray = new ArrayList();
        varTypeArray.add("String");
        varTypeArray.add(1); //Stored as Integer

        System.out.println(" Contents of array: " + varTypeArray + "\n Size of the list: " + varTypeArray.size());

        Arrays.stream(varTypeArray.toArray()).forEach(VarArrayListDemo::checkType);
    }

    private static <T> void checkType(T t) {

        if (Integer.class.isInstance(t)) {
            System.out.println(" This is an Integer " + t);
        } else {
            System.out.println(" This is not an Integer" + t);
        }
    }

}

Efficient way to do batch INSERTS with JDBC

This is a mix of the two previous answers:

  PreparedStatement ps = c.prepareStatement("INSERT INTO employees VALUES (?, ?)");

  ps.setString(1, "John");
  ps.setString(2,"Doe");
  ps.addBatch();

  ps.clearParameters();
  ps.setString(1, "Dave");
  ps.setString(2,"Smith");
  ps.addBatch();

  ps.clearParameters();
  int[] results = ps.executeBatch();

Find control by name from Windows Forms controls

You can use:

f.Controls[name];

Where f is your form variable. That gives you the control with name name.

Is it acceptable and safe to run pip install under sudo?

It looks like your permissions are messed up. Type chown -R markwalker ~ in the Terminal and try pip again? Let me know if you're sorted.

Gradle, Android and the ANDROID_HOME SDK location

Just delete the sdk.dir inside the local.preoperties file and set the ANDROID_HOME environment variable . It worked for me.

Getting request payload from POST request in Java servlet

Using Java 8 try with resources:

    StringBuilder stringBuilder = new StringBuilder();
    try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
        char[] charBuffer = new char[1024];
        int bytesRead;
        while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
            stringBuilder.append(charBuffer, 0, bytesRead);
        }
    }

Convert the values in a column into row names in an existing data frame

This should do:

samp2 <- samp[,-1]
rownames(samp2) <- samp[,1]

So in short, no there is no alternative to reassigning.

Edit: Correcting myself, one can also do it in place: assign rowname attributes, then remove column:

R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10])
R> rownames(df) <- df[,1]
R> df[,1] <- NULL
R> df
   b c
a  1 A
b  2 B
c  3 C
d  4 D
e  5 E
f  6 F
g  7 G
h  8 H
i  9 I
j 10 J
R> 

Convert Rows to columns using 'Pivot' in SQL Server

If you are using SQL Server 2005+, then you can use the PIVOT function to transform the data from rows into columns.

It sounds like you will need to use dynamic sql if the weeks are unknown but it is easier to see the correct code using a hard-coded version initially.

First up, here are some quick table definitions and data for use:

CREATE TABLE #yt 
(
  [Store] int, 
  [Week] int, 
  [xCount] int
);

INSERT INTO #yt
(
  [Store], 
  [Week], [xCount]
)
VALUES
    (102, 1, 96),
    (101, 1, 138),
    (105, 1, 37),
    (109, 1, 59),
    (101, 2, 282),
    (102, 2, 212),
    (105, 2, 78),
    (109, 2, 97),
    (105, 3, 60),
    (102, 3, 123),
    (101, 3, 220),
    (109, 3, 87);

If your values are known, then you will hard-code the query:

select *
from 
(
  select store, week, xCount
  from yt
) src
pivot
(
  sum(xcount)
  for week in ([1], [2], [3])
) piv;

See SQL Demo

Then if you need to generate the week number dynamically, your code will be:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Week) 
                    from yt
                    group by Week
                    order by Week
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT store,' + @cols + ' from 
             (
                select store, week, xCount
                from yt
            ) x
            pivot 
            (
                sum(xCount)
                for week in (' + @cols + ')
            ) p '

execute(@query);

See SQL Demo.

The dynamic version, generates the list of week numbers that should be converted to columns. Both give the same result:

| STORE |   1 |   2 |   3 |
---------------------------
|   101 | 138 | 282 | 220 |
|   102 |  96 | 212 | 123 |
|   105 |  37 |  78 |  60 |
|   109 |  59 |  97 |  87 |

XSLT - How to select XML Attribute by Attribute?

Note: using // at the beginning of the xpath is a bit CPU intensitve -- it will search every node for a match. Using a more specific path, such as /root/DataSet will create a faster query.