Programs & Examples On #Lwjgl

The Lightweight Java Game Library (LWJGL) allows access to high performance crossplatform libraries such as OpenGL, OpenCL and OpenAL to write state of the art 2D and 3D applications with Java.

How to resolve this JNI error when trying to run LWJGL "Hello World"?

A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib to include all the .jar files in that directory, it won't. You have to name them explicitly.

Recreate the default website in IIS

Check out this answer on SuperUser:

In short: Reinstall both IIS and WAS.

In details -

Step 1

Go to "Add remove programs" "Turn windows features on or off" Remove both IIS and WAS (Windows Process Activation Service) Restart the PC Step 2

Go to "Add remove programs" "Turn windows features on or off" Turn on both IIS and WAS (Windows Process Activation Service) Note: Reinstalling IIS alone won't help. You have to reinstall both IIS and WAS

This approach fixed the problem for me.

android layout with visibility GONE

Done by having it like that:

view = inflater.inflate(R.layout.entry_detail, container, false);
TextView tp1= (TextView) view.findViewById(R.id.tp1);
LinearLayout layone= (LinearLayout) view.findViewById(R.id.layone);
tp1.setVisibility(View.VISIBLE);
layone.setVisibility(View.VISIBLE);

shift a std_logic_vector of n bit to right or left

I would not suggest to use sll or srl with std_logic_vector.

During simulation sll gave me 'U' value for those bits, where I expected 0's.

Use shift_left(), shift_right() functions.

For example:

OP1 : in std_logic_vector(7 downto 0); signal accum: std_logic_vector(7 downto 0);

accum <= std_logic_vector(shift_left(unsigned(accum), to_integer(unsigned(OP1)))); accum <= std_logic_vector(shift_right(unsigned(accum), to_integer(unsigned(OP1))));

What does `void 0` mean?

void is a reserved JavaScript keyword. It evaluates the expression and always returns undefined.

How to access private data members outside the class without making "friend"s?

Bad idea, don't do it ever - but here it is how it can be done:

int main()
{
   A aObj;
   int* ptr;

   ptr = (int*)&aObj;

   // MODIFY!
   *ptr = 100;
}

MySQL JOIN the most recent row only?

Presuming the autoincrement column in customer_data is named Id, you can do:

SELECT CONCAT(title,' ',forename,' ',surname) AS name *
FROM customer c
    INNER JOIN customer_data d 
        ON c.customer_id=d.customer_id
WHERE name LIKE '%Smith%'
    AND d.ID = (
                Select Max(D2.Id)
                From customer_data As D2
                Where D2.customer_id = D.customer_id
                )
LIMIT 10, 20

The name 'controlname' does not exist in the current context

Check your code behind file name and Inherits property on the @Page directive, make sure they both match.

Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

I agree with Mark. I set the output to text mode and then sp_HelpText 'sproc'. I have this binded to Crtl-F1 to make it easy.

How to create a floating action button (FAB) in android, using AppCompat v21?

I've generally used xml drawables to create shadow/elevation on a pre-lollipop widget. Here, for example, is an xml drawable that can be used on pre-lollipop devices to simulate the floating action button's elevation.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="8px">
    <layer-list>
        <item>
            <shape android:shape="oval">
                <solid android:color="#08000000"/>
                <padding
                    android:bottom="3px"
                    android:left="3px"
                    android:right="3px"
                    android:top="3px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#09000000"/>
                <padding
                    android:bottom="2px"
                    android:left="2px"
                    android:right="2px"
                    android:top="2px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#10000000"/>
                <padding
                    android:bottom="2px"
                    android:left="2px"
                    android:right="2px"
                    android:top="2px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#11000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#12000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#13000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#14000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#15000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#16000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#17000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
    </layer-list>
</item>
<item>
    <shape android:shape="oval">
        <solid android:color="?attr/colorPrimary"/>
    </shape>
</item>
</layer-list>

In place of ?attr/colorPrimary you can choose any color. Here's a screenshot of the result:

enter image description here

Limiting the output of PHP's echo to 200 characters

This one worked for me and it's also very easy

<?php

$position=14; // Define how many character you want to display.

$message="You are now joining over 2000 current"; 
$post = substr($message, 0, $position); 

echo $post;
echo "..."; 

?>

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

I had to be logged into Ubuntu as root in order to access Mariadb as root. It may have something to do with that "Harden ..." that it prompts you to do when you first install. So:

$ sudo su
[sudo] password for user: yourubunturootpassword
# mysql -r root -p
Enter password: yourmariadbrootpassword

and you're in.

Cropping images in the browser BEFORE the upload

The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:

  1. supply a server-side fallback, or
  2. tell the user that you're very sorry, but he'll need to get a more modern browser.

Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.

EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage function with Jcrop.

Extract the filename from a path

You could get the result you want like this.

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

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

Docker: How to delete all local Docker images

Another way with xargs

docker image ls -q | xargs -I {} docker image rm -f {}

how to call url of any other website in php

use curl php library: http://php.net/manual/en/book.curl.php

direct example: CURL_EXEC:

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Do you know the Maven profile for mvnrepository.com?

Once you've found your jar through mvnrepository.com, hover the "download (JAR)" link, and you'll see the link to the repository which contains your jar (you can probably Right clic and "Copy link URL" to get the URL, what ever your browser is).

Then, you have to add this repository to the repositories used by your project, in your pom.xml :

<project>
  ...
  <repositories>
    <repository>
      <id>my-alternate-repository</id>
      <url>http://myrepo.net/repo</url>
    </repository>
  </repositories>
  ...
</project>

EDIT : now MVNrepository.com has evolved : You can find the link to the repository in the "Repositories" section :

License

Categories

HomePage

Date

Files

Repositories

'Operation is not valid due to the current state of the object' error during postback

If your stack trace looks like following then you are sending a huge load of json objects to server

Operation is not valid due to the current state of the object. 
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
    at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
    at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
    at Failing.Page_Load(Object sender, EventArgs e) 
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
    at System.Web.UI.Control.OnLoad(EventArgs e)
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something

<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>

For more details, please read this Microsoft kb article

Stylesheet not loaded because of MIME-type

In my case I had to both make sure that the link was relative and the rel property was after the href property:

<link href="/assets/styles/iframe.css" rel="stylesheet">

How to get DropDownList SelectedValue in Controller in MVC

If you want to use @Html.DropDownList , follow.

Controller:

var categoryList = context.Categories.Select(c => c.CategoryName).ToList();

ViewBag.CategoryList = categoryList;

View:

@Html.DropDownList("Category", new SelectList(ViewBag.CategoryList), "Choose Category", new { @class = "form-control" })

$("#Category").on("change", function () {
 var q = $("#Category").val();

console.log("val = " + q);
});

How to center links in HTML

One solution is to put them inside <center>, like this:

<center>
<a href="http//www.google.com">Search</a>
<a href="Contact Us">Contact Us</a>
</center>

I've also created a jsfiddle for you: https://jsfiddle.net/9acgLf8e/

Comparing two java.util.Dates to see if they are in the same day

How about:

SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));

You can also set the timezone to the SimpleDateFormat, if needed.

Convert a String of Hex into ASCII in Java

Just use a for loop to go through each couple of characters in the string, convert them to a character and then whack the character on the end of a string builder:

String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
    String str = hex.substring(i, i+2);
    output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);

Or (Java 8+) if you're feeling particularly uncouth, use the infamous "fixed width string split" hack to enable you to do a one-liner with streams instead:

System.out.println(Arrays
        .stream(hex.split("(?<=\\G..)")) //https://stackoverflow.com/questions/2297347/splitting-a-string-at-every-n-th-character
        .map(s -> Character.toString((char)Integer.parseInt(s, 16)))
        .collect(Collectors.joining()));

Either way, this gives a few lines starting with the following:

uTorrent\Completed\nfsuc_ost_by_mustang\Pendulum-9,000 Miles.mp3

Hmmm... :-)

Python urllib2: Receive JSON response from url

you can also get json by using requests as below:

import requests

r = requests.get('http://yoursite.com/your-json-pfile.json')
json_response = r.json()

C# DLL config file

if you want to read settings from the DLL's config file but not from the the root applications web.config or app.config use below code to read configuration in the dll.

var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
string dllConfigData = appConfig.AppSettings.Settings["dllConfigData"].Value;

Submit button not working in Bootstrap form

Replace this

 <button type="button" value=" Send" class="btn btn-success" type="submit" id="submit">

with

<button  value=" Send" class="btn btn-success" type="submit" id="submit">

Verify host key with pysftp

Do not set cnopts.hostkeys = None (as the second most upvoted answer shows), unless you do not care about security. You lose a protection against Man-in-the-middle attacks by doing so.


Use CnOpts.hostkeys (returns HostKeys) to manage trusted host keys.

cnopts = pysftp.CnOpts(knownhosts='known_hosts')

with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:

where the known_hosts contains a server public key(s)] in a format like:

example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...

If you do not want to use an external file, you can also use

from base64 import decodebytes
# ...

keydata = b"""AAAAB3NzaC1yc2EAAAADAQAB..."""
key = paramiko.RSAKey(data=decodebytes(keydata))
cnopts = pysftp.CnOpts()
cnopts.hostkeys.add('example.com', 'ssh-rsa', key)

with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:

Though as of pysftp 0.2.9, this approach will issue a warning, what seems like a bug:
"Failed to load HostKeys" warning while connecting to SFTP server with pysftp


An easy way to retrieve the host key in the needed format is using OpenSSH ssh-keyscan:

$ ssh-keyscan example.com
# example.com SSH-2.0-OpenSSH_5.3
example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...

(due to a bug in pysftp, this does not work, if the server uses non-standard port – the entry starts with [example.com]:port + beware of redirecting ssh-keyscan to a file in PowerShell)

You can also make the application do the same automatically:
Use Paramiko AutoAddPolicy with pysftp
(It will automatically add host keys of new hosts to known_hosts, but for known host keys, it will not accept a changed key)


Though for an absolute security, you should not retrieve the host key remotely, as you cannot be sure, if you are not being attacked already.

See my article Where do I get SSH host key fingerprint to authorize the server?
It's for my WinSCP SFTP client, but most information there is valid in general.


If you need to verify the host key using its fingerprint only, see Python - pysftp / paramiko - Verify host key using its fingerprint.

How to Generate unique file names in C#

Use

Path.GetTempFileName()

or use new GUID().

Path.GetTempFilename() on MSDN.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

How to sort a collection by date in MongoDB?

Just a slight modification to @JohnnyHK answer

collection.find().sort({datefield: -1}, function(err, cursor){...});

In many use cases we wish to have latest records to be returned (like for latest updates / inserts).

How to Add a Dotted Underline Beneath HTML Text

Without CSS, you basically are stuck with using an image tag. Basically make an image of the text and add the underline. That basically means your page is useless to a screen reader.

With CSS, it is simple.

HTML:

<u class="dotted">I like cheese</u>

CSS:

u.dotted{
  border-bottom: 1px dashed #999;
  text-decoration: none; 
}

Running Example

Example page

<!DOCTYPE HTML>
<html>
<head>
    <style>
        u.dotted{
          border-bottom: 1px dashed #999;
          text-decoration: none; 
        }
    </style>
</head>
<body>
    <u class="dotted">I like cheese</u>
</body>
</html>

How to remove underline from a name on hover

_x000D_
_x000D_
legend.green-color{_x000D_
    color:green !important;_x000D_
}
_x000D_
_x000D_
_x000D_

GCM with PHP (Google Cloud Messaging)

You can use this PHP library available on packagist:

https://github.com/CoreProc/gcm-php

After installing it you can do this:

$gcmClient = new GcmClient('your-gcm-api-key-here');

$message = new Message($gcmClient);

$message->addRegistrationId('xxxxxxxxxx');
$message->setData([
    'title' => 'Sample Push Notification',
    'message' => 'This is a test push notification using Google Cloud Messaging'
]);

try {

    $response = $message->send();

    // The send() method returns a Response object
    print_r($response);

} catch (Exception $exception) {

    echo 'uh-oh: ' . $exception->getMessage();

}

Android Min SDK Version vs. Target SDK Version

If you get some compile errors for example:

<uses-sdk
            android:minSdkVersion="10"
            android:targetSdkVersion="15" />

.

private void methodThatRequiresAPI11() {
        BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
                options.inSampleSize = 8;    // API Level 1
                options.inBitmap = bitmap;   // **API Level 11**
        //...
    }

You get compile error:

Field requires API level 11 (current min is 10): android.graphics.BitmapFactory$Options#inBitmap

Since version 17 of Android Development Tools (ADT) there is one new and very useful annotation @TargetApi that can fix this very easily. Add it before the method that is enclosing the problematic declaration:

@TargetApi
private void methodThatRequiresAPI11() {            
  BitmapFactory.Options options = new BitmapFactory.Options();
      options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
      options.inSampleSize = 8;    // API Level 1

      // This will avoid exception NoSuchFieldError (or NoSuchMethodError) at runtime. 
      if (Integer.valueOf(android.os.Build.VERSION.SDK) >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        options.inBitmap = bitmap;   // **API Level 11**
            //...
      }
    }

