Programs & Examples On #Mongo scala driver

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

For me this happened within a class function.

In PHP 5.3 and above $this::$defaults worked fine; when I swapped the code into a server that for whatever reason had a lower version number it threw this error.

The solution, in my case, was to use the keyword self instead of $this:

self::$defaults works just fine.

Set "Homepage" in Asp.Net MVC

Step 1: Click on Global.asax File in your Solution.

Step 2: Then Go to Definition of

RouteConfig.RegisterRoutes(RouteTable.Routes);

Step 3: Change Controller Name and View Name

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

How to convert string to integer in C#

int i;
string whatever;

//Best since no exception raised
int.TryParse(whatever, out i);

//Better use try catch on this one
i = Convert.ToInt32(whatever);

What is java pojo class, java bean, normal class?

POJO stands for Plain Old Java Object, and would be used to describe the same things as a "Normal Class" whereas a JavaBean follows a set of rules. Most commonly Beans use getters and setters to protect their member variables, which are typically set to private and have a no-argument public constructor. Wikipedia has a pretty good rundown of JavaBeans: http://en.wikipedia.org/wiki/JavaBeans

POJO is usually used to describe a class that doesn't need to be a subclass of anything, or implement specific interfaces, or follow a specific pattern.

How to make a stable two column layout in HTML/CSS

I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5

This makes me happy.

Try this: Live Demo

display: table is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>.

CSS:

#container {
    background: #ccc;
    display: table
}
#left, #right {
    display: table-cell
}
#left {
    width: 150px;
    background: #f0f;
    border: 5px dotted blue;
}
#right {
    background: #aaa;
    border: 3px solid #000
}

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^[a-zA-Z] means any a-z or A-Z at the start of a line

[^a-zA-Z] means any character that IS NOT a-z OR A-Z

Is Visual Studio Community a 30 day trial?

For my case the problem was in fact that i broke machine.config and looks like VS couldn't have a connection I've added the following lines to my machine.config

<!--
<system.net>
 <defaultProxy>
  <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
 </defaultProxy>
</system.net>
<!--
-->

After replacing the previous section to:

<!--
<system.net>
 <defaultProxy>
  <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
 </defaultProxy>
</system.net>
-->

VS started to work.

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

User this function:-

function dateRange($first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
                $dates = array();
                $current = strtotime($first);
                $last = strtotime($last);

                while( $current <= $last ) {    
                    $dates[] = date($format, $current);
                    $current = strtotime($step, $current);
                }
                return $dates;
        }

Usage / function call:-

Increase by one day:-

dateRange($start, $end); //increment is set to 1 day.

Increase by Month:-

dateRange($start, $end, "+1 month");//increase by one month

use third parameter if you like to set date format:-

   dateRange($start, $end, "+1 month", "Y-m-d H:i:s");//increase by one month and format is mysql datetime

Bind event to right mouse click

To disable right click context menu on all images of a page simply do this with following:

jQuery(document).ready(function(){
    // Disable context menu on images by right clicking
    for(i=0;i<document.images.length;i++) {
        document.images[i].onmousedown = protect;
    }
});

function protect (e) {
    //alert('Right mouse button not allowed!');
    this.oncontextmenu = function() {return false;};
}

Update records using LINQ

I assume person_id is the primary key of Person table, so here's how you update a single record:

Person result = (from p in Context.Persons
              where p.person_id == 5
              select p).SingleOrDefault();

result.is_default = false;

Context.SaveChanges();

and here's how you update multiple records:

List<Person> results = (from p in Context.Persons
                        where .... // add where condition here
                        select p).ToList();

foreach (Person p in results)
{
    p.is_default = false;
}

Context.SaveChanges();

Open Redis port for remote connections

1- Comment out bind 127.0.0.1

2- set requirepass yourpassword

then check if the firewall blocked your port

iptables -L -n

service iptables stop

How to store Node.js deployment settings/configuration files?

You might also look to node-config which loads configuration file depending on $HOST and $NODE_ENV variable (a little bit like RoR) : documentation.

This can be quite useful for different deployment settings (development, test or production).

Convert interface{} to int

Instead of

iAreaId := int(val)

you want a type assertion:

iAreaId := val.(int)
iAreaId, ok := val.(int) // Alt. non panicking version 

The reason why you cannot convert an interface typed value are these rules in the referenced specs parts:

Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.

...

A non-constant value x can be converted to type T in any of these cases:

  1. x is assignable to T.
  2. x's type and T have identical underlying types.
  3. x's type and T are unnamed pointer types and their pointer base types have identical underlying types.
  4. x's type and T are both integer or floating point types.
  5. x's type and T are both complex types.
  6. x is an integer or a slice of bytes or runes and T is a string type.
  7. x is a string and T is a slice of bytes or runes.

But

iAreaId := int(val)

is not any of the cases 1.-7.

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

According to the new documentation, the link is now:

<a href="https://wa.me/?text=urlencodedtext">Share this</a>

If it doesn't work, try this one :

<a href="whatsapp://send?text=urlencodedtext">Share this</a>

Change the Value of h1 Element within a Form with JavaScript

You can do it with regular JavaScript this way:

document.getElementById('h1_id').innerHTML = 'h1 content here';

Here is the doc for getElementById and the innerHTML property.

The innerHTML property description:

A DOMString containing the HTML serialization of the element's descendants. Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.

web-api POST body object always null

It can be helpful to add TRACING to the json serializer so you can see what's up when things go wrong.

Define an ITraceWriter implementation to show their debug output like:

class TraceWriter : Newtonsoft.Json.Serialization.ITraceWriter
{
    public TraceLevel LevelFilter {
        get {
            return TraceLevel.Error;
        }
    }

    public void Trace(TraceLevel level, string message, Exception ex)
    {
        Console.WriteLine("JSON {0} {1}: {2}", level, message, ex);
    }
}

Then in your WebApiConfig do:

    config.Formatters.JsonFormatter.SerializerSettings.TraceWriter = new TraceWriter();

(maybe wrap it in an #if DEBUG)

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

writing a batch file that opens a chrome URL

start "Chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 2"

start "webpage name" "http://someurl.com/"

start "Chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 3"

start "webpage name" "http://someurl.com/"

How do you get a directory listing in C?

The following POSIX program will print the names of the files in the current directory:

#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (void)
{
  DIR *dp;
  struct dirent *ep;     
  dp = opendir ("./");

  if (dp != NULL)
  {
    while (ep = readdir (dp))
      puts (ep->d_name);

    (void) closedir (dp);
  }
  else
    perror ("Couldn't open the directory");

  return 0;
}

Credit: http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html

Tested in Ubuntu 16.04.

fileReader.readAsBinaryString to upload files

Use fileReader.readAsDataURL( fileObject ), this will encode it to base64, which you can safely upload to your server.

Add a fragment to the URL without causing a redirect?

For straight HTML, with no JavaScript required:

<a href="#something">Add '#something' to URL</a>

Or, to take your question more literally, to just add '#' to the URL:

<a href="#">Add '#' to URL</a>

asp.net Button OnClick event not firing

i had the same problem did all changed the button and all above mentioned methods then I did a simple thing I was using two forms on a single page and form with in the form so I removed one and it worked :)

SQL left join vs multiple tables on FROM line?

I think there are some good reasons on this page to adopt the second method -using explicit JOINs. The clincher though is that when the JOIN criteria are removed from the WHERE clause it becomes much easier to see the remaining selection criteria in the WHERE clause.

In really complex SELECT statements it becomes much easier for a reader to understand what is going on.

rejected master -> master (non-fast-forward)

This is because you have made conflicting changes to its master. And your repository server is not able to tell you that with these words, so it gives this error because it is not a matter of him deal with these conflicts for you, so he asks you to do it by itself. As ?

1- git pull This will merge your code from your repository to your code of your site master. So conflicts are shown.

2- treat these manualemente conflicts.

3-

git push origin master

And presto, your problem has been resolved.

When restoring a backup, how do I disconnect all active connections?

Restarting SQL server will disconnect users. Easiest way I've found - good also if you want to take the server offline.

But for some very wierd reason the 'Take Offline' option doesn't do this reliably and can hang or confuse the management console. Restarting then taking offline works

Sometimes this is an option - if for instance you've stopped a webserver that is the source of the connections.

GET and POST methods with the same Action name in the same Controller

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

[HttpGet]
public ActionResult Index()
{
  // your code
  return View();
}

[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
  // your code
  return View();
}

Also see "How a Method Becomes An Action"

Close window automatically after printing dialog closes

The following solution is working for IE9, IE8, Chrome, and FF newer versions as of 2014-03-10. The scenario is this: you are in a window (A), where you click a button/link to launch the printing process, then a new window (B) with the contents to be printed is opened, the printing dialog is shown immediately, and you can either cancel or print, and then the new window (B) closes automatically.

The following code allows this. This javascript code is to be placed in the html for window A (not for window B):

/**
 * Opens a new window for the given URL, to print its contents. Then closes the window.
 */
function openPrintWindow(url, name, specs) {
  var printWindow = window.open(url, name, specs);
    var printAndClose = function() {
        if (printWindow.document.readyState == 'complete') {
            clearInterval(sched);
            printWindow.print();
            printWindow.close();
        }
    }
    var sched = setInterval(printAndClose, 200);
};

The button/link to launch the process has simply to invoke this function, as in:

openPrintWindow('http://www.google.com', 'windowTitle', 'width=820,height=600');

How to stop PHP code execution?

You could try to kill the PHP process:

exec('kill -9 ' . getmypid());

How to invoke a Linux shell command from Java

Building on @Tim's example to make a self-contained method:

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Shell {

    /** Returns null if it failed for some reason.
     */
    public static ArrayList<String> command(final String cmdline,
    final String directory) {
        try {
            Process process = 
                new ProcessBuilder(new String[] {"bash", "-c", cmdline})
                    .redirectErrorStream(true)
                    .directory(new File(directory))
                    .start();

            ArrayList<String> output = new ArrayList<String>();
            BufferedReader br = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
            String line = null;
            while ( (line = br.readLine()) != null )
                output.add(line);

            //There should really be a timeout here.
            if (0 != process.waitFor())
                return null;

            return output;

        } catch (Exception e) {
            //Warning: doing this is no good in high quality applications.
            //Instead, present appropriate error messages to the user.
            //But it's perfectly fine for prototyping.

            return null;
        }
    }

    public static void main(String[] args) {
        test("which bash");

        test("find . -type f -printf '%T@\\\\t%p\\\\n' "
            + "| sort -n | cut -f 2- | "
            + "sed -e 's/ /\\\\\\\\ /g' | xargs ls -halt");

    }

    static void test(String cmdline) {
        ArrayList<String> output = command(cmdline, ".");
        if (null == output)
            System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
        else
            for (String line : output)
                System.out.println(line);

    }
}

(The test example is a command that lists all files in a directory and its subdirectories, recursively, in chronological order.)

By the way, if somebody can tell me why I need four and eight backslashes there, instead of two and four, I can learn something. There is one more level of unescaping happening than what I am counting.

Edit: Just tried this same code on Linux, and there it turns out that I need half as many backslashes in the test command! (That is: the expected number of two and four.) Now it's no longer just weird, it's a portability problem.

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

I had the same problem, I had to update MVC Future (Microsoft.AspNet.Mvc.Futures)

Install-Package Microsoft.AspNet.Mvc.Futures

How do I `jsonify` a list in Flask?

jsonify prevents you from doing this in Flask 0.10 and lower for security reasons.

To do it anyway, just use json.dumps in the Python standard library.

http://docs.python.org/library/json.html#json.dumps

Click in OK button inside an Alert (Selenium IDE)

Try Selenium 2.0b1. It has different core than the first version. It should support popup dialogs according to documentation:

Popup Dialogs

Starting with Selenium 2.0 beta 1, there is built in support for handling popup dialog boxes. After you’ve triggered and action that would open a popup, you can access the alert with the following:

Java

Alert alert = driver.switchTo().alert();

Ruby

driver.switch_to.alert

This will return the currently open alert object. With this object you can now accept, dismiss, read it’s contents or even type into a prompt. This interface works equally well on alerts, confirms, prompts. Refer to the JavaDocs for more information.

the MySQL service on local computer started and then stopped

the MySQL service on local computer started and then stopped

This Error happen when you modified my.ini in C:\ProgramData\MySQL\MySQL Server 8.0\my.ini not correct.

You can search my.ini original configuration or checking yours to make sure everything is OK

Send response to all clients except sender

From the @LearnRPG answer but with 1.0:

 // send to current request socket client
 socket.emit('message', "this is a test");

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); //still works
 //or
 io.emit('message', 'this is a test');

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');

 // sending to all clients in 'game' room(channel), include sender
 // docs says "simply use to or in when broadcasting or emitting"
 io.in('game').emit('message', 'cool game');

 // sending to individual socketid, socketid is like a room
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');

To answer @Crashalot comment, socketid comes from:

var io = require('socket.io')(server);
io.on('connection', function(socket) { console.log(socket.id); })

How to pass in a react component into another react component to transclude the first component's content?

Facebook recommends stateless component usage Source: https://facebook.github.io/react/docs/reusable-components.html

In an ideal world, most of your components would be stateless functions because in the future we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations. This is the recommended pattern, when possible.

function Label(props){
    return <span>{props.label}</span>;
}

function Hello(props){
    return <div>{props.label}{props.name}</div>;
}

