Programs & Examples On #Navision

Navision is the former name of Dynamics NAV, an enterprise resource planning (ERP) development platform produced by Microsoft.

BLOB to String, SQL Server

The accepted answer works for me only for the first 30 characters. This works for me:

select convert(varchar(max), convert(varbinary(max),myBlobColumn)) FROM table_name

Easy way to build Android UI?

The Android Development Tools (ADT) plugin for Eclipse includes a visual editor for android application layout files:

http://developer.android.com/tools/help/adt.html

Make Https call using HttpClient

If the server only supports higher TLS version like TLS 1.2 only, it will still fail unless your client PC is configured to use higher TLS version by default. To overcome this problem add the following in your code.

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

Modifying your example code, it would be

HttpClient httpClient = new HttpClient();   

//specify to use TLS 1.2 as default connection
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

httpClient.BaseAddress = new Uri("https://foobar.com/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

var task = httpClient.PostAsXmlAsync<DeviceRequest>("api/SaveData", request);

How to store images in mysql database using php

insert image zh

-while we insert image in database using insert query

$Image = $_FILES['Image']['name'];
    if(!$Image)
    {
      $Image="";
    }
    else
    {
      $file_path = 'upload/';
      $file_path = $file_path . basename( $_FILES['Image']['name']);    
      if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path)) 
     { 
}
}

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

Adding only android-support-v7-appcompat.jar to library dependencies is not enough, you have also to import in your project the module that you can find in your SDK at the path \android-sdk\extras\android\support\v7\appcompatand after that add module dependencies configuring the project structure in this way

enter image description here

otherwise are included only the class files of support library and the app is not able to load the other resources causing the error.

In addition as reVerse suggested replace this

public CustomActionBarDrawerToggle(Activity mActivity,
                                           DrawerLayout mDrawerLayout) {
            super(mActivity, mDrawerLayout,new Toolbar(MyActivity.this) ,
                    R.string.ns_menu_open, R.string.ns_menu_close);
        }

with

public CustomActionBarDrawerToggle(Activity mActivity,
                                           DrawerLayout mDrawerLayout) {
            super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
        }

How can I delete one element from an array by value

You can also monkey patch it. I never understood why Ruby has an except method for Hash but not for Array:

class Array
  def except value
    value = value.kind_of(Array) ? value : [value]
    self - value
  end
end

Now you can do:

[1,3,7,"436",354,nil].except(354) #=> [1,3,7,"436",nil]

Or:

[1,3,7,"436",354,nil].except([354, 1]) #=> [3,7,"436",nil]

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

You should run:

composer dump-autoload

and if does not work you should:

re-install composer

How to open a PDF file in an <iframe>?

Using an iframe to "render" a PDF will not work on all browsers; it depends on how the browser handles PDF files. Some browsers (such as Firefox and Chrome) have a built-in PDF rendered which allows them to display the PDF inline where as some older browsers (perhaps older versions of IE attempt to download the file instead).

Instead, I recommend checking out PDFObject which is a Javascript library to embed PDFs in HTML files. It handles browser compatibility pretty well and will most likely work on IE8.

In your HTML, you could set up a div to display the PDFs:

<div id="pdfRenderer"></div>

Then, you can have Javascript code to embed a PDF in that div:

var pdf = new PDFObject({
  url: "https://something.com/HTC_One_XL_User_Guide.pdf",
  id: "pdfRendered",
  pdfOpenParams: {
    view: "FitH"
  }
}).embed("pdfRenderer");

Aligning rotated xticklabels with their respective xticks

If you dont want to modify the xtick labels, you can just use:

plt.xticks(rotation=45)

How can I run PowerShell with the .NET 4 runtime?

If you're still stuck on PowerShell v1.0 or v2.0, here is my variation on Jason Stangroome's excellent answer.

Create a powershell4.cmd somewhere on your path with the following contents:

@echo off
:: http://stackoverflow.com/questions/7308586/using-batch-echo-with-special-characters
if exist %~dp0powershell.exe.activation_config goto :run
echo.^<?xml version="1.0" encoding="utf-8" ?^>                 > %~dp0powershell.exe.activation_config
echo.^<configuration^>                                        >> %~dp0powershell.exe.activation_config
echo.  ^<startup useLegacyV2RuntimeActivationPolicy="true"^>  >> %~dp0powershell.exe.activation_config
echo.    ^<supportedRuntime version="v4.0"/^>                 >> %~dp0powershell.exe.activation_config
echo.  ^</startup^>                                           >> %~dp0powershell.exe.activation_config
echo.^</configuration^>                                       >> %~dp0powershell.exe.activation_config
:run
:: point COMPLUS_ApplicationMigrationRuntimeActivationConfigPath to the directory that this cmd file lives in
:: and the directory contains a powershell.exe.activation_config file which matches the executable name powershell.exe
set COMPLUS_ApplicationMigrationRuntimeActivationConfigPath=%~dp0
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe %*
set COMPLUS_ApplicationMigrationRuntimeActivationConfigPath=

This will allow you to launch an instance of the powershell console running under .NET 4.0.

You can see the difference on my system where I have PowerShell 2.0 by examining the output of the following two commands run from cmd.

C:\>powershell -ExecutionPolicy ByPass -Command $PSVersionTable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.5485
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1


C:\>powershell4.cmd -ExecutionPolicy ByPass -Command $PSVersionTable

Name                           Value
----                           -----
PSVersion                      2.0
PSCompatibleVersions           {1.0, 2.0}
BuildVersion                   6.1.7601.17514
CLRVersion                     4.0.30319.18408
WSManStackVersion              2.0
PSRemotingProtocolVersion      2.1
SerializationVersion           1.1.0.1

JQuery Parsing JSON array

Use the parseJSON method:

var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);

Then you have an array with the city names.

Resetting MySQL Root Password with XAMPP on Localhost

On Dashboard, Go to User Accounts, Select user, Click Change Password, Fill the New Password, Go.

How can I find out a file's MIME type (Content-Type)?

one of the other tool (besides file) you can use is xdg-mime

eg xdg-mime query filetype <file>

if you have yum,

yum install xdg-utils.noarch

An example comparison of xdg-mime and file on a Subrip(subtitles) file

$ xdg-mime query filetype subtitles.srt
application/x-subrip

$ file --mime-type subtitles.srt
subtitles.srt: text/plain

in the above file only show it as plain text.

How to upload a file to directory in S3 bucket using boto

For upload folder example as following code and S3 folder picture enter image description here

import boto
import boto.s3
import boto.s3.connection
import os.path
import sys    

# Fill in info on data to upload
# destination bucket name
bucket_name = 'willie20181121'
# source directory
sourceDir = '/home/willie/Desktop/x/'  #Linux Path
# destination directory name (on s3)
destDir = '/test1/'   #S3 Path

#max size in bytes before uploading in parts. between 1 and 5 GB recommended
MAX_SIZE = 20 * 1000 * 1000
#size of parts when uploading in parts
PART_SIZE = 6 * 1000 * 1000

access_key = 'MPBVAQ*******IT****'
secret_key = '11t63yDV***********HgUcgMOSN*****'

conn = boto.connect_s3(
        aws_access_key_id = access_key,
        aws_secret_access_key = secret_key,
        host = '******.org.tw',
        is_secure=False,               # uncomment if you are not using ssl
        calling_format = boto.s3.connection.OrdinaryCallingFormat(),
        )
bucket = conn.create_bucket(bucket_name,
        location=boto.s3.connection.Location.DEFAULT)


uploadFileNames = []
for (sourceDir, dirname, filename) in os.walk(sourceDir):
    uploadFileNames.extend(filename)
    break

def percent_cb(complete, total):
    sys.stdout.write('.')
    sys.stdout.flush()

for filename in uploadFileNames:
    sourcepath = os.path.join(sourceDir + filename)
    destpath = os.path.join(destDir, filename)
    print ('Uploading %s to Amazon S3 bucket %s' % \
           (sourcepath, bucket_name))

    filesize = os.path.getsize(sourcepath)
    if filesize > MAX_SIZE:
        print ("multipart upload")
        mp = bucket.initiate_multipart_upload(destpath)
        fp = open(sourcepath,'rb')
        fp_num = 0
        while (fp.tell() < filesize):
            fp_num += 1
            print ("uploading part %i" %fp_num)
            mp.upload_part_from_file(fp, fp_num, cb=percent_cb, num_cb=10, size=PART_SIZE)

        mp.complete_upload()

    else:
        print ("singlepart upload")
        k = boto.s3.key.Key(bucket)
        k.key = destpath
        k.set_contents_from_filename(sourcepath,
                cb=percent_cb, num_cb=10)

PS: For more reference URL

Python: avoid new line with print command

If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try

from __future__ import print_function

print("abcd", end='')
print("efg")

results in

abcdefg

For those using 3.x, this is already built-in.

test attribute in JSTL <c:if> tag

You can also use something like

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

Difference between OData and REST web services

ODATA is a special kind of REST where we can query data uniformly from URL.

row-level trigger vs statement-level trigger

The main difference is not what can be modified by the trigger, that depends on the DBMS. A trigger (row or statement level) may modify one or many rows*, of the same or other tables as well and may have cascading effects (trigger other actions/triggers) but all these depend on the DBMS of course.

The main difference is how many times the trigger is activated. Imagine you have a 1M rows table and you run:

UPDATE t
SET columnX = columnX + 1

A statement-level trigger will be activated once (and even if no rows are updated). A row-level trigger will be activated a million times, once for every updated row.


Another difference is the order or activation. For example in Oracle the 4 different types of triggers will be activated in the following order:

Before the triggering statement executes
Before each row that the triggering statement affects
After each row that the triggering statement affects
After the triggering statement executes

In the previous example, we'd have something like:

Before statement-level trigger executes

  Before row-level trigger executes
  One row is updated
  After row-level trigger executes

  Before row-level trigger executes
  Second row is updated
  After row-level trigger executes

  ...

  Before row-level trigger executes
  Millionth row is updated
  After row-level trigger executes

After statement-level trigger executes

Addendum

* Regarding what rows can be modified by a trigger: Different DBMS have different limitations on this, depending on the specific implementation or triggers in the DBMS. For example, Oracle may show a "mutating table" errors for some cases, e.g. when a row-level trigger selects from the whole table (SELECT MAX(col) FROM tablename) or if it modifies other rows or the whole table and not only the row that is related to / triggered from.

It is perfectly valid of course for a row-level trigger (in Oracle or other) to modify the row that its change has triggered it and that is a very common use. Example in dbfiddle.uk.

Other DBMS may have different limitations on what any type of trigger can do and even what type of triggers are offered (some do not have BEFORE triggers for example, some do not have statement level triggers at all, etc).

How to set environment variables in Python?

I have been trying to add environment variables. My goal was to store some user information to system variables such that I can use those variables for future solutions, as an alternative to config files. However, the method described in the code below did not help me at all.

import os
os.environ["variable_1"] = "value_1"
os.environ["variable_2"] = "value_2"
# To Verify above code
os.environ.get("variable_1")
os.environ.get("variable_2")

This simple code block works well, however, these variables exist inside the respective processes such that you will not find them in the environment variables tab of windows system settings. Pretty much above code did not serve my purpose. This problem is discussed here: variable save problem

os.environ.putenv(key, value)

Another unsuccessful attempt. So, finally, I managed to save variable successfully inside the window environment register by mimicking the windows shell commands wrapped inside the system class of os package. The following code describes this successful attempt.

os.system("SETX {0} {1} /M".format(key, value))

I hope this will be helpful for some of you.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

you can use this way

 map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: { lat: parseFloat(lat), lng: parseFloat(lng) },
        mapTypeId: 'terrain', 
        disableDefaultUI: true
 });

EX : center: { lat: parseFloat(lat), lng: parseFloat(lng) },

Slide a layout up from bottom of screen

You just need to add some line in your app, please find it from below link:

Show and hide a View with a slide up/down animation

Just add an animation to your layout like this:

mLayoutTab.animate()
  .translationYBy(120)
  .translationY(0)
  .setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));

javascript windows alert with redirect function

You could do this:

echo "<script>alert('Successfully Updated'); window.location = './edit.php';</script>";

CSV new-line character seen in unquoted field error