No compile errors now and it will run !

EDIT: This will result in runtime error on API level lower than 11. On 11 or higher it will run without problems. So you must be sure you call this method on an execution path guarded by version check. TargetApi just allows you to compile it but you run it on your own risk.

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

There is very good package available to parse the email contents with proper documentation.

import mailparser

mail = mailparser.parse_from_file(f)
mail = mailparser.parse_from_file_obj(fp)
mail = mailparser.parse_from_string(raw_mail)
mail = mailparser.parse_from_bytes(byte_mail)

How to Use:

mail.attachments: list of all attachments
mail.body
mail.to

How to add an image to an svg container using D3.js

My team also wanted to add images inside d3-drawn circles, and came up with the following (fiddle):

index.html:

<!doctype html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="timeline.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
  <script src="https://code.jquery.com/jquery-2.2.4.js"
    integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
    crossorigin="anonymous"></script>
  <script src="./timeline.js"></script>
</head>
  <body>
    <div class="timeline"></div>
  </body>
</html>

timeline.css:

.axis path,
.axis line,
.tick line,
.line {
  fill: none;
  stroke: #000000;
  stroke-width: 1px;
}

timeline.js:

// container target
var elem = ".timeline";

var props = {
  width: 1000,
  height: 600,
  class: "timeline-point",

  // margins
  marginTop: 100,
  marginRight: 40,
  marginBottom: 100,
  marginLeft: 60,

  // data inputs
  data: [
    {
      x: 10,
      y: 20,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "a"
    },
    {
      x: 20,
      y: 10,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "b"
    },
    {
      x: 60,
      y: 30,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "c"
    },
    {
      x: 40,
      y: 30,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "d"
    },
    {
      x: 50,
      y: 70,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "e"
    },
    {
      x: 30,
      y: 50,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "f"
    },
    {
      x: 50,
      y: 60,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "g"
    }
  ],

  // y label
  yLabel: "Y label",
  yLabelLength: 50,

  // axis ticks
  xTicks: 10,
  yTicks: 10

}

// component start
var Timeline = {};

/***
*
* Create the svg canvas on which the chart will be rendered
*
***/

Timeline.create = function(elem, props) {

  // build the chart foundation
  var svg = d3.select(elem).append('svg')
      .attr('width', props.width)
      .attr('height', props.height);

  var g = svg.append('g')
      .attr('class', 'point-container')
      .attr("transform",
              "translate(" + props.marginLeft + "," + props.marginTop + ")");

  var g = svg.append('g')
      .attr('class', 'line-container')
      .attr("transform", 
              "translate(" + props.marginLeft + "," + props.marginTop + ")");

  var xAxis = g.append('g')
    .attr("class", "x axis")
    .attr("transform", "translate(0," + (props.height - props.marginTop - props.marginBottom) + ")");

  var yAxis = g.append('g')
    .attr("class", "y axis");

  svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", 1)
    .attr("x", 0 - ((props.height - props.yLabelLength)/2) )
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text(props.yLabel);

  // add placeholders for the axes
  this.update(elem, props);
};

/***
*
* Update the svg scales and lines given new data
*
***/

Timeline.update = function(elem, props) {
  var self = this;
  var domain = self.getDomain(props);
  var scales = self.scales(elem, props, domain);

  self.drawPoints(elem, props, scales);
};


/***
*
* Use the range of values in the x,y attributes
* of the incoming data to identify the plot domain
*
***/

Timeline.getDomain = function(props) {
  var domain = {};
  domain.x = props.xDomain || d3.extent(props.data, function(d) { return d.x; });
  domain.y = props.yDomain || d3.extent(props.data, function(d) { return d.y; });
  return domain;
};


/***
*
* Compute the chart scales
*
***/

Timeline.scales = function(elem, props, domain) {

  if (!domain) {
    return null;
  }

  var width = props.width - props.marginRight - props.marginLeft;
  var height = props.height - props.marginTop - props.marginBottom;

  var x = d3.scale.linear()
    .range([0, width])
    .domain(domain.x);

  var y = d3.scale.linear()
    .range([height, 0])
    .domain(domain.y);

  return {x: x, y: y};
};


/***
*
* Create the chart axes
*
***/

Timeline.axes = function(props, scales) {

  var xAxis = d3.svg.axis()
    .scale(scales.x)
    .orient("bottom")
    .ticks(props.xTicks)
    .tickFormat(d3.format("d"));

  var yAxis = d3.svg.axis()
    .scale(scales.y)
    .orient("left")
    .ticks(props.yTicks);

  return {
    xAxis: xAxis,
    yAxis: yAxis
  }
};


/***
*
* Use the general update pattern to draw the points
*
***/

Timeline.drawPoints = function(elem, props, scales, prevScales, dispatcher) {
  var g = d3.select(elem).selectAll('.point-container');
  var color = d3.scale.category10();

  // add images
  var image = g.selectAll('.image')
    .data(props.data)

  image.enter()
    .append("pattern")
    .attr("id", function(d) {return d.id})
    .attr("class", "svg-image")
    .attr("x", "0")
    .attr("y", "0")
    .attr("height", "70px")
    .attr("width", "70px")
    .append("image")
      .attr("x", "0")
      .attr("y", "0")
      .attr("height", "70px")
      .attr("width", "70px")
      .attr("xlink:href", function(d) {return d.image})

  var point = g.selectAll('.point')
    .data(props.data);

  // enter
  point.enter()
    .append("circle")
      .attr("class", "point")
      .on('mouseover', function(d) {
        d3.select(elem).selectAll(".point").classed("active", false);
        d3.select(this).classed("active", true);
        if (props.onMouseover) {
          props.onMouseover(d)
        };
      })
      .on('mouseout', function(d) {
        if (props.onMouseout) {
          props.onMouseout(d)
        };
      })

  // enter and update
  point.transition()
    .duration(1000)
    .attr("cx", function(d) {
      return scales.x(d.x); 
    })
    .attr("cy", function(d) { 
      return scales.y(d.y); 
    })
    .attr("r", 30)
    .style("stroke", function(d) {
      if (props.pointStroke) {
        return d.color = props.pointStroke;
      } else {
        return d.color = color(d.key);
      }
    })
    .style("fill", function(d) {
      if (d.image) {
        return ("url(#" + d.id + ")");
      }

      if (props.pointFill) {
        return d.color = props.pointFill;
      } else {
        return d.color = color(d.key);
      }
    });

  // exit
  point.exit()
    .remove();

  // update the axes
  var axes = this.axes(props, scales);
  d3.select(elem).selectAll('g.x.axis')
    .transition()
    .duration(1000)
    .call(axes.xAxis);

  d3.select(elem).selectAll('g.y.axis')
    .transition()
    .duration(1000)
    .call(axes.yAxis);
};


$(document).ready(function() {
  Timeline.create(elem, props);
})

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

node.js Error: connect ECONNREFUSED; response from server

just run the following command in the node project

npm install

its worked for me

Calling a JavaScript function named in a variable

Definitely avoid using eval to do something like this, or you will open yourself to XSS (Cross-Site Scripting) vulnerabilities.

For example, if you were to use the eval solutions proposed here, a nefarious user could send a link to their victim that looked like this:

http://yoursite.com/foo.html?func=function(){alert('Im%20In%20Teh%20Codez');}

And their javascript, not yours, would get executed. This code could do something far worse than just pop up an alert of course; it could steal cookies, send requests to your application, etc.

So, make sure you never eval untrusted code that comes in from user input (and anything on the query string id considered user input). You could take user input as a key that will point to your function, but make sure that you don't execute anything if the string given doesn't match a key in your object. For example:

// set up the possible functions:
var myFuncs = {
  func1: function () { alert('Function 1'); },
  func2: function () { alert('Function 2'); },
  func3: function () { alert('Function 3'); },
  func4: function () { alert('Function 4'); },
  func5: function () { alert('Function 5'); }
};
// execute the one specified in the 'funcToRun' variable:
myFuncs[funcToRun]();

This will fail if the funcToRun variable doesn't point to anything in the myFuncs object, but it won't execute any code.

Wait until ActiveWorkbook.RefreshAll finishes - VBA

Though @Wayne G. Dunn has given in code. Here is the place when you don't want to code. And uncheck to disable the background refresh.

enter image description here

How to take screenshot of a div with JavaScript?

As far as I know you can't do that, I may be wrong. However I'd do this with php, generate a JPEG using php standard functions and then display the image, should not be a very hard job, however depends on how flashy the contents of the DIV are

Merge development branch with master

It would be great if you can use the Git Flow workflow. It can merge develop branch into master easily.

What you want to do is just follow the git-flow instruction mentioned here:

STEPS:

  • setup the git-flow project
  • create branches and merge everything to develop
  • run the command git flow release start <version_number>
  • then provide a meaningful message for the release
  • run the command git flow release finish <version_number>
  • it will merge everything into master and change the branch to master.
  • run the command git push to publish the changes to the remote master.

For more information, visit the page - http://danielkummer.github.io/git-flow-cheatsheet/

Linux / Bash, using ps -o to get process by specific name?

Sometimes you need to grep the process by name - in that case:

ps aux | grep simple-scan

Example output:

simple-scan  1090  0.0  0.1   4248  1432 ?        S    Jun11   0:00

Is it possible to add dynamically named properties to JavaScript object?

Here, using your notation:

var data = {
    'PropertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to 
//my object?
data[propName] = 'Some New Property value'

Is it possible to have multiple statements in a python lambda expression?

Or if you want to avoid lambda and have a generator instead of a list:

(sorted(col)[1] for col in lst)

java.io.IOException: Server returned HTTP response code: 500

I have encountered the same problem and found out the solution.

You may look within the first server response and see if the server sent you a cookie.

To check if the server sent you a cookie, you can use HttpURLConnection#getHeaderFields() and look for headers named "Set-Cookie".

If existing, here's the solution for your problem. 100% Working for this case!

+1 if it worked for you.

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

The head command can get the first n lines. Variations are:

head -7 file
head -n 7 file
head -7l file

which will get the first 7 lines of the file called "file". The command to use depends on your version of head. Linux will work with the first one.

To append lines to the end of the same file, use:

echo 'first line to add' >>file
echo 'second line to add' >>file
echo 'third line to add' >>file

or:

echo 'first line to add
second line to add
third line to add' >>file

to do it in one hit.

So, tying these two ideas together, if you wanted to get the first 10 lines of the input.txt file to output.txt and append a line with five "=" characters, you could use something like:

( head -10 input.txt ; echo '=====' ) > output.txt

In this case, we do both operations in a sub-shell so as to consolidate the output streams into one, which is then used to create or overwrite the output file.

Forward request headers from nginx proxy server

The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

When do I need to do "git pull", before or after "git add, git commit"?

I'd suggest pulling from the remote branch as often as possible in order to minimise large merges and possible conflicts.

Having said that, I would go with the first option:

git add foo.js
git commit foo.js -m "commit"
git pull
git push

Commit your changes before pulling so that your commits are merged with the remote changes during the pull. This may result in conflicts which you can begin to deal with knowing that your code is already committed should anything go wrong and you have to abort the merge for whatever reason.

I'm sure someone will disagree with me though, I don't think there's any correct way to do this merge flow, only what works best for people.

Read a local text file using Javascript

You can use a FileReader object to read text file here is example code:

  <div id="page-wrapper">

        <h1>Text File Reader</h1>
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>

    </div>
<script>
window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);    
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        });
}

</script>

Here is the codepen demo

If you have a fixed file to read every time your application load then you can use this code :

<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

readTextFile("file:///C:/your/path/to/file.txt");
</script>

Truncating a table in a stored procedure

As well as execute immediate you can also use

DBMS_UTILITY.EXEC_DDL_STATEMENT('TRUNCATE TABLE tablename;');

The statement fails because the stored proc is executing DDL and some instances of DDL could invalidate the stored proc. By using the execute immediate or exec_ddl approaches the DDL is implemented through unparsed code.

When doing this you neeed to look out for the fact that DDL issues an implicit commit both before and after execution.

Error In PHP5 ..Unable to load dynamic library

Well for Ubuntu 14.04 I was getting that error just for mcrypt:

PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20121212/mcrypt.ini' - /usr/lib/php5/20121212/mcrypt.ini: cannot open shared object file: No such file or directory in Unknown on line 0

If you have a closer look at the error, php is looking for mcrypt.ini and not for mcrypt.so at that location. I just copy mcrypt.so to mcrypt.ini and that's it, the warning is gone and the extension now is properly installed. It might look a bit dirty but it worked!

how to make a div to wrap two float divs inside?

This should do it:

<div id="wrap">
  <div id="nav"></div>
  <div id="content"></div>
  <div style="clear:both"></div>
</div>

What's the difference between "2*2" and "2**2" in Python?

The ** operator in Python is really "power;" that is, 2**3 = 8.

php: how to get associative array key from numeric index?

The key function helped me and is very simple:

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.

Example:

<?php
    $array = array(
        'fruit1' => 'apple',
        'fruit2' => 'orange',
        'fruit3' => 'grape',
        'fruit4' => 'apple',
        'fruit5' => 'apple');

    // this cycle echoes all associative array
    // key where value equals "apple"
    while ($fruit_name = current($array)) {
        if ($fruit_name == 'apple') {
            echo key($array).'<br />';
        }
        next($array);
    }
?>

The above example will output:

fruit1<br />
fruit4<br />
fruit5<br />

How to read a list of files from a folder using PHP?

There is also a really simple way to do this with the help of the RecursiveTreeIterator class, answered here: https://stackoverflow.com/a/37548504/2032235

Use cases for the 'setdefault' dict method

As most answers state setdefault or defaultdict would let you set a default value when a key doesn't exist. However, I would like to point out a small caveat with regard to the use cases of setdefault. When the Python interpreter executes setdefaultit will always evaluate the second argument to the function even if the key exists in the dictionary. For example:

In: d = {1:5, 2:6}

In: d
Out: {1: 5, 2: 6}

In: d.setdefault(2, 0)
Out: 6

In: d.setdefault(2, print('test'))
test
Out: 6

As you can see, print was also executed even though 2 already existed in the dictionary. This becomes particularly important if you are planning to use setdefault for example for an optimization like memoization. If you add a recursive function call as the second argument to setdefault, you wouldn't get any performance out of it as Python would always be calling the function recursively.

Since memoization was mentioned, a better alternative is to use functools.lru_cache decorator if you consider enhancing a function with memoization. lru_cache handles the caching requirements for a recursive function better.

Oracle insert if not exists statement

insert into OPT (email, campaign_id) 
select '[email protected]',100
from dual
where not exists(select * 
                 from OPT 
                 where (email ='[email protected]' and campaign_id =100));

for-in statement

TypeScript isn't giving you a gun to shoot yourself in the foot with.

The iterator variable is a string because it is a string, full stop. Observe:

var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';

for(var key in obj) {
    console.log('Type: ' + typeof key);
    console.log(key + ' => ' + obj[key]);
}

How many key/value pairs are in obj now? 6, more or less? No, 3, and all of the keys are strings:

Type: string
0 => zero point zero
Type: string
[object Object] => this obj; 
Type: string
undefined => the literal string "undefined" 

How to remove the underline for anchors(links)?

in my case there was a rule about hover-effect by the anchor, like this:

#content a:hover {
    border-bottom: 1px solid #333;
}

Of course, text-decoration: none; could not help in this situation. And I spend a lot of time until I found it out.

So: An underscore is not to be confused with a border-bottom.

How do I resolve "Run-time error '429': ActiveX component can't create object"?

This download fixed my VB6 EXE and Access 2016 (using ACEDAO.DLL) run-time error 429. Took me 2 long days to get it resolved because there are so many causes of 429.

http://www.microsoft.com/en-ca/download/details.aspx?id=13255

QUOTE from link: "This download will install a set of components that can be used to facilitate transfer of data between 2010 Microsoft Office System files and non-Microsoft Office applications"

How to convert a Scikit-learn dataset to a Pandas dataset?

One of the best ways:

data = pd.DataFrame(digits.data)

Digits is the sklearn dataframe and I converted it to a pandas DataFrame

Google.com and clients1.google.com/generate_204

204 responses are sometimes used in AJAX to track clicks and page activity. In this case, the only information being passed to the server in the get request is a cookie and not specific information in request parameters, so this doesn't seem to be the case here.

It seems that clients1.google.com is the server behind google search suggestions. When you visit http://www.google.com, the cookie is passed to http://clients1.google.com/generate_204. Perhaps this is to start up some kind of session on the server? Whatever the use, I doubt it's a very standard use.

How to convert JSON string into List of Java object?

use below simple code, no need to use any library

String list = "your_json_string";
Gson gson = new Gson();                         
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);

How to show current user name in a cell?

Based on the instructions at the link below, do the following.

In VBA insert a new module and paste in this code:

Public Function UserName()
    UserName = Environ$("UserName")
End Function

Call the function using the formula:

=Username()

Based on instructions at:

https://support.office.com/en-us/article/Create-Custom-Functions-in-Excel-2007-2f06c10b-3622-40d6-a1b2-b6748ae8231f

Find all files with a filename beginning with a specified string?

ls | grep "^abc"  

will give you all files beginning (which is what the OP specifically required) with the substringabc.
It operates only on the current directory whereas find operates recursively into sub folders.

To use find for only files starting with your string try

find . -name 'abc'*

Detecting Back Button/Hash Change in URL

Another great implementation is balupton's jQuery History which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.

Another project worth noting as well is jQuery Ajaxy which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's quite complicated!

Travel/Hotel API's?

In my search for hotel APIs I have found only one API giving unrestricted open access to their hotel database and allowing you to book their hotels:

Expedia's EAN http://developer.ean.com/

You need to sign for their affiliate program, which is very easy. You get immediate access to their hotel databases plus you can make availability/booking requests with several response options, including JSON, which is more convenient and lightweight than the (unfortunately) more widespread XML.

As you immediately access their API, you can start developing and testing, but still need their approval to launch the site, basically to make sure it provides the needed quality and security, which is reasonable.

They also offer "deep linking", i.e. you may customize your requests by adding parameters. Then if it sufficient for your purpose (for mine it is not), you don't even need to store their content on your server.


I have also signed for HotelsCombined program: (link removed as this site doesn't seem to let me put more links)

However, they do not immediately allow you to use their API even for testing. From their answer:

"Apologies for the inconvenience caused, but it’s simply a business decision to limit access to our rich hotel content. Please kindly check back within the next 2-3 months, where we will be able to judge your traffic, and in turn judge your status on standard data feeds."


I have also signed for Booking.com affiliate program: (link removed as this site doesn't seem to let me put more links)

Unfortunately, again, they limit access, from their answer: "Please do note that, since there's a high amount of time and cost involved in the XML integration, we are only able to offer the XML integration to a small amount of partners with a high potential."


I did not explore Tripadvisor as they seem only to offer top 10 hotels and only as widgets, but most importantly for me, they wouldn't allow booking through them.

I've checked the hotelbase.org mentioned above, they have very extensive list but not as rich as by Expedia, also they don't seem to have images and don't allow booking either.

How to match "any character" in regular expression?

Try the regex .{3,}. This will match all characters except a new line.

Dynamically load a JavaScript file

For those of you, who love one-liners:

import('./myscript.js');

Chances are you might get an error, like:

Access to script at 'http://..../myscript.js' from origin 'http://127.0.0.1' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In which case, you can fallback to:

fetch('myscript.js').then(r => r.text()).then(t => new Function(t)());

Is it possible to run selenium (Firefox) web driver without a GUI?

Be aware that HtmlUnitDriver webclient is single-threaded and Ghostdriver is only at 40% of the functionalities to be a WebDriver.

Nonetheless, Ghostdriver run properly for tests and I have problems to connect it to the WebDriver hub.

How do I clear only a few specific objects from the workspace?

If you're using RStudio, please consider never using the rm(list = ls()) approach!* Instead, you should build your workflow around frequently employing the Ctrl+Shift+F10 shortcut to restart your R session. This is the fastest way to both nuke the current set of user-defined variables AND to clear loaded packages, devices, etc. The reproducibility of your work will increase markedly by adopting this habit.

See this excellent thread on Rstudio community for (h/t @kierisi) for a more thorough discussion (the main gist is captured by what I've stated already).

I must admit my own first few years of R coding featured script after script starting with the rm "trick" -- I'm writing this answer as advice to anyone else who may be starting out their R careers.

*of course there are legitimate uses for this -- much like attach -- but beginning users will be much better served (IMO) crossing that bridge at a later date.

What is the use of the square brackets [] in sql statements?

Column names can contain characters and reserved words that will confuse the query execution engine, so placing brackets around them at all times prevents this from happening. Easier than checking for an issue and then dealing with it, I guess.

Reloading a ViewController

You really don't need to do:

[self.view setNeedsDisplay];

Honestly, I think it's "let's hope for the best" type of solution, in this case. There are several approaches to update your UIViews:

  1. KVO
  2. Notifications
  3. Delegation

Each one has is pros and cons. Depending of what you are updating and what kind of "connection" you have between your business layer (the server connectivity) and the UIViewController, I can recommend one that would suit your needs.

Trying to fire the onload event on script tag

I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload instruction was immediately evaluated, and then the $ usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).

So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.

var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
    console.log("script loaded :)");
    onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);

For my needs, it works fine now. Hope this can help others :)

How to initialize private static members in C++?

int foo::i = 0; 

Is the correct syntax for initializing the variable, but it must go in the source file (.cpp) rather than in the header.

Because it is a static variable the compiler needs to create only one copy of it. You have to have a line "int foo:i" some where in your code to tell the compiler where to put it otherwise you get a link error. If that is in a header you will get a copy in every file that includes the header, so get multiply defined symbol errors from the linker.

Passing argument to alias in bash

This is the solution which can avoid using function:

alias addone='{ num=$(cat -); echo "input: $num"; echo "result:$(($num+1))"; }<<<'

test result

addone 200
input: 200
result:201

Convert Java Date to UTC String

Well if you want to use java.util.Date only, here is a small trick you can use:

String dateString = Long.toString(Date.UTC(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

Select every Nth element in CSS

Try this

div:nth-child(4n+4)

HTML to PDF with Node.js

The best solution I found is html-pdf. It's simple and work with big html.

https://www.npmjs.com/package/html-pdf

Its as simple as that:

    pdf.create(htm, options).toFile('./pdfname.pdf', function(err, res) {
        if (err) {
          console.log(err);
        }
    });

How to get single value from this multi-dimensional PHP array

The first element of $myarray is the array of values you want. So, right now,

echo $myarray[0]['email']; // This outputs '[email protected]'

If you want that array to become $myarray, then you just have to do

$myarray = $myarray[0];

Now, $myarray['email'] etc. will output as expected.

Draggable div without jQuery UI

Dragging like jQueryUI: JsFiddle

You can drag the element from any point without weird centering.

$(document).ready(function() {

        var $body = $('body');
        var $target = null;
        var isDraggEnabled = false;

        $body.on("mousedown", "div", function(e) {

            $this = $(this);
            isDraggEnabled = $this.data("draggable");

            if (isDraggEnabled) {
                if(e.offsetX==undefined){
                    x = e.pageX-$(this).offset().left;
                    y = e.pageY-$(this).offset().top;
                }else{
                    x = e.offsetX;
                    y = e.offsetY;
                };

                $this.addClass('draggable');
                $body.addClass('noselect');
                $target = $(e.target);
            };

        });

         $body.on("mouseup", function(e) {
            $target = null;
            $body.find(".draggable").removeClass('draggable');
            $body.removeClass('noselect');
        });

         $body.on("mousemove", function(e) {
            if ($target) {
                $target.offset({
                    top: e.pageY  - y,
                    left: e.pageX - x
                });
            };     
         });

    });

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

How does "cat << EOF" work in bash?

Long story short, EOF marker(but a different literal can be used as well) is a heredoc format that allows you to provide your input as multiline. A lot of confusion comes from how cat actually works it seems. You can use cat with >> or > as follows:

$ cat >> temp.txt
line 1
line 2

While cat can be used this way when writing manually into console, it's not convenient if I want to provide the input in a more declarative way so that it can be reused by tools and also to keep indentations, whitespaces, etc.
Heredoc allows to define your entire input as if you are not working with stdin but typing in a separate text editor. This is what Wikipedia article means by:

it is a section of a source code file that is treated as if it were a separate file.

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

 var span = TimeSpan.FromMinutes(2);
 var t = Task.Factory.StartNew(async delegate / () =>
   {
        this.SomeAsync();
        await Task.Delay(span, source.Token);
  }, source.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

source.Cancel(true/or not);

// or use ThreadPool(whit defaul options thread) like this
Task.Start(()=>{...}), source.Token)

if u like use some loop thread inside ...

public async void RunForestRun(CancellationToken token)
{
  var t = await Task.Factory.StartNew(async delegate
   {
       while (true)
       {
           await Task.Delay(TimeSpan.FromSeconds(1), token)
                 .ContinueWith(task => { Console.WriteLine("End delay"); });
           this.PrintConsole(1);
        }
    }, token) // drop thread options to default values;
}

// And somewhere there
source.Cancel();
//or
token.ThrowIfCancellationRequested(); // try/ catch block requred.

what's the differences between r and rb in fopen

This makes a difference on Windows, at least. See that link for details.

Split string with PowerShell and do something with each token

"Once upon a time there were three little pigs".Split(" ") | ForEach {
    "$_ is a token"
 }

The key is $_, which stands for the current variable in the pipeline.

About the code you found online:

% is an alias for ForEach-Object. Anything enclosed inside the brackets is run once for each object it receives. In this case, it's only running once, because you're sending it a single string.

$_.Split(" ") is taking the current variable and splitting it on spaces. The current variable will be whatever is currently being looped over by ForEach.

How do I share a global variable between c files?

In the second .c file use extern keyword with the same variable name.

Entity Framework 5 Updating a Record

I have added an extra update method onto my repository base class that's similar to the update method generated by Scaffolding. Instead of setting the entire object to "modified", it sets a set of individual properties. (T is a class generic parameter.)

public void Update(T obj, params Expression<Func<T, object>>[] propertiesToUpdate)
{
    Context.Set<T>().Attach(obj);

    foreach (var p in propertiesToUpdate)
    {
        Context.Entry(obj).Property(p).IsModified = true;
    }
}

And then to call, for example:

public void UpdatePasswordAndEmail(long userId, string password, string email)
{
    var user = new User {UserId = userId, Password = password, Email = email};

    Update(user, u => u.Password, u => u.Email);

    Save();
}

I like one trip to the database. Its probably better to do this with view models, though, in order to avoid repeating sets of properties. I haven't done that yet because I don't know how to avoid bringing the validation messages on my view model validators into my domain project.

Add/delete row from a table

Hi I would do something like this:

var id = 4; // inital number of rows plus one
function addRow(){
   // add a new tr with id 
   // increment id;
}

function deleteRow(id){
   $("#" + id).remove();
}

and i would have a table like this:

<table id = 'dsTable' >
      <tr id=1>
         <td> Relationship Type </td>
         <td> Date of Birth </td>
         <td> Gender </td>
      </tr>
      <tr id=2>
         <td> Spouse </td>
         <td> 1980-22-03 </td>
         <td> female </td>
         <td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
         <td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)"  </td>
      </tr>
       <tr id=3>
         <td> Child </td>
         <td> 2008-23-06 </td>
         <td> female </td>
         <td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
         <td>  <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
      </tr>
   </table>

Also if you want you can make a loop to build up the table. So it will be easy to build the table. The same you can do with edit:)