var hello = Hello({name:"Joe", label:Label({label:"I am "})});

ReactDOM.render(hello,mountNode);

Git resolve conflict using --ours/--theirs for all files

git diff --name-only --diff-filter=U | xargs git checkout --theirs

Seems to do the job. Note that you have to be cd'ed to the root directory of the git repo to achieve this.

Way to get all alphabetic chars in an array in PHP?

Maybe it's a little offtopic (topic starter asked solution for A-Z only), but for cyrrilic character soltion is:

// to place letters into the array
$alphas = array();
foreach (range(chr(0xC0), chr(0xDF)) as $b) {
    $alphas[] = iconv('CP1251', 'UTF-8', $b);
}    

// or conver array into comma-separated string
$alphas = array_reduce($alphas, function($p, $n) {
  return $p . '\'' . $n . '\',';
});
$alphas = rtrim($alphas, ',');

// echo string for testing
echo $alphas;
// or echo mb_strtolower($alphas); for lowercase letters

How to set an iframe src attribute from a variable in AngularJS

I suspect looking at the excerpt that the function trustSrc from trustSrc(currentProject.url) is not defined in the controller.

You need to inject the $sce service in the controller and trustAsResourceUrl the url there.

In the controller:

function AppCtrl($scope, $sce) {
    // ...
    $scope.setProject = function (id) {
      $scope.currentProject = $scope.projects[id];
      $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
    }
}

In the Template:

<iframe ng-src="{{currentProjectUrl}}"> <!--content--> </iframe>

Convert list to array in Java

For ArrayList the following works:

ArrayList<Foo> list = new ArrayList<Foo>();

//... add values

Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);

Comparing boxed Long values 127 and 128

TL;DR

Java caches boxed Integer instances from -128 to 127. Since you are using == to compare objects references instead of values, only cached objects will match. Either work with long unboxed primitive values or use .equals() to compare your Long objects.

Long (pun intended) version

Why there is problem in comparing Long variable with value greater than 127? If the data type of above variable is primitive (long) then code work for all values.

Java caches Integer objects instances from the range -128 to 127. That said:

  • If you set to N Long variables the value 127 (cached), the same object instance will be pointed by all references. (N variables, 1 instance)
  • If you set to N Long variables the value 128 (not cached), you will have an object instance pointed by every reference. (N variables, N instances)

That's why this:

Long val1 = 127L;
Long val2 = 127L;

System.out.println(val1 == val2);

Long val3 = 128L;
Long val4 = 128L;

System.out.println(val3 == val4);

Outputs this:

true
false

For the 127L value, since both references (val1 and val2) point to the same object instance in memory (cached), it returns true.

On the other hand, for the 128 value, since there is no instance for it cached in memory, a new one is created for any new assignments for boxed values, resulting in two different instances (pointed by val3 and val4) and returning false on the comparison between them.

That happens solely because you are comparing two Long object references, not long primitive values, with the == operator. If it wasn't for this Cache mechanism, these comparisons would always fail, so the real problem here is comparing boxed values with == operator.

Changing these variables to primitive long types will prevent this from happening, but in case you need to keep your code using Long objects, you can safely make these comparisons with the following approaches:

System.out.println(val3.equals(val4));                     // true
System.out.println(val3.longValue() == val4.longValue());  // true
System.out.println((long)val3 == (long)val4);              // true

(Proper null checking is necessary, even for castings)

IMO, it's always a good idea to stick with .equals() methods when dealing with Object comparisons.

Reference links:

how to specify new environment location for conda create

like Paul said, use

conda create --prefix=/users/.../yourEnvName python=x.x

if you are located in the folder in which you want to create your virtual environment, just omit the path and use

conda create --prefix=yourEnvName python=x.x

conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with

source activate yourEnvName

How to import csv file in PHP?

I know that this has been asked more than three years ago. But the answer accepted is not extremely useful.

The following code is more useful.

<?php
$File = 'loginevents.csv';

$arrResult  = array();
$handle     = fopen($File, "r");
if(empty($handle) === false) {
    while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){
        $arrResult[] = $data;
    }
    fclose($handle);
}
print_r($arrResult);
?>

From io.Reader to string in Go

var b bytes.Buffer
b.ReadFrom(r)

// b.String()

No provider for Router?

If you created a separate module (eg. AppRoutingModule) to contain your routing commands you can get this same error:

Error: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]: 
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]: 
NullInjectorError: No provider for Router!