I realize this is an old post, but I ran into the same problem and don't see the correct answer so I will give it a try

Python Error:

_csv.Error: new-line character seen in unquoted field

Caused by trying to read Macintosh (pre OS X formatted) CSV files. These are text files that use CR for end of line. If using MS Office make sure you select either plain CSV format or CSV (MS-DOS). Do not use CSV (Macintosh) as save-as type.

My preferred EOL version would be LF (Unix/Linux/Apple), but I don't think MS Office provides the option to save in this format.

Padding a table row

The trick is to give padding on the td elements, but make an exception for the first (yes, it's hacky, but sometimes you have to play by the browser's rules):

td {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;   
}

td:first-child {
  padding-left:20px;
  padding-right:0;
}

First-child is relatively well supported: https://developer.mozilla.org/en-US/docs/CSS/:first-child

You can use the same reasoning for the horizontal padding by using tr:first-child td.

Alternatively, exclude the first column by using the not operator. Support for this is not as good right now, though.

td:not(:first-child) {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;       
}

How to upgrade safely php version in wamp server

WAMP server generally provide addond for different php/mysql versions. However you mentioned you have downloaded latest wamp server. As of now, latest Wamp server v2.5 provide PHP version 5.5.12

So you need to upgrade it manually as follow:

  1. Download binaries on php.net
  2. Extract all files in a new folder : C:/wamp/bin/php/php5.5.27/
  3. Copy the wampserver.conf from another php folder (like php/php5.5.12/) to the new folder
  4. Rename php.ini-development file to phpForApache.ini
  5. Done ! Restart WampServer (>Right Mouseclick on trayicon >Exit)

Although not asked, I'd recommend to vagrant/puppet or docker for local development. Check puphpet.com for details. It has slight learning curve but it will give you much better control of different versions of every tool.

How to run shell script file using nodejs?

you can go:

var cp = require('child_process');

and then:

cp.exec('./myScript.sh', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a command in your $SHELL.
Or go

cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a file WITHOUT a shell.
Or go

cp.execFile();

which is the same as cp.exec() but doesn't look in the $PATH.

You can also go

cp.fork('myJS.js', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a javascript file with node.js, but in a child process (for big programs).

EDIT

You might also have to access stdin and stdout with event listeners. e.g.:

var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
  // handle stdout as `data`
});

jQuery map vs. each

The each function iterates over an array, calling the supplied function once per element, and setting this to the active element. This:

function countdown() {
    alert(this + "..");
}

$([5, 4, 3, 2, 1]).each(countdown);

will alert 5.. then 4.. then 3.. then 2.. then 1..

Map on the other hand takes an array, and returns a new array with each element changed by the function. This:

function squared() {
    return this * this;
}

var s = $([5, 4, 3, 2, 1]).map(squared);

would result in s being [25, 16, 9, 4, 1].

Not an enclosing class error Android Studio

startActivity(new Intent(this, Katra_home.class));

try this one it will be work

How do I disable form resizing for users?

I always use this:

// Lock form
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;

This way you can always resize the form from Designer without changing code.

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

I ran into this problem and inspired by @Jeremy Cook's answer, I bit the bullet to find out what the heck caused IIS 7 Integrated mode to not like my web.config. Here's my scenario:

  1. Web API (version 4.0.030506.0 aka the old one)
  2. .NET 4.0
  3. Attribute Routing 3.5.6 for Web API [spoiler alert: it was this guy!]

I wanted to use attribute routing in a project that (unfortunately) had to use .NET 4 and hence could not use Web API 2.2 (which needs .NET 4.5). The well meaning NuGet package added this section under the <system.web> section:

<system.web>
<httpHandlers>
      <add verb="*" path="routes.axd" type="AttributeRouting.Web.Logging.LogRoutesHandler, AttributeRouting.Web" />
    </httpHandlers>
</system.web>

[I say well meaning, because this part is required on older versions of IIS]

Removing this section got me past the HTTP 500.23!!

Summary: I second Jeremy's words that it is important to understand why things don't work rather than just "masking the symptom". Even if you have to mask the symptom, you know what you are doing (and why) :-)

CSS Auto hide elements after 5 seconds

Of course you can, just use setTimeout to change a class or something to trigger the transition.

HTML:

<p id="aap">OHAI!</p>

CSS:

p {
    opacity:1;
    transition:opacity 500ms;
}
p.waa {
    opacity:0;
}

JS to run on load or DOMContentReady:

setTimeout(function(){
    document.getElementById('aap').className = 'waa';
}, 5000);

Example fiddle here.

What's the best way to cancel event propagation between nested ng-click calls?

What @JosephSilber said, or pass the $event object into ng-click callback and stop the propagation inside of it:

<div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
  <img src="http://some_src" ng-click="nextImage($event)"/>
</div>
$scope.nextImage = function($event) {
  $event.stopPropagation();
  // Some code to find and display the next image
}

How long is the SHA256 hash?

A sha256 is 256 bits long -- as its name indicates.

Since sha256 returns a hexadecimal representation, 4 bits are enough to encode each character (instead of 8, like for ASCII), so 256 bits would represent 64 hex characters, therefore you need a varchar(64), or even a char(64), as the length is always the same, not varying at all.

And the demo :

$hash = hash('sha256', 'hello, world!');
var_dump($hash);

Will give you :

$ php temp.php
string(64) "68e656b251e67e8358bef8483ab0d51c6619f3e7a1a9f0e75838d41ff368f728"

i.e. a string with 64 characters.

Enum to String C++

You could throw the enum value and string into an STL map. Then you could use it like so.

   return myStringMap[Enum::Apple];

What is aria-label and how should I use it?

It's an attribute designed to help assistive technology (e.g. screen readers) attach a label to an otherwise anonymous HTML element.

So there's the <label> element:

<label for="fmUserName">Your name</label>
<input id="fmUserName">

The <label> explicitly tells the user to type their name into the input box where id="fmUserName".

aria-label does much the same thing, but it's for those cases where it isn't practical or desirable to have a label on screen. Take the MDN example:

<button aria-label="Close" onclick="myDialog.close()">X</button>`

Most people would be able to infer visually that this button will close the dialog. A blind person using assistive technology might just hear "X" read aloud, which doesn't mean much without the visual clues. aria-label explicitly tells them what the button will do.

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

If you added the key-string pairs in Info.plist (see Murat's answer above ) and still getting the error, try to check if the target you're currently working on has the keys.

In my case I had 2 targets (dev and development). I added the keys in the editor, but it only works for the main target and I was testing on development target. So I had to open XCode, click on the project > Info > Add the key-pair for the development target there.

Passing parameters in Javascript onClick event

This will work from JS without coupling to HTML:

document.getElementById("click-button").onclick = onClickFunction;

function onClickFunction()
{
    return functionWithArguments('You clicked the button!');
}

function functionWithArguments(text) {
    document.getElementById("some-div").innerText = text;
}

Environment variables in Eclipse

You can also define an environment variable that is visible only within Eclipse.

Go to Run -> Run Configurations... and Select tab "Environment".

enter image description here

There you can add several environment variables that will be specific to your application.

How to recover the deleted files using "rm -R" command in linux server?

Short answer: You can't. rm removes files blindly, with no concept of 'trash'.

Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i by default, but not all do.

Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete.

In the future, use rm with caution. Either create a del alias that provides interactivity, or use a file manager.

Do HttpClient and HttpClientHandler have to be disposed between requests?

Since it doesn't appear that anyone has mentioned it here yet, the new best way to manage HttpClient and HttpClientHandler in .NET Core 2.1 is using HttpClientFactory.

It solves most of the aforementioned issues and gotchas in a clean and easy-to-use way. From Steve Gordon's great blog post:

Add the following packages to your .Net Core (2.1.1 or later) project:

Microsoft.AspNetCore.All
Microsoft.Extensions.Http

Add this to Startup.cs:

services.AddHttpClient();

Inject and use:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    private readonly IHttpClientFactory _httpClientFactory;

    public ValuesController(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    [HttpGet]
    public async Task<ActionResult> Get()
    {
        var client = _httpClientFactory.CreateClient();
        var result = await client.GetStringAsync("http://www.google.com");
        return Ok(result);
    }
}

Explore the series of posts in Steve's blog for lots more features.

for each loop in groovy

as simple as:

tmpHM.each{ key, value -> 
  doSomethingWithKeyAndValue key, value
}

What is an alternative to execfile in Python 3?

If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?

If you need to dynamically import code the built-in function __ import__ and the module imp are worth looking at.

>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'

test.py:

def run():
        return "Hello world!"

If you're using Python 3.1 or later, you should also take a look at importlib.

Detect when a window is resized using JavaScript ?

If You want to check only when scroll ended, in Vanilla JS, You can come up with a solution like this:

Super Super compact

var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }

All 3 possible combinations together (ES6)

var t
window.onresize = () => {
    resizing(this, this.innerWidth, this.innerHeight) //1
    if (typeof t == 'undefined') resStarted() //2
    clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}

function resizing(target, w, h) {
    console.log(`Youre resizing: width ${w} height ${h}`)
}    
function resStarted() { 
    console.log('Resize Started') 
}
function resEnded() { 
    console.log('Resize Ended') 
}

How to convert nanoseconds to seconds using the TimeUnit enum?

In Java 8 or Kotlin, I use Duration.ofNanos(1_000_000_000) like

val duration = Duration.ofNanos(1_000_000_000)
logger.info(String.format("%d %02dm %02ds %03d",
                elapse, duration.toMinutes(), duration.toSeconds(), duration.toMillis()))

Read more https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html

Unresolved external symbol on static class members

Since this is the first SO thread that seemed to come up for me when searching for "unresolved externals with static const members" in general, I'll leave another hint to solve one problem with unresolved externals here:

For me, the thing that I forgot was to mark my class definition __declspec(dllexport), and when called from another class (outside that class's dll's boundaries), I of course got the my unresolved external error.
Still, easy to forget when you're changing an internal helper class to a one accessible from elsewhere, so if you're working in a dynamically linked project, you might as well check that, too.

How to get value of a div using javascript

As I said in the comments, a <div> element does not have a value attribute. Although (very) bad, it can be accessed as:

console.log(document.getElementById('demo').getAttribute);

I suggest using HTML5 data-* attributes rather. Something like this:

<div id="demo" data-myValue="1">...</div>

in which case you could access it using:

element.getAttribute('data-myValue');
//Or using jQuery:
$('#demo').data('myValue');

How can I download a specific Maven artifact in one command line?

Here's an example to get ASM-7 using Maven 3.6:

mvn dependency:get -DremoteRepositories=maven.apache.org -Dartifact=org.ow2.asm:7.0:sources:jar

Or you can download the jar from here: https://search.maven.org/search?q=g:org.ow2.asm%20AND%20a:asm and then

mvn install:install-file -DgroupId=org.ow2.asm -DartifactId=asm -Dversion=7.0 -Dclassifier=sources -Dpackaging=jar -Dfile=/path/to/asm-7.0.jar

How to inspect Javascript Objects

The for-in loops for each property in an object or array. You can use this property to get to the value as well as change it.

Note: Private properties are not available for inspection, unless you use a "spy"; basically, you override the object and write some code which does a for-in loop inside the object's context.

For in looks like:

for (var property in object) loop();

Some sample code:

function xinspect(o,i){
    if(typeof i=='undefined')i='';
    if(i.length>50)return '[MAX ITERATIONS]';
    var r=[];
    for(var p in o){
        var t=typeof o[p];
        r.push(i+'"'+p+'" ('+t+') => '+(t=='object' ? 'object:'+xinspect(o[p],i+'  ') : o[p]+''));
    }
    return r.join(i+'\n');
}

// example of use:
alert(xinspect(document));

Edit: Some time ago, I wrote my own inspector, if you're interested, I'm happy to share.

Edit 2: Well, I wrote one up anyway.

S3 limit to objects in a bucket

It looks like the limit has changed. You can store 5TB for a single object.

The total volume of data and number of objects you can store are unlimited. Individual Amazon S3 objects can range in size from a minimum of 0 bytes to a maximum of 5 terabytes. The largest object that can be uploaded in a single PUT is 5 gigabytes. For objects larger than 100 megabytes, customers should consider using the Multipart Upload capability.

http://aws.amazon.com/s3/faqs/#How_much_data_can_I_store

How to post data using HttpClient?

You need to use:

await client.PostAsync(uri, content);

Something like that:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync();

Hope it helps ;)

Set width of dropdown element in HTML select dropdown options

Small And Better One

var i = 0;
$("#container > option").each(function(){ 
    if($(this).val().length > i) {
        i = $(this).val().length;

        console.log(i);
        console.log($(this).val());
    }
});

ImportError: No module named request

The SpeechRecognition library requires Python 3.3 or up:

Requirements

[...]

The first software requirement is Python 3.3 or better. This is required to use the library.

and from the Trove classifiers:

Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4

The urllib.request module is part of the Python 3 standard library; in Python 2 you'd use urllib2 here.

What's the difference between REST & RESTful

REST based Services/Architecture vs. RESTFUL Services/Architecture

To differentiate or compare these 2, you should know what REST is.

REST (REpresentational State Transfer) is basically an architectural style of development having some principles:

  • It should be stateless

  • It should access all the resources from the server using only URI

  • It does not have inbuilt encryption

  • It does not have session

  • It uses one and only one protocol - HTTP

  • For performing CRUD operations, it should use HTTP verbs such as get, post, put and delete

  • It should return the result only in the form of JSON or XML, atom, OData etc. (lightweight data )

REST based services follow some of the above principles and not all

RESTFUL services means it follows all the above principles.

It is similar to the concept of:

Object oriented languages support all the OOP concepts, examples: C++, C#

Object-based languages support some of the OOP features, examples: JavaScript, VB


Example:

ASP Dot NET MVC 4 is REST-Based while Microsoft WEB API is RESTFul.

MVC supports only some of the above REST principles whereas WEB API supports all the above REST Principles.

MVC only supports the following from the REST API

  • We can access the resource using URI

  • It supports the HTTP verb to access the resource from server

  • It can return the results in the form of JSON, XML, that is the HTTPResponse.

However, at the same time in MVC

  • We can use the session

  • We can make it stateful

  • We can return video or image from the controller action method which basically violates the REST principles

That is why MVC is REST-Based whereas WEB API supports all the above principles and is RESTFul.

How do I update zsh to the latest version?

If you're using oh-my-zsh

Type omz update in the terminal

Note: upgrade_oh_my_zsh is deprecated

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

If you have multiple Java versions installed on your Mac, here's a quick way to switch the default version using Terminal. In this example, I am going to switch Java 10 to Java 8.

$ java -version
java version "10.0.1" 2018-04-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    10.0.1, x86_64: "Java SE 10.0.1"    /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
    1.8.0_171, x86_64:  "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home

Then, in your .bash_profile add the following.

# Java 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home

Now if you try java -version again, you should see the version you want.

$ java -version
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)

How to record phone calls in android?

Ok, for this first of all you need to use Device Policy Manager, and need to make your device Admin device. After that you have to create one BroadCast receiver and one service. I am posting code here and its working fine.

MainActivity:

public class MainActivity extends Activity {
    private static final int REQUEST_CODE = 0;
    private DevicePolicyManager mDPM;
    private ComponentName mAdminName;

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

        try {
            // Initiate DevicePolicyManager.
            mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
            mAdminName = new ComponentName(this, DeviceAdminDemo.class);

            if (!mDPM.isAdminActive(mAdminName)) {
                Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
                intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Click on Activate button to secure your application.");
                startActivityForResult(intent, REQUEST_CODE);
            } else {
                // mDPM.lockNow();
                // Intent intent = new Intent(MainActivity.this,
                // TrackDeviceService.class);
                // startService(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }

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

        if (REQUEST_CODE == requestCode) {
                Intent intent = new Intent(MainActivity.this, TService.class);
                startService(intent);
        }
    }

}

//DeviceAdminDemo class

public class DeviceAdminDemo extends DeviceAdminReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
    }

    public void onEnabled(Context context, Intent intent) {
    };

    public void onDisabled(Context context, Intent intent) {
    };
}

//TService Class

public class TService extends Service {
    MediaRecorder recorder;
    File audiofile;
    String name, phonenumber;
    String audio_format;
    public String Audio_Type;
    int audioSource;
    Context context;
    private Handler handler;
    Timer timer;
    Boolean offHook = false, ringing = false;
    Toast toast;
    Boolean isOffHook = false;
    private boolean recordstarted = false;

    private static final String ACTION_IN = "android.intent.action.PHONE_STATE";
    private static final String ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL";
    private CallBr br_call;




    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onDestroy() {
        Log.d("service", "destroy");

        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // final String terminate =(String)
        // intent.getExtras().get("terminate");//
        // intent.getStringExtra("terminate");
        // Log.d("TAG", "service started");
        //
        // TelephonyManager telephony = (TelephonyManager)
        // getSystemService(Context.TELEPHONY_SERVICE); // TelephonyManager
        // // object
        // CustomPhoneStateListener customPhoneListener = new
        // CustomPhoneStateListener();
        // telephony.listen(customPhoneListener,
        // PhoneStateListener.LISTEN_CALL_STATE);
        // context = getApplicationContext();

        final IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_OUT);
        filter.addAction(ACTION_IN);
        this.br_call = new CallBr();
        this.registerReceiver(this.br_call, filter);

        // if(terminate != null) {
        // stopSelf();
        // }
        return START_NOT_STICKY;
    }

    public class CallBr extends BroadcastReceiver {
        Bundle bundle;
        String state;
        String inCall, outCall;
        public boolean wasRinging = false;

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_IN)) {
                if ((bundle = intent.getExtras()) != null) {
                    state = bundle.getString(TelephonyManager.EXTRA_STATE);
                    if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                        inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                        wasRinging = true;
                        Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
                    } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                        if (wasRinging == true) {

                            Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();

                            String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
                            File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
                            if (!sampleDir.exists()) {
                                sampleDir.mkdirs();
                            }
                            String file_name = "Record";
                            try {
                                audiofile = File.createTempFile(file_name, ".amr", sampleDir);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            String path = Environment.getExternalStorageDirectory().getAbsolutePath();

                            recorder = new MediaRecorder();
//                          recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);

                            recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
                            recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
                            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                            recorder.setOutputFile(audiofile.getAbsolutePath());
                            try {
                                recorder.prepare();
                            } catch (IllegalStateException e) {
                                e.printStackTrace();
                            } catch (IOException e) { 
                                e.printStackTrace();
                            }
                            recorder.start();
                            recordstarted = true;
                        }
                    } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                        wasRinging = false;
                        Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                        if (recordstarted) {
                            recorder.stop();
                            recordstarted = false;
                        }
                    }
                }
            } else if (intent.getAction().equals(ACTION_OUT)) {
                if ((bundle = intent.getExtras()) != null) {
                    outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                    Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
                }
            }
        }
    }

}

//Permission in manifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.STORAGE" />

//my_admin.xml

<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>

//Declare following thing in manifest:

Declare DeviceAdminDemo class to manifest:

 <receiver
            android:name="com.example.voicerecorder1.DeviceAdminDemo"
            android:description="@string/device_description"
            android:label="@string/device_admin_label"
            android:permission="android.permission.BIND_DEVICE_ADMIN" >
            <meta-data
                android:name="android.app.device_admin"
                android:resource="@xml/my_admin" />


            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
                <action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
                <action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
            </intent-filter>
        </receiver>

<service android:name=".TService" >
        </service>

Spell Checker for Python

Maybe it is too late, but I am answering for future searches. TO perform spelling mistake correction, you first need to make sure the word is not absurd or from slang like, caaaar, amazzzing etc. with repeated alphabets. So, we first need to get rid of these alphabets. As we know in English language words usually have a maximum of 2 repeated alphabets, e.g., hello., so we remove the extra repetitions from the words first and then check them for spelling. For removing the extra alphabets, you can use Regular Expression module in Python.

Once this is done use Pyspellchecker library from Python for correcting spellings.

For implementation visit this link: https://rustyonrampage.github.io/text-mining/2017/11/28/spelling-correction-with-python-and-nltk.html

Parse RSS with jQuery

Update (Oct 15, 2019)

I extracted the core logic from jquery-rss to a new library called Vanilla RSS which is using the fetch API and can work without any additional dependencies:

const RSS = require('vanilla-rss');
const rss = new RSS(
    document.querySelector("#your-div"),
    "http://www.recruiter.com/feed/career.xml",
    { 
      // options go here
    }
);
rss.render().then(() => {
  console.log('Everything is loaded and rendered');
});

Original

post:

You can also use jquery-rss, which comes with nice templating and is super easy to use:

$("#your-div").rss("http://www.recruiter.com/feed/career.xml", {
    limit: 3,
    layoutTemplate: '<ul class="inline">{entries}</ul>',
    entryTemplate: '<li><a href="{url}">[{author}@{date}] {title}</a><br/>{shortBodyPlain}</li>'
})

yields (as of Sept 18, 2013):

<div id="your-div">
    <ul class="inline">
    <entries></entries>
    </ul>
    <ul class="inline">
        <li><a href="http://www.recruiter.com/i/when-to-go-over-a-recruiter%e2%80%99s-head/">[@Tue, 10 Sep 2013 22:23:51 -0700] When to Go Over a Recruiter's Head</a><br>Job seekers tend to have a certain "fear" of recruiters and hiring managers, and I mean fear in the reverence and respect ...</li>
        <li><a href="http://www.recruiter.com/i/the-perfect-job/">[@Tue, 10 Sep 2013 14:52:40 -0700] The Perfect Job</a><br>Having long ago dealt with the "perfect resume" namely God's, in a previous article of mine, it makes sense to consider the ...</li>
        <li><a href="http://www.recruiter.com/i/unemployment-benefits-applications-remain-near-5-year-low-decline-again/">[@Mon, 09 Sep 2013 12:49:17 -0700] Unemployment Benefits Applications Remain Near 5-Year Low, Decline Again</a><br>As reported by the U.S. Department of Labor, the number of workers seeking unemployment benefits continued to sit near ...</li>
    </ul>
</div>

See http://jsfiddle.net/sdepold/ozq2dn9e/1/ for a working example.

How do I install Python packages in Google's Colab?

Joining the party late, but just as a complement, I ran into some problems with Seaborn not so long ago, because CoLab installed a version with !pip that wasn't updated. In my specific case, I couldn't use Scatterplot, for example. The answer to this is below:

To install the module, all you need is:

!pip install seaborn

To upgrade it to the most updated version:

!pip install --upgrade seaborn

If you want to install a specific version

!pip install seaborn==0.9.0

I believe all the rules common to pip apply normally, so that pretty much should work.

How to catch exception output from Python subprocess.check_output()?

There are good answers here, but in these answers, there has not been an answer that comes up with the text from the stack-trace output, which is the default behavior of an exception.

If you wish to use that formatted traceback information, you might wish to:

import traceback

try:
    check_call( args )
except CalledProcessError:
    tb = traceback.format_exc()
    tb = tb.replace(passwd, "******")
    print(tb)
    exit(1)

As you might be able to tell, the above is useful in case you have a password in the check_call( args ) that you wish to prevent from displaying.

Changing cell color using apache poi

checkout the example here

http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java

style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());

What's the difference between JavaScript and Java?

Java and Javascript are similar like Car and Carpet are similar.

Read tab-separated file line into array

If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

while IFS=$'\t' read -r column1 column2 column3 ; do
  printf "%b\n" "column1<${column1}>"
  printf "%b\n" "column2<${column2}>"
  printf "%b\n" "column3<${column3}>"
done < "myfile"

to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

Change primary key column in SQL Server

Necromancing.
It looks you have just as good a schema to work with as me... Here is how to do it correctly:

In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID

-- First, chech if the table exists...
IF 0 < (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_SCHEMA = 'dbo'
    AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
    -- Check for NULL values in the primary-key column
    IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
    BEGIN
        ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 

        -- No, don't drop, FK references might already exist...
        -- Drop PK if exists 
        -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
        --DECLARE @pkDropCommand nvarchar(1000) 
        --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
        --AND TABLE_SCHEMA = 'dbo' 
        --AND TABLE_NAME = 'T_SYS_Language_Forms' 
        ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
        --))
        ---- PRINT @pkDropCommand 
        --EXECUTE(@pkDropCommand) 

        -- Instead do
        -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';


        -- Check if they keys are unique (it is very possible they might not be) 
        IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
        BEGIN

            -- If no Primary key for this table
            IF 0 =  
            (
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND TABLE_SCHEMA = 'dbo' 
                AND TABLE_NAME = 'T_SYS_Language_Forms' 
                -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            )
                ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
            ;

            -- Adding foreign key
            IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') 
                ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); 
        END -- End uniqueness check
        ELSE
            PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
    END -- End NULL check
    ELSE
        PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
END 

Difference between Big-O and Little-O Notation

Big-O is to little-o as = is to <. Big-O is an inclusive upper bound, while little-o is a strict upper bound.

For example, the function f(n) = 3n is:

  • in O(n²), o(n²), and O(n)
  • not in O(lg n), o(lg n), or o(n)

Analogously, the number 1 is:

  • = 2, < 2, and = 1
  • not = 0, < 0, or < 1

Here's a table, showing the general idea:

Big o table

(Note: the table is a good guide but its limit definition should be in terms of the superior limit instead of the normal limit. For example, 3 + (n mod 2) oscillates between 3 and 4 forever. It's in O(1) despite not having a normal limit, because it still has a lim sup: 4.)

I recommend memorizing how the Big-O notation converts to asymptotic comparisons. The comparisons are easier to remember, but less flexible because you can't say things like nO(1) = P.

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

In my case the problem was the 32/64 bit driver which I solved by configuring the properties of the sql server job:

enter image description here

an htop-like tool to display disk activity in linux

It is not htop-like, but you could use atop. However, to display disk activity per process, it needs a kernel patch (available from the site). These kernel patches are now obsoleted, only to show per-process network activity an optional module is provided.

PostgreSQL delete all content

For small tables DELETE is often faster and needs less aggressive locking (for heavy concurrent load):

DELETE FROM tbl;

With no WHERE condition.

For medium or bigger tables, go with TRUNCATE tbl, like @Greg posted.

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

In Chrome, you are supposed to be able to allow this capability with a runtime flag --allow-file-access-from-files

However, it looks like there is a problem with current versions of Chrome (37, 38) where this doesn't work unless you also pass the runtime flag --disable-web-security

That's an unacceptable solution, except perhaps as a short-term workaround, but it has been identified as an issue: https://code.google.com/p/chromium/issues/detail?id=379206

How to copy a string of std::string type in C++?

strcpy example:

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

int main ()
{
  char str1[]="Sample string" ;
  char str2[40] ;
  strcpy (str2,str1) ;
  printf ("str1: %s\n",str1) ;
  return 0 ;
}

Output: str1: Sample string

Your case:

A simple = operator should do the job.

string str1="Sample string" ;
string str2 = str1 ;

No == operator found while comparing structs in C++

Because you did not write a comparison operator for your struct. The compiler does not generate it for you, so if you want comparison, you have to write it yourself.

opening html from google drive

Not available any more, https://support.google.com/drive/answer/2881970?hl=en

Host web pages with Google Drive

Note: This feature will not be available after August 31, 2016.

I highly recommend https://www.heroku.com/ and https://www.netlify.com/

Decode JSON with unknown structure

The issue I had is that sometimes I will need to get at a value that is deeply nested. Normally you would need to do a type assertion at each level, so I went ahead and just made a method that takes a map[string]interface{} and a string key, and returns the resulting map[string]interface{}.

The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:

package main
type Slice []interface{}
type Map map[string]interface{}

func (m Map) M(s string) Map {
   return m[s].(map[string]interface{})
}

func (m Map) A(s string) Slice {
   return m[s].([]interface{})
}

func (a Slice) M(n int) Map {
   return a[n].(map[string]interface{})
}

and example code:

package main

import (
   "encoding/json"
   "fmt"
   "log"
   "os"
)

func main() {
   o, e := os.Open("a.json")
   if e != nil {
      log.Fatal(e)
   }
   in_m := Map{}
   json.NewDecoder(o).Decode(&in_m)
   out_m := in_m.
      M("contents").
      M("sectionListRenderer").
      A("contents").
      M(0).
      M("musicShelfRenderer").
      A("contents").
      M(0).
      M("musicResponsiveListItemRenderer").
      M("navigationEndpoint").
      M("browseEndpoint")
   fmt.Println(out_m)
}

How to search for file names in Visual Studio?

With Visual Studio 2017 Community edition on mac, the shortcut is:

  • Cmd+Shift+D: Find by file name
  • Cmd+Shift+T: Find by type name

To see these commands, navigate to the top menu: Search > Go To

What is the role of the bias in neural networks?

In particular, Nate’s answer, zfy’s answer, and Pradi’s answer are great.

In simpler terms, biases allow for more and more variations of weights to be learnt/stored... (side-note: sometimes given some threshold). Anyway, more variations mean that biases add richer representation of the input space to the model's learnt/stored weights. (Where better weights can enhance the neural net’s guessing power)

For example, in learning models, the hypothesis/guess is desirably bounded by y=0 or y=1 given some input, in maybe some classification task... i.e some y=0 for some x=(1,1) and some y=1 for some x=(0,1). (The condition on the hypothesis/outcome is the threshold I talked about above. Note that my examples setup inputs X to be each x=a double or 2 valued-vector, instead of Nate's single valued x inputs of some collection X).

If we ignore the bias, many inputs may end up being represented by a lot of the same weights (i.e. the learnt weights mostly occur close to the origin (0,0). The model would then be limited to poorer quantities of good weights, instead of the many many more good weights it could better learn with bias. (Where poorly learnt weights lead to poorer guesses or a decrease in the neural net’s guessing power)

So, it is optimal that the model learns both close to the origin, but also, in as many places as possible inside the threshold/decision boundary. With the bias we can enable degrees of freedom close to the origin, but not limited to origin's immediate region.

Set element width or height in Standards Mode

The style property lets you specify values for CSS properties.

The CSS width property takes a length as its value.

Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.

e1.style.width = "400px";

How do I calculate a trendline for a graph?

Here's what I ended up using.

public class DataPoint<T1,T2>
{
    public DataPoint(T1 x, T2 y)
    {
        X = x;
        Y = y;
    }

    [JsonProperty("x")]
    public T1 X { get; }

    [JsonProperty("y")]
    public T2 Y { get; }
}

public class Trendline
{
    public Trendline(IEnumerable<DataPoint<long, decimal>> dataPoints)
    {
        int count = 0;
        long sumX = 0;
        long sumX2 = 0;
        decimal sumY = 0;
        decimal sumXY = 0;

        foreach (var dataPoint in dataPoints)
        {
            count++;
            sumX += dataPoint.X;
            sumX2 += dataPoint.X * dataPoint.X;
            sumY += dataPoint.Y;
            sumXY += dataPoint.X * dataPoint.Y;
        }

        Slope = (sumXY - ((sumX * sumY) / count)) / (sumX2 - ((sumX * sumX) / count));
        Intercept = (sumY / count) - (Slope * (sumX / count));
    }

    public decimal Slope { get; private set; }
    public decimal Intercept { get; private set; }
    public decimal Start { get; private set; }
    public decimal End { get; private set; }

    public decimal GetYValue(decimal xValue)
    {
        return Slope * xValue + Intercept;
    }
}

My data set is using a Unix timestamp for the x-axis and a decimal for the y. Change those datatypes to fit your need. I do all the sum calculations in one iteration for the best possible performance.

Returning JSON object from an ASP.NET page

In your Page_Load you will want to clear out the normal output and write your own, for example:

string json = "{\"name\":\"Joe\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();

To convert a C# object to JSON you can use a library such as Json.NET.

Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.

shell script to remove a file if it already exist

You can use this:

#!/bin/bash

file="file_you_want_to_delete"

if [ -f "$file" ] ; then
    rm "$file"
fi

Connecting to Postgresql in a docker container from outside

docker ps -a to get container ids then docker exec -it psql -U -W

How to get href value using jQuery?

If your html link is like this:

<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>

Then you can access the href in jquery as given below (there is no need to use "a" in href for this)

$(".linkClass").on("click",accesshref);

function accesshref()
 {
 var url = $(".linkClass").attr("href");
 //OR
 var url = $(this).attr("href");
}

Parsing jQuery AJAX response

 $.ajax({     
     type: "POST",
     url: '/admin/systemgoalssystemgoalupdate?format=html',
     data: formdata,
     success: function (data) {
         console.log(data);
     },
     dataType: "json"
 });

List of macOS text editors and code editors

I would love to use a different editor than XCode for coding, but I feel, that no other editor integrates tightly enough with it to be really worthwhile.
However, given some time, TextMate might eventually get to that point. At the moment though, it primarily lacks debugging features and refactoring.

For everything that does not need XCode, I love TextMate. If I had another Mac-user in my workgroup I would probably consider SubEthaEdit for its collaboration features. If it is Emacs you want, I would recommend Aquamacs (more Mac-like) or Carbon Emacs (more GNU-Emacs-like)

Android fastboot waiting for devices

Just use sudo, fast boot needs Root Permission

Sorting arraylist in alphabetical order (case insensitive)

Unfortunately, all answers so far do not take into account that "a" must not be considered equal to "A" when it comes to sorting.

String[] array = {"b", "A", "C", "B", "a"};

// Approach 1
Arrays.sort(array);
// array is [A, B, C, a, b]

// Approach 2
Arrays.sort(array, String.CASE_INSENSITIVE_ORDER);
// array is [A, a, b, B, C]

// Approach 3
Arrays.sort(array, java.text.Collator.getInstance());
// array is [a, A, b, B, C]

In approach 1 any lower case letters are considered greater than any upper case letters.

Approach 2 makes it worse, since CASE_INSENSITIVE_ORDER considers "a" and "A" equal (comparation result is 0). This makes sorting non-deterministic.

Approach 3 (using a java.text.Collator) is IMHO the only way of doing it correctly, since it considers "a"and "A" not equal, but puts them in the correct order according to the current (or any other desired) Locale.

How to redirect on another page and pass parameter in url from table?

Do this :

<script type="text/javascript">
function showDetails(username)
{
   window.location = '/player_detail?username='+username;
}
</script>

<input type="button" name="theButton" value="Detail" onclick="showDetails('username');">

Execution failed app:processDebugResources Android Studio

aapt is 32 bit so will not execute on a 64 bit box until 32 bit architecture is enabled

dpkg --print-foreign-architectures  #  if prints nothing then below is fix

sudo dpkg --add-architecture i386  #  add a 32 bit architecture to box

sudo apt-get install -y lib32gcc1 libc6-i386 lib32z1 lib32stdc++6

sudo apt-get install -y lib32ncurses5 lib32gomp1 lib32z1-dev

it work for me.

How to iterate object in JavaScript?

Here's all the options you have:

1. for...of (ES2015)

_x000D_
_x000D_
var dictionary = {_x000D_
    "data": [_x000D_
        {"id":"0","name":"ABC"},_x000D_
        {"id":"1","name":"DEF"}_x000D_
    ],_x000D_
    "images": [_x000D_
        {"id":"0","name":"PQR"},_x000D_
        {"id":"1","name":"xyz"}_x000D_
    ]_x000D_
};_x000D_
_x000D_
for (const entry of dictionary.data) {_x000D_
  console.log(JSON.stringify(entry))_x000D_
}
_x000D_
_x000D_
_x000D_

2. Array.prototype.forEach (ES5)

_x000D_
_x000D_
var dictionary = {_x000D_
    "data": [_x000D_
        {"id":"0","name":"ABC"},_x000D_
        {"id":"1","name":"DEF"}_x000D_
    ],_x000D_
    "images": [_x000D_
        {"id":"0","name":"PQR"},_x000D_
        {"id":"1","name":"xyz"}_x000D_
    ]_x000D_
};_x000D_
_x000D_
dictionary.data.forEach(function(entry) {_x000D_
  console.log(JSON.stringify(entry))_x000D_
})
_x000D_
_x000D_
_x000D_

3. for() (ES1)

_x000D_
_x000D_
var dictionary = {_x000D_
    "data": [_x000D_
        {"id":"0","name":"ABC"},_x000D_
        {"id":"1","name":"DEF"}_x000D_
    ],_x000D_
    "images": [_x000D_
        {"id":"0","name":"PQR"},_x000D_
        {"id":"1","name":"xyz"}_x000D_
    ]_x000D_
};_x000D_
_x000D_
for (let i = 0; i < dictionary.data.length; i++) {_x000D_
  console.log(JSON.stringify(dictionary.data[i]))_x000D_
}
_x000D_
_x000D_
_x000D_

Remove duplicate values from JS array

Although ES6 Solution is the best, I'm baffled as to how nobody has shown the following solution:

function removeDuplicates(arr){
    o={}
    arr.forEach(function(e){
        o[e]=true
    })
    return Object.keys(o)
}

The thing to remember here is that objects MUST have unique keys. We are exploiting this to remove all the duplicates. I would have thought this would be the fastest solution (before ES6).

Bear in mind though that this also sorts the array.

MySQL Multiple Joins in one query?

You can simply add another join like this:

SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data 
    INNER JOIN dashboard_messages 
        ON dashboard_message_id = dashboard_messages.id
    INNER JOIN images
        ON dashboard_messages.image_id = images.image_id 

However be aware that, because it is an INNER JOIN, if you have a message without an image, the entire row will be skipped. If this is a possibility, you may want to do a LEFT OUTER JOIN which will return all your dashboard messages and an image_filename only if one exists (otherwise you'll get a null)

SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data 
    INNER JOIN dashboard_messages 
        ON dashboard_message_id = dashboard_messages.id
    LEFT OUTER JOIN images
        ON dashboard_messages.image_id = images.image_id 

Infinity symbol with HTML

8

This does not require a HTML entity if you are using a modern encoding (such as UTF-8). And if you're not already, you probably should be.

How do I get the last four characters from a string in C#?

Ok, so I see this is an old post, but why are we rewriting code that is already provided in the framework?

I would suggest that you add a reference to the framework DLL "Microsoft.VisualBasic"

using Microsoft.VisualBasic;
//...

string value = Strings.Right("34234234d124", 4);

Centering a button vertically in table cell, using Twitter Bootstrap

To fix this, i put this class on the webpage

<style>                        
    td.vcenter {
        vertical-align: middle !important;
        text-align: center !important;
    }
</style>

and this in my TemplateField

<asp:TemplateField ItemStyle-CssClass="vcenter">

as the CSS class points directly to the td (tabledata) element and has the !important statment at the end each setting. It will over rule bootsraps CSS class settings.

Hope it helps

Bootstrap - floating navbar button right

Create a separate ul.nav for just that list item and float that ul right.

jsFiddle

No line-break after a hyphen

Try using the non-breaking hyphen &#8209;. I've replaced the dash with that character in your jsfiddle, shrunk the frame down as small as it can go, and the line doesn't split there any more.

Normal arguments vs. keyword arguments

There is one last language feature where the distinction is important. Consider the following function:

def foo(*positional, **keywords):
    print "Positional:", positional
    print "Keywords:", keywords

The *positional argument will store all of the positional arguments passed to foo(), with no limit to how many you can provide.

>>> foo('one', 'two', 'three')
Positional: ('one', 'two', 'three')
Keywords: {}

The **keywords argument will store any keyword arguments:

>>> foo(a='one', b='two', c='three')
Positional: ()
Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}

And of course, you can use both at the same time:

>>> foo('one','two',c='three',d='four')
Positional: ('one', 'two')
Keywords: {'c': 'three', 'd': 'four'}

These features are rarely used, but occasionally they are very useful, and it's important to know which arguments are positional or keywords.

How to change the size of the font of a JLabel to take the maximum size

label = new JLabel("A label");
label.setFont(new Font("Serif", Font.PLAIN, 14));

taken from How to Use HTML in Swing Components

How to retrieve checkboxes values in jQuery

The following may be useful since I got here looking for a slightly different solution. My script needed to automatically loop through input elements and had to return their values (for jQuery.post() function), the problem was with checkboxes returning their values regardless of checked status. This was my solution:

jQuery.fn.input_val = function(){

    if(jQuery(this).is("input[type=checkbox]")) {
        if(jQuery(this).is(":checked")) {
            return jQuery(this).val();
        } else {
            return false;
        }
    } else {
        return jQuery(this).val();
    }
};

Usage:

jQuery(".element").input_val();

If the given input field is a checkbox, the input_val function only returns a value if its checked. For all other elements, the value is returned regardless of checked status.

How do I fetch only one branch of a remote Git repository?

  1. Pick any <remote_name> you'd like to use (feel free to use origin and skip step 1.)
  2. git remote add <remote_name> <remote_url>
  3. git fetch <remote_name> <branch>
  4. Pick any <your_local_branch_name> you'd like to use. Could be the same as <branch>.
  5. git checkout <remote_name>/<branch> -b <your_local_branch_name>

Hope that helps!

Write HTML to string

You could write your own classes with its Render method, and another attributes, to avoid a great mess if you use it a lot, and then use the HTMLWriter or the xmlwriter as well. This logic is used in the asp.net pages, you can inherit from webControl and override the render method, wich is great if you are developing server-side controls.
This could be a good example.

Regards

How to show full height background image?

This worked for me (though it's for reactjs & tachyons used as inline CSS)

<div className="pa2 cf vh-100-ns" style={{backgroundImage: `url(${a6})`}}> 
........
</div>

This takes in css as height: 100vh

Print time in a batch file (milliseconds)

If you're doing something like

for /l %%i in (1,1,500) do @echo %time%

or

if foo (
    echo %time%
    do_something
    echo %time%
)

then you could simply put a setlocal enabledelayedexpansion at the beginning of your batch file and use !time! instead of %time% which gets evaluated on execution, not on parsing the line (which includes complete blocks enclosed in parentheses).

Is Ruby pass by reference or by value?

The other answerers are all correct, but a friend asked me to explain this to him and what it really boils down to is how Ruby handles variables, so I thought I would share some simple pictures / explanations I wrote for him (apologies for the length and probably some oversimplification):


Q1: What happens when you assign a new variable str to a value of 'foo'?

str = 'foo'
str.object_id # => 2000

enter image description here

A: A label called str is created that points at the object 'foo', which for the state of this Ruby interpreter happens to be at memory location 2000.


Q2: What happens when you assign the existing variable str to a new object using =?

str = 'bar'.tap{|b| puts "bar: #{b.object_id}"} # bar: 2002
str.object_id # => 2002

enter image description here

A: The label str now points to a different object.


Q3: What happens when you assign a new variable = to str?

str2 = str
str2.object_id # => 2002

enter image description here

A: A new label called str2 is created that points at the same object as str.


Q4: What happens if the object referenced by str and str2 gets changed?

str2.replace 'baz'
str2 # => 'baz'
str  # => 'baz'
str.object_id # => 2002
str2.object_id # => 2002

enter image description here

A: Both labels still point at the same object, but that object itself has mutated (its contents have changed to be something else).


How does this relate to the original question?

It's basically the same as what happens in Q3/Q4; the method gets its own private copy of the variable / label (str2) that gets passed in to it (str). It can't change which object the label str points to, but it can change the contents of the object that they both reference to contain else:

str = 'foo'

def mutate(str2)
  puts "str2: #{str2.object_id}"
  str2.replace 'bar'
  str2 = 'baz'
  puts "str2: #{str2.object_id}"
end

str.object_id # => 2004
mutate(str) # str2: 2004, str2: 2006
str # => "bar"
str.object_id # => 2004

How to get Url Hash (#) from server side

RFC 2396 section 4.1:

When a URI reference is used to perform a retrieval action on the identified resource, the optional fragment identifier, separated from the URI by a crosshatch ("#") character, consists of additional reference information to be interpreted by the user agent after the retrieval action has been successfully completed. As such, it is not part of a URI, but is often used in conjunction with a URI.

(emphasis added)

Replace "\\" with "\" in a string in C#

Try -

var newstring = @"a\\b".Replace(@"\\",@"\");

How to check whether a Button is clicked by using JavaScript

if(button.clicked==true) {
    console.log("Button Clicked");
} ==> // This Code Doesn't Work Properly So Please Use Below One // 


function check() { 
    console.log("Button Clicked");
}; // This Code Works Fine // 

var button= document.querySelector("button"); // Accessing The Button // 
button.addEventListener("click", check); // Adding event to call function when clicked // 

Positioning background image, adding padding

you can use background-origin:padding-box; and then add some padding where you want, for example: #logo {background-image: url(your/image.jpg); background-origin:padding-box; padding-left: 15%;} This way you attach the image to the div padding box that contains it so you can position it wherever you want.

How do I split an int into its digits?

cast it to a string or char[] and loop on it

How can I change the image of an ImageView?

Just to go a little bit further in the matter, you can also set a bitmap directly, like this:

ImageView imageView = new ImageView(this);  
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);

Of course, this technique is only useful if you need to change the image.

IE 8: background-size fix

I created jquery.backgroundSize.js: a 1.5K jquery plugin that can be used as a IE8 fallback for "cover" and "contain" values. Have a look at the demo.

Solving your problem could be as simple as:

$("h2#news").css({backgroundSize: "cover"});

Convert tabs to spaces in Notepad++

I follow this simple way:

  • Double click (Highlight) single tab (ie: \t).
  • Press ctrl + F (Find/repace).
  • You may not see \t or single tab area on Find What: field. But don't worry.
  • Enter a space in Replace With: field.
  • Click Replce All .

Done! :)

See:

Replace *Tab* by *Space* in <code>Notepad++</code>

Note: This method applies to reverse (Replace a space by a tab) case too.

python replace single backslash with double backslash

You could use

os.path.abspath(path_with_backlash)

it returns the path with \

Show/hide 'div' using JavaScript

Set your HTML as

<div id="body" hidden="">
 <h1>Numbers</h1>
 </div>
 <div id="body1" hidden="hidden">
 Body 1
 </div>

And now set the javascript as

function changeDiv()
  {
  document.getElementById('body').hidden = "hidden"; // hide body div tag
  document.getElementById('body1').hidden = ""; // show body1 div tag
  document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; 
  // display text if JavaScript worked
   }

JavaScript check if variable exists (is defined/initialized)

if (typeof console != "undefined") {    
   ...
}

Or better

if ((typeof console == "object") && (typeof console.profile == "function")) {    
   console.profile(f.constructor);    
}

Works in all browsers

OAuth 2.0 Authorization Header

You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.

It's documented in this spec: https://tools.ietf.org/html/rfc6750#section-2.1

E.g.:

   GET /resource HTTP/1.1
   Host: server.example.com
   Authorization: Bearer mF_9.B5f-4.1JqM

Where mF_9.B5f-4.1JqM is your OAuth access token.

Get records with max value for each group of grouped SQL results

This is how I'm getting the N max rows per group in mysql

SELECT co.id, co.person, co.country
FROM person co
WHERE (
SELECT COUNT(*)
FROM person ci
WHERE  co.country = ci.country AND co.id < ci.id
) < 1
;

how it works:

  • self join to the table
  • groups are done by co.country = ci.country
  • N elements per group are controlled by ) < 1 so for 3 elements - ) < 3
  • to get max or min depends on: co.id < ci.id
    • co.id < ci.id - max
    • co.id > ci.id - min

Full example here:

mysql select n max values per group

MetadataException when using Entity Framework Entity Connection

I moved my Database First DataModel to a different project midway through development. Poor planning (or lack there of) on my part.

Initially I had a solution with one project. Then I added another project to the solution and recreated my Database First DataModel from the Sql Server Dataase.

To fix the problem - MetadataException when using Entity Framework Entity Connection. I copied my the ConnectionString from the new Project Web.Config to the original project Web.Config. However, this occurred after I updated my all the references in the original project to new DataModel project.

Check if selected dropdown value is empty using jQuery

Try this it will work --

if($('#EventStartTimeMin').val() === " ") {

    alert("Please enter start time!");

}

How to switch databases in psql?

You can select the database when connecting with psql. This is handy when using it from a script:

sudo -u postgres psql -c "CREATE SCHEMA test AUTHORIZATION test;" test

How to convert a Drawable to a Bitmap?

 // get image path from gallery
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
    super.onActivityResult(requestCode, resultcode, intent);

    if (requestCode == 1) {
        if (intent != null && resultcode == RESULT_OK) {             
            Uri selectedImage = intent.getData();

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);

            //display image using BitmapFactory

            cursor.close(); bmp = BitmapFactory.decodeFile(filepath); 
            iv.setBackgroundResource(0);
            iv.setImageBitmap(bmp);
        }
    }
}

Why are elementwise additions much faster in separate loops than in a combined loop?

The second loop involves a lot less cache activity, so it's easier for the processor to keep up with the memory demands.

fill an array in C#

Say you want to fill with number 13.

int[] myarr = Enumerable.Range(0, 10).Select(n => 13).ToArray();

or

List<int> myarr = Enumerable.Range(0,10).Select(n => 13).ToList();

if you prefer a list.

Can typescript export a function?

If you are using this for Angular, then export a function via a named export. Such as:

function someFunc(){}

export { someFunc as someFuncName }

otherwise, Angular will complain that object is not a function.

How to get the day name from a selected date?

DateTime now = DateTime.Now
string s = now.DayOfWeek.ToString();

How to create a timeline with LaTeX?

Tim Storer wrote a more flexible and nicer looking timeline.sty (Internet Archive Wayback Machine link, as original is gone). In addition, the line is horizontal rather than vertical. So for instance:

\begin{timeline}{2008}{2010}{50}{250}
  \MonthAndYearEvent{4}{2008}{First Podcast}
  \MonthAndYearEvent{7}{2008}{Private Beta}
  \MonthAndYearEvent{9}{2008}{Public Beta}
  \YearEvent{2009}{IPO?}
\end{timeline}

produces a timeline that looks like this:

2008                              2010
 · · April, 2008 First Podcast    ·
       · July, 2008 Private Beta
           · September, 2008 Public Beta
                · 2009 IPO?

Personally, I find this a more pleasing solution than the other answers. But I also find myself modifying the code to get something closer to what I think a timeline should look like. So there's not definitive solution in my opinion.

Simultaneously merge multiple data.frames in a list

I will reuse the data example from @PaulRougieux

x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)

Here's a short and sweet solution using purrr and tidyr

library(tidyverse)

 list(x, y, z) %>% 
  map_df(gather, key=key, value=value, -i) %>% 
  spread(key, value)

How to cache Google map tiles for offline usage?

update:

I found the terms of use from Google Map:

Section 10.5

No caching or storage. You will not pre-fetch, cache, index, or store any Content to be used outside the Service, except that you may store limited amounts of Content solely for the purpose of improving the performance of your Maps API Implementation due to network latency (and not for the purpose of preventing Google from accurately tracking usage), and only if such storage: is temporary (and in no event more than 30 calendar days); is secure; does not manipulate or aggregate any part of the Content or Service; and does not modify attribution in any way.

It means we can cache for limited time actually

Loop X number of times

Use:

1..10 | % { write "loop $_" }

Output:

PS D:\temp> 1..10 | % { write "loop $_" }
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
loop 10

SHA-256 or MD5 for file integrity

  1. Yes, on most CPUs, SHA-256 is two to three times slower than MD5, though not primarily because of its longer hash. See other answers here and the answers to this Stack Overflow questions.
  2. Here's a backup scenario where MD5 would not be appropriate:
    • Your backup program hashes each file being backed up. It then stores each file's data by its hash, so if you're backing up the same file twice you only end up with one copy of it.
    • An attacker can cause the system to backup files they control.
    • The attacker knows the MD5 hash of a file they want to remove from the backup.
    • The attacker can then use the known weaknesses of MD5 to craft a new file that has the same hash as the file to remove. When that file is backed up, it will replace the file to remove, and that file's backed up data will be lost.
    • This backup system could be strengthened a bit (and made more efficient) by not replacing files whose hash it has previously encountered, but then an attacker could prevent a target file with a known hash from being backed up by preemptively backing up a specially constructed bogus file with the same hash.
    • Obviously most systems, backup and otherwise, do not satisfy the conditions necessary for this attack to be practical, but I just wanted to give an example of a situation where SHA-256 would be preferable to MD5. Whether this would be the case for the system you're creating depends on more than just the characteristics of MD5 and SHA-256.
  3. Yes, cryptographic hashes like the ones generated by MD5 and SHA-256 are a type of checksum.

Happy hashing!

Post a json object to mvc controller with jquery and ajax

instead of receiving the json string a model binding is better. For example:

[HttpPost]       
public ActionResult AddUser(UserAddModel model)
{
    if (ModelState.IsValid) {
        return Json(new { Response = "Success" });
    }
    return Json(new { Response = "Error" });
}

<script>
function submitForm() {    
    $.ajax({
        type: 'POST',
        url: "@Url.Action("AddUser")",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: $("form[name=UserAddForm]").serialize(),
        success: function (data) {
            console.log(data);
        }
    });
}
</script>

Converting double to string

double total = 44;
String total2= new Double(total).toString();

this code works

Best Regular Expression for Email Validation in C#

Email Validation Regex

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+.)+[a-z]{2,5}$

Or

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+[.])+[a-z]{2,5}$

Demo Link:

https://regex101.com/r/kN4nJ0/53

Position absolute but relative to parent

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 0;
}

#son2 {
   position: absolute;
   bottom: 0;
}

This works because position: absolute means something like "use top, right, bottom, left to position yourself in relation to the nearest ancestor who has position: absolute or position: relative."

So we make #father have position: relative, and the children have position: absolute, then use top and bottom to position the children.

How to rename a file using Python

import os
import re
from pathlib import Path

for f in os.listdir(training_data_dir2):
  for file in os.listdir( training_data_dir2 + '/' + f):
    oldfile= Path(training_data_dir2 + '/' + f + '/' + file)
    newfile = Path(training_data_dir2 + '/' + f + '/' + file[49:])
    p=oldfile
    p.rename(newfile)

Insert ellipsis (...) into HTML tag if content too wide

The following CSS only solution for truncating text on a single line works with all browers listed at http://www.caniuse.com as of writing with the exception of Firefox 6.0. Note that JavaScript is totally unnecessary unless you need to support wrapping multiline text or earlier versions of Firefox.

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
}

If you need support for earlier versions of Firefox check out my answer on this other question.

What is a Memory Heap?

It's a chunk of memory allocated from the operating system by the memory manager in use by a process. Calls to malloc() et alia then take memory from this heap instead of having to deal with the operating system directly.

npm install vs. update - what's the difference?

Many distinctions have already been mentioned. Here is one more:

Running npm install at the top of your source directory will run various scripts: prepublish, preinstall, install, postinstall. Depending on what these scripts do, a npm install may do considerably more work than just installing dependencies.

I've just had a use case where prepublish would call make and the Makefile was designed to fetch dependencies if the package.json got updated. Calling npm install from within the Makefile would have lead to an infinite recursion, while calling npm update worked just fine, installing all dependencies so that the build could proceed even if make was called directly.

IIS_IUSRS and IUSR permissions in IIS8

IIS_IUSRS group has prominence only if you are using ApplicationPool Identity. Even though you have this group looks empty at run time IIS adds to this group to run a worker process according to microsoft literature.

Can I give a default value to parameters or optional parameters in C# functions?

This functionality is available from C# 4.0 - it was introduced in Visual Studio 2010. And you can use it in project for .NET 3.5. So there is no need to upgrade old projects in .NET 3.5 to .NET 4.0.

You have to just use Visual Studio 2010, but remember that it should compile to default language version (set it in project Properties->Buid->Advanced...)

This MSDN page has more information about optional parameters in VS 2010.

How do I install pip on macOS or OS X?

I recommend Anaconda to you. It's the leading open data science platform powered by Python. There are many basic packages installed. Anaconda (conda) comes with its own installation of pip.

What is the equivalent of the C++ Pair<L,R> in Java?

Collections.singletonMap(left, rigth);

Pick images of root folder from sub-folder

when you upload your files to the server be careful ,some tomes your images will not appear on the web page and a crashed icon will appear that means your file path is not properly arranged or coded when you have the the following file structure the code should be like this File structure: ->web(main folder) ->images(subfolder)->logo.png(image in the sub folder)the code for the above is below follow this standard

 <img src="../images/logo.jpg" alt="image1" width="50px" height="50px">

if you uploaded your files to the web server by neglecting the file structure with out creating the folder web if you directly upload the files then your images will be broken you can't see images,then change the code as following

 <img src="images/logo.jpg" alt="image1" width="50px" height="50px">

thank you->vamshi krishnan

ASP.NET Bundles how to disable minification

This may become useful to someone in the future as the new framework, when setup through VS, gets a default web.config, web.Debug.config and web.Release.config. In the web.release.config you will find this line:

<compilation xdt:Transform="RemoveAttributes(debug)" />

this was seeming to override any inline changes I made. I commented this line out and we were gravy (in terms of seeing non-minified code in a "release" build)

Check if string ends with certain pattern

I tried all the different things mentioned here to get the index of the . character in a filename that ends with .[0-9][0-9]*, e.g. srcfile.1, srcfile.12, etc. Nothing worked. Finally, the following worked: int dotIndex = inputfilename.lastIndexOf(".");

Weird! This is with java -version:

openjdk version "1.8.0_131"
OpenJDK Runtime Environment (build 1.8.0_131-8u131-b11-0ubuntu1.16.10.2-b11)
OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)

Also, the official Java doc page for regex (from which there is a quote in one of the answers above) does not seem to specify how to look for the . character. Because \., \\., and [.] did not work for me, and I don't see any other options specified apart from these.

How do I format a number in Java?

As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).

Use Spring's Numberformatter instead, which is thread safe.

npm ERR! Error: EPERM: operation not permitted, rename

Running commands as Super Admin worked for me. Retry after closing Editor your are working in.

onCreateOptionsMenu inside Fragments

try this,

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_sample, menu);
    super.onCreateOptionsMenu(menu,inflater);
}

Finally, in onCreateView method, add this line to make the options appear in your Toolbar

setHasOptionsMenu(true);

Right HTTP status code to wrong input

409 Conflict could be an acceptable solution.

According to: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

The doc continues with an example:

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.


In my case, I would like to PUT a string, that must be unique, to a database via an API. Before adding it to the database, I am checking that it is not already in the database.

If it is, I will return "Error: The string is already in the database", 409.

I believe this is what the OP wanted: an error code suitable for when the data does not pass the server's criteria.

Append lines to a file using a StreamWriter

Try this:

StreamWriter file2 = new StreamWriter(@"c:\file.txt", true);
file2.WriteLine(someString);
file2.Close();

jQuery Combobox/select autocomplete?

[edit] The lovely chosen jQuery plugin has been bought to my attention, looks like a great alternative to me.

Or if you just want to use jQuery autocomplete, I've extended the combobox example to support defaults and remove the tooltips to give what I think is more expected behaviour. Try it out.

(function ($) {
    $.widget("ui.combobox", {
        _create: function () {
            var input,
              that = this,
              wasOpen = false,
              select = this.element.hide(),
              selected = select.children(":selected"),
              defaultValue = selected.text() || "",
              wrapper = this.wrapper = $("<span>")
                .addClass("ui-combobox")
                .insertAfter(select);

            function removeIfInvalid(element) {
                var value = $(element).val(),
                  matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(value) + "$", "i"),
                  valid = false;
                select.children("option").each(function () {
                    if ($(this).text().match(matcher)) {
                        this.selected = valid = true;
                        return false;
                    }
                });

                if (!valid) {
                    // remove invalid value, as it didn't match anything
                    $(element).val(defaultValue);
                    select.val(defaultValue);
                    input.data("ui-autocomplete").term = "";
                }
            }

            input = $("<input>")
              .appendTo(wrapper)
              .val(defaultValue)
              .attr("title", "")
              .addClass("ui-state-default ui-combobox-input")
              .width(select.width())
              .autocomplete({
                  delay: 0,
                  minLength: 0,
                  autoFocus: true,
                  source: function (request, response) {
                      var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                      response(select.children("option").map(function () {
                          var text = $(this).text();
                          if (this.value && (!request.term || matcher.test(text)))
                              return {
                                  label: text.replace(
                                    new RegExp(
                                      "(?![^&;]+;)(?!<[^<>]*)(" +
                                      $.ui.autocomplete.escapeRegex(request.term) +
                                      ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                    ), "<strong>$1</strong>"),
                                  value: text,
                                  option: this
                              };
                      }));
                  },
                  select: function (event, ui) {
                      ui.item.option.selected = true;
                      that._trigger("selected", event, {
                          item: ui.item.option
                      });
                  },
                  change: function (event, ui) {
                      if (!ui.item) {
                          removeIfInvalid(this);
                      }
                  }
              })
              .addClass("ui-widget ui-widget-content ui-corner-left");

            input.data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>")
                  .append("<a>" + item.label + "</a>")
                  .appendTo(ul);
            };

            $("<a>")
              .attr("tabIndex", -1)
              .appendTo(wrapper)
              .button({
                  icons: {
                      primary: "ui-icon-triangle-1-s"
                  },
                  text: false
              })
              .removeClass("ui-corner-all")
              .addClass("ui-corner-right ui-combobox-toggle")
              .mousedown(function () {
                  wasOpen = input.autocomplete("widget").is(":visible");
              })
              .click(function () {
                  input.focus();

                  // close if already visible
                  if (wasOpen) {
                      return;
                  }

                  // pass empty string as value to search for, displaying all results
                  input.autocomplete("search", "");
              });
        },

        _destroy: function () {
            this.wrapper.remove();
            this.element.show();
        }
    });
})(jQuery);

How do I open the "front camera" on the Android platform?

For API 21 (5.0) and later you can use the CameraManager API's

try {
    String desiredCameraId = null;
    for(String cameraId : mCameraIDsList) {
        CameraCharacteristics chars =  mCameraManager.getCameraCharacteristics(cameraId);
        List<CameraCharacteristics.Key<?>> keys = chars.getKeys();
        try {
            if(CameraCharacteristics.LENS_FACING_FRONT == chars.get(CameraCharacteristics.LENS_FACING)) {
               // This is the one we want.
               desiredCameraId = cameraId;
               break;
            }
        } catch(IllegalArgumentException e) {
            // This key not implemented, which is a bit of a pain. Either guess - assume the first one
            // is rear, second one is front, or give up.
        }
    }
}

Command for restarting all running docker containers?

To start multiple containers with the only particular container id's $ docker restart contianer-id1 container-id2 container-id3 ...

How to use a client certificate to authenticate and authorize in a Web API

Make sure HttpClient has access to the full client certificate (including the private key).

You are calling GetCert with a file "ClientCertificate.cer" which leads to the assumption that there is no private key contained - should rather be a pfx file within windows. It may be even better to access the certificate from the windows cert store and search it using the fingerprint.

Be careful when copying the fingerprint: There are some non-printable characters when viewing in cert management (copy the string over to notepad++ and check the length of the displayed string).

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

You have to add this permission in Info.plist for iOS 10.

Photo :

Key       :  Privacy - Photo Library Usage Description    
Value   :  $(PRODUCT_NAME) photo use

Microphone :

Key        :  Privacy - Microphone Usage Description    
Value    :  $(PRODUCT_NAME) microphone use

Camera :

Key       :  Privacy - Camera Usage Description   
Value   :  $(PRODUCT_NAME) camera use

How to change current working directory using a batch file

Try this

chdir /d D:\Work\Root

Enjoy rooting ;)

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

How to enable local network users to access my WAMP sites?

go to... 
C:\wamp\alias

Inside alias folder you will see some files like phpmyadmin,phpsysinfo,etc...

open each file, and you can see inside file some commented instruction are give to access from outside ,like to give access to phpmyadmin from outside replace the lines

Require local

by

Require all granted

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I think you should make a subquery to do grouping. In this case inner subquery returns few rows and you don't need a CASE statement. So I think this is going to be faster:

select Detail.ReceiptDate AS 'DATE',
       SUM(TotalMailed),
       SUM(TotalReturnMail),
       SUM(TraceReturnedMail)

from
(

select SentDate AS 'ReceiptDate', 
       count('TotalMailed') AS TotalMailed, 
       0 as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract
where sentdate is not null
GROUP BY SentDate

UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       count(TotalReturnMail) as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract MDE
where MDE.ReturnMailDate is not null
GROUP BY  MDE.ReturnMailDate

UNION ALL

select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       0 as TotalReturnMail, 
       count(TraceReturnedMail) as TraceReturnedMail

from MailDataExtract MDE
    inner join DTSharedData.dbo.ScanData SD 
        ON SD.ScanDataID = MDE.ReturnScanDataID
   where MDE.ReturnMailDate is not null AND SD.ReturnMailTypeID = 1
GROUP BY MDE.ReturnMailDate

) as Detail
GROUP BY Detail.ReceiptDate
ORDER BY 1

plot legends without border and with white background

Use option bty = "n" in legend to remove the box around the legend. For example:

legend(1, 5,
       "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
       bty = "n")

Get refresh token google api

Found out by adding this to your url parameters

approval_prompt=force

Update:

Use access_type=offline&prompt=consent instead.

approval_prompt=force no longer works https://github.com/googleapis/oauth2client/issues/453

Mongoose, update values in array of objects

There is a mongoose way for doing it.

const itemId = 2;
const query = {
  item._id: itemId 
};
Person.findOne(query).then(doc => {
  item = doc.items.id(itemId );
  item["name"] = "new name";
  item["value"] = "new value";
  doc.save();

  //sent respnse to client
}).catch(err => {
  console.log('Oh! Dark')
});

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

How to display a jpg file in Python?

from PIL import Image

image = Image.open('File.jpg')
image.show()

What is the maximum characters for the NVARCHAR(MAX)?

From MSDN Documentation

nvarchar [ ( n | max ) ]

Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size, in bytes, is two times the actual length of data entered + 2 bytes

Updating records codeigniter

How to update in codeignitor?

whenever you want to update same status with multiple rows you use where_in insteam of where or if you want to change only single record can use where.

below is my code

$conditionArray = array(1, 3, 4, 6);
$this->db->where_in("ip_id", $conditionArray);
$this->db->update($this->table, array("status" => 'active'));

its working perfect.

How do I display the current value of an Android Preference in the Preference summary?

Here is my solution... FWIW

package com.example.PrefTest;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;

public class Preferences extends PreferenceActivity implements
        OnSharedPreferenceChangeListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        PreferenceManager.setDefaultValues(Preferences.this, R.xml.preferences,
            false);
        initSummary(getPreferenceScreen());
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Set up a listener whenever a key changes
        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Unregister the listener whenever a key changes
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
        updatePrefSummary(findPreference(key));
    }

    private void initSummary(Preference p) {
        if (p instanceof PreferenceGroup) {
            PreferenceGroup pGrp = (PreferenceGroup) p;
            for (int i = 0; i < pGrp.getPreferenceCount(); i++) {
                initSummary(pGrp.getPreference(i));
            }
        } else {
            updatePrefSummary(p);
        }
    }

    private void updatePrefSummary(Preference p) {
        if (p instanceof ListPreference) {
            ListPreference listPref = (ListPreference) p;
            p.setSummary(listPref.getEntry());
        }
        if (p instanceof EditTextPreference) {
            EditTextPreference editTextPref = (EditTextPreference) p;
            if (p.getTitle().toString().toLowerCase().contains("password"))
            {
                p.setSummary("******");
            } else {
                p.setSummary(editTextPref.getText());
            }
        }
        if (p instanceof MultiSelectListPreference) {
            EditTextPreference editTextPref = (EditTextPreference) p;
            p.setSummary(editTextPref.getText());
        }
    }
}

How to recover closed output window in netbeans?

If you want to see three windows along with Log Then go to windows on NetBeans then output and click NetBeans->windows->output. Next go to service next to you project select server right click on it select server log and server output NetBeans->service(next to you project)->server->View server log and view service output.

Print new output on same line

Lets take an example where you want to print numbers from 0 to n in the same line. You can do this with the help of following code.

n=int(raw_input())
i=0
while(i<n):
    print i,
    i = i+1

At input, n = 5

Output : 0 1 2 3 4 

Spring Boot - Loading Initial Data

As suggestion try this:

@Bean
public CommandLineRunner loadData(CustomerRepository repository) {
    return (args) -> {
        // save a couple of customers
        repository.save(new Customer("Jack", "Bauer"));
        repository.save(new Customer("Chloe", "O'Brian"));
        repository.save(new Customer("Kim", "Bauer"));
        repository.save(new Customer("David", "Palmer"));
        repository.save(new Customer("Michelle", "Dessler"));

        // fetch all customers
        log.info("Customers found with findAll():");
        log.info("-------------------------------");
        for (Customer customer : repository.findAll()) {
            log.info(customer.toString());
        }
        log.info("");

        // fetch an individual customer by ID
        Customer customer = repository.findOne(1L);
        log.info("Customer found with findOne(1L):");
        log.info("--------------------------------");
        log.info(customer.toString());
        log.info("");

        // fetch customers by last name
        log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
        log.info("--------------------------------------------");
        for (Customer bauer : repository
                .findByLastNameStartsWithIgnoreCase("Bauer")) {
            log.info(bauer.toString());
        }
        log.info("");
    }
}

Option 2: Initialize with schema and data scripts

Prerequisites: in application.properties you have to mention this:

spring.jpa.hibernate.ddl-auto=none (otherwise scripts will be ignored by hibernate, and it will scan project for @Entity and/or @Table annotated classes)

Then, in your MyApplication class paste this:

@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUrl("jdbc:h2:~/myDB;MV_STORE=false");
    dataSource.setUsername("sa");
    dataSource.setPassword("");

    // schema init
    Resource initSchema = new ClassPathResource("scripts/schema-h2.sql");
    Resource initData = new ClassPathResource("scripts/data-h2.sql");
    DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
    DatabasePopulatorUtils.execute(databasePopulator, dataSource);

    return dataSource;
}

Where scripts folder is located under resources folder (IntelliJ Idea)

Hope it helps someone

jQuery textbox change event

The HTML4 spec for the <input> element specifies the following script events are available:

onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

here's an example that bind's to all these events and shows what's going on http://jsfiddle.net/pxfunc/zJ7Lf/

I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

JSONObject obj=(JSONObject)JSONValue.parse(content); 
JSONArray arr=(JSONArray)obj.get("units"); 
System.out.println(arr.get(1));  //this will print {"id":42,...sities ..}

@cyberz is right but explain it reverse

Guzzlehttp - How get the body of a response from Guzzle 6?

Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator:

$contents = (string) $response->getBody();

You can also do it with

$contents = $response->getBody()->getContents();

The difference between the two approaches is that getContents returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewind or seek .

$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents

Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.

$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents

Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses

Any way to break if statement in PHP?

You could use a do-while(false):

    <?php
    do if ($foo)
    {
      // Do something first...

      // Shall we continue with this block, or exit now?
      if ($abort_if_block) break;

      // Continue doing something...

    } while (false);
    ?>

as described in http://php.net/manual/en/control-structures.if.php#90073

Sending POST parameters with Postman doesn't work, but sending GET parameters does

For me, the server was expect HTTPS requests, but I didn't specify that in the URL. The hook would reach the server, but the body would be empty.

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

SQL Query for Selecting Multiple Records

You can try this
SELECT * FROM Buses WHERE BusID in (1,2,3,4,...)

Most pythonic way to delete a file which may not exist

This is another solution:

if os.path.isfile(os.path.join(path, filename)):
    os.remove(os.path.join(path, filename))

Default values for Vue component props & how to check if a user did not set the prop?

Vue allows for you to specify a default prop value and type directly, by making props an object (see: https://vuejs.org/guide/components.html#Prop-Validation):

props: {
  year: {
    default: 2016,
    type: Number
  }
}

If the wrong type is passed then it throws an error and logs it in the console, here's the fiddle:

https://jsfiddle.net/cexbqe2q/

Is there an effective tool to convert C# code to Java code?

C# has a few more features than Java. Take delegates for example: Many very simple C# applications use delegates, while the Java folks figures that the observer pattern was sufficient. So, in order for a tool to convert a C# application which uses delegates it would have to translate the structure from using delegates to an implementation of the observer pattern. Another problem is the fact that C# methods are not virtual by default while Java methods are. Additionally, Java doesn't have a way to make methods non virtual. This creates another problem: an application in C# could leverage non virtual method behavior through polymorphism in a way the does not translate directly to Java. If you look around you will probably find that there are lots of tools to convert Java to C# since it is a simpler language (please don't flame me I didn't say worse I said simpler); however, you will find very few if any decent tools that convert C# to Java.

I would recommend changing your approach to converting from Java to C# as it will create fewer headaches in the long run. Db4Objects recently released their internal tool which they use to convert Db4o into C# to the public. It is called Sharpen. If you register with their site you can view this link with instructions on how to use Sharpen: http://developer.db4o.com/Resources/view.aspx/Reference/Sharpen/How_To_Setup_Sharpen

(I've been registered with them for a while and they're good about not spamming)

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

How to set socket timeout in C when making multiple connections?

connect timeout has to be handled with a non-blocking socket (GNU LibC documentation on connect). You get connect to return immediately and then use select to wait with a timeout for the connection to complete.

This is also explained here : Operation now in progress error on connect( function) error.

int wait_on_sock(int sock, long timeout, int r, int w)
{
    struct timeval tv = {0,0};
    fd_set fdset;
    fd_set *rfds, *wfds;
    int n, so_error;
    unsigned so_len;

    FD_ZERO (&fdset);
    FD_SET  (sock, &fdset);
    tv.tv_sec = timeout;
    tv.tv_usec = 0;

    TRACES ("wait in progress tv={%ld,%ld} ...\n",
            tv.tv_sec, tv.tv_usec);

    if (r) rfds = &fdset; else rfds = NULL;
    if (w) wfds = &fdset; else wfds = NULL;

    TEMP_FAILURE_RETRY (n = select (sock+1, rfds, wfds, NULL, &tv));
    switch (n) {
    case 0:
        ERROR ("wait timed out\n");
        return -errno;
    case -1:
        ERROR_SYS ("error during wait\n");
        return -errno;
    default:
        // select tell us that sock is ready, test it
        so_len = sizeof(so_error);
        so_error = 0;
        getsockopt (sock, SOL_SOCKET, SO_ERROR, &so_error, &so_len);
        if (so_error == 0)
            return 0;
        errno = so_error;
        ERROR_SYS ("wait failed\n");
        return -errno;
    }
}

Is it possible to reference one CSS rule within another?

You can't unless you're using some kind of extended CSS such as SASS. However it is very reasonable to apply those two extra classes to .someDiv.

If .someDiv is unique I would also choose to give it an id and referencing it in css using the id.

Serialize form data to JSON

Using jQuery and avoiding serializeArray, the following code serializes and sends the form data in JSON format:

$("#commentsForm").submit(function(event){
    var formJqObj = $("#commentsForm");
    var formDataObj = {};
    (function(){
        formJqObj.find(":input").not("[type='submit']").not("[type='reset']").each(function(){
            var thisInput = $(this);
            formDataObj[thisInput.attr("name")] = thisInput.val();
        });
    })();
    $.ajax({
        type: "POST",
        url: YOUR_URL_HERE,
        data: JSON.stringify(formDataObj),
        contentType: "application/json"
    })
    .done(function(data, textStatus, jqXHR){
        console.log("Ajax completed: " + data);
    })
    .fail(function(jqXHR, textStatus, errorThrown){
        console.log("Ajax problem: " + textStatus + ". " + errorThrown);
    });
    event.preventDefault();
});

How to break a while loop from an if condition inside the while loop?

while(something.hasnext())
do something...
   if(contains something to process){
      do something...
      break;
   }
}

Just use the break statement;

For eg:this just prints "Breaking..."

while (true) {
     if (true) {
         System.out.println("Breaking...");
         break;
     }
     System.out.println("Did this print?");
}

How to correctly use the ASP.NET FileUpload control

I have noticed that when intellisence doesn't work for an object there is usually an error somewhere in the class above line you are working on.

The other option is that you didn't instantiated the FileUpload object as an instance variable. make sure the code:

FileUpload fileUpload = new FileUpload();

is not inside a function in your code behind.

Gradle proxy configuration

In case my I try to set up proxy from android studio Appearance & Behaviour => System Settings => HTTP Proxy. But the proxy did not worked out so I click no proxy.

Checking NO PROXY will not remove the proxy setting from the gradle.properties(Global). You need to manually remove it.

So I remove all the properties starting with systemProp for example - systemProp.http.nonProxyHosts=*.local, localhost

What is the difference between concurrent programming and parallel programming?

Concurrent programming regards operations that appear to overlap and is primarily concerned with the complexity that arises due to non-deterministic control flow. The quantitative costs associated with concurrent programs are typically both throughput and latency. Concurrent programs are often IO bound but not always, e.g. concurrent garbage collectors are entirely on-CPU. The pedagogical example of a concurrent program is a web crawler. This program initiates requests for web pages and accepts the responses concurrently as the results of the downloads become available, accumulating a set of pages that have already been visited. Control flow is non-deterministic because the responses are not necessarily received in the same order each time the program is run. This characteristic can make it very hard to debug concurrent programs. Some applications are fundamentally concurrent, e.g. web servers must handle client connections concurrently. Erlang, F# asynchronous workflows and Scala's Akka library are perhaps the most promising approaches to highly concurrent programming.

Multicore programming is a special case of parallel programming. Parallel programming concerns operations that are overlapped for the specific goal of improving throughput. The difficulties of concurrent programming are evaded by making control flow deterministic. Typically, programs spawn sets of child tasks that run in parallel and the parent task only continues once every subtask has finished. This makes parallel programs much easier to debug than concurrent programs. The hard part of parallel programming is performance optimization with respect to issues such as granularity and communication. The latter is still an issue in the context of multicores because there is a considerable cost associated with transferring data from one cache to another. Dense matrix-matrix multiply is a pedagogical example of parallel programming and it can be solved efficiently by using Straasen's divide-and-conquer algorithm and attacking the sub-problems in parallel. Cilk is perhaps the most promising approach for high-performance parallel programming on multicores and it has been adopted in both Intel's Threaded Building Blocks and Microsoft's Task Parallel Library (in .NET 4).

Is there an easy way to reload css without reloading the page?

Based on previous solutions, I have created bookmark with JavaScript code:

javascript: { var toAppend = "trvhpqi=" + (new Date()).getTime(); var links = document.getElementsByTagName("link"); for (var i = 0; i < links.length;i++) { var link = links[i]; if (link.rel === "stylesheet") { if (link.href.indexOf("?") === -1) { link.href += "?" + toAppend; } else { if (link.href.indexOf("trvhpqi") === -1) { link.href += "&" + toAppend; } else { link.href = link.href.replace(/trvhpqi=\d{13}/, toAppend)} }; } } }; void(0);

Image from Firefox:

enter image description here

What does it do?

It reloads CSS by adding query string params (as solutions above):

adb shell su works but adb root does not

I have a rooted Samsung Galaxy Trend Plus (GT-S7580).

Running 'adb root' gives me the same 'adbd cannot run as root in production builds' error.

For devices that have Developer Options -> Root access, choose "ADB only" to provide adb root access to the device (as suggested by NgaNguyenDuy).

Then try to run the command as per the solution at Launch a script as root through ADB. In my case, I just wanted to run the 'netcfg rndis0 dhcp' command, and I did it this way:

adb shell "su -c netcfg rndis0 dhcp"

Please check whether you are making any mistakes while running it this way.

If it still does not work, check whether you rooted the device correctly. If still no luck, try installing a custom ROM such as Cyanogen Mod in order for 'adb root' to work.

CSS: how to add white space before element's content?

Don't fart around with inserting spaces. For one, older versions of IE won't know what you're talking about. Besides that, though, there are cleaner ways in general.

For colorless indents, use the text-indent property.

p { text-indent: 1em; }

JSFiddle demo

Edit:

If you want the space to be colored, you might consider adding a thick left border to the first letter. (I'd almost-but-not-quite say "instead", because the indent can be an issue if you use both. But it feels dirty to me to rely solely on the border to indent.) You can specify how far away, and how wide, the color is using the first letter's left margin/padding/border width.

p:first-letter { border-left: 1em solid red; }

Demo

Jupyter notebook not running code. Stuck on In [*]

I have fix for this issue,

example if you are assigning some values to DataFrame

[*] symbol has shown this because of the script running

to see the outout of the script have to mention df like this, output

How to set null to a GUID property

You can use typeof(Guid), "00000000-0000-0000-0000-000000000000" for DefaultValue of the property.

What is Bootstrap?

By today's standards and web terminology, I'd say Bootstrap is actually not a framework, although that's what their website claims. Most developers consider Angular, Vue and React frameworks, while Bootstrap is commonly referred to as a "library".

But, to be exact and correct, Bootstrap is an open-source, mobile-first collection of CSS, JavaScript and HTML design utilities aimed at providing means to develop commonly used web elements considerably faster (and smarter) than having to code them from scratch.

A few core principles which contributed to Bootstrap's success:

  • it's reusable
  • it's flexible (i.e: allows custom grid systems, changing responsiveness breakpoints, column gutter sizes or state colors with ease; as a rule of thumb, most settings are controlled by global variables)
  • it's intuitive
  • it's modular (both JavaScript and (S)CSS use a modular approach; one can easily find tutorials on making custom Bootstrap builds, to include only the parts they need)
  • has above average cross-browser compatibility
  • web accessibility out of the box (screenreader ready)
  • it's fairly well documented

It contains design templates and functionality for: layout, typography, forms, navigation, menus (including dropdowns), buttons, panels, badges, modals, alerts, tabs, collapsible, accordions, carousels, lists, tables, pagination, media utilities (including embeds, images and image replacement), responsiveness utilities, color-based utilities (primary, secondary, danger, warning, info, light, dark, muted, white), other utilities (position, margin, padding, sizing, spacing, alignment, visibility), scrollspy, affix, tooltips, popovers.


By default it relies on jQuery, but you'll find jQuery free variants powered by each of the modern popular progressive JavaScript frameworks:

Working with Bootstrap relies heavily on applying certain classes (or, depending on JS framework: directives, methods or attributes/props) and on using particular markup structures.

Documentation typically contains generic examples which can be easily copy-pasted and used as starter templates.


Another advantage of developing with Bootstrap is its vibrant community, translated into an abundance of themes, templates and plugins available for it, most of which are open-source (i.e: calendars, date/time-pickers, plugins for tabular content management, as well as libraries/component collections built on top of Bootstrap, such as MDB, portfolio templates, admin templates, etc...)

Last, but not least, Bootstrap has been well maintained over the years, which makes it a solid choice for production-ready applications/websites.

Applications are expected to have a root view controller at the end of application launch

I was getting this error (Applications are expected to have a root view controller at the end of application launch), and I was creating the view controllers programmatically.

Solved it by ensuring the loadView method in my root view controller was calling [super loadView].

DateTime.MinValue and SqlDateTime overflow

use extensions

public static class DateTimeExtensions
{
    public static DateTime MinValue(this DateTime sqlDateTime)
    {
        return new DateTime(1900, 01, 01, 00, 00, 00);
    }
}


DateTime date = DateTime.Now;
Console.WriteLine("Minvalue is {0} ", date.MinValue().ToShortDateString());

How to test the `Mosquitto` server?

In separate terminal windows do the following:

  1. Start the broker:

    mosquitto
    
  2. Start the command line subscriber:

    mosquitto_sub -v -t 'test/topic'
    
  3. Publish test message with the command line publisher:

    mosquitto_pub -t 'test/topic' -m 'helloWorld'
    

As well as seeing both the subscriber and publisher connection messages in the broker terminal the following should be printed in the subscriber terminal:

test/topic helloWorld

Adding Counter in shell script

You may do this with a for loop instead of a while:

max_loop=20
for ((count = 0; count < max_loop; count++)); do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  else
       echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

if [ "$count" -eq "$max_loop" ]; then
  echo "Maximum number of trials reached" >&2
  exit 1
fi

Swapping pointers in C (char, int)

If you have the luxury of working in C++, use this:

template<typename T>
void swapPrimitives(T& a, T& b)
{
    T c = a;
    a = b;
    b = c;
}

Granted, in the case of char*, it would only swap the pointers themselves, not the data they point to, but in most cases, that is OK, right?