How do I output text without a newline in PowerShell?

desired o/p: Enabling feature XYZ......Done

you can use below command

$a = "Enabling feature XYZ"

Write-output "$a......Done"

you have to add variable and statement inside quotes. hope this is helpful :)

Thanks Techiegal

How to set index.html as root file in Nginx?

For me, the try_files directive in the (currently most voted) answer https://stackoverflow.com/a/11957896/608359 led to rewrite cycles,

*173 rewrite or internal redirection cycle while internally redirecting

I had better luck with the index directive. Note that I used a forward slash before the name, which might or might not be what you want.

server {
  listen 443 ssl;
  server_name example.com;

  root /home/dclo/example;
  index /index.html;
  error_page 404 /index.html;

  # ... ssl configuration
}

In this case, I wanted all paths to lead to /index.html, including when returning a 404.

How can I access localhost from another computer in the same network?

You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.

You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig. It will give out some information and your local IP should look like 192.168.1.x.

What is lazy loading in Hibernate?

Lazy Loading? Well, it simply means that child records are not fetched immediately, but automatically as soon as you try to access them.

Writing a new line to file in PHP (line feed)

You can also use file_put_contents():

file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);

How to get mouse position in jQuery without mouse-events?

use window.event - it contains last event and as any event contains pageX, pageY etc. Works for Chrome, Safari, IE but not FF.

How can I remove jenkins completely from linux

For sentOs, it's works for me At first stop service by sudo service jenkins stop

Than remove by sudo yum remove jenkins

How to prevent page scrolling when scrolling a DIV element?

here a simple solution without jQuery which does not destroy the browser native scroll (this is: no artificial/ugly scrolling):

var scrollable = document.querySelector('.scrollable');

scrollable.addEventListener('wheel', function(event) {
    var deltaY = event.deltaY;
    var contentHeight = scrollable.scrollHeight;
    var visibleHeight = scrollable.offsetHeight;
    var scrollTop = scrollable.scrollTop;

    if (scrollTop === 0 && deltaY < 0)
        event.preventDefault();
    else if (visibleHeight + scrollTop === contentHeight && deltaY > 0)
        event.preventDefault();
});

Live demo: http://jsfiddle.net/ibcaliax/bwmzfmq7/4/

How can I list all cookies for the current page with Javascript?

I found this code on https://electrictoolbox.com/javascript-get-all-cookies/, which worked for me better than the other solutions:

function get_cookies_array() {

    var cookies = { };

    if (document.cookie && document.cookie != '') {
        var split = document.cookie.split(';');
        for (var i = 0; i < split.length; i++) {
            var name_value = split[i].split("=");
            name_value[0] = name_value[0].replace(/^ /, '');
            cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
         }
     }

     return cookies;
}

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

How to set upload_max_filesize in .htaccess?

What to do to correct this is create a file called php.ini and save it in the same location as your .htaccess file and enter the following code instead:

upload_max_filesize = "250M"
post_max_size = "250M"

How can I rebuild indexes and update stats in MySQL innoDB?

This is done with

ANALYZE TABLE table_name;

Read more about it here.

ANALYZE TABLE analyzes and stores the key distribution for a table. During the analysis, the table is locked with a read lock for MyISAM, BDB, and InnoDB. This statement works with MyISAM, BDB, InnoDB, and NDB tables.

Android: show/hide status bar/power bar

I know its a very old question, but just in case anyone lands here looking for the newest supported way to hide status bar on the go programmatically, you can do it as follows:

window.insetsController?.hide(WindowInsets.Type.statusBars())

and to show it again:

window.insetsController?.show(WindowInsets.Type.statusBars())

keypress, ctrl+c (or some combo like that)

I am a little late to the party but here is my part

$(document).on('keydown', function ( e ) {
    // You may replace `c` with whatever key you want
    if ((e.metaKey || e.ctrlKey) && ( String.fromCharCode(e.which).toLowerCase() === 'c') ) {
        console.log( "You pressed CTRL + C" );
    }
});

Rollback a Git merge

Reverting a merge commit has been exhaustively covered in other questions. When you do a fast-forward merge, the second one you describe, you can use git reset to get back to the previous state:

git reset --hard <commit_before_merge>

You can find the <commit_before_merge> with git reflog, git log, or, if you're feeling the moxy (and haven't done anything else): git reset --hard HEAD@{1}

SQL: How to properly check if a record exists

You can use:

SELECT 1 FROM MyTable WHERE... LIMIT 1

Use select 1 to prevent the checking of unnecessary fields.

Use LIMIT 1 to prevent the checking of unnecessary rows.

Where can I download IntelliJ IDEA Color Schemes?

I know I'm late to the party but just wanted to mention that the Jumpout II theme really is amazing.. I have a lot of themes and this one really is great for a # of reasons..

  1. it handles glare very well (yes even pure black on matte screens can produce glare, unfortunately my new matte monitor - has a more "glary" coating than my old one).. this is a grayish-black background

  2. it has enough colors that you can easily see read even dense code - some themes that look nice at first use too much of one color and it makes dense code harder to digest

  3. the comments are all gray, this is even better than dark green which is my 2nd favorite choice.. it really helps the code pop out..

so basically this is a great anti-glare, anti-dense-code theme

honorable mentions (I think these all can be found on that same site, although I'm not sure I spelled all of them correctly)

  1. Dark Flash Builder (really great but at first the use of red can be confusing, but it is really one of its strengths. I had to modify it to make my error text highlighting different - I settled on some bright red underlined text)
  2. Gedit Original Oblivion
  3. Leone Dark II
  4. Visual Studio 2013
  5. Retta (very halloweeny)

and for white / beige / blue (in that order)

  1. Oughsumm (wow best white ever, possibly the most legible theme I've ever seen - however, white is too bright for me in my current office situation, although occasionally I do switch to this when I want to quickly review a lot of code before a commit), also it is comfortably legible at 1 point smaller than all dark themes I've used.
  2. humane-ist
  3. rubyblue

p.s. please note I change the font of all the themes I use to Consolas 11 or 12 depending on the monitor. Consolas I find to be the best programming font out there. It looks great, easy to read and very well suited to LCD anti-aliasing. I tried so many programming fonts but I always come back to this one quickly. And it is not too narrow.. I'm not in the narrow camp, I believe narrow font aficionados don't program with ultra wide monitors - maybe program on a macbook or something just as bad :)

p.p.s I know solarized is supposed to be some kind of ultimate, magical, life-enhancing nirvana-inducing theme but I just don't get it.. I tried but failed to find it anything but annoying

How to skip a iteration/loop in while-loop

You don't need to skip the iteration, since the rest of it is in the else statement, it will only be executed if the condition is not true.

But if you really need to skip it, you can use the continue; statement.

Real-world examples of recursion

Real world requirement I got recently:

Requirement A: Implement this feature after thoroughly understanding Requirement A.

How can I check if PostgreSQL is installed or not via Linux script?

Go to bin directory of postgres db such as /opt/postgresql/bin & run below command :

[...bin]# ./psql --version

psql (PostgreSQL) 9.0.4

Here you go . .

MySQL compare DATE string with string from DATETIME field

SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29';

it helps , you can convert the values as DATE before comparing.

Node.js: printing to console without a trailing newline?

You can use process.stdout.write():

process.stdout.write("hello: ");

See the docs for details.

what is the differences between sql server authentication and windows authentication..?

SQL Authentication

SQL Authentication is the typical authentication used for various database systems, composed of a username and a password. Obviously, an instance of SQL Server can have multiple such user accounts (using SQL authentication) with different usernames and passwords. In shared servers where different users should have access to different databases, SQL authentication should be used. Also, when a client (remote computer) connects to an instance of SQL Server on other computer than the one on which the client is running, SQL Server authentication is needed. Even if you don't define any SQL Server user accounts, at the time of installation a root account - sa - is added with the password you provided. Just like any SQL Server account, this can be used to log-in localy or remotely, however if an application is the one that does the log in, and it should have access to only one database, it's strongly recommended that you don't use the sa account, but create a new one with limited access. Overall, SQL authentication is the main authentication method to be used while the one we review below - Windows Authentication - is more of a convenience.

Windows Authentication

When you are accessing SQL Server from the same computer it is installed on, you shouldn't be prompted to type in an username and password. And you are not, if you're using Windows Authentication. With Windows Authentication, the SQL Server service already knows that someone is logged in into the operating system with the correct credentials, and it uses these credentials to allow the user into its databases. Of course, this works as long as the client resides on the same computer as the SQL Server, or as long as the connecting client matches the Windows credentials of the server. Windows Authentication is often used as a more convenient way to log-in into a SQL Server instance without typing a username and a password, however when more users are envolved, or remote connections are being established with the SQL Server, SQL authentication should be used.

How to do what head, tail, more, less, sed do in Powershell?

"-TotalCount" in this instance responds exactly like "-head". You have to use -TotalCount or -head to run the command like that. But -TotalCount is misleading - it does not work in ACTUALLY giving you ANY counts...

gc -TotalCount 25 C:\scripts\logs\robocopy_report.txt

The above script, tested in PS 5.1 is the SAME response as below...

gc -head 25 C:\scripts\logs\robocopy_report.txt

So then just use '-head 25" already!

Replacing all non-alphanumeric characters with empty strings

You could also try this simpler regex:

 str = str.replaceAll("\\P{Alnum}", "");

AngularJS: Service vs provider vs factory

After reading all these post It created more confuse for me.. But still all is worthfull information.. finally I found following table which will give information with simple comparision

  • The injector uses recipes to create two types of objects: services and special purpose objects
  • There are five recipe types that define how to create objects: Value, Factory, Service, Provider and Constant.
  • Factory and Service are the most commonly used recipes. The only difference between them is that the Service recipe works better for objects of a custom type, while the Factory can produce JavaScript primitives and functions.
  • The Provider recipe is the core recipe type and all the other ones are just syntactic sugar on it.
  • Provider is the most complex recipe type. You don't need it unless you are building a reusable piece of code that needs global configuration.
  • All special purpose objects except for the Controller are defined via Factory recipes.

enter image description here

And for beginner understand:- This may not correct use case but in high level this is what usecase for these three.

  1. If you want to use in angular module config function should created as provider

_x000D_
_x000D_
angular.module('myApp').config(function($testProvider){_x000D_
$testProvider.someFunction();_x000D_
})
_x000D_
_x000D_
_x000D_

  1. Ajax call or third party integrations needs to be service.
  2. For Data manipulations create it as factory

For basic scenarios factory&Service behaves same.

how to define variable in jquery

jQuery is just a javascript library that makes some extra stuff available when writing javascript - so there is no reason to use jQuery for declaring variables. Use "regular" javascript:

var name = document.myForm.txtname.value;
alert(name);

EDIT: As Canavar points out in his example, it is also possible to use jQuery to get the form value:

var name = $('#txtname').val(); // Yes, it's called .val(), not .value()

given that the text box has its id attribute set to txtname. However, you don't need to use jQuery just because you can.

How to set encoding in .getJSON jQuery

Use this function to regain the utf-8 characters

function decode_utf8(s) { 
  return decodeURIComponent(escape(s)); 
}

Example: var new_Str=decode_utf8(str);

How do I activate a virtualenv inside PyCharm's terminal?

Another alternative is to use virtualenvwrapper to manage your virtual environments. It appears that once the virtualenvwrapper script is activated, pycharm can use that and then the simple workon command will be available from the pycharm console and present you with the available virtual environments:

kevin@debian:~/Development/django-tutorial$ workon
django-tutorial
FlaskHF
SQLAlchemy
themarkdownapp
kevin@debian:~/Development/django-tutorial$ workon django-tutorial
(django-tutorial)kevin@debian:~/Development/django-tutorial$ 

How to put a List<class> into a JSONObject and then read that object?

Just to update this thread, here is how to add a list (as a json array) into JSONObject. Plz substitute YourClass with your class name;

List<YourClass> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();

org.codehaus.jackson.map.ObjectMapper objectMapper = new 
org.codehaus.jackson.map.ObjectMapper();
org.codehaus.jackson.JsonNode listNode = objectMapper.valueToTree(list);
org.json.JSONArray request = new org.json.JSONArray(listNode.toString());
jsonObject.put("list", request);

How to downgrade tensorflow, multiple versions possible?

You can try to use the options of --no-cache-dir together with -I to overwrite the cache of the previous version and install the new version. For example:

pip3 install --no-cache-dir -I tensorflow==1.1

Then use the following command to check the version of tensorflow:

python3 -c ‘import tensorflow as tf; print(tf.__version__)’

It should show the right version got installed.

align right in a table cell with CSS

Use

text-align: right

The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.

See

text-align

<td class='alnright'>text to be aligned to right</td>

<style>
    .alnright { text-align: right; }
</style>

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

I think I have an idea. This has been doing my nut in too and I'm still having trouble getting it to display in Chrome.

Save document(name.docx) in word as single file webpage (name.mht) In your html use

<iframe src= "name.mht" width="100%" height="800"> </iframe>

Alter the heights and widths as you see fit.

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

It is an abbreviation for 'optional' , used for optional software in some distros.

Line Break in XML?

In XML a line break is a normal character. You can do this:

<xml>
  <text>some text
with
three lines</text>
</xml>

and the contents of <text> will be

some text
with
three lines

If this does not work for you, you are doing something wrong. Special "workarounds" like encoding the line break are unnecessary. Stuff like \n won't work, on the other hand, because XML has no escape sequences*.


* Note that &#xA; is the character entity that represents a line break in serialized XML. "XML has no escape sequences" means the situation when you interact with a DOM document, setting node values through the DOM API.

This is where neither &#xA; nor things like \n will work, but an actual newline character will. How this character ends up in the serialized document (i.e. "file") is up to the API and should not concern you.


Since you seem to wonder where your line breaks go in HTML: Take a look into your source code, there they are. HTML ignores line breaks in source code. Use <br> tags to force line breaks on screen.

Here is a JavaScript function that inserts <br> into a multi-line string:

function nl2br(s) { return s.split(/\r?\n/).join("<br>"); }

Alternatively you can force line breaks at new line characters with CSS:

div.lines {
    white-space: pre-line;
}

HTML5 Form Input Pattern Currency Format

I like to give the users a bit of flexibility and trust, that they will get the format right, but I do want to enforce only digits and two decimals for currency

^[$\-\s]*[\d\,]*?([\.]\d{0,2})?\s*$

Takes care of:

$ 1.
-$ 1.00
$ -1.0
.1
.10
-$ 1,000,000.0

Of course it will also match:

$$--$1,92,9,29.1 => anyway after cleanup => -192,929.10

Replace multiple strings at once

A simple forEach loop solves this quite well:

let text = 'the red apple and the green ball';
const toStrip = ['red', 'green'];
toStrip.forEach(x => {
   text = text.replace(x, '');
});

console.log(text);
// logs -> the apple and the ball

Style disabled button with CSS

Add the below code in your page. Trust me, no changes made to button events, to disable/enable button simply add/remove the button class in Javascript.

Method 1

 <asp Button ID="btnSave" CssClass="disabledContent" runat="server" />

<style type="text/css">
    .disabledContent 
    {
        cursor: not-allowed;
        background-color: rgb(229, 229, 229) !important;
    }

    .disabledContent > * 
    {
        pointer-events:none;
    }
</style>

Method 2

<asp Button ID="btnSubmit" CssClass="btn-disable" runat="server" />

<style type="text/css">
    .btn-disable
        {
        cursor: not-allowed;
        pointer-events: none;

        /*Button disabled - CSS color class*/
        color: #c0c0c0;
        background-color: #ffffff;

        }
</style>

How to deal with ModalDialog using selenium webdriver?

Use

following methods to switch to modelframe

driver.switchTo().frame("ModelFrameTitle");

or

driver.switchTo().activeElement()

Hope this will work

How do I change the default port (9000) that Play uses when I execute the "run" command?

I did this. sudo is necessary.

$ sudo play debug -Dhttp.port=80
...
[MyPlayApp] $ run

EDIT: I had problems because of using sudo so take care. Finally I cleaned up the project and I haven't used that trick anymore.

List comprehension vs. lambda + filter

Since any speed difference is bound to be miniscule, whether to use filters or list comprehensions comes down to a matter of taste. In general I'm inclined to use comprehensions (which seems to agree with most other answers here), but there is one case where I prefer filter.

A very frequent use case is pulling out the values of some iterable X subject to a predicate P(x):

[x for x in X if P(x)]

but sometimes you want to apply some function to the values first:

[f(x) for x in X if P(f(x))]


As a specific example, consider

primes_cubed = [x*x*x for x in range(1000) if prime(x)]

I think this looks slightly better than using filter. But now consider

prime_cubes = [x*x*x for x in range(1000) if prime(x*x*x)]

In this case we want to filter against the post-computed value. Besides the issue of computing the cube twice (imagine a more expensive calculation), there is the issue of writing the expression twice, violating the DRY aesthetic. In this case I'd be apt to use

prime_cubes = filter(prime, [x*x*x for x in range(1000)])

Defining arrays in Google Scripts

This may be of help to a few who are struggling like I was:

var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];