You may have forgotten to import it to the main AppModule as shown here:

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule, AppRoutingModule ],
  declarations: [ AppComponent, Page1Component, Page2Component ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

How do you change the formatting options in Visual Studio Code?

If we are talking Visual Studio Code nowadays you set a default formatter in your settings.json:

  // Defines a default formatter which takes precedence over all other formatter settings. 
  // Must be the identifier of an extension contributing a formatter.
  "editor.defaultFormatter": null,

Point to the identifier of any installed extension, i.e.

"editor.defaultFormatter": "esbenp.prettier-vscode"

You can also do so format-specific:

"[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[sass]": {
    "editor.defaultFormatter": "michelemelluso.code-beautifier"
},

Also see here.


You could also assign other keys for different formatters in your keyboard shortcuts (keybindings.json). By default, it reads:

{
  "key": "shift+alt+f",
  "command": "editor.action.formatDocument",
  "when": "editorHasDocumentFormattingProvider && editorHasDocumentFormattingProvider && editorTextFocus && !editorReadonly"
}

Lastly, if you decide to use the Prettier plugin and prettier.rc, and you want for example different indentation for html, scss, json...

{
    "semi": true,
    "singleQuote": false,
    "trailingComma": "none",
    "useTabs": false,

    "overrides": [
        {
            "files": "*.component.html",
            "options": {
                "parser": "angular",
                "tabWidth": 4
            }
        },
        {
            "files": "*.scss",
            "options": {
                "parser": "scss",
                "tabWidth": 2
            }
        },
        {
            "files": ["*.json", ".prettierrc"],
            "options": {
                "parser": "json",
                "tabWidth": 4
            }
        }
    ]
}

How to execute a JavaScript function when I have its name as a string

Thanks for the very helpful answer. I'm using Jason Bunting's function in my projects.

I extended it to use it with an optional timeout, because the normal way to set a timeout wont work. See abhishekisnot's question

_x000D_
_x000D_
function executeFunctionByName(functionName, context, timeout /*, args */ ) {_x000D_
 var args = Array.prototype.slice.call(arguments, 3);_x000D_
 var namespaces = functionName.split(".");_x000D_
 var func = namespaces.pop();_x000D_
 for (var i = 0; i < namespaces.length; i++) {_x000D_
  context = context[namespaces[i]];_x000D_
 }_x000D_
 var timeoutID = setTimeout(_x000D_
  function(){ context[func].apply(context, args)},_x000D_
  timeout_x000D_
 );_x000D_
    return timeoutID;_x000D_
}_x000D_
_x000D_
var _very = {_x000D_
    _deeply: {_x000D_
        _defined: {_x000D_
            _function: function(num1, num2) {_x000D_
                console.log("Execution _very _deeply _defined _function : ", num1, num2);_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
console.log('now wait')_x000D_
executeFunctionByName("_very._deeply._defined._function", window, 2000, 40, 50 );
_x000D_
_x000D_
_x000D_

Function or sub to add new row and data to table

This should help you.

Dim Ws As Worksheet
Set Ws = Sheets("Sheet-Name")
Dim tbl As ListObject
Set tbl = Ws.ListObjects("Table-Name")
Dim newrow As ListRow
Set newrow = tbl.ListRows.Add

With newrow

        .Range(1, Ws.Range("Table-Name[Table-Column-Name]").Column) = "Your Data"

End With

How can you remove all documents from a collection with Mongoose?

.remove() is deprecated. instead we can use deleteMany

DateTime.deleteMany({}, callback).

Unix command to find lines common in two files

awk 'NR==FNR{a[$1]++;next} a[$1] ' file1 file2

What can cause a “Resource temporarily unavailable” on sock send() command

That's because you're using a non-blocking socket and the output buffer is full.

From the send() man page

   When the message does not fit into  the  send  buffer  of  the  socket,
   send() normally blocks, unless the socket has been placed in non-block-
   ing I/O mode.  In non-blocking mode it  would  return  EAGAIN  in  this
   case.  

EAGAIN is the error code tied to "Resource temporarily unavailable"

Consider using select() to get a better control of this behaviours

td widths, not working?

Note that adjusting the width of a column in the thead will affect the whole table

<table>
    <thead>
        <tr width="25">
            <th>Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tr>
        <td>Joe</td>
        <td>[email protected]</td>
    </tr>
</table>

In my case, the width on the thead > tr was overriding the width on table > tr > td directly.

How do you modify the web.config appSettings at runtime?

Try This:

using System;
using System.Configuration;
using System.Web.Configuration;

namespace SampleApplication.WebConfig
{
    public partial class webConfigFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Helps to open the Root level web.config file.
            Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
            //Modifying the AppKey from AppValue to AppValue1
            webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
            //Save the Modified settings of AppSettings.
            webConfigApp.Save();
        }
    }
}

How can I indent multiple lines in Xcode?

The keyboard shortcuts are ?+] for indent and ?+[ for un-indent.

  • In Xcode's preferences window, click the Key Bindings toolbar button. The Key Bindings section is where you customize keyboard shortcuts.

jQuery creating objects

May be you want this (oop in javascript)

function box(color)
{
    this.color=color;
}

var box1=new box('red');    
var box2=new box('white');    

DEMO.

For more information.

How to execute a remote command over ssh with arguments?

Do it this way instead:

function mycommand {
    ssh [email protected] "cd testdir;./test.sh \"$1\""
}

You still have to pass the whole command as a single string, yet in that single string you need to have $1 expanded before it is sent to ssh so you need to use "" for it.

Update

Another proper way to do this actually is to use printf %q to properly quote the argument. This would make the argument safe to parse even if it has spaces, single quotes, double quotes, or any other character that may have a special meaning to the shell:

function mycommand {
    printf -v __ %q "$1"
    ssh [email protected] "cd testdir;./test.sh $__"
}
  • When declaring a function with function, () is not necessary.
  • Don't comment back about it just because you're a POSIXist.

How to fix committing to the wrong Git branch?

To elaborate on this answer, in case you have multiple commits to move from, e.g. develop to new_branch:

git checkout develop # You're probably there already
git reflog # Find LAST_GOOD, FIRST_NEW, LAST_NEW hashes
git checkout new_branch
git cherry-pick FIRST_NEW^..LAST_NEW # ^.. includes FIRST_NEW
git reflog # Confirm that your commits are safely home in their new branch!
git checkout develop
git reset --hard LAST_GOOD # develop is now back where it started

Disable double-tap "zoom" option in browser on touch devices

If there is anyone like me who is experiencing this issue using Vue.js, simply adding .prevent will do the trick: @click.prevent="someAction"

Get Application Directory

Just use this in your code

 context.getApplicationInfo().dataDir

Check if a radio button is checked jquery

Something like this:

 $("input[name=test]").is(":checked");

Using the jQuery is() function should work.

MySql : Grant read only options?

GRANT SELECT ON *.* TO 'user'@'localhost' IDENTIFIED BY 'password';

This will create a user with SELECT privilege for all database including Views.

How to convert a currency string to a double with jQuery or Javascript?

Such a headache and so less consideration to other cultures for nothing...

here it is folks:

let floatPrice = parseFloat(price.replace(/(,|\.)([0-9]{3})/g,'$2').replace(/(,|\.)/,'.'));

as simple as that.

How to read from stdin line by line in Node

// Work on POSIX and Windows
var fs = require("fs");
var stdinBuffer = fs.readFileSync(0); // STDIN_FILENO = 0
console.log(stdinBuffer.toString());

Import Excel to Datagridview

Since you have not replied to my comment above, I am posting a solution for both.

You are missing ' in Extended Properties

For Excel 2003 try this (TRIED AND TESTED)

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                        "C:\\Sample.xls" + 
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

BTW, I stopped working with Jet longtime ago. I use ACE now.

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        "C:\\Sample.xls" + 
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

enter image description here

For Excel 2007+

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        "C:\\Sample.xlsx" + 
                        ";Extended Properties='Excel 12.0 XML;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

mysql query: SELECT DISTINCT column1, GROUP BY column2

you can use COUNT(DISTINCT ip), this will only count distinct values

How to make a whole 'div' clickable in html and css without JavaScript?

Nesting block level elements in anchors is not invalid anymore in HTML5. See http://html5doctor.com/block-level-links-in-html-5/ and http://www.w3.org/TR/html5/the-a-element.html. I'm not saying you should use it, but in HTML5 it's fine to use <a href="#"><div></div></a>.

The accepted answer is otherwise the best one. Using JavaScript like others suggested is also bad because it would make the "link" inaccessible (to users without JavaScript, which includes search engines and others).

How do I export a project in the Android studio?

1.- Export signed packages:

  • Use the Extract a Signed Android Application Package Wizard (On the main menu, choose Build | Generate Signed APK). The package will be signed during extraction.

    OR

  • Configure the .apk file as an artifact by creating an artifact definition of the type Android application with the Release signed package mode.

2.- Export unsigned packages: this can only be done through artifact definitions with the Debug or Release unsigned package mode specified.

Using DataContractSerializer to serialize, but can't deserialize back

Here is how I've always done it:

    public static string Serialize(object obj) {
        using(MemoryStream memoryStream = new MemoryStream())
        using(StreamReader reader = new StreamReader(memoryStream)) {
            DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
            serializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            return reader.ReadToEnd();
        }
    }

    public static object Deserialize(string xml, Type toType) {
        using(Stream stream = new MemoryStream()) {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            DataContractSerializer deserializer = new DataContractSerializer(toType);
            return deserializer.ReadObject(stream);
        }
    }

How to prevent gcc optimizing some statements in C?

You can use

#pragma GCC push_options
#pragma GCC optimize ("O0")

your code

#pragma GCC pop_options

to disable optimizations since GCC 4.4.

See the GCC documentation if you need more details.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

Just to complete the other answers, I would like to quote Effective Java, 2nd Edition, by Joshua Bloch, chapter 10, Item 68 :

"Choosing the executor service for a particular application can be tricky. If you’re writing a small program, or a lightly loaded server, using Executors.new- CachedThreadPool is generally a good choice, as it demands no configuration and generally “does the right thing.” But a cached thread pool is not a good choice for a heavily loaded production server!

In a cached thread pool, submitted tasks are not queued but immediately handed off to a thread for execution. If no threads are available, a new one is created. If a server is so heavily loaded that all of its CPUs are fully utilized, and more tasks arrive, more threads will be created, which will only make matters worse.

Therefore, in a heavily loaded production server, you are much better off using Executors.newFixedThreadPool, which gives you a pool with a fixed number of threads, or using the ThreadPoolExecutor class directly, for maximum control."

Java equivalent to C# extension methods

One could be use the decorator object-oriented design pattern. An example of this pattern being used in Java's standard library would be the DataOutputStream.

Here's some code for augmenting the functionality of a List:

public class ListDecorator<E> implements List<E>
{
    public final List<E> wrapee;

    public ListDecorator(List<E> wrapee)
    {
        this.wrapee = wrapee;
    }

    // implementation of all the list's methods here...

    public <R> ListDecorator<R> map(Transform<E,R> transformer)
    {
        ArrayList<R> result = new ArrayList<R>(size());
        for (E element : this)
        {
            R transformed = transformer.transform(element);
            result.add(transformed);
        }
        return new ListDecorator<R>(result);
    }
}

P.S. I'm a big fan of Kotlin. It has extension methods and also runs on the JVM.

Disable activity slide-in animation when launching new activity?

In my opinion the best answer is to use "overridePendingTransition(0, 0);"

to avoid seeing animation when you want to Intent to an Activity use:

this.startActivity(new Intent(v.getContext(), newactivity.class));
this.overridePendingTransition(0, 0);

and to not see the animation when you press back button Override onPause method in your newactivity

@Override
protected void onPause() {
    super.onPause();
    overridePendingTransition(0, 0);
}

Log4Net configuring log level

Within the definition of the appender, I believe you can do something like this:

<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
    <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO"/>
        <param name="LevelMax" value="INFO"/>
    </filter>
    ...
</appender>

How to open a file / browse dialog using javascript?

you can't use input.click() directly, but you can call this in other element click event.

html

<input type="file">
<button>Select file</button>

js

var botton = document.querySelector('button');
var input = document.querySelector('input');
botton.addEventListener('click', function (e) {
    input.click();
});

this tell you Using hidden file input elements using the click() method

How to modify a CSS display property from JavaScript?

CSS properties should be set by cssText property or setAttribute method.

// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black"; 
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");

Styles should not be set by assigning a string directly to the style property (as in elt.style = "color: blue;"), since it is considered read-only, as the style attribute returns a CSSStyleDeclaration object which is also read-only.

Dynamically create and submit form

Assuming you want create a form with some parameters and make a POST call

var param1 = 10;

$('<form action="./your_target.html" method="POST">' +
'<input type="hidden" name="param" value="' + param + '" />' +
'</form>').appendTo('body').submit();

You could also do it all on one line if you so wish :-)

How to import keras from tf.keras in Tensorflow?

Its not quite fine to downgrade everytime, you may need to make following changes as shown below:

Tensorflow

import tensorflow as tf

#Keras
from tensorflow.keras.models import Sequential, Model, load_model, save_model
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.layers import Dense, Activation, Dropout, Input, Masking, TimeDistributed, LSTM, Conv1D, Embedding
from tensorflow.keras.layers import GRU, Bidirectional, BatchNormalization, Reshape
from tensorflow.keras.optimizers import Adam

from tensorflow.keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding
from tensorflow.keras import optimizers
from tensorflow.keras.callbacks import ModelCheckpoint

The point is that instead of using

from keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding

you need to add

from tensorflow.keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding

Android Stop Emulator from Command Line

Use adb kill-server. It should helps. or

adb -s emulator-5554 emu kill, where emulator-5554 is the emulator name.

For Ubuntu users I found a good command to stop all running emulators (Thanks to @uwe)

adb devices | grep emulator | cut -f1 | while read line; do adb -s $line emu kill; done

How do I return multiple values from a function?

I prefer:

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

It seems everything else is just extra code to do the same thing.

Select the values of one property on all objects of an array in PowerShell

To complement the preexisting, helpful answers with guidance of when to use which approach and a performance comparison.

  • Outside of a pipeline[1], use (PSv3+):

    $objects.Name
    as demonstrated in rageandqq's answer, which is both syntactically simpler and much faster.

    • Accessing a property at the collection level to get its members' values as an array is called member enumeration and is a PSv3+ feature.

    • Alternatively, in PSv2, use the foreach statement, whose output you can also assign directly to a variable:

      $results = foreach ($obj in $objects) { $obj.Name }

    • If collecting all output from a (pipeline) command in memory first is feasible, you can also combine pipelines with member enumeration; e.g.:

       (Get-ChildItem -File | Where-Object Length -lt 1gb).Name
      
    • Tradeoffs:

      • Both the input collection and output array must fit into memory as a whole.
      • If the input collection is itself the result of a command (pipeline) (e.g., (Get-ChildItem).Name), that command must first run to completion before the resulting array's elements can be accessed.
  • In a pipeline, in case you must pass the results to another command, notably if the original input doesn't fit into memory as a whole, use:

    $objects | Select-Object -ExpandProperty Name

    • The need for -ExpandProperty is explained in Scott Saad's answer (you need it to get only the property value).
    • You get the usual pipeline benefits of the pipeline's streaming behavior, i.e. one-by-one object processing, which typically produces output right away and keeps memory use constant (unless you ultimately collect the results in memory anyway).
    • Tradeoff:
      • Use of the pipeline is comparatively slow.

For small input collections (arrays), you probably won't notice the difference, and, especially on the command line, sometimes being able to type the command easily is more important.


Here is an easy-to-type alternative, which, however is the slowest approach; it uses simplified ForEach-Object syntax called an operation statement (again, PSv3+): ; e.g., the following PSv3+ solution is easy to append to an existing command:

$objects | % Name      # short for: $objects | ForEach-Object -Process { $_.Name }

The PSv4+ .ForEach() array method, more comprehensively discussed in this article, is yet another, well-performing alternative, but note that it requires collecting all input in memory first, just like member enumeration:

# By property name (string):
$objects.ForEach('Name')

# By script block (more flexibility; like ForEach-Object)
$objects.ForEach({ $_.Name })
  • This approach is similar to member enumeration, with the same tradeoffs, except that pipeline logic is not applied; it is marginally slower than member enumeration, though still noticeably faster than the pipeline.

  • For extracting a single property value by name (string argument), this solution is on par with member enumeration (though the latter is syntactically simpler).

  • The script-block variant ({ ... }) allows arbitrary transformations; it is a faster - all-in-memory-at-once - alternative to the pipeline-based ForEach-Object cmdlet (%).

Note: The .ForEach() array method, like its .Where() sibling (the in-memory equivalent of Where-Object), always returns a collection (an instance of [System.Collections.ObjectModel.Collection[psobject]]), even if only one output object is produced.
By contrast, member enumeration, Select-Object, ForEach-Object and Where-Object return a single output object as-is, without wrapping it in a collection (array).


Comparing the performance of the various approaches

Here are sample timings for the various approaches, based on an input collection of 10,000 objects, averaged across 10 runs; the absolute numbers aren't important and vary based on many factors, but it should give you a sense of relative performance (the timings come from a single-core Windows 10 VM:

Important

  • The relative performance varies based on whether the input objects are instances of regular .NET Types (e.g., as output by Get-ChildItem) or [pscustomobject] instances (e.g., as output by Convert-FromCsv).
    The reason is that [pscustomobject] properties are dynamically managed by PowerShell, and it can access them more quickly than the regular properties of a (statically defined) regular .NET type. Both scenarios are covered below.

  • The tests use already-in-memory-in-full collections as input, so as to focus on the pure property extraction performance. With a streaming cmdlet / function call as the input, performance differences will generally be much less pronounced, as the time spent inside that call may account for the majority of the time spent.

  • For brevity, alias % is used for the ForEach-Object cmdlet.

General conclusions, applicable to both regular .NET type and [pscustomobject] input:

  • The member-enumeration ($collection.Name) and foreach ($obj in $collection) solutions are by far the fastest, by a factor of 10 or more faster than the fastest pipeline-based solution.

  • Surprisingly, % Name performs much worse than % { $_.Name } - see this GitHub issue.

  • PowerShell Core consistently outperforms Windows Powershell here.

Timings with regular .NET types:

  • PowerShell Core v7.0.0-preview.3
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.005
1.06   foreach($o in $objects) { $o.Name }           0.005
6.25   $objects.ForEach('Name')                      0.028
10.22  $objects.ForEach({ $_.Name })                 0.046
17.52  $objects | % { $_.Name }                      0.079
30.97  $objects | Select-Object -ExpandProperty Name 0.140
32.76  $objects | % Name                             0.148
  • Windows PowerShell v5.1.18362.145
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.012
1.32   foreach($o in $objects) { $o.Name }           0.015
9.07   $objects.ForEach({ $_.Name })                 0.105
10.30  $objects.ForEach('Name')                      0.119
12.70  $objects | % { $_.Name }                      0.147
27.04  $objects | % Name                             0.312
29.70  $objects | Select-Object -ExpandProperty Name 0.343

Conclusions:

  • In PowerShell Core, .ForEach('Name') clearly outperforms .ForEach({ $_.Name }). In Windows PowerShell, curiously, the latter is faster, albeit only marginally so.

Timings with [pscustomobject] instances:

  • PowerShell Core v7.0.0-preview.3
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.006
1.11   foreach($o in $objects) { $o.Name }           0.007
1.52   $objects.ForEach('Name')                      0.009
6.11   $objects.ForEach({ $_.Name })                 0.038
9.47   $objects | Select-Object -ExpandProperty Name 0.058
10.29  $objects | % { $_.Name }                      0.063
29.77  $objects | % Name                             0.184
  • Windows PowerShell v5.1.18362.145
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.008
1.14   foreach($o in $objects) { $o.Name }           0.009
1.76   $objects.ForEach('Name')                      0.015
10.36  $objects | Select-Object -ExpandProperty Name 0.085
11.18  $objects.ForEach({ $_.Name })                 0.092
16.79  $objects | % { $_.Name }                      0.138
61.14  $objects | % Name                             0.503

Conclusions:

  • Note how with [pscustomobject] input .ForEach('Name') by far outperforms the script-block based variant, .ForEach({ $_.Name }).

  • Similarly, [pscustomobject] input makes the pipeline-based Select-Object -ExpandProperty Name faster, in Windows PowerShell virtually on par with .ForEach({ $_.Name }), but in PowerShell Core still about 50% slower.

  • In short: With the odd exception of % Name, with [pscustomobject] the string-based methods of referencing the properties outperform the scriptblock-based ones.


Source code for the tests:

Note:

  • Download function Time-Command from this Gist to run these tests.

    • Assuming you have looked at the linked code to ensure that it is safe (which I can personally assure you of, but you should always check), you can install it directly as follows:

      irm https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27/raw/Time-Command.ps1 | iex
      
  • Set $useCustomObjectInput to $true to measure with [pscustomobject] instances instead.

$count = 1e4 # max. input object count == 10,000
$runs  = 10  # number of runs to average 

# Note: Using [pscustomobject] instances rather than instances of 
#       regular .NET types changes the performance characteristics.
# Set this to $true to test with [pscustomobject] instances below.
$useCustomObjectInput = $false

# Create sample input objects.
if ($useCustomObjectInput) {
  # Use [pscustomobject] instances.
  $objects = 1..$count | % { [pscustomobject] @{ Name = "$foobar_$_"; Other1 = 1; Other2 = 2; Other3 = 3; Other4 = 4 } }
} else {
  # Use instances of a regular .NET type.
  # Note: The actual count of files and folders in your file-system
  #       may be less than $count
  $objects = Get-ChildItem / -Recurse -ErrorAction Ignore | Select-Object -First $count
}

Write-Host "Comparing property-value extraction methods with $($objects.Count) input objects, averaged over $runs runs..."

# An array of script blocks with the various approaches.
$approaches = { $objects | Select-Object -ExpandProperty Name },
              { $objects | % Name },
              { $objects | % { $_.Name } },
              { $objects.ForEach('Name') },
              { $objects.ForEach({ $_.Name }) },
              { $objects.Name },
              { foreach($o in $objects) { $o.Name } }

# Time the approaches and sort them by execution time (fastest first):
Time-Command $approaches -Count $runs | Select Factor, Command, Secs*

[1] Technically, even a command without |, the pipeline operator, uses a pipeline behind the scenes, but for the purpose of this discussion using the pipeline refers only to commands that do use | and therefore involve multiple commands connected by a pipeline.

Downloading a large file using curl

when curl is used to download a large file then CURLOPT_TIMEOUT is the main option you have to set for.

CURLOPT_RETURNTRANSFER has to be true in case you are getting file like pdf/csv/image etc.

You may find the further detail over here(correct url) Curl Doc

From that page:

curl_setopt($request, CURLOPT_TIMEOUT, 300); //set timeout to 5 mins

curl_setopt($request, CURLOPT_RETURNTRANSFER, true); // true to get the output as string otherwise false

Bulk Insert to Oracle using .NET

A really fast way to solve this problem is to make a database link from the Oracle database to the MySQL database. You can create database links to non-Oracle databases. After you have created the database link you can retrieve your data from the MySQL database with a ... create table mydata as select * from ... statement. This is called heterogeneous connectivity. This way you don't have to do anything in your .net application to move the data.

Another way is to use ODP.NET. In ODP.NET you can use the OracleBulkCopy-class.

But I don't think that inserting 160k records in an Oracle table with System.Data.OracleClient should take 25 minutes. I think you commit too many times. And do you bind your values to the insert statement with parameters or do you concatenate your values. Binding is much faster.

How to find the Target *.exe file of *.appref-ms

I know this question is old, but the way I found the executable file for a similar application was to first open the application, then open Windows Task Manager, and in the "Processes" list right-click on it and choose "Open File Location".

I couldn't seem to find the location in the application reference file in my case...

Default port for SQL Server

  1. The default SQL Server port is 1433 but only if it's a default install. Named instances get a random port number.

  2. The browser service runs on port UDP 1434.

  3. Reporting services is a web service - so it's port 80, or 443 if it's SSL enabled.

  4. Analysis services is 2382 but only if it's a default install. Named instances get a random port number.

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

Here's what I don't like about git:

First of all, I think the distributed idea flies in the face of reality. Everybody who's actually using git is doing so in a centralised way, even Linus Torvalds. If the kernel was managed in a distributed way, that would mean I couldn't actually download the "official" kernel sources - there wouldn't be one - I'd have to decide whether I want Linus' version, or Joe's version, or Bill's version. That would obviously be ridiculous, and that's why there is an official definition which Linus controls using a centralised workflow.

If you accept that you want a centralised definition of your stuff, then it becomes clear that the server and client roles are completely different, so the dogma that the client and server softwares should be the same becomes purely limiting. The dogma that the client and server data should be the same becomes patently ridiculous, especially in a codebase that's got fifteen years of history that nobody cares about but everybody would have to clone.

What we actually want to do with all that old stuff is bung it in a cupboard and forget that it's there, just like any normal VCS does. The fact that git hauls it all back and forth over the network every day is very dangerous, because it nags you to prune it. That pruning involves a lot of tedious decisions and it can go wrong. So people will probably keep a whole series of snapshot repos from various points in history, but wasn't that what source control was for in the first place? This problem didn't exist until somebody invented the distributed model.

Git actively encourages people to rewrite history, and the above is probably one reason for that. Every normal VCS makes rewriting history impossible for all but the admins, and makes sure the admins have no reason to consider it. Correct me if I'm wrong, but as far as I know, git provides no way to grant normal users write access but ban them from rewriting history. That means any developer with a grudge (or who was still struggling with the learning curve) could trash the whole codebase. How do we tighten that one? Well, either you make regular backups of the entire history, i.e. you keep history squared, or you ban write access to all except some poor sod who would receive all the diffs by email and merge them by hand.

Let's take an example of a well-funded, large project and see how git is working for them: Android. I once decided to have a play with the android system itself. I found out that I was supposed to use a bunch of scripts called repo to get at their git. Some of repo runs on the client and some on the server, but both, by their very existence, are illustrating the fact that git is incomplete in either capacity. What happened is that I was unable to pull the sources for about a week and then gave up altogether. I would have had to pull a truly vast amount of data from several different repositories, but the server was completely overloaded with people like me. Repo was timing out and was unable to resume from where it had timed out. If git is so distributable, you'd have thought that they'd have done some kind of peer-to-peer thing to relieve the load on that one server. Git is distributable, but it's not a server. Git+repo is a server, but repo is not distributable cos it's just an ad-hoc collection of hacks.

A similar illustration of git's inadequacy is gitolite (and its ancestor which apparently didn't work out so well.) Gitolite describes its job as easing the deployment of a git server. Again, the very existence of this thing proves that git is not a server, any more than it is a client. What's more, it never will be, because if it grew into either it would be betraying it's founding principles.

Even if you did believe in the distributed thing, git would still be a mess. What, for instance, is a branch? They say that you implicitly make a branch every time you clone a repository, but that can't be the same thing as a branch in a single repository. So that's at least two different things being referred to as branches. But then, you can also rewind in a repo and just start editing. Is that like the second type of branch, or something different again? Maybe it depends what type of repo you've got - oh yes - apparently the repo is not a very clear concept either. There are normal ones and bare ones. You can't push to a normal one because the bare part might get out of sync with its source tree. But you can't cvsimport to a bare one cos they didn't think of that. So you have to cvsimport to a normal one, clone that to a bare one which developers hit, and cvsexport that to a cvs working copy which still has to be checked into cvs. Who can be bothered? Where did all these complications come from? From the distributed idea itself. I ditched gitolite in the end because it was imposing even more of these restrictions on me.

Git says that branching should be light, but many companies already have a serious rogue branch problem so I'd have thought that branching should be a momentous decision with strict policing. This is where perforce really shines...

In perforce you rarely need branches because you can juggle changesets in a very agile way. For instance, the usual workflow is that you sync to the last known good version on mainline, then write your feature. Whenever you attempt to modify a file, the diff of that file gets added to your "default changeset". When you attempt to check in the changeset, it automatically tries to merge the news from mainline into your changeset (effectively rebasing it) and then commits. This workflow is enforced without you even needing to understand it. Mainline thus collects a history of changes which you can quite easily cherry pick your way through later. For instance, suppose you want to revert an old one, say, the one before the one before last. You sync to the moment before the offending change, mark the affected files as part of the changeset, sync to the moment after and merge with "always mine". (There was something very interesting there: syncing doesn't mean having the same thing - if a file is editable (i.e. in an active changeset) it won't be clobbered by the sync but marked as due for resolving.) Now you have a changelist that undoes the offending one. Merge in the subsequent news and you have a changelist that you can plop on top of mainline to have the desired effect. At no point did we rewrite any history.

Now, supposing half way through this process, somebody runs up to you and tells you to drop everything and fix some bug. You just give your default changelist a name (a number actually) then "suspend" it, fix the bug in the now empty default changelist, commit it, and resume the named changelist. It's typical to have several changelists suspended at a time where you try different things out. It's easy and private. You get what you really want from a branch regime without the temptation to procrastinate or chicken out of merging to mainline.

I suppose it would be theoretically possible to do something similar in git, but git makes practically anything possible rather than asserting a workflow we approve of. The centralised model is a bunch of valid simplifications relative to the distributed model which is an invalid generalisation. It's so overgeneralised that it basically expects you to implement source control on top of it, as repo does.

The other thing is replication. In git, anything is possible so you have to figure it out for yourself. In perforce, you get an effectively stateless cache. The only configuration it needs to know is where the master is, and the clients can point at either the master or the cache at their discretion. That's a five minute job and it can't go wrong.

You've also got triggers and customisable forms for asserting code reviews, bugzilla references etc, and of course, you have branches for when you actually need them. It's not clearcase, but it's close, and it's dead easy to set up and maintain.

All in all, I think that if you know you're going to work in a centralised way, which everybody does, you might as well use a tool that was designed with that in mind. Git is overrated because of Linus' fearsome wit together with peoples' tendency to follow each other around like sheep, but its main raison d'etre doesn't actually stand up to common sense, and by following it, git ties its own hands with the two huge dogmas that (a) the software and (b) the data have to be the same at both client and server, and that will always make it complicated and lame at the centralised job.

jQuery - getting custom attribute from selected option

You can also try this one as well with data-myTag

<select id="location">
    <option value="a" data-myTag="123">My option</option>
    <option value="b" data-myTag="456">My other option</option>
</select>

<input type="hidden" id="setMyTag" />

<script>
    $(function() {
        $("#location").change(function(){
           var myTag = $('option:selected', this).data("myTag");

           $('#setMyTag').val(myTag);
        });
    });
</script>

How to detect a USB drive has been plugged in?

Here is a code that works for me, which is a part from the website above combined with my early trials: http://www.codeproject.com/KB/system/DriveDetector.aspx

This basically makes your form listen to windows messages, filters for usb drives and (cd-dvds), grabs the lparam structure of the message and extracts the drive letter.

protected override void WndProc(ref Message m)
    {

        if (m.Msg == WM_DEVICECHANGE)
        {
            DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
            if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) &&  (vol.dbcv_devicetype == DBT_DEVTYPVOLUME) )
            {
                MessageBox.Show(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
            }
            if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
            {
                MessageBox.Show("usb out");
            }
        }
        base.WndProc(ref m);
    }

    [StructLayout(LayoutKind.Sequential)] //Same layout in mem
    public struct DEV_BROADCAST_VOLUME
    {
        public int dbcv_size;
        public int dbcv_devicetype;
        public int dbcv_reserved;
        public int dbcv_unitmask;
    }

    private static char DriveMaskToLetter(int mask)
    {
        char letter;
        string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //1 = A, 2 = B, 3 = C
        int cnt = 0;
        int pom = mask / 2;
        while (pom != 0)    // while there is any bit set in the mask shift it right        
        {        
            pom = pom / 2;
            cnt++;
        }
        if (cnt < drives.Length)
            letter = drives[cnt];
        else
            letter = '?';
        return letter;
    }

Do not forget to add this:

using System.Runtime.InteropServices;

and the following constants:

    const int WM_DEVICECHANGE = 0x0219; //see msdn site
    const int DBT_DEVICEARRIVAL = 0x8000;
    const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
    const int DBT_DEVTYPVOLUME = 0x00000002;  

Create a circular button in BS3

If you have downloaded these files locally then you can change following classes in bootstrap-social.css, just added border-radius: 50%;

.btn-social-icon.btn-lg{height:45px;width:45px;
   padding-left:0;padding-right:0; border-radius: 50%; }

And here is teh HTML

<a class="btn btn-social-icon btn-lg btn-twitter" >
   <i class="fa fa-twitter"></i>
</a>
<a class=" btn btn-social-icon btn-lg btn-facebook">
   <i class="fa fa-facebook sbg-facebook"></i>
</a>
<a class="btn btn-social-icon btn-lg btn-google-plus">
   <i class="fa fa-google-plus"></i>
</a>

It works smooth for me.

RGB to hex and hex to RGB

My example =)

_x000D_
_x000D_
color: {_x000D_
            toHex: function(num){_x000D_
                var str = num.toString(16);_x000D_
                return (str.length<6?'#00'+str:'#'+str);_x000D_
            },_x000D_
            toNum: function(hex){_x000D_
                return parseInt(hex.replace('#',''), 16);_x000D_
            },_x000D_
            rgbToHex: function(color)_x000D_
            {_x000D_
                color = color.replace(/\s/g,"");_x000D_
                var aRGB = color.match(/^rgb\((\d{1,3}[%]?),(\d{1,3}[%]?),(\d{1,3}[%]?)\)$/i);_x000D_
                if(aRGB)_x000D_
                {_x000D_
                    color = '';_x000D_
                    for (var i=1;  i<=3; i++) color += Math.round((aRGB[i][aRGB[i].length-1]=="%"?2.55:1)*parseInt(aRGB[i])).toString(16).replace(/^(.)$/,'0$1');_x000D_
                }_x000D_
                else color = color.replace(/^#?([\da-f])([\da-f])([\da-f])$/i, '$1$1$2$2$3$3');_x000D_
                return '#'+color;_x000D_
            }
_x000D_
_x000D_
_x000D_

Removing Data From ElasticSearch

For mass-delete by query you may use special delete by query API:

$ curl -XDELETE 'http://localhost:9200/twitter/tweet/_query' -d '{
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

In history that API was deleted and then reintroduced again

Who interesting it has long history.

  1. In first version of that answer I refer to documentation of elasticsearch version 1.6. In it that functionality was marked as deprecated but works good.
  2. In elasticsearch version 2.0 it was moved to separate plugin. And even reasons why it became plugin explained.
  3. And it again appeared in core API in version 5.0!

How to use opencv in using Gradle?

Since the integration of OpenCV is such an effort, we pre-packaged it and published it via JCenter here: https://github.com/quickbirdstudios/opencv-android

Just include this in your module's build.gradle dependencies section

dependencies {
  implementation 'com.quickbirdstudios:opencv:3.4.1'
}

and this in your project's build.gradle repositories section

repositories {
  jcenter()
}

You won't get lint error after gradle import but don't forget to initialize the OpenCV library like this in MainActivity

public class MainActivity extends Activity {
    static {
        if (!OpenCVLoader.initDebug())
            Log.d("ERROR", "Unable to load OpenCV");
        else
            Log.d("SUCCESS", "OpenCV loaded");
    }
...
...
...
...

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified his example to do this here: http://jsfiddle.net/QLfMU/116/

react-router go back a page how do you configure history?

I think you just need to enable BrowserHistory on your router by intializing it like that : <Router history={new BrowserHistory}>.

Before that, you should require BrowserHistory from 'react-router/lib/BrowserHistory'

I hope that helps !

UPDATE : example in ES6

const BrowserHistory = require('react-router/lib/BrowserHistory').default;

const App = React.createClass({
    render: () => {
        return (
            <div><button onClick={BrowserHistory.goBack}>Go Back</button></div>
        );
    }
});

React.render((
    <Router history={BrowserHistory}>
        <Route path="/" component={App} />
    </Router>
), document.body);

How can I view the allocation unit size of a NTFS partition in Vista?

I know this is an old thread, but there's a newer way then having to use fsutil or diskpart.

Run this powershell command.

Get-Volume | Format-List AllocationUnitSize, FileSystemLabel

Authentication plugin 'caching_sha2_password' is not supported

Please install below command using command prompt.

pip install mysql-connector-python

enter image description here

Set space between divs

Float them both the same way and add the margin of 40px. If you have 2 elements floating opposite ways you will have much less control and the containing element will determine how far apart they are.

#left{
    float: left;
    margin-right: 40px;
}
#right{
   float: left;
}

Find the smallest positive integer that does not occur in a given sequence

The code below will run in O(N) time and O(N) space complexity. Check this codility link for complete running report.

The program first put all the values inside a HashMap meanwhile finding the max number in the array. The reason for doing this is to have only unique values in provided array and later check them in constant time. After this, another loop will run until the max found number and will return the first integer that is not present in the array.

   static int solution(int[] A) {
      int max = -1;
      HashMap<Integer, Boolean> dict = new HashMap<>();
      for(int a : A) {
         if(dict.get(a) == null) {
            dict.put(a, Boolean.TRUE);
         }
         if(max<a) {
            max = a;
         }
      }
      for(int i = 1; i<max; i++) {
         if(dict.get(i) == null) {
            return i;
         }
      }
      return max>0 ? max+1 : 1;
   }

How to do a regular expression replace in MySQL?

With MySQL 8.0+ you could use natively REGEXP_REPLACE function.

12.5.2 Regular Expressions:

REGEXP_REPLACE(expr, pat, repl[, pos[, occurrence[, match_type]]])

Replaces occurrences in the string expr that match the regular expression specified by the pattern pat with the replacement string repl, and returns the resulting string. If expr, pat, or repl is NULL, the return value is NULL.

and Regular expression support:

Previously, MySQL used the Henry Spencer regular expression library to support regular expression operators (REGEXP, RLIKE).

Regular expression support has been reimplemented using International Components for Unicode (ICU), which provides full Unicode support and is multibyte safe. The REGEXP_LIKE() function performs regular expression matching in the manner of the REGEXP and RLIKE operators, which now are synonyms for that function. In addition, the REGEXP_INSTR(), REGEXP_REPLACE(), and REGEXP_SUBSTR() functions are available to find match positions and perform substring substitution and extraction, respectively.

SELECT REGEXP_REPLACE('Stackoverflow','[A-Zf]','-',1,0,'c'); 
-- Output:
-tackover-low

DBFiddle Demo

What is declarative programming?

I have refined my understanding of declarative programming, since Dec 2011 when I provided an answer to this question. Here follows my current understanding.

The long version of my understanding (research) is detailed at this link, which you should read to gain a deep understanding of the summary I will provide below.

Imperative programming is where mutable state is stored and read, thus the ordering and/or duplication of program instructions can alter the behavior (semantics) of the program (and even cause a bug, i.e. unintended behavior).

In the most naive and extreme sense (which I asserted in my prior answer), declarative programming (DP) is avoiding all stored mutable state, thus the ordering and/or duplication of program instructions can NOT alter the behavior (semantics) of the program.

However, such an extreme definition would not be very useful in the real world, since nearly every program involves stored mutable state. The spreadsheet example conforms to this extreme definition of DP, because the entire program code is run to completion with one static copy of the input state, before the new states are stored. Then if any state is changed, this is repeated. But most real world programs can't be limited to such a monolithic model of state changes.

A more useful definition of DP is that the ordering and/or duplication of programming instructions do not alter any opaque semantics. In other words, there are not hidden random changes in semantics occurring-- any changes in program instruction order and/or duplication cause only intended and transparent changes to the program's behavior.

The next step would be to talk about which programming models or paradigms aid in DP, but that is not the question here.

How to remove line breaks (no characters!) from the string?

Ben's solution is acceptable, but str_replace() is by far faster than preg_replace()

$buffer = str_replace(array("\r", "\n"), '', $buffer);

Using less CPU power, reduces the world carbon dioxide emissions.

Undefined reference to 'vtable for xxx'

You may take a look at this answer to an identical question (as I understand): https://stackoverflow.com/a/1478553 The link posted there explains the problem.

For quick solving your problem you should try to code something like this:

ImplementingClass::virtualFunctionToImplement(){...} It helped me a lot.

Unzip files (7-zip) via cmd command

make sure that your path is pointing to .exe file in C:\Program Files\7-Zip (may in bin directory)

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I solved it now. However it only is solved in Netbeans. Not sure why eclipse still won't take the settings.xml that is changed. The solution is however to remove/comment the User/Password param in settings.xml

Before:

<proxies>
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxyserver.company.com</host>
      <port>8080</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
  </proxies> 

After:

<proxies>
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxyserver.company.com</host>
      <port>8080</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
  </proxies> 

How to style readonly attribute with CSS?

Use the following to work in all browsers:

 var readOnlyAttr = $('.textBoxClass').attr('readonly');
    if (typeof readOnlyAttr !== 'undefined' && readOnlyAttr !== false) {
        $('.textBoxClass').addClass('locked');
    }

How to force file download with PHP

In case you have to download a file with a size larger than the allowed memory limit (memory_limit ini setting), which would cause the PHP Fatal error: Allowed memory size of 5242880 bytes exhausted error, you can do this:

// File to download.
$file = '/path/to/file';

// Maximum size of chunks (in bytes).
$maxRead = 1 * 1024 * 1024; // 1MB

// Give a nice name to your download.
$fileName = 'download_file.txt';

// Open a file in read mode.
$fh = fopen($file, 'r');

// These headers will force download on browser,
// and set the custom file name for the download, respectively.
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');

// Run this until we have read the whole file.
// feof (eof means "end of file") returns `true` when the handler
// has reached the end of file.
while (!feof($fh)) {
    // Read and output the next chunk.
    echo fread($fh, $maxRead);

    // Flush the output buffer to free memory.
    ob_flush();
}

// Exit to make sure not to output anything else.
exit;

Response::json() - Laravel 5.1

However, the previous answer could still be confusing for some programmers. Most especially beginners who are most probably using an older book or tutorial. Or perhaps you still feel the facade is needed. Sure you can use it. Me for one I still love to use the facade, this is because some times while building my api I forget to use the '\' before the Response.

if you are like me, simply add

   "use Response;"

above your class ...extends contoller. this should do.

with this you can now use:

$response = Response::json($posts, 200);

instead of:

$response = \Response::json($posts, 200);

Debugging with Android Studio stuck at "Waiting For Debugger" forever

This solution works for me:

turning off the USB debugging from my device settings , and then turning it on again.

its Much quicker and easier than restart the device.

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

How to convert current date into string in java?

String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());