How can I use Ruby to colorize the text output to a terminal?

I wrote a little method to test out the basic color modes, based on answers by Erik Skoglund and others.

#outputs color table to console, regular and bold modes
def colortable
  names = %w(black red green yellow blue pink cyan white default)
  fgcodes = (30..39).to_a - [38]

  s = ''
  reg  = "\e[%d;%dm%s\e[0m"
  bold = "\e[1;%d;%dm%s\e[0m"
  puts '                       color table with these background codes:'
  puts '          40       41       42       43       44       45       46       47       49'
  names.zip(fgcodes).each {|name,fg|
    s = "#{fg}"
    puts "%7s "%name + "#{reg}  #{bold}   "*9 % [fg,40,s,fg,40,s,  fg,41,s,fg,41,s,  fg,42,s,fg,42,s,  fg,43,s,fg,43,s,  
      fg,44,s,fg,44,s,  fg,45,s,fg,45,s,  fg,46,s,fg,46,s,  fg,47,s,fg,47,s,  fg,49,s,fg,49,s ]
  }
end

example output: ruby colortest

Under what conditions is a JSESSIONID created?

JSESSIONID cookie is created/sent when session is created. Session is created when your code calls request.getSession() or request.getSession(true) for the first time. If you just want to get the session, but not create it if it doesn't exist, use request.getSession(false) -- this will return you a session or null. In this case, new session is not created, and JSESSIONID cookie is not sent. (This also means that session isn't necessarily created on first request... you and your code are in control when the session is created)

Sessions are per-context:

SRV.7.3 Session Scope

HttpSession objects must be scoped at the application (or servlet context) level. The underlying mechanism, such as the cookie used to establish the session, can be the same for different contexts, but the object referenced, including the attributes in that object, must never be shared between contexts by the container.

(Servlet 2.4 specification)

Update: Every call to JSP page implicitly creates a new session if there is no session yet. This can be turned off with the session='false' page directive, in which case session variable is not available on JSP page at all.

Sending JSON to PHP using ajax

That's because $_POST is pre-populated with form data.

To get JSON data (or any raw input), use php://input.

$json = json_decode(file_get_contents("php://input"));

How to read barcodes with the camera on Android?

module app:

implementation 'com.google.zxing:core:3.2.1'

implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'

AndroidManifest.xml

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button BarCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BarCode = findViewById(R.id.button_barcode);
        final Activity activity = this;

        BarCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                IntentIntegrator intentIntegrator = new IntentIntegrator(activity);
                intentIntegrator.setDesiredBarcodeFormats(intentIntegrator.ALL_CODE_TYPES);
                intentIntegrator.setBeepEnabled(false);
                intentIntegrator.setCameraId(0);
                intentIntegrator.setPrompt("SCAN");
                intentIntegrator.setBarcodeImageEnabled(false);
                intentIntegrator.initiateScan();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        IntentResult Result = IntentIntegrator.parseActivityResult(requestCode , resultCode ,data);
        if(Result != null){
            if(Result.getContents() == null){
                Log.d("MainActivity" , "cancelled scan");
                Toast.makeText(this, "cancelled", Toast.LENGTH_SHORT).show();
            }
            else {
                Log.d("MainActivity" , "Scanned");
                Toast.makeText(this,"Scanned -> " + Result.getContents(), Toast.LENGTH_SHORT).show();
            }
        }
        else {
            super.onActivityResult(requestCode , resultCode , data);
        }
    }
}

Radio buttons not checked in jQuery

(!$('#radio').is(':checked'))

This worked for me

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

Updated to High Sierra 10.13.2

xcode-select --install ALONE did not work for me.

  1. Download X-code from app store
  2. $xcode-select --install
    a. May need to update after install using softwareupdate in command line. $sudo softwareupdate -i "Command Line Tools (macOS High Sierra version 10.13) for Xcode-9.1"

  3. $sudo xcodebuild -license

CSS: auto height on containing div, 100% height on background div inside containing div

Just a quick note because I had a hard time with this.

By using #container { overflow: hidden; } the page I had started to have layout issues in Firefox and IE (when the zoom would go in and out the content would bounce in and out of the parent div).

The solution to this issue is to add a display: inline-block; to the same div with overflow:hidden;

C program to check little vs. big endian

This is big endian test from a configure script:

#include <inttypes.h>
int main(int argc, char ** argv){
    volatile uint32_t i=0x01234567;
    // return 0 for big endian, 1 for little endian.
    return (*((uint8_t*)(&i))) == 0x67;
}

change <audio> src with javascript

Try this:

Replace:

audio.load();

with:

audio.play();

How to pass a parameter to routerLink that is somewhere inside the URL?

In your particular example you'd do the following routerLink:

[routerLink]="['user', user.id, 'details']"

To do so in a controller, you can inject Router and use:

router.navigate(['user', user.id, 'details']);

More info in the Angular docs Link Parameters Array section of Routing & Navigation

how to move elasticsearch data from one server to another

If you can add the second server to cluster, you may do this:

  1. Add Server B to cluster with Server A
  2. Increment number of replicas for indices
  3. ES will automatically copy indices to server B
  4. Close server A
  5. Decrement number of replicas for indices

This will only work if number of replaces equal to number of nodes.

How to use QueryPerformanceCounter?

I use these defines:

/** Use to init the clock */
#define TIMER_INIT \
    LARGE_INTEGER frequency; \
    LARGE_INTEGER t1,t2; \
    double elapsedTime; \
    QueryPerformanceFrequency(&frequency);


/** Use to start the performance timer */
#define TIMER_START QueryPerformanceCounter(&t1);

/** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */
#define TIMER_STOP \
    QueryPerformanceCounter(&t2); \
    elapsedTime=(float)(t2.QuadPart-t1.QuadPart)/frequency.QuadPart; \
    std::wcout<<elapsedTime<<L" sec"<<endl;

Usage (brackets to prevent redefines):

TIMER_INIT

{
   TIMER_START
   Sleep(1000);
   TIMER_STOP
}

{
   TIMER_START
   Sleep(1234);
   TIMER_STOP
}

Output from usage example:

1.00003 sec
1.23407 sec

Converting Pandas dataframe into Spark dataframe error

I have tried this with your data and it is working :

%pyspark
import pandas as pd
from pyspark.sql import SQLContext
print sc
df = pd.read_csv("test.csv")
print type(df)
print df
sqlCtx = SQLContext(sc)
sqlCtx.createDataFrame(df).show()

When and why to 'return false' in JavaScript?

When you want to trigger javascript code from an anchor tag, the onclick handler should be used rather than the javascript: pseudo-protocol. The javascript code that runs within the onclick handler must return true or false (or an expression than evalues to true or false) back to the tag itself - if it returns true, then the HREF of the anchor will be followed like a normal link. If it returns false, then the HREF will be ignored. This is why "return false;" is often included at the end of the code within an onclick handler.

Using varchar(MAX) vs TEXT on SQL Server

You can't search a text field without converting it from text to varchar.

declare @table table (a text)
insert into @table values ('a')
insert into @table values ('a')
insert into @table values ('b')
insert into @table values ('c')
insert into @table values ('d')


select *
from @table
where a ='a'

This give an error:

The data types text and varchar are incompatible in the equal to operator.

Wheras this does not:

declare @table table (a varchar(max))

Interestingly, LIKE still works, i.e.

where a like '%a%'

Using pg_dump to only get insert statements from one table within database

just in case you are using a remote access and want to dump all database data, you can use:

pg_dump -a -h your_host -U your_user -W -Fc your_database > DATA.dump

it will create a dump with all database data and use

pg_restore -a -h your_host -U your_user -W -Fc your_database < DATA.dump

to insert the same data in your data base considering you have the same structure

MySQL: can't access root account

There is a section in the MySQL manual on how to reset the root password which will solve your problem.

Getting the closest string match

A sample using C# is here.

public static void Main()
{
    Console.WriteLine("Hello World " + LevenshteinDistance("Hello","World"));
    Console.WriteLine("Choice A " + LevenshteinDistance("THE BROWN FOX JUMPED OVER THE RED COW","THE RED COW JUMPED OVER THE GREEN CHICKEN"));
    Console.WriteLine("Choice B " + LevenshteinDistance("THE BROWN FOX JUMPED OVER THE RED COW","THE RED COW JUMPED OVER THE RED COW"));
    Console.WriteLine("Choice C " + LevenshteinDistance("THE BROWN FOX JUMPED OVER THE RED COW","THE RED FOX JUMPED OVER THE BROWN COW"));
}

public static float LevenshteinDistance(string a, string b)
{
    var rowLen = a.Length;
    var colLen = b.Length;
    var maxLen = Math.Max(rowLen, colLen);

    // Step 1
    if (rowLen == 0 || colLen == 0)
    {
        return maxLen;
    }

    /// Create the two vectors
    var v0 = new int[rowLen + 1];
    var v1 = new int[rowLen + 1];

    /// Step 2
    /// Initialize the first vector
    for (var i = 1; i <= rowLen; i++)
    {
        v0[i] = i;
    }

    // Step 3
    /// For each column
    for (var j = 1; j <= colLen; j++)
    {
        /// Set the 0'th element to the column number
        v1[0] = j;

        // Step 4
        /// For each row
        for (var i = 1; i <= rowLen; i++)
        {
            // Step 5
            var cost = (a[i - 1] == b[j - 1]) ? 0 : 1;

            // Step 6
            /// Find minimum
            v1[i] = Math.Min(v0[i] + 1, Math.Min(v1[i - 1] + 1, v0[i - 1] + cost));
        }

        /// Swap the vectors
        var vTmp = v0;
        v0 = v1;
        v1 = vTmp;
    }

    // Step 7
    /// The vectors were swapped one last time at the end of the last loop,
    /// that is why the result is now in v0 rather than in v1
    return v0[rowLen];
}

The output is:

Hello World 4
Choice A 15
Choice B 6
Choice C 8

SQL LIKE condition to check for integer?

PostgreSQL supports regular expressions matching.

So, your example would look like

SELECT * FROM books WHERE title ~ '^\d+ ?' 

This will match a title starting with one or more digits and an optional space

Have a div cling to top of screen if scrolled down past it

Use position:fixed; and set the top:0;left:0;right:0;height:100px; and you should be able to have it "stick" to the top of the page.

<div style="position:fixed;top:0;left:0;right:0;height:100px;">Some buttons</div>

Get first word of string

To get first word of string you can do this:

let myStr = "Hello World"
let firstWord = myStr.split(" ")[0]

How do I make an html link look like a button?

If you want nice button with rounded corners, then use this class:

_x000D_
_x000D_
.link_button {_x000D_
    -webkit-border-radius: 4px;_x000D_
    -moz-border-radius: 4px;_x000D_
    border-radius: 4px;_x000D_
    border: solid 1px #20538D;_x000D_
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4);_x000D_
    -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
    -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
    background: #4479BA;_x000D_
    color: #FFF;_x000D_
    padding: 8px 12px;_x000D_
    text-decoration: none;_x000D_
}
_x000D_
<a href="#" class="link_button">Example</a>
_x000D_
_x000D_
_x000D_

Postgres: check if array field contains value?

Instead of IN we can use ANY with arrays casted to enum array, for example:

create type example_enum as enum (
  'ENUM1', 'ENUM2'
);

create table example_table (
  id integer,
  enum_field example_enum
);

select 
  * 
from 
  example_table t
where
  t.enum_field = any(array['ENUM1', 'ENUM2']::example_enum[]);

Or we can still use 'IN' clause, but first, we should 'unnest' it:

select 
  * 
from 
  example_table t
where
  t.enum_field in (select unnest(array['ENUM1', 'ENUM2']::example_enum[]));

Example: https://www.db-fiddle.com/f/LaUNi42HVuL2WufxQyEiC/0

Android Studio Emulator and "Process finished with exit code 0"

In AVD Manager,

Go to Edit Icon on AVD Manager for selected Device.

Click on show advanced settings and increase ram size from 1500 mb to 2 GB.

Then it works.

NOTE: Some virtual devices do not allow you to update RAM, but if so, try installing Nexus 4. because it does.

NOTE2: If still doesnt work, dont give up. just uninstall and reinstall the device with changing RAM again. in some cases this is how it works

NOTE3: If still doesnt work, this means your pc doesnt have enough ram space. so increase the ram to 3gb. it might work but it will suffer

NOTE4: If still doesnt work, try it with multicore 2 instead of 4.

NOTE5: Still doesnt work. Close the Android Studio and NEVER open it back :)

Git blame -- prior commits?

As of Git 2.23 you can use git blame --ignore-rev

For the example given in the question this would be:

git blame -L10,+1 src/options.cpp --ignore-rev fe25b6d

(however it's a trick question because fe25b6d is the file's first revision!)

CURL alternative in Python

import urllib2

manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, 'https://app.streamsend.com/emails', 'login', 'key')
handler = urllib2.HTTPBasicAuthHandler(manager)

director = urllib2.OpenerDirector()
director.add_handler(handler)

req = urllib2.Request('https://app.streamsend.com/emails', headers = {'Accept' : 'application/xml'})

result = director.open(req)
# result.read() will contain the data
# result.info() will contain the HTTP headers

# To get say the content-length header
length = result.info()['Content-Length']

Your cURL call using urllib2 instead. Completely untested.

Checkout subdirectories in Git?

You can revert uncommitted changes only to particular file or directory:

git checkout [some_dir|file.txt]

How can I read an input string of unknown length?

With the computers of today, you can get away with allocating very large strings (hundreds of thousands of characters) while hardly making a dent in the computer's RAM usage. So I wouldn't worry too much.

However, in the old days, when memory was at a premium, the common practice was to read strings in chunks. fgets reads up to a maximum number of chars from the input, but leaves the rest of the input buffer intact, so you can read the rest from it however you like.

in this example, I read in chunks of 200 chars, but you can use whatever chunk size you want of course.

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

char* readinput()
{
#define CHUNK 200
   char* input = NULL;
   char tempbuf[CHUNK];
   size_t inputlen = 0, templen = 0;
   do {
       fgets(tempbuf, CHUNK, stdin);
       templen = strlen(tempbuf);
       input = realloc(input, inputlen+templen+1);
       strcpy(input+inputlen, tempbuf);
       inputlen += templen;
    } while (templen==CHUNK-1 && tempbuf[CHUNK-2]!='\n');
    return input;
}

int main()
{
    char* result = readinput();
    printf("And the result is [%s]\n", result);
    free(result);
    return 0;
}

Note that this is a simplified example with no error checking; in real life you will have to make sure the input is OK by verifying the return value of fgets.

Also note that at the end if the readinput routine, no bytes are wasted; the string has the exact memory size it needs to have.

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

How to run a SQL query on an Excel table?

There are many fine ways to get this done, which others have already suggestioned. Following along the "get Excel data via SQL track", here are some pointers.

  1. Excel has the "Data Connection Wizard" which allows you to import or link from another data source or even within the very same Excel file.

  2. As part of Microsoft Office (and OS's) are two providers of interest: the old "Microsoft.Jet.OLEDB", and the latest "Microsoft.ACE.OLEDB". Look for them when setting up a connection (such as with the Data Connection Wizard).

  3. Once connected to an Excel workbook, a worksheet or range is the equivalent of a table or view. The table name of a worksheet is the name of the worksheet with a dollar sign ("$") appended to it, and surrounded with square brackets ("[" and "]"); of a range, it is simply the name of the range. To specify an unnamed range of cells as your recordsource, append standard Excel row/column notation to the end of the sheet name in the square brackets.

  4. The native SQL will (more or less be) the SQL of Microsoft Access. (In the past, it was called JET SQL; however Access SQL has evolved, and I believe JET is deprecated old tech.)

  5. Example, reading a worksheet: SELECT * FROM [Sheet1$]

  6. Example, reading a range: SELECT * FROM MyRange

  7. Example, reading an unnamed range of cells: SELECT * FROM [Sheet1$A1:B10]

  8. There are many many many books and web sites available to help you work through the particulars.

=== Further notes ===

By default, it is assumed that the first row of your Excel data source contains column headings that can be used as field names. If this is not the case, you must turn this setting off, or your first row of data "disappears" to be used as field names. This is done by adding the optional HDR= setting to the Extended Properties of the connection string. The default, which does not need to be specified, is HDR=Yes. If you do not have column headings, you need to specify HDR=No; the provider names your fields F1, F2, etc.

A caution about specifying worksheets: The provider assumes that your table of data begins with the upper-most, left-most, non-blank cell on the specified worksheet. In other words, your table of data can begin in Row 3, Column C without a problem. However, you cannot, for example, type a worksheeet title above and to the left of the data in cell A1.

A caution about specifying ranges: When you specify a worksheet as your recordsource, the provider adds new records below existing records in the worksheet as space allows. When you specify a range (named or unnamed), Jet also adds new records below the existing records in the range as space allows. However, if you requery on the original range, the resulting recordset does not include the newly added records outside the range.

Data types (worth trying) for CREATE TABLE: Short, Long, Single, Double, Currency, DateTime, Bit, Byte, GUID, BigBinary, LongBinary, VarBinary, LongText, VarChar, Decimal.

Connecting to "old tech" Excel (files with the xls extention): Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyFolder\MyWorkbook.xls;Extended Properties=Excel 8.0;. Use the Excel 5.0 source database type for Microsoft Excel 5.0 and 7.0 (95) workbooks and use the Excel 8.0 source database type for Microsoft Excel 8.0 (97), 9.0 (2000) and 10.0 (2002) workbooks.

Connecting to "latest" Excel (files with the xlsx file extension): Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Excel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;"

Treating data as text: IMEX setting treats all data as text. Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Excel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";

(More details at http://www.connectionstrings.com/excel)

More information at http://msdn.microsoft.com/en-US/library/ms141683(v=sql.90).aspx, and at http://support.microsoft.com/kb/316934

Connecting to Excel via ADODB via VBA detailed at http://support.microsoft.com/kb/257819

Microsoft JET 4 details at http://support.microsoft.com/kb/275561

How do I set the selected item in a drop down box

Check this:

<select class="form-control" id="department" name="department" type="text">
    <option value="medical-furniture" @if($list->department == "medical-furniture") selected @endif>Medical furniture</option>
    <option value="medical-table" @if($list->department == "medical-table") selected @endif>Medical table</option>
    <option value="service" @if($list->department == "service") selected @endif>Service</option>
</select>

Detect enter press in JTextField

Just use this code:

SwingUtilities.getRootPane(myButton).setDefaultButton(myButton);

jQuery creating objects

Another way to make objects in Javascript using JQuery, getting data from the dom and pass it to the object Box and, for example, store them in an array of Boxes, could be:

var box = {}; // my object
var boxes =  []; // my array

$('div.test').each(function (index, value) {
    color = $('p', this).attr('color');
    box = {
        _color: color // being _color a property of `box`
    }
    boxes.push(box);
});

Hope it helps!

Disabling SSL Certificate Validation in Spring RestTemplate

This problem is about SSL connection. When you try to connect to some resource https protocol requires to create secured connection. That means only your browser and website server know what data is being sent in requests bodies. This security is achieved by ssl certificates that stored on website and are being downloaded by your browser (or any other client, Spring RestTemplate with Apache Http Client behind in our case) with first connection to host. There are RSA256 encryption and many other cool things around. But in the end of a day: In case certificate is not registered or is invalid you will see certificate error (HTTPS connection is not secure). To fix certificate error website provider need to buy it for particular website or fix somehow e.g. https://www.register.com/ssl-certificates

Right way how problem can be solved

  • Register SSL certificate

Not a right way how problem can be solved

  • download broken SSL certificate from website
  • import SSL certificate to Java cacerts (certificate storage)

    keytool -importcert -trustcacerts -noprompt -storepass changeit -alias citrix -keystore "C:\Program Files\Java\jdk-11.0.2\lib\security\cacerts" -file citrix.cer

Dirty (Insecure) way how problem can be solved

  • make RestTemplate to ignore SSL verification

    @Bean
    public RestTemplateBuilder restTemplateBuilder(@Autowired SSLContext sslContext) {
        return new RestTemplateBuilder() {
            @Override
            public ClientHttpRequestFactory buildRequestFactory() {
                return new HttpComponentsClientHttpRequestFactory(
                        HttpClients.custom().setSSLSocketFactory(
                                new SSLConnectionSocketFactory(sslContext
                                        , NoopHostnameVerifier.INSTANCE)).build());
            }
        };
    }
    
    @Bean
        public SSLContext insecureSslContext() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
           return SSLContexts.custom()
                    .loadTrustMaterial(null, (x509Certificates, s) -> true)
                    .build();
        }
    

How to use Bash to create a folder if it doesn't already exist?

First, in bash "[" is just a command, which expects string "]" as a last argument, so the whitespace before the closing bracket (as well as between "!" and "-d" which need to be two separate arguments too) is important:

if [ ! -d /home/mlzboy/b2c2/shared/db ]; then
  mkdir -p /home/mlzboy/b2c2/shared/db;
fi

Second, since you are using -p switch to mkdir, this check is useless, because this is what does in the first place. Just write:

mkdir -p /home/mlzboy/b2c2/shared/db;

and thats it.

sprintf like functionality in Python

Python has a % operator for this.

>>> a = 5
>>> b = "hello"
>>> buf = "A = %d\n , B = %s\n" % (a, b)
>>> print buf
A = 5
 , B = hello

>>> c = 10
>>> buf = "C = %d\n" % c
>>> print buf
C = 10

See this reference for all supported format specifiers.

You could as well use format:

>>> print "This is the {}th tome of {}".format(5, "knowledge")
This is the 5th tome of knowledge

Java function for arrays like PHP's join()?

Google guava's library also has this kind of capability. You can see the String[] example also from the API.

As already described in the api, beware of the immutability of the builder methods.

It can accept an array of objects so it'll work in your case. In my previous experience, i tried joining a Stack which is an iterable and it works fine.

Sample from me :

Deque<String> nameStack = new ArrayDeque<>();
nameStack.push("a coder");
nameStack.push("i am");
System.out.println("|" + Joiner.on(' ').skipNulls().join(nameStack) + "|");

prints out : |i am a coder|

How to check if a file exists in the Documents directory in Swift?

An alternative/recommended Code Pattern in Swift 3 would be:

  1. Use URL instead of FileManager
  2. Use of exception handling

    func verifyIfSqliteDBExists(){
        let docsDir     : URL       = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let dbPath      : URL       = docsDir.appendingPathComponent("database.sqlite")
    
        do{
            let sqliteExists : Bool = try dbPath.checkResourceIsReachable()
            print("An sqlite database exists at this path :: \(dbPath.path)")
    
        }catch{
            print("SQLite NOT Found at :: \(strDBPath)")
        }
    }
    

Array of strings in groovy

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

Looks like you're trying to both inherit the groupId from the parent, and simultaneously specify the parent using an inherited groupId!

In the child pom, use something like this:

<modelVersion>4.0.0</modelVersion>

<parent>
  <groupId>org.felipe</groupId>
  <artifactId>tutorial_maven</artifactId>
  <version>1.0-SNAPSHOT</version>
  <relativePath>../pom.xml</relativePath>
</parent>

<artifactId>tutorial_maven_jar</artifactId>

Using properties like ${project.groupId} won't work there. If you specify the parent in this way, then you can inherit the groupId and version in the child pom. Hence, you only need to specify the artifactId in the child pom.

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

What is a 'NoneType' object?

NoneType is simply the type of the None singleton:

>>> type(None)
<type 'NoneType'>

From the latter link above:

None

The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None are illegal and raise a SyntaxError.

In your case, it looks like one of the items you are trying to concatenate is None, hence your error.

Get string after character

This should work:

your_str='GenFiltEff=7.092200e-01'
echo $your_str | cut -d "=" -f2

python date of the previous month

Just for fun, a pure math answer using divmod. Pretty inneficient because of the multiplication, could do just as well a simple check on the number of month (if equal to 12, increase year, etc)

year = today.year
month = today.month

nm = list(divmod(year * 12 + month + 1, 12))
if nm[1] == 0:
    nm[1] = 12
    nm[0] -= 1
pm = list(divmod(year * 12 + month - 1, 12))
if pm[1] == 0:
    pm[1] = 12
    pm[0] -= 1

next_month = nm
previous_month = pm

How to specify a port to run a create-react-app based project?

This works on both Windows and Linux (Doesn't work on Mac)

package.json

"scripts": {
    "start": "(set PORT=3006 || export PORT=3006) && react-scripts start"
    ...
}

but you propably prefer to create .env with PORT=3006 written inside it

How do I set path while saving a cookie value in JavaScript?

For access cookie in whole app (use path=/):

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/"; 
}

Note:

If you set path=/,
Now the cookie is available for whole application/domain. If you not specify the path then current cookie is save just for the current page you can't access it on another page(s).

For more info read- http://www.quirksmode.org/js/cookies.html (Domain and path part)

If you use cookies in jquery by plugin jquery-cookie:

$.cookie('name', 'value', { expires: 7, path: '/' });
//or
$.cookie('name', 'value', { path: '/' });

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

I see three solutions to this:

  1. Change the output encoding, so it will always output UTF-8. See e.g. Setting the correct encoding when piping stdout in Python, but I could not get these example to work.

  2. Following example code makes the output aware of your target charset.

    # -*- coding: utf-8 -*-
    import sys
    
    print sys.stdout.encoding
    print u"Stöcker".encode(sys.stdout.encoding, errors='replace')
    print u"????????".encode(sys.stdout.encoding, errors='replace')
    

    This example properly replaces any non-printable character in my name with a question mark.

    If you create a custom print function, e.g. called myprint, using that mechanisms to encode output properly you can simply replace print with myprint whereever necessary without making the whole code look ugly.

  3. Reset the output encoding globally at the begin of the software:

    The page http://www.macfreek.nl/memory/Encoding_of_Python_stdout has a good summary what to do to change output encoding. Especially the section "StreamWriter Wrapper around Stdout" is interesting. Essentially it says to change the I/O encoding function like this:

    In Python 2:

    if sys.stdout.encoding != 'cp850':
      sys.stdout = codecs.getwriter('cp850')(sys.stdout, 'strict')
    if sys.stderr.encoding != 'cp850':
      sys.stderr = codecs.getwriter('cp850')(sys.stderr, 'strict')
    

    In Python 3:

    if sys.stdout.encoding != 'cp850':
      sys.stdout = codecs.getwriter('cp850')(sys.stdout.buffer, 'strict')
    if sys.stderr.encoding != 'cp850':
      sys.stderr = codecs.getwriter('cp850')(sys.stderr.buffer, 'strict')
    

    If used in CGI outputting HTML you can replace 'strict' by 'xmlcharrefreplace' to get HTML encoded tags for non-printable characters.

    Feel free to modify the approaches, setting different encodings, .... Note that it still wont work to output non-specified data. So any data, input, texts must be correctly convertable into unicode:

    # -*- coding: utf-8 -*-
    import sys
    import codecs
    sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, 'xmlcharrefreplace')
    print u"Stöcker"                # works
    print "Stöcker".decode("utf-8") # works
    print "Stöcker"                 # fails
    

Jquery to change form action

$('#button1').click(function(){
$('#myform').prop('action', 'page1.php');
});

How to determine CPU and memory consumption from inside a process?

Windows

Some of the above values are easily available from the appropriate WIN32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit "unintuitive" and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...)

Note: for clarity all error checking has been omitted from the following code. Do check the return codes...!


  • Total Virtual Memory:

    #include "windows.h"
    
    MEMORYSTATUSEX memInfo;
    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
    GlobalMemoryStatusEx(&memInfo);
    DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;
    

    Note: The name "TotalPageFile" is a bit misleading here. In reality this parameter gives the "Virtual Memory Size", which is size of swap file plus installed RAM.

  • Virtual Memory currently used:

    Same code as in "Total Virtual Memory" and then

     DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;
    
  • Virtual Memory currently used by current process:

    #include "windows.h"
    #include "psapi.h"
    
    PROCESS_MEMORY_COUNTERS_EX pmc;
    GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));
    SIZE_T virtualMemUsedByMe = pmc.PrivateUsage;
    



  • Total Physical Memory (RAM):

    Same code as in "Total Virtual Memory" and then

    DWORDLONG totalPhysMem = memInfo.ullTotalPhys;
    
  • Physical Memory currently used:

    Same code as in "Total Virtual Memory" and then

    DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;
    
  • Physical Memory currently used by current process:

    Same code as in "Virtual Memory currently used by current process" and then

    SIZE_T physMemUsedByMe = pmc.WorkingSetSize;
    



  • CPU currently used:

    #include "TCHAR.h"
    #include "pdh.h"
    
    static PDH_HQUERY cpuQuery;
    static PDH_HCOUNTER cpuTotal;
    
    void init(){
        PdhOpenQuery(NULL, NULL, &cpuQuery);
        // You can also use L"\\Processor(*)\\% Processor Time" and get individual CPU values with PdhGetFormattedCounterArray()
        PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
        PdhCollectQueryData(cpuQuery);
    }
    
    double getCurrentValue(){
        PDH_FMT_COUNTERVALUE counterVal;
    
        PdhCollectQueryData(cpuQuery);
        PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
        return counterVal.doubleValue;
    }
    
  • CPU currently used by current process:

    #include "windows.h"
    
    static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    static HANDLE self;
    
    void init(){
        SYSTEM_INFO sysInfo;
        FILETIME ftime, fsys, fuser;
    
        GetSystemInfo(&sysInfo);
        numProcessors = sysInfo.dwNumberOfProcessors;
    
        GetSystemTimeAsFileTime(&ftime);
        memcpy(&lastCPU, &ftime, sizeof(FILETIME));
    
        self = GetCurrentProcess();
        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
        memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
    }
    
    double getCurrentValue(){
        FILETIME ftime, fsys, fuser;
        ULARGE_INTEGER now, sys, user;
        double percent;
    
        GetSystemTimeAsFileTime(&ftime);
        memcpy(&now, &ftime, sizeof(FILETIME));
    
        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&sys, &fsys, sizeof(FILETIME));
        memcpy(&user, &fuser, sizeof(FILETIME));
        percent = (sys.QuadPart - lastSysCPU.QuadPart) +
            (user.QuadPart - lastUserCPU.QuadPart);
        percent /= (now.QuadPart - lastCPU.QuadPart);
        percent /= numProcessors;
        lastCPU = now;
        lastUserCPU = user;
        lastSysCPU = sys;
    
        return percent * 100;
    }
    

Linux

On Linux the choice that seemed obvious at first was to use the POSIX APIs like getrusage() etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!?

In the end I got all values via a combination of reading the pseudo-filesystem /proc and kernel calls.

  • Total Virtual Memory:

    #include "sys/types.h"
    #include "sys/sysinfo.h"
    
    struct sysinfo memInfo;
    
    sysinfo (&memInfo);
    long long totalVirtualMem = memInfo.totalram;
    //Add other values in next statement to avoid int overflow on right hand side...
    totalVirtualMem += memInfo.totalswap;
    totalVirtualMem *= memInfo.mem_unit;
    
  • Virtual Memory currently used:

    Same code as in "Total Virtual Memory" and then

    long long virtualMemUsed = memInfo.totalram - memInfo.freeram;
    //Add other values in next statement to avoid int overflow on right hand side...
    virtualMemUsed += memInfo.totalswap - memInfo.freeswap;
    virtualMemUsed *= memInfo.mem_unit;
    
  • Virtual Memory currently used by current process:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    int parseLine(char* line){
        // This assumes that a digit will be found and the line ends in " Kb".
        int i = strlen(line);
        const char* p = line;
        while (*p <'0' || *p > '9') p++;
        line[i-3] = '\0';
        i = atoi(p);
        return i;
    }
    
    int getValue(){ //Note: this value is in KB!
        FILE* file = fopen("/proc/self/status", "r");
        int result = -1;
        char line[128];
    
        while (fgets(line, 128, file) != NULL){
            if (strncmp(line, "VmSize:", 7) == 0){
                result = parseLine(line);
                break;
            }
        }
        fclose(file);
        return result;
    }
    



  • Total Physical Memory (RAM):

    Same code as in "Total Virtual Memory" and then

    long long totalPhysMem = memInfo.totalram;
    //Multiply in next statement to avoid int overflow on right hand side...
    totalPhysMem *= memInfo.mem_unit;
    
  • Physical Memory currently used:

    Same code as in "Total Virtual Memory" and then

    long long physMemUsed = memInfo.totalram - memInfo.freeram;
    //Multiply in next statement to avoid int overflow on right hand side...
    physMemUsed *= memInfo.mem_unit;
    
  • Physical Memory currently used by current process:

    Change getValue() in "Virtual Memory currently used by current process" as follows:

    int getValue(){ //Note: this value is in KB!
        FILE* file = fopen("/proc/self/status", "r");
        int result = -1;
        char line[128];
    
        while (fgets(line, 128, file) != NULL){
            if (strncmp(line, "VmRSS:", 6) == 0){
                result = parseLine(line);
                break;
            }
        }
        fclose(file);
        return result;
    }
    



  • CPU currently used:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
    
    void init(){
        FILE* file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow,
            &lastTotalSys, &lastTotalIdle);
        fclose(file);
    }
    
    double getCurrentValue(){
        double percent;
        FILE* file;
        unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;
    
        file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow,
            &totalSys, &totalIdle);
        fclose(file);
    
        if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||
            totalSys < lastTotalSys || totalIdle < lastTotalIdle){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +
                (totalSys - lastTotalSys);
            percent = total;
            total += (totalIdle - lastTotalIdle);
            percent /= total;
            percent *= 100;
        }
    
        lastTotalUser = totalUser;
        lastTotalUserLow = totalUserLow;
        lastTotalSys = totalSys;
        lastTotalIdle = totalIdle;
    
        return percent;
    }
    
  • CPU currently used by current process:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    #include "sys/times.h"
    #include "sys/vtimes.h"
    
    static clock_t lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    
    void init(){
        FILE* file;
        struct tms timeSample;
        char line[128];
    
        lastCPU = times(&timeSample);
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        file = fopen("/proc/cpuinfo", "r");
        numProcessors = 0;
        while(fgets(line, 128, file) != NULL){
            if (strncmp(line, "processor", 9) == 0) numProcessors++;
        }
        fclose(file);
    }
    
    double getCurrentValue(){
        struct tms timeSample;
        clock_t now;
        double percent;
    
        now = times(&timeSample);
        if (now <= lastCPU || timeSample.tms_stime < lastSysCPU ||
            timeSample.tms_utime < lastUserCPU){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            percent = (timeSample.tms_stime - lastSysCPU) +
                (timeSample.tms_utime - lastUserCPU);
            percent /= (now - lastCPU);
            percent /= numProcessors;
            percent *= 100;
        }
        lastCPU = now;
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        return percent;
    }
    