Powershell remoting with ip-address as target

For those of you who don't care about following arbitrary restriction imposed by Microsoft you can simply add a host file entry to the IP of the server your attempting to connect to rather then use that instead of the IP to bypass this restriction:

Enter-PSSession -Computername NameOfComputerIveAddedToMyHostFile -credentials $cred 

How to retry image pull in a kubernetes Pods?

In case of not having the yaml file:

kubectl get pod PODNAME -n NAMESPACE -o yaml | kubectl replace --force -f -

Convert time span value to format "hh:mm Am/Pm" using C#

string displayValue="03:00 AM";

This is a point in time , not a duration (TimeSpan).

So something is wrong with your basic design or assumptions.

If you do want to use it, you'll have to convert it to a DateTime (point in time) first. You can format a DateTime without the date part, that would be your desired string.

TimeSpan t1 = ...;
DateTime d1 = DateTime.Today + t1;               // any date will do
string result = d1.ToString("hh:mm:ss tt");

storeTime variable can have value like
storeTime=16:00:00;

No, it can have a value of 4 o'clock but the representation is binary, a TimeSpan cannot record the difference between 16:00 and 4 pm.

Replace String in all files in Eclipse

Depending on the file type you are focused on, Ctrl+H will open up different types of search screens.

A more consistent hotkey would be using the Alt method: Tap Alt, then A, then F.

Efficient Order of Operations:

  1. Ctrl+C the text you want to do the replacing (if available)
  2. Highlight the text you want to be replaced
  3. Tap ALT, then A, then F. Brings you to File Search. The selection from (2) will auto-fill the search box
  4. In the “File name patterns” input box, type in “.java” for replacing all Java files or type in "" to replace in all files
  5. Click “Replace…”
  6. Ctrl+V (Paste). Or type in the value you want to do the replacing
  7. Enter

You can find more details in my blog post: http://blog.simplyadvanced.net/android-how-to-findreplace-in-multiple-files-using-eclipse/

How can I convert ticks to a date format?

A DateTime object can be constructed with a specific value of ticks. Once you have determined the ticks value, you can do the following:

DateTime myDate = new DateTime(numberOfTicks);
String test = myDate.ToString("MMMM dd, yyyy");

How to check if spark dataframe is empty?

dataframe.limit(1).count > 0

This also triggers a job but since we are selecting single record, even in case of billion scale records the time consumption could be much lower.

From: https://medium.com/checking-emptiness-in-distributed-objects/count-vs-isempty-surprised-to-see-the-impact-fa70c0246ee0

java calling a method from another class

You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.

So, instead of simply calling addWord("someWord"), you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();), and then call the method using that (i.e. list.addWord("someWord");.

However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord() static, or change the methods in the Words class so that they're not static.

My bad with the above paragraph - however you might want to reconsider ProcessInput() being a static method - does it really need to be?

UITextField border color

borderColor on any view(or UIView Subclass) could also be set using storyboard with a little bit of coding and this approach could be really handy if you're setting border color on multiple UI Objects.

Below are the steps how to achieve it,

  1. Create a category on CALayer class. Declare a property of type UIColor with a suitable name, I'll name it as borderUIColor .
  2. Write the setter and getter for this property.
  3. In the 'Setter' method just set the "borderColor" property of layer to the new colors CGColor value.
  4. In the 'Getter' method return UIColor with layer's borderColor.

P.S: Remember, Categories can't have stored properties. 'borderUIColor' is used as a calculated property, just as a reference to achieve what we're focusing on.

Please have a look at the below code sample;

Objective C:

Interface File:

#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

@interface CALayer (BorderProperties)

// This assigns a CGColor to borderColor.
@property (nonatomic, assign) UIColor* borderUIColor;

@end

Implementation File:

#import "CALayer+BorderProperties.h"

@implementation CALayer (BorderProperties)

- (void)setBorderUIColor:(UIColor *)color {
    self.borderColor = color.CGColor;
}

- (UIColor *)borderUIColor {
    return [UIColor colorWithCGColor:self.borderColor];
}

@end

Swift 2.0:

extension CALayer {
var borderUIColor: UIColor {
    set {
        self.borderColor = newValue.CGColor
    }

    get {
        return UIColor(CGColor: self.borderColor!)
    }
}
}

And finally go to your storyboard/XIB, follow the remaining steps;

  1. Click on the View object for which you want to set border Color.
  2. Click on "Identity Inspector"(3rd from Left) in "Utility"(Right side of the screen) panel.
  3. Under "User Defined Runtime Attributes", click on the "+" button to add a key path.
  4. Set the type of the key path to "Color".
  5. Enter the value for key path as "layer.borderUIColor". [Remember this should be the variable name you declared in category, not borderColor here it's borderUIColor].
  6. Finally chose whatever color you want.

You've to set layer.borderWidth property value to at least 1 to see the border color.

Build and Run. Happy Coding. :)

How to clear/delete the contents of a Tkinter Text widget?

A lot of answers ask you to use END, but if that's not working for you, try:

text.delete("1.0", "end-1c")

c# write text on bitmap

You need to use the Graphics class in order to write on the bitmap.

Specifically, one of the DrawString methods.

Bitmap a = new Bitmap(@"path\picture.bmp");

using(Graphics g = Graphics.FromImage(a))
{
  g.DrawString(....); // requires font, brush etc
}

pictuteBox1.Image = a;

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

solution:

This will work for tables where there are no dependencies on the changing table which would trigger cascading events. First make sure you can drop the table you want to restructure without any disastrous repercussions. Take a note of all the dependencies and column constraints associated with your table (i.e. triggers, indexes, etc.). You may need to put them back in when you are done.

STEP 1: create the temp table to hold all the records from the table you want to restructure. Do not forget to include the new column.

CREATE TABLE #tmp_myTable
(   [new_column] [int] NOT NULL, <-- new column has been inserted here!
    [idx] [bigint] NOT NULL,
    [name] [nvarchar](30) NOT NULL,
    [active] [bit] NOT NULL
)

STEP 2: Make sure all records have been copied over and that the column structure looks the way you want.

SELECT TOP 10 * FROM #tmp_myTable ORDER BY 1 DESC -- you can do COUNT(*) or anything to make sure you copied all the records

STEP 3: DROP the original table:

DROP TABLE myTable

If you are paranoid about bad things could happen, just rename the original table (instead of dropping it). This way it can be always returned back.

EXEC sp_rename myTable, myTable_Copy

STEP 4: Recreate the table myTable the way you want (should match match the #tmp_myTable table structure)

CREATE TABLE myTable
(   [new_column] [int] NOT NULL,
    [idx] [bigint] NOT NULL,
    [name] [nvarchar](30) NOT NULL,
    [active] [bit] NOT NULL
)

-- do not forget any constraints you may need

STEP 5: Copy the all the records from the temp #tmp_myTable table into the new (improved) table myTable.

INSERT INTO myTable ([new_column],[idx],[name],[active])
SELECT [new_column],[idx],[name],[active]
FROM #tmp_myTable

STEP 6: Check if all the data is back in your new, improved table myTable. If yes, clean up after yourself and DROP the temp table #tmp_myTable and the myTable_Copy table if you chose to rename it instead of dropping it.

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

Install lxml from http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml for your python version. It's a precompiled WHL with required modules/dependencies.

The site lists several packages, when e.g. using Win32 Python 3.9, use lxml-4.5.2-cp39-cp39-win32.whl.

Download the file, and then install with:

pip install C:\path\to\downloaded\file\lxml-4.5.2-cp39-cp39-win32.whl

require is not defined? Node.js

In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.

node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().

require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().

There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).

But, you won't be running a web server in your browser as that is not something the browser has the capability to do.


You may be interested in browserify which lets you use node-style modules in a browser using require() statements.

How to convert php array to utf8?

array_walk(
    $myArray,
    function (&$entry) {
        $entry = iconv('Windows-1250', 'UTF-8', $entry);
    }
);

Progress during large file copy (Copy-Item & Write-Progress?)

It seems like a much better solution to just use BitsTransfer, it seems to come OOTB on most Windows machines with PowerShell 2.0 or greater.

Import-Module BitsTransfer
Start-BitsTransfer -Source $Source -Destination $Destination -Description "Backup" -DisplayName "Backup"

add new element in laravel collection object

If you want to add item to the beginning of the collection you can use prepend:

$item->prepend($product, 'key');

Fixing slow initial load for IIS

I was getting a consistent 15 second delay on the first request after 4 minutes of inactivity. My problem was that my app was using Windows Integrated Authentication to SQL Server and the service profile was in a different domain than the server. This caused a cross-domain authentication from IIS to SQL upon app initialization - and this was the real source of my delay. I changed to using a SQL login instead of windows authentication. The delay was immediately gone. I still have all the app initialization settings in place to help improve performance but they may have not been needed at all in my case.

How to convert CharSequence to String?

You can directly use String.valueOf()

String.valueOf(charSequence)

Though this is same as toString() it does a null check on the charSequence before actually calling toString.

This is useful when a method can return either a charSequence or null value.

Passing $_POST values with cURL

Should work fine.

$data = array('name' => 'Ross', 'php_master' => true);

// You can POST a file by prefixing with an @ (for <input type="file"> fields)
$data['file'] = '@/home/user/world.jpg';

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle)