TODO: Other Platforms

I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by getrusage() and similar functions? If someone with Unix know-how could edit this answer and fill in the details?!

Echoing the last command run in Bash?

There is a racecondition between the last command ($_) and last error ( $?) variables. If you try to store one of them in an own variable, both encountered new values already because of the set command. Actually, last command hasn't got any value at all in this case.

Here is what i did to store (nearly) both informations in own variables, so my bash script can determine if there was any error AND setting the title with the last run command:

   # This construct is needed, because of a racecondition when trying to obtain
   # both of last command and error. With this the information of last error is
   # implied by the corresponding case while command is retrieved.

   if   [[ "${?}" == 0 && "${_}" != "" ]] ; then
    # Last command MUST be retrieved first.
      LASTCOMMAND="${_}" ;
      RETURNSTATUS='?' ;
   elif [[ "${?}" == 0 && "${_}" == "" ]] ; then
      LASTCOMMAND='unknown' ;
      RETURNSTATUS='?' ;
   elif [[ "${?}" != 0 && "${_}" != "" ]] ; then
    # Last command MUST be retrieved first.
      LASTCOMMAND="${_}" ;
      RETURNSTATUS='?' ;
      # Fixme: "$?" not changing state until command executed.
   elif [[ "${?}" != 0 && "${_}" == "" ]] ; then
      LASTCOMMAND='unknown' ;
      RETURNSTATUS='?' ;
      # Fixme: "$?" not changing state until command executed.
   fi

This script will retain the information, if an error occured and will obtain the last run command. Because of the racecondition i can not store the actual value. Besides, most commands actually don't even care for error noumbers, they just return something different from '0'. You'll notice that, if you use the errono extention of bash.

It should be possible with something like a "intern" script for bash, like in bash extention, but i'm not familiar with something like that and it wouldn't be compatible as well.

CORRECTION

I didn't think, that it was possible to retrieve both variables at the same time. Although i like the style of the code, i assumed it would be interpreted as two commands. This was wrong, so my answer devides down to:

   # Because of a racecondition, both MUST be retrieved at the same time.
   declare RETURNSTATUS="${?}" LASTCOMMAND="${_}" ;

   if [[ "${RETURNSTATUS}" == 0 ]] ; then
      declare RETURNSYMBOL='?' ;
   else
      declare RETURNSYMBOL='?' ;
   fi

Although my post might not get any positive rating, i solved my problem myself, finally. And this seems appropriate regarding the intial post. :)

Best Practices: working with long, multiline strings in PHP?

Sure, you could use HEREDOC, but as far as code readability goes it's not really any better than the first example, wrapping the string across multiple lines.

If you really want your multi-line string to look good and flow well with your code, I'd recommend concatenating strings together as such:

$text = "Hello, {$vars->name},\r\n\r\n"
    . "The second line starts two lines below.\r\n"
    . ".. Third line... etc";

This might be slightly slower than HEREDOC or a multi-line string, but it will flow well with your code's indentation and make it easier to read.

How to read a file from jar in Java?

Ah, this is one of my favorite subjects. There are essentially two ways you can load a resource through the classpath:

Class.getResourceAsStream(resource)

and

ClassLoader.getResourceAsStream(resource)

(there are other ways which involve getting a URL for the resource in a similar fashion, then opening a connection to it, but these are the two direct ways).

The first method actually delegates to the second, after mangling the resource name. There are essentially two kinds of resource names: absolute (e.g. "/path/to/resource/resource") and relative (e.g. "resource"). Absolute paths start with "/".

Here's an example which should illustrate. Consider a class com.example.A. Consider two resources, one located at /com/example/nested, the other at /top, in the classpath. The following program shows nine possible ways to access the two resources:

package com.example;

public class A {

    public static void main(String args[]) {

        // Class.getResourceAsStream
        Object resource = A.class.getResourceAsStream("nested");
        System.out.println("1: A.class nested=" + resource);

        resource = A.class.getResourceAsStream("/com/example/nested");
        System.out.println("2: A.class /com/example/nested=" + resource);

        resource = A.class.getResourceAsStream("top");
        System.out.println("3: A.class top=" + resource);

        resource = A.class.getResourceAsStream("/top");
        System.out.println("4: A.class /top=" + resource);

        // ClassLoader.getResourceAsStream
        ClassLoader cl = A.class.getClassLoader();
        resource = cl.getResourceAsStream("nested");        
        System.out.println("5: cl nested=" + resource);

        resource = cl.getResourceAsStream("/com/example/nested");
        System.out.println("6: cl /com/example/nested=" + resource);
        resource = cl.getResourceAsStream("com/example/nested");
        System.out.println("7: cl com/example/nested=" + resource);

        resource = cl.getResourceAsStream("top");
        System.out.println("8: cl top=" + resource);

        resource = cl.getResourceAsStream("/top");
        System.out.println("9: cl /top=" + resource);
    }

}

The output from the program is:

1: A.class nested=java.io.BufferedInputStream@19821f
2: A.class /com/example/nested=java.io.BufferedInputStream@addbf1
3: A.class top=null
4: A.class /top=java.io.BufferedInputStream@42e816
5: cl nested=null
6: cl /com/example/nested=null
7: cl com/example/nested=java.io.BufferedInputStream@9304b1
8: cl top=java.io.BufferedInputStream@190d11
9: cl /top=null

Mostly things do what you'd expect. Case-3 fails because class relative resolving is with respect to the Class, so "top" means "/com/example/top", but "/top" means what it says.

Case-5 fails because classloader relative resolving is with respect to the classloader. But, unexpectedly Case-6 also fails: one might expect "/com/example/nested" to resolve properly. To access a nested resource through the classloader you need to use Case-7, i.e. the nested path is relative to the root of the classloader. Likewise Case-9 fails, but Case-8 passes.

Remember: for java.lang.Class, getResourceAsStream() does delegate to the classloader:

     public InputStream getResourceAsStream(String name) {
        name = resolveName(name);
        ClassLoader cl = getClassLoader0();
        if (cl==null) {
            // A system class.
            return ClassLoader.getSystemResourceAsStream(name);
        }
        return cl.getResourceAsStream(name);
    }

so it is the behavior of resolveName() that is important.

Finally, since it is the behavior of the classloader that loaded the class that essentially controls getResourceAsStream(), and the classloader is often a custom loader, then the resource-loading rules may be even more complex. e.g. for Web-Applications, load from WEB-INF/classes or WEB-INF/lib in the context of the web application, but not from other web-applications which are isolated. Also, well-behaved classloaders delegate to parents, so that duplicateed resources in the classpath may not be accessible using this mechanism.

Finding the handle to a WPF window

you can use :

Process.GetCurrentProcess().MainWindowHandle

How to center canvas in html5

I have had the same problem, as I have pictures with many different widths which I load only with height info. Setting a width allows the browser to stretch and squeeze the picture. I solve the problem by having the text line just before the image_tag line centred (also getting rid of float: left;). I would have liked the text to be left aligned, but this is a minor inconvienence, that I can tolerate.

How to show "if" condition on a sequence diagram?

If else condition, also called alternatives in UML terms can indeed be represented in sequence diagrams. Here is a link where you can find some nice resources on the subject http://www.ibm.com/developerworks/rational/library/3101.html

branching with alt

Custom Date/Time formatting in SQL Server

Yes Depart is a solution for that but I think this kind of methods are long trips!

SQL SERVER:

SELECT CAST(DATEPART(DD,GETDATE()) AS VARCHAR)+'/'
+CAST(DATEPART(MM,GETDATE()) AS VARCHAR)
+'/'+CAST(DATEPART(YYYY,GETDATE()) AS VARCHAR)
+' '+CAST(DATEPART(HH,GETDATE()) AS VARCHAR)
+':'+CAST(DATEPART(MI,GETDATE()) AS VARCHAR)

Oracle:

Select to_char(sysdate,'DD/MM/YYYY HH24:MI') from dual

You may write your own function by this way you can get rid of this mess;

http://sql.dzone.com/news/custom-date-formatting-sql-ser

select myshortfun(getdate(),myformat)
GO

Sort hash by key, return hash in Ruby

I liked the solution in the earlier post.

I made a mini-class, called it class AlphabeticalHash. It also has a method called ap, which accepts one argument, a Hash, as input: ap variable. Akin to pp (pp variable)

But it will (try and) print in alphabetical list (its keys). Dunno if anyone else wants to use this, it's available as a gem, you can install it as such: gem install alphabetical_hash

For me, this is simple enough. If others need more functionality, let me know, I'll include it into the gem.

EDIT: Credit goes to Peter, who gave me the idea. :)

svn: E155004: ..(path of resource).. is already locked

Still if it doesn't work, just lock all the files and unlock. Now clean up again, It will work.

svn update svn cleanup

Looking for simple Java in-memory cache

Another option for an in-memory java cache is cache2k. The in-memory performance is superior to EHCache and google guava, see the cache2k benchmarks page.

The usage pattern is similar to other caches. Here is an example:

Cache<String,String> cache = new Cache2kBuilder<String, String>() {}
  .expireAfterWrite(5, TimeUnit.MINUTES)    // expire/refresh after 5 minutes
  .resilienceDuration(30, TimeUnit.SECONDS) // cope with at most 30 seconds
                                          // outage before propagating 
                                          // exceptions
  .refreshAhead(true)                       // keep fresh when expiring
  .loader(new CacheLoader<String, String>() {
    @Override
    public String load(final String key) throws Exception {
      return ....;
    }
  })
  .build();
String val = cache.peek("something");
cache.put("something", "hello");
val = cache.get("something");

If you have google guava as dependency then trying out guava cache, may be a good alternative.

Deciding between HttpClient and WebClient

HttpClient is the newer of the APIs and it has the benefits of

  • has a good async programming model
  • being worked on by Henrik F Nielson who is basically one of the inventors of HTTP, and he designed the API so it is easy for you to follow the HTTP standard, e.g. generating standards-compliant headers
  • is in the .Net framework 4.5, so it has some guaranteed level of support for the forseeable future
  • also has the xcopyable/portable-framework version of the library if you want to use it on other platforms - .Net 4.0, Windows Phone etc.

If you are writing a web service which is making REST calls to other web services, you should want to be using an async programming model for all your REST calls, so that you don't hit thread starvation. You probably also want to use the newest C# compiler which has async/await support.

Note: It isn't more performant AFAIK. It's probably somewhat similarly performant if you create a fair test.

Visual Studio loading symbols

I had the same problem and even after turning the symbol loading off, the module loading in Visual Studio was terribly slow.

The solution was to turn off the antivirus software (in my case NOD32) or better yet, to add exceptions to it so that it ignores the paths from which your process is loading assemblies (in my case it is the GAC folder and the Temporary ASP.NET Files folder).

cvc-elt.1: Cannot find the declaration of element 'MyElement'

I got this same error working in Eclipse with Maven with the additional information

schema_reference.4: Failed to read schema document 'https://maven.apache.org/xsd/maven-4.0.0.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

This was after copying in a new controller and it's interface from a Thymeleaf example. Honestly, no matter how careful I am I still am at a loss to understand how one is expected to figure this out. On a (lucky) guess I right clicked the project, clicked Maven and Update Project which cleared up the issue.