We have two options here, CURLOPT_POST which turns HTTP POST on, and CURLOPT_POSTFIELDS which contains an array of our post data to submit. This can be used to submit data to POST <form>s.


It is important to note that curl_setopt($handle, CURLOPT_POSTFIELDS, $data); takes the $data in two formats, and that this determines how the post data will be encoded.

  1. $data as an array(): The data will be sent as multipart/form-data which is not always accepted by the server.

    $data = array('name' => 'Ross', 'php_master' => true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
    
  2. $data as url encoded string: The data will be sent as application/x-www-form-urlencoded, which is the default encoding for submitted html form data.

    $data = array('name' => 'Ross', 'php_master' => true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
    

I hope this will help others save their time.

See:

Loading/Downloading image from URL on Swift

class func downloadImageFromUrl(with urlStr: String, andCompletionHandler:@escaping (_ result:Bool) -> Void) {
        guard let url = URL(string: urlStr) else {
            andCompletionHandler(false)
            return
        }
        DispatchQueue.global(qos: .background).async {
            URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
                if error == nil {
                    let httpURLResponse = response as? HTTPURLResponse
                    Utils.print( "status code ID : \(String(describing: httpURLResponse?.statusCode))")
                    if httpURLResponse?.statusCode == 200 {
                        if let data = data {
                            if let image = UIImage(data: data) {
                                ImageCaching.sharedInterface().setImage(image, withID: url.absoluteString as NSString)
                                DispatchQueue.main.async {
                                    andCompletionHandler(true)
                                }
                            }else {
                                andCompletionHandler(false)
                            }
                        }else {
                            andCompletionHandler(false)
                        }
                    }else {
                        andCompletionHandler(false)
                    }
                }else {
                    andCompletionHandler(false)
                }
            }).resume()
        }
    }

I have created a simple class function in my Utils.swift class for calling that method you can simply accesss by classname.methodname and your images are saved in NSCache using ImageCaching.swift class

Utils.downloadImageFromUrl(with: URL, andCompletionHandler: { (isDownloaded) in
                            if isDownloaded {
                                if  let image = ImageCaching.sharedInterface().getImage(URL as NSString) {
                                    self.btnTeam.setBackgroundImage(image, for: .normal)
                                }
                            }else {
                                DispatchQueue.main.async {
                                    self.btnTeam.setBackgroundImage(#imageLiteral(resourceName: "com"), for: .normal)
                                }
                            }
                        })

Happy Codding. Cheers:)

Cannot send a content-body with this verb-type

Don't get the request stream, quite simply. GET requests don't usually have bodies (even though it's not technically prohibited by HTTP) and WebRequest doesn't support it - but that's what calling GetRequestStream is for, providing body data for the request.

Given that you're trying to read from the stream, it looks to me like you actually want to get the response and read the response stream from that:

WebRequest request = WebRequest.Create(get.AbsoluteUri + args);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        XmlTextReader reader = new XmlTextReader(stream);
        ...
    }
}

How to list files inside a folder with SQL Server

If you want you can achieve this using a CLR Function/Assembly.

  1. Create a SQL Server CLR Assembly Project.
  2. Go to properties and ensure the permission level on the Connection is setup to external
  3. Add A Sql Function to the Assembly.

Here's an example which will allow you to select form your result set like a table.

public partial class UserDefinedFunctions
{
    [SqlFunction(DataAccess = DataAccessKind.Read,
        FillRowMethodName = "GetFiles_FillRow", TableDefinition = "FilePath nvarchar(4000)")]
    public static IEnumerable GetFiles(SqlString path)
    {
        return System.IO.Directory.GetFiles(path.ToString()).Select(s => new SqlString(s));
    }

    public static void GetFiles_FillRow(object obj,out SqlString filePath)
    {
        filePath = (SqlString)obj;
    }
};

And your SQL query.

use MyDb

select * From GetFiles('C:\Temp\');

Be aware though, your database needs to have CLR Assembly functionaliy enabled using the following SQL Command.

sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

CLR Assemblies (like XP_CMDShell) are disabled by default so if the reason for not using XP Cmd Shell is because you don't have permission, then you may be stuck with this option as well... just FYI.

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

finished with non zero exit value

Errors in the execution of aapt in task processDebugResources or processReleaseResources generally happen when one or more resources of your project are unsupported.

To find out go to the root dir of your project and run:

gradle processDebugResources --debug

This will print aapt specific error. In my case it was a file in the assets folder whose name had invalid character (LEÃO.jpg). aapt doesn't support some characters in the Latin alphabet.

But, as I explained your problem can be other than that. To know for sure you have to run processDebugResources with the option --debug.

The number of method references in a .dex file cannot exceed 64k API 17

You have too many methods. There can only be 65536 methods for dex.

As suggested you can use the multidex support.

Just add these lines in the module/build.gradle:

android {

    defaultConfig {
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'  //with support libraries
  //implementation 'androidx.multidex:multidex:2.0.1'  //with androidx libraries
}

Also in your Manifest add the MultiDexApplication class from the multidex support library to the application element

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.android.multidex.myapplication">
        <application
            ...
            android:name="android.support.multidex.MultiDexApplication">

            <!-- If you are using androidx use android:name="androidx.multidex.MultiDexApplication" -->

            <!--If you are using your own custom Application class then extend -->
            <!--MultiDexApplication and change above line as-->
            <!--android:name=".YourCustomApplicationClass"> -->

            ...
        </application>
    </manifest>

If you are using your own Application class, change the parent class from Application to MultiDexApplication.
If you can't do it, in your Application class override the attachBaseContext method with:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(newBase);
    MultiDex.install(this);
}

Another solution is to try to remove unused code with ProGuard - Configure the ProGuard settings for your app to run ProGuard and ensure you have shrinking enabled for release builds.

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Calling jQuery method from onClick attribute in HTML

I know this was answered long ago, but if you don't mind creating the button dynamically, this works using only the jQuery framework:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $button = $('<input id="1" type="button" value="ahaha" />');_x000D_
  $('body').append($button);_x000D_
  $button.click(function() {_x000D_
    console.log("Id clicked: " + this.id ); // or $(this) or $button_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>And here is my HTML page:</p>_x000D_
_x000D_
<div class="Title">Welcome!</div>
_x000D_
_x000D_
_x000D_

Oracle 'Partition By' and 'Row_Number' keyword

PARTITION BY segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.

In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER

But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of cdt.country_code, cdt.account, cdt.currency

newid() produces GUID, so what shall you expect by this expression?

select
   hi,ho,
   row_number() over(partition by newid() order by hi,ho)
from tbl;

...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1

Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1

An example, this is your data:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','Y'),
('A','Z'),
('B','W'),
('B','W'),
('C','L'),
('C','L');

Then this is analogous to your query:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho)
from tbl;

What will be the output of that?

HI  HO  COLUMN_2
A   X   1
A   Y   1
A   Z   1
B   W   1
B   W   2
C   L   1
C   L   2

You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.

Now, why is the ORDER BY needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

But alas, Oracle(and Sql Server too) doesn't allow partition with no ORDER BY; whereas in Postgresql, ORDER BY on PARTITION is optional: http://www.sqlfiddle.com/#!1/27821/1

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

Your ORDER BY on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow PARTITION with no ORDER BY, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:

SELECT cdt.*,
        ROW_NUMBER ()
        OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency
              ORDER BY newid())
           seq_no
   FROM CUSTOMER_DETAILS cdt

You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the same values anyway. You can use GUID for example(you use newid() for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow PARTITION with no ORDER BY

Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: How to get one unique record from the same list of records from table? No Unique constraint in the table

It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.

Live test: http://www.sqlfiddle.com/#!3/27821/6


But as dbaseman have noticed also, it's useless to partition and order on same columns.

You have a set of data like this:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','X'),
('A','X'),
('B','Y'),
('B','Y'),
('C','Z'),
('C','Z');

Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) http://www.sqlfiddle.com/#!3/29ab8/3

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

Output:

HI  HO  ROW_QUERY_A
A   X   1
A   X   2
A   X   3
B   Y   1
B   Y   2
C   Z   1
C   Z   2

See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)


You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s unique-ing column. Example will make it more clear:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','D'),
('A','E'),
('A','F'),
('B','F'),
('B','E'),
('C','E'),
('C','D');

select
   hi,ho,
   row_number() over(partition by hi order by ho) as nr
from tbl;

PARTITION BY hi operates on non unique column, then on each partitioned column, you order on its unique column(ho), ORDER BY ho

Output:

HI  HO  NR
A   D   1
A   E   2
A   F   3
B   E   1
B   F   2
C   D   1
C   E   2

That data set makes more sense

Live test: http://www.sqlfiddle.com/#!3/d0b44/1

And this is similar to your query with same columns on both PARTITION BY and ORDER BY:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

And this is the ouput:

HI  HO  NR
A   D   1
A   E   1
A   F   1
B   E   1
B   F   1
C   D   1
C   E   1

See? no sense?

Live test: http://www.sqlfiddle.com/#!3/d0b44/3


Finally this might be the right query:

SELECT cdt.*,
     ROW_NUMBER ()
     OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency
           ORDER BY 
               -- removed: cdt.country_code, cdt.account, 
               cdt.currency) -- keep
        seq_no
FROM CUSTOMER_DETAILS cdt

Resolve conflicts using remote changes when pulling from Git remote

If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:

# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master

I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.

If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours merge strategy:

# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master

How to always show the vertical scrollbar in a browser?

Add the class to the div you want to be scrollable.

overflow-x: hidden; hides the horizantal scrollbar. While overflow-y: scroll; allows you to scroll vertically.

<!DOCTYPE html>
<html>
<head>
<style>
.scroll {
    width: 500px;
    height: 300px;
    overflow-x: hidden; 
    overflow-y: scroll;
}


</style>
</head>
<body>

<div class="scroll"><h1> DATA </h1></div>

How to iterate over array of objects in Handlebars?

I meant in the template() call..

You just need to pass the results as an object. So instead of calling

var html = template(data);

do

var html = template({apidata: data});

and use {{#each apidata}} in your template code

demo at http://jsfiddle.net/KPCh4/4/
(removed some leftover if code that crashed)

Static extension methods

No, but you could have something like:

bool b;
b = b.YourExtensionMethod();

Call break in nested if statements

Javascript will throw an exception if you attempt to use a break; statement inside an if else. It is used mainly for loops. You can "break" out of an if else statement with a condition, which does not make sense to include a "break" statement.

JSFiddle

How to Convert Datetime to Date in dd/MM/yyyy format

Give a different alias

SELECT  Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate 

Capitalize or change case of an NSString in Objective-C

In case anyone needed the above in swift :

SWIFT 3.0 and above :

this will capitalize your string, make the first letter capital :

viewNoteDateMonth.text  = yourString.capitalized

this will uppercase your string, make all the string upper case :

viewNoteDateMonth.text  = yourString.uppercased()

How to import and use image in a Vue single file component?

I came across this issue recently, and i'm using Typescript. If you're using Typescript like I am, then you need to import assets like so:

<img src="@/assets/images/logo.png" alt="">

How to detect IE11?

Quite frankly I would say use a library that does what you need (like platform.js for example). At some point things will change and the library will be equipped for those changes and manual parsing using regular expressions will fail.

Thank god IE goes away...

Simplest Way to Test ODBC on WIndows

One way to create a quick test query in Windows via an ODBC connection is using the DQY format.

To achieve this, create a DQY file (e.g. test.dqy) containing the magic first two lines (XLODBC and 1) as below, followed by your ODBC connection string on the third line and your query on the fourth line (all on one line), e.g.:

XLODBC
1
Driver={Microsoft ODBC for Oracle};server=DB;uid=scott;pwd=tiger;
SELECT COUNT(1) n FROM emp

Then, if you open the file by double-clicking it, it will open in Excel and populate the worksheet with the results of the query.

Where can I find the TypeScript version installed in Visual Studio?

You can run it in NuGet Package Manager Console in Visual Studio 2013.

Spring's overriding bean

Another good approach not mentioned in other posts is to use PropertyOverrideConfigurer in case you just want to override properties of some beans.

For example if you want to override the datasource for testing (i.e. use an in-memory database) in another xml config, you just need to use <context:property-override ..."/> in new config and a .properties file containing key-values taking the format beanName.property=newvalue overriding the main props.

application-mainConfig.xml:

<bean id="dataSource" 
    class="org.apache.commons.dbcp.BasicDataSource" 
    p:driverClassName="org.postgresql.Driver"
    p:url="jdbc:postgresql://localhost:5432/MyAppDB" 
    p:username="myusername" 
    p:password="mypassword"
    destroy-method="close" />

application-testConfig.xml:

<import resource="classpath:path/to/file/application-mainConfig.xml"/>

<!-- override bean props -->
<context:property-override location="classpath:path/to/file/beanOverride.properties"/>

beanOverride.properties:

dataSource.driverClassName=org.h2.Driver
dataSource.url=jdbc:h2:mem:MyTestDB

How to change Status Bar text color in iOS

Simply calling

[[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];

in the

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

method of my AppDelegate works great for me in iOS7.

How to get the Enum Index value in C#

One reason that the designers c# might have chosen to NOT have enums auto convert was to prevent accidentally mixing different enum types...

e.g. this is bad code followed by a good version
enum ParkingLevel { GroundLevel, FirstFloor};
enum ParkingFacing { North, East, South, West }
void Test()
{
    var parking = ParkingFacing.North; // NOT A LEVEL
    // WHOOPS at least warning in editor/compile on calls
    WhichLevel(parking); 

    // BAD  wrong type of index, no warning
    var info = ParkinglevelArray[ (int)parking ];
}


// however you can write this, looks complicated 
// but avoids using casts every time AND stops miss-use
void Test()
{
  ParkingLevelManager levels = new ParkingLevelManager();
  // assign info to each level
  var parking = ParkingFacing.North;

  // Next line wrong mixing type 
  // but great you get warning in editor or at compile time      
  var info=levels[parking];

  // and.... no cast needed for correct use
  var pl = ParkingLevel.GroundLevel;
  var infoCorrect=levels[pl];

}
class ParkingLevelInfo { /*...*/ }
class ParkingLevelManager
{
    List<ParkingLevelInfo> m_list;
    public ParkingLevelInfo this[ParkingLevel x] 
 { get{ return m_list[(int)x]; } }}

How do you strip a character out of a column in SQL Server?

Use the "REPLACE" string function on the column in question:

UPDATE (yourTable)
SET YourColumn = REPLACE(YourColumn, '*', '')
WHERE (your conditions)

Replace the "*" with the character you want to strip out and specify your WHERE clause to match the rows you want to apply the update to.

Of course, the REPLACE function can also be used - as other answerer have shown - in a SELECT statement - from your question, I assumed you were trying to update a table.

Marc

Send data from javascript to a mysql database

You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".

What is the easiest way to get current GMT time in Unix timestamp format?

Or just simply using the datetime standard module

In [2]: from datetime import timezone, datetime
   ...: int(datetime.now(tz=timezone.utc).timestamp() * 1000)
   ...: 
Out[2]: 1514901741720

You can truncate or multiply depending on the resolution you want. This example is outputting millis.

If you want a proper Unix timestamp (in seconds) remove the * 1000

what is reverse() in Django

The function supports the dry principle - ensuring that you don't hard code urls throughout your app. A url should be defined in one place, and only one place - your url conf. After that you're really just referencing that info.

Use reverse() to give you the url of a page, given either the path to the view, or the page_name parameter from your url conf. You would use it in cases where it doesn't make sense to do it in the template with {% url 'my-page' %}.

There are lots of possible places you might use this functionality. One place I've found I use it is when redirecting users in a view (often after the successful processing of a form)-

return HttpResponseRedirect(reverse('thanks-we-got-your-form-page'))

You might also use it when writing template tags.

Another time I used reverse() was with model inheritance. I had a ListView on a parent model, but wanted to get from any one of those parent objects to the DetailView of it's associated child object. I attached a get__child_url() function to the parent which identified the existence of a child and returned the url of it's DetailView using reverse().

How to resolve git stash conflict without commit?

The fastest way I have found is to resolve the conflict, then do git add -u, and then do git reset HEAD, that doesn't even involve a commit.

How can I use a custom font in Java?

From the Java tutorial, you need to create a new font and register it in the graphics environment:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));

After this step is done, the font is available in calls to getAvailableFontFamilyNames() and can be used in font constructors.

Reduce left and right margins in matplotlib plot

All you need is

plt.tight_layout()

before your output.

In addition to cutting down the margins, this also tightly groups the space between any subplots:

x = [1,2,3]
y = [1,4,9]
import matplotlib.pyplot as plt
fig = plt.figure()
subplot1 = fig.add_subplot(121)
subplot1.plot(x,y)
subplot2 = fig.add_subplot(122)
subplot2.plot(y,x)
fig.tight_layout()
plt.show()

C# password TextBox in a ASP.net website

Simply select texbox property 'TextMode' and select password...

<asp:TextBox ID="TextBox1" TextMode="Password" runat="server" />

Is it possible to run an .exe or .bat file on 'onclick' in HTML

No, that would be a huge security breach. Imagine if someone could run

format c:

whenever you visted their website.

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

Hibernate has a built-in "yes_no" type that would do what you want. It maps to a CHAR(1) column in the database.

Basic mapping: <property name="some_flag" type="yes_no"/>

Annotation mapping (Hibernate extensions):

@Type(type="yes_no")
public boolean getFlag();

How to call one shell script from another shell script?

First you have to include the file you call:

#!/bin/bash
. includes/included_file.sh

then you call your function like this:

#!/bin/bash
my_called_function

How to open a txt file and read numbers in Java

Read file, parse each line into an integer and store into a list:

List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;

try {
    reader = new BufferedReader(new FileReader(file));
    String text = null;

    while ((text = reader.readLine()) != null) {
        list.add(Integer.parseInt(text));
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
    }
}

//print out the list
System.out.println(list);

Uncaught SyntaxError: Unexpected token with JSON.parse

Check this code. It gives you the clear solution of JSON parse error. It commonly happen by the newlines and the space between json key start and json key end

data_val = data_val.replace(/[\n\s]{1,}\"/g, "\"")  
               .replace(/\"[\n\s]{1,}/g, "\"")  
               .replace(/[\n]/g, "\\n") 

Python calling method in class

The first argument of all methods is usually called self. It refers to the instance for which the method is being called.

Let's say you have:

class A(object):
    def foo(self):
        print 'Foo'

    def bar(self, an_argument):
        print 'Bar', an_argument

Then, doing:

a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'

There's nothing special about this being called self, you could do the following:

class B(object):
    def foo(self):
        print 'Foo'

    def bar(this_object):
        this_object.foo()

Then, doing:

b = B()
b.bar() # prints 'Foo'

In your specific case:

dangerous_device = MissileDevice(some_battery)
dangerous_device.move(dangerous_device.RIGHT) 

(As suggested in comments MissileDevice.RIGHT could be more appropriate here!)

You could declare all your constants at module level though, so you could do:

dangerous_device.move(RIGHT)

This, however, is going to depend on how you want your code to be organized!

How can I get all the request headers in Django?

Starting from Django 2.2, you can use request.headers to access the HTTP headers. From the documentation on HttpRequest.headers:

A case insensitive, dict-like object that provides access to all HTTP-prefixed headers (plus Content-Length and Content-Type) from the request.

The name of each header is stylized with title-casing (e.g. User-Agent) when it’s displayed. You can access headers case-insensitively:

>>> request.headers
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}

>>> 'User-Agent' in request.headers
True
>>> 'user-agent' in request.headers
True

>>> request.headers['User-Agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers['user-agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

>>> request.headers.get('User-Agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers.get('user-agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

To get all headers, you can use request.headers.keys() or request.headers.items().

Round a divided number in Bash

Given a floating point value, we can round it trivially with printf:

# round $1 to $2 decimal places
round() {
    printf "%.{$2:-0}f" "$1"
}

Then,

# do some math, bc style
math() {
    echo "$*" | bc -l
}

$ echo "Pi, to five decimal places, is $(round $(math "4*a(1)") 5)"
Pi, to five decimal places, is 3.14159

Or, to use the original request:

$ echo "3/2, rounded to the nearest integer, is $(round $(math "3/2") 0)"
3/2, rounded to the nearest integer, is 2

Downloading Java JDK on Linux via wget is shown license page instead

All of the above seem to assume you know the URL for the latest Java RPM...

Oracle provide persistent links to the latest updates of each Java version as documented at https://support.oracle.com/epmos/faces/DocumentDisplay?_afrLoop=397248601136938&id=1414485.1 - though you need to create/log in to an Oracle Support account. *Otherwise you can only access the last "public" update of each Java version, e.g. 1.6_u45 (Mar 2013; Latest update is u65, Oct 2013)*

Once you know the persistent link, you should be able to resolve it to the real download; The following works for me, though I don't yet know if the "aru" reference changes.

ME=<myOracleID>
PW=<myOraclePW>
PATCH_FILE=p13079846_17000_Linux-x86-64.zip

echo "Get real URL from the persistent link"

wget -o getrealurl.out --no-cookies --no-check-certificate --user=$ME \
--password=$PW --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com" \
https://updates.oracle.com/Orion/Services/download/$PATCH_FILE?aru=16884382&\
patch_file=$PATCH_FILE

wait    # wget appears to go into background, so "wait" waits 
        # until all background processes complete

REALURL=`grep "^--" getrealurl.out |tail -1 |sed -e 's/.*http/http/'`
wget -O $PATCH_FILE $REALURL
#These last steps must be done quickly, as the REALURL seems to have a short-lived 
#cookie on it and I've had no success with  --keep-session-cookies etc.

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

[A1].End(xlUp)
[A1].End(xlDown)
[A1].End(xlToLeft)
[A1].End(xlToRight)

is the VBA equivalent of being in Cell A1 and pressing Ctrl + Any arrow key. It will continue to travel in that direction until it hits the last cell of data, or if you use this command to move from a cell that is the last cell of data it will travel until it hits the next cell containing data.

If you wanted to find that last "used" cell in Column A, you could go to A65536 (for example, in an XL93-97 workbook) and press Ctrl + Up to "snap" to the last used cell. Or in VBA you would write:

Range("A65536").End(xlUp) which again can be re-written as Range("A" & Rows.Count).End(xlUp) for compatibility reasons across workbooks with different numbers of rows.

Is it possible to install both 32bit and 64bit Java on Windows 7?

You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.

For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".

The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button

There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.

If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.

Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.

JavaScript: How to get parent element by selector?

Here is simple way to access parent id

document.getElementById("child1").parentNode;

will do the magic for you to access the parent div.

<html>
<head>
</head>
<body id="body">
<script>
function alertAncestorsUntilID() {
var a = document.getElementById("child").parentNode;
alert(a.id);
}
</script>
<div id="master">
Master
<div id="child">Child</div>
</div>
<script>
alertAncestorsUntilID();
</script>
</body>
</html>

What is the difference between ( for... in ) and ( for... of ) statements?

The for...in statement iterates over the enumerable properties of an object, in an arbitrary order. Enumerable properties are those properties whose internal [[Enumerable]] flag is set to true, hence if there is any enumerable property in the prototype chain, the for...in loop will iterate on those as well.

The for...of statement iterates over data that iterable object defines to be iterated over.

Example:

Object.prototype.objCustom = function() {}; 
Array.prototype.arrCustom = function() {};

let iterable = [3, 5, 7];

for (let i in iterable) {
  console.log(i); // logs: 0, 1, 2, "arrCustom", "objCustom"
}

for (let i in iterable) {
  if (iterable.hasOwnProperty(i)) {
    console.log(i); // logs: 0, 1, 2,
  }
}

for (let i of iterable) {
  console.log(i); // logs: 3, 5, 7
}

Like earlier, you can skip adding hasOwnProperty in for...of loops.

C - Convert an uppercase letter to lowercase

I believe you want <= 90

lower(a) 
int a; 
{
    if ((a >= 65) && (a <= 90))
        a = a + 32; 
    return a;  
}

Although tolower would probably just save you the hassle unless you wanted to do this yourself. http://www.cplusplus.com/reference/cctype/tolower/

JAVA_HOME is set to an invalid directory:

You should set it with C:\Program Files\Java\jdk1.8.0_12.

\bin is not required.

What is the difference between SessionState and ViewState?

Usage: If you're going to store information that you want to access on different web pages, you can use SessionState

If you want to store information that you want to access from the same page, then you can use Viewstate

Storage The Viewstate is stored within the page itself (in encrypted text), while the Sessionstate is stored in the server.

The SessionState will clear in the following conditions

  1. Cleared by programmer
  2. Cleared by user
  3. Timeout

How do I rotate the Android emulator display?

  • Linux: CTRL + F12
  • Mac: Fn + CTRL + F12
  • Windows: Left CTRL + F11 or Left CTRL + F12

HttpGet with HTTPS : SSLPeerUnverifiedException

Method returning a "secureClient" (in a Java 7 environnement - NetBeans IDE and GlassFish Server: port https by default 3920 ), hope this could help :

public DefaultHttpClient secureClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    SSLSocketFactory sf;

    KeyStore trustStore;
    FileInputStream trustStream = null;
    File truststoreFile;
    // java.security.cert.PKIXParameters for the trustStore
    PKIXParameters pkixParamsTrust;

    KeyStore keyStore;
    FileInputStream keyStream = null;
    File keystoreFile;
    // java.security.cert.PKIXParameters for the keyStore
    PKIXParameters pkixParamsKey;

    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        truststoreFile = new File(TRUSTSTORE_FILE);
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystoreFile = new File(KEYSTORE_FILE);
        try {
            trustStream = new FileInputStream(truststoreFile);
            keyStream = new FileInputStream(keystoreFile);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            trustStore.load(trustStream, PASSWORD.toCharArray());
            keyStore.load(keyStream, PASSWORD.toCharArray());
        } catch (IOException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CertificateException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsTrust = new PKIXParameters(trustStore);
            // accepts Server certificate generated with keytool and (auto) signed by SUN
            pkixParamsTrust.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsKey = new PKIXParameters(keyStore);
            // accepts Client certificate generated with keytool and (auto) signed by SUN
            pkixParamsKey.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            sf = new SSLSocketFactory(trustStore);
            ClientConnectionManager manager = httpclient.getConnectionManager();
            manager.getSchemeRegistry().register(new Scheme("https", 3920, sf));
        } catch (KeyManagementException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnrecoverableKeyException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    // use the httpclient for any httpRequest
    return httpclient;
}

Replace transparency in PNG images with white background

The Alpha Remove section of the ImageMagick Usage Guide suggests using the -alpha remove option, e.g.:

convert in.png  -background white  -alpha remove  out.png

...using the -background color of your choosing.

The guide states:

This operation is simple and fast, and does the job without needing any extra memory use, or other side effects that may be associated with alternative transparency removal techniques. It is thus the prefered way of removing image transparency.

It additionally adds the note:

Note that while transparency is 'removed' the alpha channel will remain turned on, but will now be fully-opaque. If you no longer need the alpha channel you can then use Alpha Off to disable it.

Thus, if you do not need the alpha channel you can make your output image size smaller by adding the -alpha off option, e.g:

convert in.png  -background white  -alpha remove  -alpha off  out.png

There are more details on other, often-used techniques for removing transparency described in the Removing Transparency from Images section.

Included in that section is mention of an important caveat to the usage of -flatten as a technique for removing transparency:

However this will not work with "mogrify" or with a sequence of multiple images, basically because the "-flatten" operator is really designed to merge multiple images into a single image.

So, if you are converting several images at once, e.g. generating thumbnails from a PDF file, -flatten will not do what you want (it will flatten all images for all pages into one image). On the other hand, using the -alpha remove technique will still produce multiple images, each one having transparency removed.

Using Python, find anagrams for a list of words

here is the impressive solution.

funct alphabet_count_mapper:

for each word in the file/list

1.create a dictionary of alphabets/characters with initial count as 0.

2.keep count of all the alphabets in the word and increment the count in the above alphabet dict.

3.create alphabet count dict and return the tuple of the values of alphabet dict.

funct anagram_counter:

1.create a dictionary with alphabet count tuple as key and the count of the number of occurences against it.

2.iterate over the above dict and if the value > 1, add the value to the anagram count.

    import sys
    words_count_map_dict = {}
    fobj = open(sys.argv[1],"r")
    words = fobj.read().split('\n')[:-1]

    def alphabet_count_mapper(word):
        alpha_count_dict = dict(zip('abcdefghijklmnopqrstuvwxyz',[0]*26))
        for alpha in word:
            if alpha in alpha_count_dict.keys():
                alpha_count_dict[alpha] += 1
            else:
                alpha_count_dict.update(dict(alpha=0))
        return tuple(alpha_count_dict.values())

    def anagram_counter(words):
        anagram_count = 0
        for word in words:
            temp_mapper = alphabet_count_mapper(word)
            if temp_mapper in words_count_map_dict.keys():
                words_count_map_dict[temp_mapper] += 1
            else:
                words_count_map_dict.update({temp_mapper:1})
        for val in words_count_map_dict.values():
            if val > 1:
                anagram_count += val
        return anagram_count


    print anagram_counter(words)

run it with file path as command line argument

How to show disable HTML select option in by default?

 selected disabled="true"

Use this. It will work in new browsers

C# Java HashMap equivalent

the answer is

Dictionary

take look at my function, its simple add uses most important member functions inside Dictionary

this function return false if the list contain Duplicates items

 public static bool HasDuplicates<T>(IList<T> items)
    {
        Dictionary<T, bool> mp = new Dictionary<T, bool>();
        for (int i = 0; i < items.Count; i++)
        {
            if (mp.ContainsKey(items[i]))
            {
                return true; // has duplicates
            }
            mp.Add(items[i], true);
        }
        return false; // no duplicates
    }

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

Concatenating two one-dimensional NumPy arrays

The line should be:

numpy.concatenate([a,b])

The arrays you want to concatenate need to be passed in as a sequence, not as separate arguments.

From the NumPy documentation:

numpy.concatenate((a1, a2, ...), axis=0)

Join a sequence of arrays together.

It was trying to interpret your b as the axis parameter, which is why it complained it couldn't convert it into a scalar.

Set initial focus in an Android application

You could use the requestFocus tag:

<Button ...>
  <requestFocus />
</Button>

I find it odd though that it auto-focuses one of your buttons, I haven't observed that behavior in any of my views.

Default passwords of Oracle 11g?

actually during the installation process.it will prompt u to enter the password..At the last step of installation, a window will appear showing cloning database files..After copying,there will be a option..like password managament..there we hav to set our password..and user name will be default..

Compare and contrast REST and SOAP web services?

SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data

WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.

SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON

This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.

With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.

It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.

Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.

REST is over only HTTP

Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.

P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284

Convert all data frame character columns to factors

I used to do a simple for loop. As @A5C1D2H2I1M1N2O1R2T1 answer, lapply is a nice solution. But if you convert all the columns, you will need a data.frame before, otherwise you will end up with a list. Little execution time differences.

 mm2N=mm2New[,10:18]
 str(mm2N)
'data.frame':   35487 obs. of  9 variables:
 $ bb    : int  4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : int  -3 -3 -2 -2 -3 -1 0 0 3 3 ...
 $ bb55  : int  7 6 3 4 4 4 9 2 5 4 ...
 $ vabb55: int  -3 -1 0 -1 -2 -2 -3 0 -1 3 ...
 $ zr    : num  0 -2 -1 1 -1 -1 -1 1 1 0 ...
 $ z55r  : num  -2 -2 0 1 -2 -2 -2 1 -1 1 ...
 $ fechar: num  0 -1 1 0 1 1 0 0 1 0 ...
 $ varr  : num  3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: int  3 0 4 6 6 6 0 6 6 1 ...

 # For solution
 t1=Sys.time()
 for(i in 1:ncol(mm2N)) mm2N[,i]=as.factor(mm2N[,i])
 Sys.time()-t1
Time difference of 0.2020121 secs
 str(mm2N)
'data.frame':   35487 obs. of  9 variables:
 $ bb    : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
 $ bb55  : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
 $ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
 $ zr    : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
 $ z55r  : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
 $ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
 $ varr  : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...

 #lapply solution
 mm2N=mm2New[,10:18]
 t1=Sys.time()
 mm2N <- lapply(mm2N, as.factor)
 Sys.time()-t1
Time difference of 0.209012 secs
 str(mm2N)
List of 9
 $ bb    : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
 $ bb55  : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
 $ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
 $ zr    : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
 $ z55r  : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
 $ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
 $ varr  : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...

 #data.frame lapply solution
 mm2N=mm2New[,10:18]
 t1=Sys.time()
 mm2N <- data.frame(lapply(mm2N, as.factor))
 Sys.time()-t1
Time difference of 0.2010119 secs
 str(mm2N)
'data.frame':   35487 obs. of  9 variables:
 $ bb    : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
 $ bb55  : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
 $ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
 $ zr    : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
 $ z55r  : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
 $ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
 $ varr  : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...

What is an MvcHtmlString and when should I use it?

You would use an MvcHtmlString if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.

Python Serial: How to use the read or readline function to read more than 1 character at a time

I was reciving some date from my arduino uno (0-1023 numbers). Using code from 1337holiday, jwygralak67 and some tips from other sources:

import serial
import time

ser = serial.Serial(
    port='COM4',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)

#this will store the line
seq = []
count = 1

while True:
    for c in ser.read():
        seq.append(chr(c)) #convert from ANSII
        joined_seq = ''.join(str(v) for v in seq) #Make a string from array

        if chr(c) == '\n':
            print("Line " + str(count) + ': ' + joined_seq)
            seq = []
            count += 1
            break


ser.close()

Save ArrayList to SharedPreferences

This is your perfect solution.. try it,

public void saveArrayList(ArrayList<String> list, String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString(key, json);
    editor.apply();     // This line is IMPORTANT !!!
}

public ArrayList<String> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);
}

How can I simulate a print statement in MySQL?

You can print some text by using SELECT command like that:

SELECT 'some text'

Result:

+-----------+
| some text |
+-----------+
| some text |
+-----------+
1 row in set (0.02 sec)

how to make UITextView height dynamic according to text length?

Better yet swift 4 add as an extension:

extension UITextView {
    func resizeForHeight(){
        self.translatesAutoresizingMaskIntoConstraints = true
        self.sizeToFit()
        self.isScrollEnabled = false
    }
}

Compare two MySQL databases

There is a useful tool written using perl called Maatkit. It has several database comparison and syncing tools among other things.

How to count items in JSON object using command line?

A simple solution is to install jshon library :

jshon -l < /tmp/test.json
2

How to cast the size_t to double or int C++

Assuming that the program cannot be redesigned to avoid the cast (ref. Keith Thomson's answer):

To cast from size_t to int you need to ensure that the size_t does not exceed the maximum value of the int. This can be done using std::numeric_limits:

int SizeTToInt(size_t data)
{
    if (data > std::numeric_limits<int>::max())
        throw std::exception("Invalid cast.");
    return std::static_cast<int>(data);
}

If you need to cast from size_t to double, and you need to ensure that you don't lose precision, I think you can use a narrow cast (ref. Stroustrup: The C++ Programming Language, Fourth Edition):

template<class Target, class Source>
Target NarrowCast(Source v)
{
    auto r = static_cast<Target>(v);
    if (static_cast<Source>(r) != v)
        throw RuntimeError("Narrow cast failed.");
    return r;
}

I tested using the narrow cast for size_t-to-double conversions by inspecting the limits of the maximum integers floating-point-representable integers (code uses googletest):

EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 2 })), size_t{ IntegerRepresentableBoundary() - 2 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 1 })), size_t{ IntegerRepresentableBoundary() - 1 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() })), size_t{ IntegerRepresentableBoundary() });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 1 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 2 })), size_t{ IntegerRepresentableBoundary() + 2 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 3 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 4 })), size_t{ IntegerRepresentableBoundary() + 4 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 5 }), std::exception);

where

constexpr size_t IntegerRepresentableBoundary()
{
    static_assert(std::numeric_limits<double>::radix == 2, "Method only valid for binary floating point format.");
    return size_t{2} << (std::numeric_limits<double>::digits - 1);
}

That is, if N is the number of digits in the mantissa, for doubles smaller than or equal to 2^N, integers can be exactly represented. For doubles between 2^N and 2^(N+1), every other integer can be exactly represented. For doubles between 2^(N+1) and 2^(N+2) every fourth integer can be exactly represented, and so on.