If you'd like to do this using the command line, you can do this if you have ESXi 6.0 (or possibly even ESXi 5.5) running, by using govc
, which is a very helpful utility for interacting with both your vCenter and its associated resources.
Depending on your setup, you can
# setup your credentials
export GOVC_USERNAME=YOUR_USERNAME GOVC_PASSWORD=YOUR_PASSWORD
govc export.ovf -u your-vcsa-url.example.com -vm VM_NAME -dc VMS_DATACENTER export-folder
Then, you'll have your VM VM_NAME
exported in the folder export-folder
. From there, you can then
govc import.ovf -u your-other-vcsa-url.example.com -vm NEW_VM_NAME -dc NEW_DATACENTER export-folder/VM_NAME.ovf
That'll import it into your other vCenter. You might have to specify -ds NEW_DATASTORE
too, if you have more than one datastore available, but govc
will tell you so if you need to.
The commands above require that govc
is installed, which you should, because it's far better than ovftool
either way.
I’ve found that in order to properly delete the old history from the new repository, you have to do a little more work after the filter-branch
step.
Do the clone and the filter:
git clone --no-hardlinks foo bar; cd bar
git filter-branch --subdirectory-filter subdir/you/want
Remove every reference to the old history. “origin” was keeping track of your clone, and “original” is where filter-branch saves the old stuff:
git remote rm origin
git update-ref -d refs/original/refs/heads/master
git reflog expire --expire=now --all
Even now, your history might be stuck in a packfile that fsck won’t touch. Tear it to shreds, creating a new packfile and deleting the unused objects:
git repack -ad
There is an explanation of this in the manual for filter-branch.
Weston Ruther built a similar thing using the WebKit proposal for css transitions:
http://weston.ruter.net/projects/jquery-css-transitions/
This implementation might be useful for you.
The accepted answer gives me this output
# bash date.sh
Time in seconds: 51
date.sh: line 12: unexpected EOF while looking for matching `"'
date.sh: line 21: syntax error: unexpected end of file
This is how I solved the issue
#!/bin/bash
date1=$(date --date 'now' +%s) #date since epoch in seconds at the start of script
somecommand
date2=$(date --date 'now' +%s) #date since epoch in seconds at the end of script
difference=$(echo "$((date2-$date1))") # difference between two values
date3=$(echo "scale=2 ; $difference/3600" | bc) # difference/3600 = seconds in hours
echo SCRIPT TOOK $date3 HRS TO COMPLETE # 3rd variable for a pretty output.
rem set defaults:
set filename1="c:\file1.txt"
set filename2="c:\file2.txt"
set filename3="c:\file3.txt"
rem set parameters:
IF NOT "a%1"=="a" (set filename1="%1")
IF NOT "a%2"=="a" (set filename2="%2")
IF NOT "a%3"=="a" (set filename1="%3")
echo %filename1%, %filename2%, %filename3%
Be careful with quotation characters though, you may or may not need them in your variables.
You should really use the Literal ASP.NET control for that.
If the path in Ubuntu is "/home/ec2-user/Name of Directory", then do this:
1) Java's build.properties file:
build_path='/home/ec2-user/Name\\ of\\ Directory'
Where ~/
is equal to /home/ec2-user
2) Jenkinsfile:
build_path=buildprops['build_path']
echo "Build path= ${build_path}"
sh "cd ${build_path}"
xlim
and ylim
don't cut it here. You need to use expand_limits
, scale_x_continuous
, and scale_y_continuous
. Try:
df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for
p + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))
You may need to adjust things a little to make sure points are not getting cut off (see, for example, the point at x = 5
and y = 5
.
You can use text-align: center; line-height: 65px;
CSS
.loginBtn {
background:url(images/loginBtn-center.jpg) repeat-x;
width:175px;
height:65px;
margin:20px auto;
border-radius:10px;
-webkit-border-radius:10px;
box-shadow:0 1px 2px #5e5d5b;
text-align: center; <--------- Here
line-height: 65px; <--------- Here
}
I used PDFiumSharp and ImageSharp in a .NET Standard 2.1 class library.
/// <summary>
/// Saves a thumbnail (jpg) to the same folder as the PDF file, using dimensions 300x423,
/// which corresponds to the aspect ratio of 'A' paper sizes like A4 (ratio h/w=sqrt(2))
/// </summary>
/// <param name="pdfPath">Source path of the pdf file.</param>
/// <param name="thumbnailPath">Target path of the thumbnail file.</param>
/// <param name="width"></param>
/// <param name="height"></param>
public static void SaveThumbnail(string pdfPath, string thumbnailPath = "", int width = 300, int height = 423)
{
using var pdfDocument = new PdfDocument(pdfPath);
var firstPage = pdfDocument.Pages[0];
using var pageBitmap = new PDFiumBitmap(width, height, true);
firstPage.Render(pageBitmap);
var imageJpgPath = string.IsNullOrWhiteSpace(thumbnailPath)
? Path.ChangeExtension(pdfPath, "jpg")
: thumbnailPath;
var image = Image.Load(pageBitmap.AsBmpStream());
// Set the background to white, otherwise it's black. https://github.com/SixLabors/ImageSharp/issues/355#issuecomment-333133991
image.Mutate(x => x.BackgroundColor(Rgba32.White));
image.Save(imageJpgPath, new JpegEncoder());
}
Updated answer for ES6+ is here.
arr = [1, 2, 3];
arr.forEach(function(i, idx, array){
if (idx === array.length - 1){
console.log("Last callback call at index " + idx + " with value " + i );
}
});
would output:
Last callback call at index 2 with value 3
The way this works is testing arr.length
against the current index of the array, passed to the callback function.
Try getting the client computer name in Mozilla Firefox by using the code given below.
netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
Also, the same piece of code can be put as an extension, and it can called from your web page.
Please find the sample code below.
Extension code:
var myExtension = {
myListener: function(evt) {
//netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
content.document.getElementById("compname").value = compName ;
}
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); //this event will raised from the webpage
Webpage Code:
<html>
<body onload = "load()">
<script>
function showcomp()
{
alert("your computer name is " + document.getElementById("compname").value);
}
function load()
{
//var element = document.createElement("MyExtensionDataElement");
//element.setAttribute("attribute1", "foobar");
//element.setAttribute("attribute2", "hello world");
//document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
//element.dispatchEvent(evt);
document.getElementById("compname").dispatchEvent(evt); //this raises the MyExtensionEvent event , which assigns the client computer name to the hidden variable.
}
</script>
<form name="login_form" id="login_form">
<input type = "text" name = "txtname" id = "txtnamee" tabindex = "1"/>
<input type="hidden" name="compname" value="" id = "compname" />
<input type = "button" onclick = "showcomp()" tabindex = "2"/>
</form>
</body>
</html>
layout.xml
<Button
android:id="@+id/buttonBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="finishActivity"
android:text="Back" />
Activity.java
public void finishActivity(View v){
finish();
}
Related:
thats simple
ren *.* *.jpg
try this in command prompt
In case you need to the use basic authorisation for your proxy provider, just use the following:
var http = require("http");
var options = {
host: FarmerAdapter.PROXY_HOST,
port: FarmerAdapter.PROXY_PORT,
path: requestedUrl,
headers: {
'Proxy-Authorization': 'Basic ' + new Buffer(FarmerAdapter.PROXY_USER + ':' + FarmerAdapter.PROXY_PASS).toString('base64')
}
};
var request = http.request(options, function(response) {
var chunks = [];
response.on('data', function(chunk) {
chunks.push(chunk);
});
response.on('end', function() {
console.log('Response', Buffer.concat(chunks).toString());
});
});
request.on('error', function(error) {
console.log(error.message);
});
request.end();
I just dragged the certificate into the "Trusted Root Certification Authorities" folder and voila everything worked nicely.
Oh. And I first added the following from a Administrator Command Prompt:
netsh http add urlacl url=https://+:8732/Servicename user=NT-MYNDIGHET\INTERAKTIV
I am not sure of the name you need for the user (mine is norwegian as you can see !):
user=NT-AUTHORITY/INTERACTIVE
?
You can see all existing urlacl's by issuing the command: netsh http show urlacl
I was annoyed that you had to always include the namespace and the folder in the string. I wanted to simplify the access to the embedded resources. This is why I wrote this little class. Feel free to use and improve!
Usage:
using(Stream stream = EmbeddedResources.ExecutingResources.GetStream("filename.txt"))
{
//...
}
Class:
public class EmbeddedResources
{
private static readonly Lazy<EmbeddedResources> _callingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetCallingAssembly()));
private static readonly Lazy<EmbeddedResources> _entryResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetEntryAssembly()));
private static readonly Lazy<EmbeddedResources> _executingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetExecutingAssembly()));
private readonly Assembly _assembly;
private readonly string[] _resources;
public EmbeddedResources(Assembly assembly)
{
_assembly = assembly;
_resources = assembly.GetManifestResourceNames();
}
public static EmbeddedResources CallingResources => _callingResources.Value;
public static EmbeddedResources EntryResources => _entryResources.Value;
public static EmbeddedResources ExecutingResources => _executingResources.Value;
public Stream GetStream(string resName) => _assembly.GetManifestResourceStream(_resources.Single(s => s.Contains(resName)));
}
You can use docker update --restart=on-failure <container ID or name>
.
On top of what the name suggests, on-failure
will not only restart the container on failure, but also at system boot.
Per the documentation, there are multiple restart options:
Flag Description
no Do not automatically restart the container. (the default)
on-failure Restart the container if it exits due to an error, which manifests as a non-zero exit code.
always Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details)
unless-stopped Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.
In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently
data = [...data, {"label": 2, "value": 13}]
Examples
var data = [_x000D_
{"label" : "1", "value" : 12},_x000D_
{"label" : "1", "value" : 12},_x000D_
{"label" : "1", "value" : 12},_x000D_
];_x000D_
_x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
For your case (i know it was in 2011), we can do it with map() & forEach() like below
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
2 more solutions I had luck with when neither tab close + reopening the page in another tab nor closing all tabs in Chrome (and the browser) then restarting it didn't work:
1) I fixed it on my machine by closing the tab, force-closing Chrome, & restarting the browser without restoring tabs (Note: on a computer running CentOS Linux).
2) My boss (also on CentOS) had the same issue (alerts are a big part of my company's Javascript debugging process for numerous reasons e.g. legacy), but my 1st method didn't work for him. However, I managed to fix it for him with the following process:
a) Make an empty text file called FixChrome.sh, and paste in the following bash script:
#! /bin/bash
cd ~/.config/google-chrome/Default //adjust for your Chrome install location
rm Preferences
rm 'Current Session'
rm 'Current Tabs'
rm 'Last Session'
rm 'Last Tabs'
b) close Chrome, then open Terminal and run the script (bash FixChrome.sh).
It worked for him. Downside is that you lose all tabs from your current & previous session, but it's worth it if this matters to you.
I think this log entry Local package.json exists, but node_modules missing, did you mean to install? has gave me the solution.
npm install && npm run dev
Here is a TypeScript version of @meseern's answer that avoids unnecessary assignments on re-render:
import React, { useState, useEffect } from 'react';
export function useContainerDimensions(myRef: React.RefObject<any>) {
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
useEffect(() => {
const getDimensions = () => ({
width: (myRef && myRef.current.offsetWidth) || 0,
height: (myRef && myRef.current.offsetHeight) || 0,
});
const handleResize = () => {
setDimensions(getDimensions());
};
if (myRef.current) {
setDimensions(getDimensions());
}
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [myRef]);
return dimensions;
}
sudo /opt/local/etc/LaunchDaemons/org.macports.mysql5/mysql5.wrapper stop
You can also use start and restart here. I found this by looking at the contents of /Library/LaunchDaemons/org.macports.mysql.plist.
This issue has been recently fixed (Nov 2010) by Google, see https://code.google.com/p/analytics-issues/issues/detail?id=671. But be aware that as a good fix it brings more bugs :)
You will also have to follow the initialisation method listed here: https://developers.google.com/analytics/devguides/collection/ios/v2.
The latest instructions are going to give you a headache because it references utilities not included in the pod. Below will fail with the cocoapod
// Configure tracker from GoogleService-Info.plist.
NSError *configureError;
[[GGLContext sharedInstance] configureWithError:&configureError];
NSAssert(!configureError, @"Error configuring Google services: %@", configureError);
Found the best way to do it for a server which does not support pkill
kill -9 $(ps ax | grep My_pattern| fgrep -v grep | awk '{ print $1 }')
You do not have to loop.
Declare a Flask endpoint to accept POST input type and then do necessary steps. Use jQuery to post the data.
from flask import request
@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data(data):
if request.method == "POST":
#perform action here
var value = $('.textbox').val();
$.ajax({
type: 'POST',
url: "{{ url_for('parse_data') }}",
data: JSON.stringify(value),
contentType: 'application/json',
success: function(data){
// do something with the received data
}
});
Recently I had to recover my pictures with the extension .jpg. I ran photorec and recovered 4579 directories 2.2 million files within, having tremendous variety of extensions.With the script below I was able to select 50133 files havin .jpg extension within minutes:
#!/usr/binenv python2.7
import glob
import shutil
import os
src_dir = "/home/mustafa/Masaüstü/yedek"
dst_dir = "/home/mustafa/Genel/media"
for mediafile in glob.iglob(os.path.join(src_dir, "*", "*.jpg")): #"*" is for subdirectory
shutil.copy(mediafile, dst_dir)
You wrote that format can change from YYYY-mm-dd to dd-mm-YYYY you can try to find year there
$parts = explode("-","2068-06-15");
for ($i = 0; $i < count($parts); $i++)
{
if(strlen($parts[$i]) == 4)
{
$year = $parts[$i];
break;
}
}
Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.
[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
In above JSON data, you are showing that we have an array contaning the number of dictionaries.
You need to use this code for parsing it:
NSError *e = nil;
NSArray *JSONarray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
for(int i=0;i<[JSONarray count];i++)
{
NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"id"]);
NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"name"]);
}
For swift 3/3+
//Pass The response data & get the Array
let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [AnyObject]
print(jsonData)
// considering we are going to get array of dictionary from url
for item in jsonData {
let dictInfo = item as! [String:AnyObject]
print(dictInfo["id"])
print(dictInfo["name"])
}
I encountered this error message while trying to install varnish cache on ubuntu. The google search landed me here for the error
(23) Failed writing body
, hence posting a solution that worked for me.
The bug is encountered while running the command as root curl -L https://packagecloud.io/varnishcache/varnish5/gpgkey | apt-key add -
the solution is to run apt-key add
as non root
curl -L https://packagecloud.io/varnishcache/varnish5/gpgkey | apt-key add -
If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:
function formSubmit(house_number)
{
document.forms[0].house_number.value = house_number;
document.forms[0].submit();
}
Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this:
<form action="house.php" method="POST">
<input type="hidden" name="house_number" value="-1">
<?php
foreach ($houses as $id => name)
{
echo "<a href=\"javascript:formSubmit($id);\">$name</a>\n";
}
?>
</form>
That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavasScript submits the form.
You must realize what options Jackson has available for deserialization. In Java, method argument names are not present in the compiled code. That's why Jackson can't generally use constructors to create a well-defined object with everything already set.
So, if there is an empty constructor and there are also setters, it uses the empty constructor and setters. If there are no setters, some dark magic (reflections) is used to do it.
If you want to use a constructor with Jackson, you must use the annotations as mentioned by @PiersyP in his answer. You can also use a builder pattern. If you encounter some exceptions, good luck. Error handling in Jackson sucks big time, it's hard to understand that gibberish in error messages.
You need to receive the POST
data in chunks using request.on('data', function(chunk) {...})
const http = require('http');
http.createServer((req, res) => {
if (req.method == 'POST') {
whole = ''
req.on('data', (chunk) => {
# consider adding size limit here
whole += chunk.toString()
})
req.on('end', () => {
console.log(whole)
res.writeHead(200, 'OK', {'Content-Type': 'text/html'})
res.end('Data received.')
})
}
}).listen(8080)
You should consider adding a size limit at the indicated position as thejh suggested.
As sixty4bit question, if your mysql root user looks to be misconfigured, try to install the configurator extension from mysql official source:
https://dev.mysql.com/downloads/repo/apt/
It will help you to set up a new root user password.
Make sure to update your repository (debian/ubuntu) :
apt-get update
I have the same problem and I solved it by adding package to explore to the Jaxb2marshaller. For spring will be define a bean like this:
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
String[] packagesToScan= {"<packcge which contain the department class>"};
marshaller.setPackagesToScan(packagesToScan);
return marshaller;
}
By this way if all your request and response classes are in the same package you do not need to specifically indicate the classes on the JAXBcontext
You have to import the following two libraries:
import java.util.*
import kotlin.concurrent.schedule
and after that use it in this way:
Timer().schedule(10000){
//do something
}
If you want a less verbose hack:
void deleteDirectory(String path) {
Runtime.getRuntime().exec(String.format("rm -rf %s", path));
}
Using comparison operators is way, way faster than calling any function. I'm not 100% sure if this exists, but I think it doesn't.
Go to Menu Tool -> SQL Output, Run the PL/SQL statement, the output will show on SQL Output panel.
in web application in .cs page
txtbox.Style.Add("background-color","black");
in css specify it by using backcolor property
If you use unicorn.
Look at top
on your server. Unicorn likely is using 100% of CPU right now.
There are several reasons of this problem.
You should check your HTTP requests, some of their can be very hard.
Check unicorn's version. May be you've updated it recently, and something was broken.
echo $PATH
and copy it's valueexport PATH=""
export PATH="/path/you/want/to/keep"
If you got nothing when inputted fastboot devices
, it meaned you devices fail to enter fastboot model. Make sure that you enter fastboot model via press these three button simultaneously, power key, volume key(both '+' and '-').
Then you can see you devices via fastboot devices
and continue to flash your devices.
note:I entered fastboot model only pressed 'power key' and '-' key before, and present the same problem.
I know I am a bit late to the party, but here is another way. That is, this method should wait until the first one is done, the second, and so on.
start "" /wait cmd.exe /c msbuild.bat
start "" /wait cmd.exe /c unit-tests.bat
start "" /wait cmd.exe /c deploy.bat
The only issue that may come out of using this method, is that with new instances of cmd.exe being spawned, is that Errorlevel checking is kept within in each instance of cmd.exe.
Or..
start "" /wait call msbuild.bat
start "" /wait call unit-tests.bat
start "" /wait call deploy.bat
Hope this helps.
For example, your controller, retrive data and put the view
class ClassExampleController extends Controller
{
public function index()
{
$test = Test::first(1);
return view('view-form',[
'field' => $test,
]);
}
}
Add default value in the same form, create and edit, is very simple
<!-- view-form file -->
<form action="{{
isset($field) ?
@route('field.updated', $field->id) :
@route('field.store')
}}">
<!-- Input case -->
<input name="name_input" class="form-control"
value="{{ isset($field->name) ? $field->name : '' }}">
</form>
And, you remember add csrf_field, in case a POST method requesting. Therefore, repeat input, and select element, compare each option
<select name="x_select">
@foreach($field as $subfield)
@if ($subfield == $field->name)
<option val="i" checked>
@else
<option val="i" >
@endif
@endforeach
</select>
driver.execute_script("document.getElementById('your ID Element').scrollIntoView();")
it's working for my case.
If I've understood your problem correctly, there are two possible problems here:
resultset
is null
- I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.resultset.getString(i++)
will get columns 1,2,3 and so on from each subsequent row.I think that the second point is probably your problem here.
Lets say you only had 1 row returned, as follows:
Col 1, Col 2, Col 3
A , B, C
Your code as it stands would only get A - it wouldn't get the rest of the columns.
I suggest you change your code as follows:
ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
int i = 1;
while(i <= numberOfColumns) {
arrayList.add(resultset.getString(i++));
}
System.out.println(resultset.getString("Col 1"));
System.out.println(resultset.getString("Col 2"));
System.out.println(resultset.getString("Col 3"));
System.out.println(resultset.getString("Col n"));
}
Edit:
To get the number of columns:
ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();
XAMPP by default uses http://localhost/phpmyadmin
It also requires you start both Apache and MySQL from the control panel (or as a service).
In the XAMPP Control Panel, clicking [ Admin ] on the MySQL line will open your default browser at the configured URL for the phpMyAdmin application.
If you get a phpMyAdmin error stating "Cannot connect: invalid settings." You will need to make sure your MySQL config file has a matching port for server and client. If it is not the standard 3306 port, you will also need to change your phpMyAdmin config file under apache (config.inc.php) to meet the new port settings. (127.0.0.1 becomes 127.0.0.1:<port>)
If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.
Starting with your example array:
import numpy as np
x = np.array([[1000, 10, 0.5],
[ 765, 5, 0.35],
[ 800, 7, 0.09]])
x_normed = x / x.max(axis=0)
print(x_normed)
# [[ 1. 1. 1. ]
# [ 0.765 0.5 0.7 ]
# [ 0.8 0.7 0.18 ]]
x.max(0)
takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,)
containing the maximum value in each column. You can then divide x
by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.
If x
contains negative values you would need to subtract the minimum first:
x_normed = (x - x.min(0)) / x.ptp(0)
Here, x.ptp(0)
returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect
:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn
from the console by doing this:
indirect("imported_fn()");
Using eval
was my first thought, but it doesn't work. My hypothesis is that calling eval
from the console remains in the context of console, and we need to execute in the context of the module.
I don't think this is possible just using CSS (not cross browser at least) but the jQuery plugin ImageMapster will do what you're after. You can outline, colour in or use an alternative image for hover/active states on an image map.
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
2 options that you can investigate:
perhaps this is what you're looking for: https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/colors.xml
I tried searching for documentation on the EM7 OpenSource REST API. No luck so far.
http://blog.sciencelogic.com/sciencelogic-em7-the-next-generation/05/2011
There's a lot of talk about OpenSource REST API, but no link to the actual API or any documentation. Maybe I was impatient.
Here are few things you can try out
$a = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert
$a.Results | ConvertFrom-Json
Try this to see if you can filter out the columns that you are getting from the API
$a.Results | ft
or, you can try using this also
$b = Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert
$b.Content | ConvertFrom-Json
Curl Style Headers
$b.Headers
I tested the IRM / IWR with the twitter JSON api.
$a = Invoke-RestMethod http://search.twitter.com/search.json?q=PowerShell
Hope this helps.
Tried in Hive and got the below output
table1
1,wqe,chennai,india
2,stu,salem,india
3,mia,bangalore,india
4,yepie,newyork,USA
table2
1,wqe,chennai,india
2,stu,salem,india
3,mia,bangalore,india
5,chapie,Los angels,USA
Inner Join
SELECT * FROM table1 INNER JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india 1 wqe chennai india
2 stu salem india 2 stu salem india
3 mia bangalore india 3 mia bangalore india
Left Join
SELECT * FROM table1 LEFT JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india 1 wqe chennai india
2 stu salem india 2 stu salem india
3 mia bangalore india 3 mia bangalore india
4 yepie newyork USA NULL NULL NULL NULL
Left Semi Join
SELECT * FROM table1 LEFT SEMI JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india
2 stu salem india
3 mia bangalore india
note: Only records in left table are displayed whereas for Left Join both the table records displayed
Yes, the method above is so great. And I tried some of them. At last, I found a method like this:
from threading import Timer
def sync():
do something...
sync_timer = Timer(self.interval, sync, ())
sync_timer.start()
Just like Recursive.
Ok, I hope this method can meet your requirement. :)
getTime()
retrieves the milliseconds since Jan 1, 1970 GMT passed to the constructor. It should not be too hard to get the Unix time (same, but in seconds) from that.
In your project parent directory, run:
git submodule update --init
Or if you have recursive submodules run:
git submodule update --init --recursive
Sometimes this still doesn't work, because somehow you have local changes in the local submodule directory while the submodule is being updated.
Most of the time the local change might not be the one you want to commit. It can happen due to a file deletion in your submodule, etc. If so, do a reset in your local submodule directory and in your project parent directory, run again:
git submodule update --init --recursive
It is possible and is deceptively easy:
bin\Debug
folder below the project file (.csproj).app.publish
folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.
It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.
this worked well for me with safari/chrome/firefox :
const localDate = new Date(`${utcDate.replace(/-/g, '/')} UTC`);
The answer to "Any idea for getting all attributes at once?" question is just to call function with only product id:
$array=get_post_meta($product->id);
key is optional, see http://codex.wordpress.org/Function_Reference/get_post_meta
Find all word and space characters up to and including a -
^[\w ]+-
It would be great to use axios for the api request which supports cancellation, interceptors etc. Along with axios, l use react-redux for state management and redux-saga/redux-thunk for the side effects.
To improve on the answer provided by @artofwarfare, here is what I consider a neater way to check for the message
attribute and print it or print the Exception
object as a fallback.
try:
pass
except Exception as e:
print getattr(e, 'message', repr(e))
The call to repr
is optional, but I find it necessary in some use cases.
Update #1:
Following the comment by @MadPhysicist, here's a proof of why the call to repr
might be necessary. Try running the following code in your interpreter:
try:
raise Exception
except Exception as e:
print(getattr(e, 'message', repr(e)))
print(getattr(e, 'message', str(e)))
Update #2:
Here is a demo with specifics for Python 2.7 and 3.5: https://gist.github.com/takwas/3b7a6edddef783f2abddffda1439f533
URL url = Test.class.getResource(args[0]); // reading demo file path from
// same location where class
File input=null;
try {
input = new File(url.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
You can remove the existing options by using the empty
method, and then add your new options:
var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").empty().append(option);
If you have your new options in an object you can:
var newOptions = {"Option 1": "value1",
"Option 2": "value2",
"Option 3": "value3"
};
var $el = $("#selectId");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
Edit: For removing the all the options but the first, you can use the :gt
selector, to get all the option
elements with index greater than zero and remove
them:
$('#selectId option:gt(0)').remove(); // remove all options, but not the first
Adding an object in a json array
var arrList = [];
var arr = {};
arr['worker_id'] = worker_id;
arr['worker_nm'] = worker_nm;
arrList.push(arr);
Removing an object from a json
It worker for me.
arrList = $.grep(arrList, function (e) {
if(e.worker_id == worker_id) {
return false;
} else {
return true;
}
});
It returns an array without that object.
Hope it helps.
Inside container(in docker, not in VM), by default these are not installed. Even apt-get, wget will not work. My VM is running on Ubuntu 17.10. For me yum package manaager worked.
Yum is not part of debian or ubuntu. It is part of red-hat. But, it works in Ubuntu and it is installed by default like apt-get
Tu install vim, use this command
yum install -y vim-enhanced
To uninstall vim :
yum uninstall -y vim-enhanced
Similarly,
yum install -y wget
yum install -y sudo
-y is for assuming yes if prompted for any qustion asked after doing yum install packagename
To check a space symbol you can use the following approach
if ( c == ' ' ) { /*...*/ }
To check a space and/or a tab symbol (standard blank characters) you can use the following approach
#include <ctype.h>
//...
if ( isblank( c ) ) { /*...*/ }
To check a white space you can use the following approach
#include <ctype.h>
//...
if ( isspace( c ) ) { /*...*/ }
For a quick n' dirty self-signed cert, you can also use flask run --cert adhoc
or set the FLASK_RUN_CERT
env var.
$ export FLASK_APP="app.py"
$ export FLASK_ENV=development
$ export FLASK_RUN_CERT=adhoc
$ flask run
* Serving Flask app "app.py" (lazy loading)
* Environment: development
* Debug mode: on
* Running on https://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 329-665-000
The adhoc
option isn't well documented (for good reason, never do this in production), but it's mentioned in the cli.py source code.
There's a thorough explanation of this by Miguel Grinberg at Running Your Flask Application Over HTTPS.
Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl
You can use a function to generate the template string:
var app = angular.module('app',[]);
app.config(
function($routeProvider) {
$routeProvider.
when('/', {templateUrl:'/home'}).
when('/users/:user_id',
{
controller:UserView,
templateUrl: function(params){ return '/users/view/' + params.user_id; }
}
).
otherwise({redirectTo:'/'});
}
);
There are a few different ways to accomplish this, I'll outline my favourites.
Use a ToggleButton and apply a custom style to it. I suggest this because your required control is "like a toggle button" but just looks different from the default toggle button styling.
My preferred method is to define a graphic for the button in css:
.toggle-button {
-fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
}
.toggle-button:selected {
-fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}
OR use the attached css to define a background image.
// file imagetogglebutton.css deployed in the same package as ToggleButtonImage.class
.toggle-button {
-fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
-fx-background-repeat: no-repeat;
-fx-background-position: center;
}
.toggle-button:selected {
-fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}
I prefer the -fx-graphic specification over the -fx-background-* specifications as the rules for styling background images are tricky and setting the background does not automatically size the button to the image, whereas setting the graphic does.
And some sample code:
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;
public class ToggleButtonImage extends Application {
public static void main(String[] args) throws Exception { launch(args); }
@Override public void start(final Stage stage) throws Exception {
final ToggleButton toggle = new ToggleButton();
toggle.getStylesheets().add(this.getClass().getResource(
"imagetogglebutton.css"
).toExternalForm());
toggle.setMinSize(148, 148); toggle.setMaxSize(148, 148);
stage.setScene(new Scene(
StackPaneBuilder.create()
.children(toggle)
.style("-fx-padding:10; -fx-background-color: cornsilk;")
.build()
));
stage.show();
}
}
Some advantages of doing this are:
An alternate is to not use css and still use a ToggleButton, but set the image graphic in code:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.image.*;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;
public class ToggleButtonImageViaGraphic extends Application {
public static void main(String[] args) throws Exception { launch(args); }
@Override public void start(final Stage stage) throws Exception {
final ToggleButton toggle = new ToggleButton();
final Image unselected = new Image(
"http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png"
);
final Image selected = new Image(
"http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png"
);
final ImageView toggleImage = new ImageView();
toggle.setGraphic(toggleImage);
toggleImage.imageProperty().bind(Bindings
.when(toggle.selectedProperty())
.then(selected)
.otherwise(unselected)
);
stage.setScene(new Scene(
StackPaneBuilder.create()
.children(toggle)
.style("-fx-padding:10; -fx-background-color: cornsilk;")
.build()
));
stage.show();
}
}
The code based approach has the advantage that you don't have to use css if you are unfamilar with it.
For best performance and ease of porting to unsigned applet and webstart sandboxes, bundle the images with your app and reference them by relative path urls rather than downloading them off the net.
As DOC says, you can pass data to the handler as next:
// say your selector and click handler looks something like this...
$("some selector").on('click',{param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
// access element's id where click occur
alert( event.target.id );
}
create table scores (
user_id int,
score int
)
select t.range as [score range], count(*) as [number of occurences]
from (
select user_id,
case when score >= 0 and score < 10 then '0-9'
case when score >= 10 and score < 20 then '10-19'
...
else '90-99' as range
from scores) t
group by t.range
To sort file in place, try:
echo "$(sort your_file)" > your_file
As explained in other answers, you cannot directly redirect the output back to the input file. But you can evaluate the sort
command first and then redirect it back to the original file. In this way you can implement in-place sort.
Similarly, you can also apply this trick to other command like paste
to implement row-wise appending.
To set the cookie, use the ensure_csrf_cookie
decorator in your view:
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def hello(request):
code_here()
Your example is correct but not very portable. There is also a slightly cleaner syntax that can be used (as pointed out by @namespace-sid, among others).
However, suppose the templated class is part of some library that is to be shared...
Should other versions of the templated class be compiled?
Is the library maintainer supposed to anticipate all possible templated uses of the class?
Add a third file that is the template implementation/instantiation file in your sources.
lib/foo.hpp
in/from library
#pragma once
template <typename T>
class foo
{
public:
void bar(const T&);
};
lib/foo.cpp
compiling this file directly just wastes compilation time
// Include guard here, just in case
#pragma once
#include "foo.hpp"
template <typename T>
void foo::bar(const T& arg)
{
// Do something with `arg`
}
foo.MyType.cpp
using the library, explicit template instantiation of foo<MyType>
// Consider adding "anti-guard" to make sure it's not included in other translation units
#if __INCLUDE_LEVEL__ != 0
#error "Don't include this file"
#endif
// Yes, we include the .cpp file
#include <lib/foo.cpp>
#include "MyType.hpp"
template class foo<MyType>;
Of course, you can have multiple implementations in the third file. Or you might want multiple implementation files, one for each type (or set of types) you'd like to use, for instance.
This setup should reduce compile times, especially for heavily used complicated templated code, because you're not recompiling the same header file in each translation unit. It also enables better detection of which code needs to be recompiled, by compilers and build scripts, reducing incremental build burden.
foo.declarations.hpp
needs to know about foo<MyType>
's public interface but not .cpp
sources
#pragma once
#include <lib/foo.hpp>
#include "MyType.hpp"
// Declare `temp`. Doesn't need to include `foo.cpp`
extern foo<MyType> temp;
examples.cpp
can reference local declaration but also doesn't recompile foo<MyType>
#include "foo.declarations.hpp"
MyType instance;
// Define `temp`. Doesn't need to include `foo.cpp`
foo<MyType> temp;
void example_1() {
// Use `temp`
temp.bar(instance);
}
void example_2() {
// Function local instance
foo<MyType> temp2;
// Use templated library function
temp2.bar(instance);
}
error.cpp
example that would work with pure header templates but doesn't here
#include <lib/foo.hpp>
// Causes compilation errors at link time since we never had the explicit instantiation:
// template class foo<int>;
// GCC linker gives an error: "undefined reference to `foo<int>::bar()'"
void linkerError()
{
foo<int> nonExplicitlyInstantiatedTemplate;
}
Note that most compilers/linters/code helpers won't detect this as an error, since there is no error according to C++ standard.
But when you go to link this translation unit into a complete executable, the linker won't find a defined version of foo<int>
.
You can get the Silverlight Chart Controls running on WPF, they're quite nice (and free).
Another solution: change margins. Depending on the siblings of the button, display
should be modified.
button {
display: block;
margin-left: auto;
margin-right: 0;
}
=IFS(COUNTIF(A1,"*cats*"),"cats",COUNTIF(A1,"*22*"),"22",TRUE,"none")
You guys are awesome. Really amazing ideas. I like Alberthoven's and McGin's most, so I decided to combine both ideas. And develop some generic solution to cater all cases. Here is my proposed solution.
@Documented
@Constraint(validatedBy = NotFalseValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotFalse {
String message() default "NotFalse";
String[] messages();
String[] properties();
String[] verifiers();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class NotFalseValidator implements ConstraintValidator<NotFalse, Object> {
private String[] properties;
private String[] messages;
private String[] verifiers;
@Override
public void initialize(NotFalse flag) {
properties = flag.properties();
messages = flag.messages();
verifiers = flag.verifiers();
}
@Override
public boolean isValid(Object bean, ConstraintValidatorContext cxt) {
if(bean == null) {
return true;
}
boolean valid = true;
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
for(int i = 0; i< properties.length; i++) {
Boolean verified = (Boolean) beanWrapper.getPropertyValue(verifiers[i]);
valid &= isValidProperty(verified,messages[i],properties[i],cxt);
}
return valid;
}
boolean isValidProperty(Boolean flag,String message, String property, ConstraintValidatorContext cxt) {
if(flag == null || flag) {
return true;
} else {
cxt.disableDefaultConstraintViolation();
cxt.buildConstraintViolationWithTemplate(message)
.addPropertyNode(property)
.addConstraintViolation();
return false;
}
}
}
@NotFalse(
messages = {"End Date Before Start Date" , "Start Date Before End Date" } ,
properties={"endDateTime" , "startDateTime"},
verifiers = {"validDateRange" , "validDateRange"})
public class SyncSessionDTO implements ControllableNode {
@NotEmpty @NotPastDate
private Date startDateTime;
@NotEmpty
private Date endDateTime;
public Date getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(Date startDateTime) {
this.startDateTime = startDateTime;
}
public Date getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(Date endDateTime) {
this.endDateTime = endDateTime;
}
public Boolean getValidDateRange(){
if(startDateTime != null && endDateTime != null) {
return startDateTime.getTime() <= endDateTime.getTime();
}
return null;
}
}
Does React re-render all components and sub-components every time setState is called?
By default - yes.
There is a method boolean shouldComponentUpdate(object nextProps, object nextState), each component has this method and it's responsible to determine "should component update (run render function)?" every time you change state or pass new props from parent component.
You can write your own implementation of shouldComponentUpdate method for your component, but default implementation always returns true - meaning always re-run render function.
Quote from official docs http://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate
By default, shouldComponentUpdate always returns true to prevent subtle bugs when the state is mutated in place, but if you are careful to always treat the state as immutable and to read-only from props and state in render() then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.
Next part of your question:
If so, why? I thought the idea was that React only rendered as little as needed - when the state changed.
There are two steps of what we may call "render":
Virtual DOM renders: when render method is called it returns a new virtual dom structure of the component. As I mentioned before, this render method is called always when you call setState(), because shouldComponentUpdate always returns true by default. So, by default, there is no optimization here in React.
Native DOM renders: React changes real DOM nodes in your browser only if they were changed in the Virtual DOM and as little as needed - this is that great React's feature which optimizes real DOM mutation and makes React fast.
The easiest way to do this is writing a copy constructor in the MyClass class.
Something like this:
namespace Example
{
class MyClass
{
public int val;
public MyClass()
{
}
public MyClass(MyClass other)
{
val = other.val;
}
}
}
The second constructor simply accepts a parameter of his own type (the one you want to copy) and creates a new object assigned with the same value
class Program
{
static void Main(string[] args)
{
MyClass objectA = new MyClass();
MyClass objectB = new MyClass(objectA);
objectA.val = 10;
objectB.val = 20;
Console.WriteLine("objectA.val = {0}", objectA.val);
Console.WriteLine("objectB.val = {0}", objectB.val);
Console.ReadKey();
}
}
output:
objectA.val = 10
objectB.val = 20
Use Keystore Explorer gui - http://keystore-explorer.sourceforge.net/ - allows you to extract the private key from a .jks in various formats.
initialize the Start property in the constructor
Start = DateTime.Now;
This worked for me when I was trying to add few new fields to the ASP .Net Identity Framework's Users table (AspNetUsers) using Code First. I updated the Class - ApplicationUser in IdentityModels.cs and I added a field lastLogin of type DateTime.
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
CreatedOn = DateTime.Now;
LastPassUpdate = DateTime.Now;
LastLogin = DateTime.Now;
}
public String FirstName { get; set; }
public String MiddleName { get; set; }
public String LastName { get; set; }
public String EmailId { get; set; }
public String ContactNo { get; set; }
public String HintQuestion { get; set; }
public String HintAnswer { get; set; }
public Boolean IsUserActive { get; set; }
//Auditing Fields
public DateTime CreatedOn { get; set; }
public DateTime LastPassUpdate { get; set; }
public DateTime LastLogin { get; set; }
}
The message means that the host key of origin
is not present in your trusted hosts file.
To get around this, open a plain SSH connection to origin
and SSH will ask you if you want to trust the remote host (from the Git console):
$ ssh 127.0.0.1
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
RSA key fingerprint is <FINGERPRINT>.
Are you sure you want to continue connecting (yes/no)?
If you trust the remote host (i.e. type yes
), SSH will add its key to the list of known hosts.
After that, you should be able to do your git push origin
.
As an alternative, you could also manually add the key of origin
to .ssh/known_hosts
but this requires that you adhere to the format of the known_hosts
file as described in the man page of sshd
(Section AUTHORIZED_KEYS FILE FORMAT).
FireFox does not allow to open a local file. But if you want to use this for testing a different image (which is what I just needed to do), you can simply save the whole page locally, and then insert the url(file:///somewhere/file.png) - which works for me.
Use display:inline-block
You may also find vertical-align: top
or vertical-align:middle
useful.
If you order a vector x
, and find the values that is half way through the vector, you just found a median, or 50th percentile. Same logic applies for any percentage. Here are two examples.
x <- rnorm(100)
quantile(x, probs = c(0, 0.25, 0.5, 0.75, 1)) # quartile
quantile(x, probs = seq(0, 1, by= 0.1)) # decile
Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.
Markdown Anchor supports the hashmark, so a link to an anchor in the page would simply be [Pookie](#pookie)
Generating the anchor is not actually supported in Gruber Markdown, but is in other implementations, such as Markdown Extra.
In Markdown Extra, the anchor ID is appended to a header or subhead with {#pookie}
.
Github Flavored Markdown in Git repository pages (but not in Gists) automatically generates anchors with several markup tags on all headers (h1, h2, h3, etc.), including:
id="user-content-HEADERTEXT"
class="anchor"
href="#HEADERTEXT"
aria-hidden="true"
(this is for an svg link icon that displays on mouseover)Excluding the aria/svg icon, when one writes:
# Header Title
Github generates:
<h1><a id="user-content-header-title" class="anchor" href="#header-title">Header Title</a></h1>
Therefore, one need do nothing to create the header links, and can always link to them with:
[Header Title](#header-title)
http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28int,%20float%29
Example:
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 65);
I know the accepted answer is quite old, but there is a way to control formatting with AutoGeneratColumns :
First create a function that will trigger when a column is generated :
<DataGrid x:Name="dataGrid" AutoGeneratedColumns="dataGrid_AutoGeneratedColumns" Margin="116,62,10,10"/>
Then check if the type of the column generated is a DateTime and just change its String format to "d" to remove the time part :
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if(YourColumn == typeof(DateTime))
{
e.Column.ClipboardContentBinding.StringFormat = "d";
}
}
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
Try re-installing with the get-pip script:
wget https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py
This is sourced from the pip Github page, and worked for me.
There appears to be a bug with appendTo using a frameset ID appending to a FORM in Chrome. Swapped out the attribute type directly with div and it works.
The resolution is to use TypedQuery instead. When creating a query from the EntityManager instead call it like this:
TypedQuery<[YourClass]> query = entityManager.createQuery("[your sql]", [YourClass].class);
List<[YourClass]> list = query.getResultList(); //no type warning
This also works the same for named queries, native named queries, etc. The corresponding methods have the same names as the ones that would return the vanilla query. Just use this instead of a Query whenever you know the return type.
I had from a totaly different reason the same notice "Value does not fall within the expected range" from the Visual studio 2008 while trying to use the: Tools -> Windows Embedded Silverlight Tools -> Update Silverlight For Windows Embedded Project.
After spending many ohurs I found out that the problem was that there wasn't a resource file and the update tool looks for the .RC file
Therefor the solution is to add to the resource folder a .RC file and than it works perfectly. I hope it will help someone out there
You then commit the
composer.json
to your project and everyone else on your team can run composer install to install your project dependencies.The point of the lock file is to record the exact versions that are installed so they can be re-installed. This means that if you have a version spec of 1.* and your co-worker runs composer update which installs 1.2.4, and then commits the composer.lock file, when you composer install, you will also get 1.2.4, even if 1.3.0 has been released. This ensures everybody working on the project has the same exact version.
This means that if anything has been committed since the last time a composer install was done, then, without a lock file, you will get new third-party code being pulled down.
Again, this is a problem if you’re concerned about your code breaking. And it’s one of the reasons why it’s important to think about Composer as being centered around the composer.lock file.
Source: Composer: It’s All About the Lock File.
Commit your application's composer.lock (along with composer.json) into version control. This is important because the install command checks if a lock file is present, and if it is, it downloads the versions specified there (regardless of what composer.json says). This means that anyone who sets up the project will download the exact same version of the dependencies. Your CI server, production machines, other developers in your team, everything and everyone runs on the same dependencies, which mitigates the potential for bugs affecting only some parts of the deployments. Even if you develop alone, in six months when reinstalling the project you can feel confident the dependencies installed are still working even if your dependencies released many new versions since then.
Source: Composer - Basic Usage.
Alternatively, you can use the CHAR
function:
= "Maurice " & CHAR(34) & "Rocket" & CHAR(34) & " Richard"
Create a Map or a Set, and using "on connection" event set to it each connected socket, in reverse "once disconnect" event delete that socket from the Map we created earlier
import * as Server from 'socket.io';
const io = Server();
io.listen(3000);
const connections = new Set();
io.on('connection', function (s) {
connections.add(s);
s.once('disconnect', function () {
connections.delete(s);
});
});
To simply list the commits waiting to be pushed: (this is the one you will remember)
git cherry -v
Show the commit subjects next to the SHA1s.
No, according to Apple here:
Note: You cannot install apps from the App Store in simulation environments.
From C++17 onwards you can use std::from_chars
from the <charconv>
header as documented here.
For example:
#include <iostream>
#include <charconv>
#include <array>
int main()
{
char const * str = "42";
int value = 0;
std::from_chars_result result = std::from_chars(std::begin(str), std::end(str), value);
if(result.error == std::errc::invalid_argument)
{
std::cout << "Error, invalid format";
}
else if(result.error == std::errc::result_out_of_range)
{
std::cout << "Error, value too big for int range";
}
else
{
std::cout << "Success: " << result;
}
}
As a bonus, it can also handle other bases, like hexadecimal.
you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.
so if you want your code to work just put.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
In regards to deleting the symbolic links, I found this to be useful.
find /usr/local/bin -lname '../../../Library/Frameworks/Python.framework/Versions/2.7/*' -delete
expand "Java Resources" and then 'Libraries' (in eclipse project). make sure that "Apache Tomcat" present.
if not follow- right click on project -> "Build Path" -> "Java Build Path" -> "Add Library" -> select "Server Runtime" -> next -> select "Apache Tomcat -> click finish
webBrowser.NavigateToString(yourString);
According to other answers I am adding the parallel stages scenario:
pipeline {
agent any
stages {
stage('some parallel stage') {
parallel {
stage('parallel stage 1') {
when {
expression { ENV == "something" }
}
steps {
echo 'something'
}
}
stage('parallel stage 2') {
steps {
echo 'something'
}
}
}
}
}
}
Below is a combo of @machineaddict and @Mafnah answers, re-written for Bootstrap 3 (working well for me so far):
@media (min-width: 768px){
.fivecolumns .col-md-2, .fivecolumns .col-sm-2, .fivecolumns .col-lg-2 {
width: 20%;
*width: 20%;
}
}
@media (min-width: 1200px) {
.fivecolumns .col-md-2, .fivecolumns .col-sm-2, .fivecolumns .col-lg-2 {
width: 20%;
*width: 20%;
}
}
@media (min-width: 768px) and (max-width: 979px) {
.fivecolumns .col-md-2, .fivecolumns .col-sm-2, .fivecolumns .col-lg-2 {
width: 20%;
*width: 20%;
}
}
For land Line Number
03595-259506
03592 245902
03598245785
you can use this
NEW for all ;)
OLD: ((\+*)(0*|(0 )*|(0-)*|(91 )*)(\d{12}+|\d{10}+))|\d{5}([- ]*)\d{6}
NEW: ((\+*)((0[ -]+)*|(91 )*)(\d{12}+|\d{10}+))|\d{5}([- ]*)\d{6}
9775876662
0 9754845789
0-9778545896
+91 9456211568
91 9857842356
919578965389
03595-259506
03592 245902
03598245785
this site is useful for me, and maby for you .;)http://gskinner.com/RegExr/
If the two databases are on the same server, you should be able to create a SQL statement something like this:
UPDATE Test1.dbo.Employee
SET DeptID = emp2.DeptID
FROM Test2.dbo.Employee as 'emp2'
WHERE
Test1.dbo.Employee.EmployeeID = emp2.EmployeeID
From your post, I'm not quite clear whether you want to update Test1.dbo.Employee
with the values from Test2.dbo.Employee
(that's what my query does), or the other way around (since you mention the db on Test1
was the new table......)
To avoid annoying non-checksum lines : CertUtil -v -hashfile "your_file" SHA1 | FIND /V "CertUtil" This will display only line(s) NOT contaning CertUtil
Memory leak: When there is a memory area in a heap but no variable in the stack pointing to that memory.
char *myarea=(char *)malloc(10);
char *newarea=(char *)malloc(10);
myarea=newarea;
Dangling pointer: When a pointer variable in a stack but no memory in heap.
char *p =NULL;
A dangling pointer trying to dereference without allocating space will result in a segmentation fault.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
You'll see these names used throughout the Java SE API
My 2 cents
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.first = None
self.last = None
def add(self, x):
current = Node(x, None)
try:
self.last.next = current
except AttributeError:
self.first = current
self.last = current
else:
self.last = current
def print_list(self):
node = self.first
while node:
print node.value
node = node.next
ll = LinkedList()
ll.add("1st")
ll.add("2nd")
ll.add("3rd")
ll.add("4th")
ll.add("5th")
ll.print_list()
# Result:
# 1st
# 2nd
# 3rd
# 4th
# 5th
Note: The original question was answered already, but I would just like to expand on it with some extras that are relevant to the topic.
Your AIX installation would first be put into volume groups. This is done upon installation.
It will first create rootvg (as in root volume group). This is kinda like your actual hard drive mapped.
This would be equivalent to Disc Management in Windows. AIX wont use up all of that space for its file systems like we tend to do it in consumer Windows machines. Instead there will be a good bit of unallocated space.
To check how much space your rootvg would have you use the following command.
lsvg rootvg
That would stand for list volume group rootvg. This will give you information like the size of physical partitions (PP), Total PPs assigned to the volume group, Free PPs in the volume group, etc. Regardless, the output should be fairly comprehensive.
Next thing you may be interested in, is the file systems on the volume group. Each file system would have certain amount of space given within the volume group it belongs to.
To check what file systems you got on your volume group you use the following command.
lsvgfs rootvg
As in list volume group file systems for rootvg.
You can check how much space each file system has using the following command.
df
I personally like to refine it with flags like -m and -g (in megabytes and gigabytes respectively)
If you have free space available in your volume group, you can assign it to your file systems using the following command.
chfs -a size=+1G /home
As in change file system attribute size by adding 1 G where file system is /home. use man chfs for more instructions. This is a powerful tool. This example is for adjusting size, however you can do more with this command than that.
Sources: http://www.ibm.com/developerworks/aix/library/au-rootvg/ + My own experience working with AIX.
Here is some example code to help you get started:
package com.acme;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileArrayProvider {
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
}
And an example unit test:
package com.acme;
import java.io.IOException;
import org.junit.Test;
public class FileArrayProviderTest {
@Test
public void testFileArrayProvider() throws IOException {
FileArrayProvider fap = new FileArrayProvider();
String[] lines = fap
.readLines("src/main/java/com/acme/FileArrayProvider.java");
for (String line : lines) {
System.out.println(line);
}
}
}
Hope this helps.
Add /y
to the command line of xcopy
:
Example:
xcopy /y c:\mmyinbox\test.doc C:\myoutbox
There's also the function tags, a bit more flexible:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">
And here's the tag documentation.
An alternative for big files is using xreadlines():
count = 0
for line in open(thefilepath).xreadlines( ): count += 1
For Python 3 please see: What substitutes xreadlines() in Python 3?
I'm not sure if there's an absolute authoritative answer to this, but you may look upon it as a distinction of what happens when the request hits the webserver. The request may either be served by having the server return a file that's already been made (static content), or it can pass the request to an application that generates the respone sent back to the browser (dynamic content).
Both types will be called a website, but only the ones that have an application generate the contents will be called a web application.
How the application is written is of less concern. It may be ASP, PHP, Ruby, JavaScript or even C or C++.
days
, years
, etc., are part of Active Support, So this won't work in irb
, but it should work in rails console
.
WSDL: Stands for Web Service Description Language
In SOAP(simple object access protocol), when you use web service and add a web service to your project, your client application(s) doesn't know about web service Functions. Nowadays it's somehow old-fashion and for each kind of different client you have to implement different WSDL
files. For example you cannot use same file for .Net
and php
client.
The WSDL
file has some descriptions about web service functions. The type of this file is XML
. SOAP
is an alternative for REST
.
REST: Stands for Representational State Transfer
It is another kind of API service, it is really easy to use for clients. They do not need to have special file extension like WSDL
files. The CRUD operation can be implemented by different HTTP Verbs
(GET for Reading, POST for Creation, PUT or PATCH for Updating and DELETE for Deleting the desired document) , They are based on HTTP
protocol and most of times the response is in JSON
or XML
format. On the other hand the client application have to exactly call the related HTTP Verb
via exact parameters names and types. Due to not having special file for definition, like WSDL
, it is a manually job using the endpoint. But it is not a big deal because now we have a lot of plugins for different IDEs to generating the client-side implementation.
SOA: Stands for Service Oriented Architecture
Includes all of the programming with web services concepts and architecture. Imagine that you want to implement a large-scale application. One practice can be having some different services, called micro-services and the whole application mechanism would be calling needed web service at the right time.
Both REST
and SOAP
web services are kind of SOA
.
JSON: Stands for javascript Object Notation
when you serialize an object for javascript the type of object format is JSON. imagine that you have the human class :
class Human{
string Name;
string Family;
int Age;
}
and you have some instances from this class :
Human h1 = new Human(){
Name='Saman',
Family='Gholami',
Age=26
}
when you serialize the h1 object to JSON the result is :
[h1:{Name:'saman',Family:'Gholami',Age:'26'}, ...]
javascript
can evaluate this format by eval()
function and make an associative array from this JSON
string. This one is different concept in comparison to other concepts I described formerly.
I don't get that part about the string stuff, but why don't you use the modulo operator (%
) to check if a number is dividable by another? If a number is dividable by another, the other is automatically a multiple of that number.
It goes like that:
int a = 10; int b = 5;
// is a a multiple of b
if ( a % b == 0 ) ....
Use this
openssl ciphers -v | awk '{print $2}' | sort | uniq
Alternatively You can use the brew or curl command for installing things, wherever apt-get is mentioned with a URL...
For example,
curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz
The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.
Try using the success()
call back
$http.get('/Documents/DocumentsList/' + caseId).success(function (result) {
$scope.Documents = result;
});
But now since Documents
is an array and not a promise, remove the ()
<li ng-repeat="document in Documents" ng-class="IsFiltered(document.Filtered)"> <span>
<input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" />
</span>
<span>{{document.Name}}</span>
</li>
1) bitmap to Drawable :
Drawable mDrawable = new BitmapDrawable(getResources(), bitmap);
// mImageView.setDrawable(mDrawable);
2) drawable to Bitmap :
Bitmap mIcon = BitmapFactory.decodeResource(context.getResources(),R.drawable.icon_resource);
// mImageView.setImageBitmap(mIcon);
Based on @returntrue answer I managed to implement it in Interface Builder.
To get round corners button using Interface Builder add a Key Path = "layer.cornerRadius"
with Type = "Number"
and Value = "10"
(or other value as required) in the "User Defined RunTime Attribute
" of the Identity Inspector
of the button.
In your AppDelegate, in the didRegisterForRemoteNotificationsWithDeviceToken
method:
Updated for Swift:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("\(deviceToken.reduce("") { $0 + String(format: "%02.2hhx", arguments: [$1]) })")
}
Placing favicon.ico in the root of your domain only really affects IE5, IIRC. For more modern browsers you should be able to include a link tag to point to another directory:
<link rel="SHORTCUT ICON" href="http://www.mydomain.com/content/favicon.ico"/>
You can also use non-ico files for browsers other than IE, for which I'd maybe use the following conditional statement to serve a PNG to FF,etc, and an ICO to IE:
<link rel="icon" type="image/png" href="http://www.mydomain.com/content/favicon.png" />
<!--[if IE]>
<link rel="shortcut icon" href="http://www.mydomain.com/content/favicon.ico" type="image/vnd.microsoft.icon" />
<![endif]-->
I assume "direction" is "ASC" or "DESC" and dt contains a column named "colName"
public static DataTable resort(DataTable dt, string colName, string direction)
{
DataTable dtOut = null;
dt.DefaultView.Sort = colName + " " + direction;
dtOut = dt.DefaultView.ToTable();
return dtOut;
}
OR without creating dtOut
public static DataTable resort(DataTable dt, string colName, string direction)
{
dt.DefaultView.Sort = colName + " " + direction;
dt = dt.DefaultView.ToTable();
return dt;
}
Not sure why no one mentioned to just use the built-in sticky header style for elements. Worked great for me.
.tableContainerDiv {
overflow: auto;
max-height: 80em;
}
th {
position: sticky;
top: 0;
background: white;
}
Put a min-width on the in @media if you need to make responsive (or similar).
see Table headers position:sticky or Position Sticky and Table Headers
For Guzzle 5, 6 and 7 you do it like this:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('url', [
GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);
Avoid for loops whenever possible.
sum(A(:))
is great however if you have some logical indexing going on you can't use the (:) but you can write
% Sum all elements under 45 in the matrix
sum ( sum ( A *. ( A < 45 ) )
Since sum sums the columns and sums the row vector that was created by the first sum. Note that this only works if the matrix is 2-dim.
SELECT REGEXP_SUBSTR('STRING_EXAMPLE','[^_]+',1,1) from dual
is the right answer, as posted by user1717270
If you use INSTR
, it will give you the position for a string that assumes it contains "_" in it. What if it doesn't? Well the answer will be 0. Therefore, when you want to print the string, it will print a NULL
.
Example: If you want to remove the domain from a "host.domain". In some cases you will only have the short name, i.e. "host". Most likely you would like to print "host". Well, with INSTR
it will give you a NULL
because it did not find any ".", i.e. it will print from 0 to 0. With REGEXP_SUBSTR
you will get the right answer in all cases:
SELECT REGEXP_SUBSTR('HOST.DOMAIN','[^.]+',1,1) from dual;
HOST
and
SELECT REGEXP_SUBSTR('HOST','[^.]+',1,1) from dual;
HOST
bootstrap.js is using jquery library so you need to add jquery library before bootstrap js.
so please add it jquery library like
Note : Please maintain order of js file. html page use top to bottom approach for compilation
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
/**
* ReplaceAll by Fagner Brack (MIT Licensed)
* Replaces all occurrences of a substring in a string
*/
String.prototype.replaceAll = function( token, newToken, ignoreCase ) {
var _token;
var str = this + "";
var i = -1;
if ( typeof token === "string" ) {
if ( ignoreCase ) {
_token = token.toLowerCase();
while( (
i = str.toLowerCase().indexOf(
_token, i >= 0 ? i + newToken.length : 0
) ) !== -1
) {
str = str.substring( 0, i ) +
newToken +
str.substring( i + token.length );
}
} else {
return this.split( token ).join( newToken );
}
}
return str;
};
alert('okay.this.is.a.string'.replaceAll('.', ' '));
Faster than using regex...
EDIT:
Maybe at the time I did this code I did not used jsperf. But in the end such discussion is totally pointless, the performance difference is not worth the legibility of the code in the real world, so my answer is still valid, even if the performance differs from the regex approach.
EDIT2:
I have created a lib that allows you to do this using a fluent interface:
replace('.').from('okay.this.is.a.string').with(' ');
Change the REGEXP
to Like
SELECT * FROM table_name WHERE column_name like '%[^a-zA-Z0-9]%'
this one works fine
System.setProperty("gate.home", "/some/directory");
After that you can retrieve its value later by calling
String value = System.getProperty("gate.home");
Array.join
is what you need, but if you like, the friendly people at phpjs.org have created implode
for you.
Then some slightly off topic ranting. As @jon_darkstar alreadt pointed out, jQuery is JavaScript and not vice versa. You don't need to know JavaScript to be able to understand how to use jQuery, but it certainly doesn't hurt and once you begin to appreciate reusability or start looking at the bigger picture you absolutely need to learn it.
11 years later...
Here's a small python3 snippet to retrieve the download count of the last 100 release assets:
import requests
owner = "twbs"
repo = "bootstrap"
h = {"Accept": "application/vnd.github.v3+json"}
u = f"https://api.github.com/repos/{owner}/{repo}/releases?per_page=100"
r = requests.get(u, headers=h).json()
r.reverse() # older tags first
for rel in r:
if rel['assets']:
tag = rel['tag_name']
dls = rel['assets'][0]['download_count']
pub = rel['published_at']
print(f"Pub: {pub} | Tag: {tag} | Dls: {dls} ")
Pub: 2013-07-18T00:03:17Z | Tag: v1.2.0 | Dls: 1193
Pub: 2013-08-19T21:20:59Z | Tag: v3.0.0 | Dls: 387786
Pub: 2013-10-30T17:07:16Z | Tag: v3.0.1 | Dls: 102278
Pub: 2013-11-06T21:58:55Z | Tag: v3.0.2 | Dls: 381136
...
Pub: 2020-12-07T16:24:37Z | Tag: v5.0.0-beta1 | Dls: 93943
You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):
const rows = [
["name1", "city1", "some other info"],
["name2", "city2", "more info"]
];
let csvContent = "data:text/csv;charset=utf-8,";
rows.forEach(function(rowArray) {
let row = rowArray.join(",");
csvContent += row + "\r\n";
});
or the shorter way (using arrow functions):
const rows = [
["name1", "city1", "some other info"],
["name2", "city2", "more info"]
];
let csvContent = "data:text/csv;charset=utf-8,"
+ rows.map(e => e.join(",")).join("\n");
Then you can use JavaScript's window.open
and encodeURI
functions to download the CSV file like so:
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
window.open
method. In order to achieve this, you can create a hidden <a>
DOM node and set its download
attribute as follows:
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "my_data.csv".
Better to use willDisplayCell
method to check if which cell will be loaded.
Once we get the current indexPath.row
is last we can load more cells.
This will load more cells on scrolling down.
- (void)tableView:(UITableView *)tableView
willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
{
// check if indexPath.row is last row
// Perform operation to load new Cell's.
}
You must use .clearAnimation(); method in UI thread:
runOnUiThread(new Runnable() {
@Override
public void run() {
v.clearAnimation();
}
});
I'd like to point that something that i missed ...
I'm new at Laravel, and i didn't copy the "use Illuminate....." because i really didn'at paid atention, because right above the function boot you alread have a use Statement.
Hope that helps anyone
**use Illuminate\Support\Facades\Schema;**
public function boot()
{
Schema::defaultStringLength(191);
}
If this is a personal script, rather than one you're planning on distributing, it might be simpler to write a shell function for this:
function warextract { jar xf $1 $2 && mv $2 $3 }
which you could then call from python like so:
warextract /home/foo/bar/Portal.ear Binaries.war /home/foo/bar/baz/
If you really feel like it, you could use sed to parse out the filename from the path, so that you'd be able to call it with
warextract /home/foo/bar/Portal.ear /home/foo/bar/baz/Binaries.war
I'll leave that as an excercise to the reader, though.
Of course, since this will extract the .war out into the current directory first, and then move it, it has the possibility of overwriting something with the same name where you are.
Changing directory, extracting it, and cd-ing back is a bit cleaner, but I find myself using little one-line shell functions like this all the time when I want to reduce code clutter.
PYTHONPATH
only affects import
statements, not the top-level Python interpreter's lookup of python files given as arguments.
Needing PYTHONPATH
to be set is not a great idea - as with anything dependent on environment variables, replicating things consistently across different machines gets tricky. Better is to use Python 'packages' which can be installed (using 'pip', or distutils) in system-dependent paths which Python already knows about.
Have a read of https://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/ - 'The Hitchhiker's Guide to Packaging', and also http://docs.python.org/3/tutorial/modules.html - which explains PYTHONPATH and packages at a lower level.
You can call the method getBoundingClientRect()
on a reference to the element. Then you can examine the top
, left
, right
and/or bottom
properties...
var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;
If using jQuery, you can use the more succinct code...
var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;
You can run below commands. I believe this is what you want!
Note: Make sure the port 8080 is open. If not, kill the process that is using 8080 port using sudo kill -9 $(sudo lsof -t -i:8080)
./catalina.sh run
This happened to me once after I merged a pull request on Bitbucket.
I just had to do:
git fetch
My problem was solved. I hope this helps!!!
.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following
Example :
var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;
Answer to add multiple markers.
UPDATE (GEOCODE MULTIPLE ADDRESSES)
Here's the working Example Geocoding with multiple addresses.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var delay = 100;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(21.0000, 78.0000);
var mapOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status)
{
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
}
}
next();
}
);
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
var locations = [
'New Delhi, India',
'Mumbai, India',
'Bangaluru, Karnataka, India',
'Hyderabad, Ahemdabad, India',
'Gurgaon, Haryana, India',
'Cannaught Place, New Delhi, India',
'Bandra, Mumbai, India',
'Nainital, Uttranchal, India',
'Guwahati, India',
'West Bengal, India',
'Jammu, India',
'Kanyakumari, India',
'Kerala, India',
'Himachal Pradesh, India',
'Shillong, India',
'Chandigarh, India',
'Dwarka, New Delhi, India',
'Pune, India',
'Indore, India',
'Orissa, India',
'Shimla, India',
'Gujarat, India'
];
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
As we can resolve this issue with setTimeout()
function.
Still we should not geocode known locations every time you load your page as said by @geocodezip
Another alternatives of these are explained very well in the following links:
How To Avoid GoogleMap Geocode Limit!
I assume that I do have a <div>
input container area with text, sliders and buttons in it, and want to inhibit accidental double-taps in that <div>
.
The following does not inhibit zooming on the input area, and it does not relate to double-tap and zooming outside my <div>
area. There are variations depending on the browser app.
I just tried it.
(1) For Safari on iOS, and Chrome on Android, and is the preferred method. Works except for Internet app on Samsung, where it disables double-taps not on the full <div>
, but at least on elements that handle taps. It returns return false
, with exception on text
and range
inputs.
$('selector of <div> input area').on('touchend',disabledoubletap);
function disabledoubletap(ev) {
var preventok=$(ev.target).is('input[type=text],input[type=range]');
if(preventok==false) return false;
}
(2) Optionally for built-in Internet app on Android (5.1, Samsung), inhibits double-taps on the <div>
, but inhibits zooming on the <div>
:
$('selector of <div> input area').on('touchstart touchend',disabledoubletap);
(3) For Chrome on Android 5.1, disables double-tap at all, does not inhibit zooming, and does nothing about double-tap in the other browsers.
The double-tap-inhibiting of the <meta name="viewport" ...>
is irritating, because <meta name="viewport" ...>
seems good practice.
<meta name="viewport" content="width=device-width, initial-scale=1,
maximum-scale=5, user-scalable=yes">
com.nhaarman.mockitokotlin2.mock {}
This error occurs when, for example, we create a mock inside another mock
mock {
on { x() } doReturn mock {
on { y() } doReturn z()
}
}
The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.
val liveDataMock = mock {
on { y() } doReturn z()
}
mock {
on { x() } doReturn liveDataMock
}
GL
This is what worked for me. It can be found in git documentation here
If you are on your desired branch you can do this:
git fetch origin
# Fetches updates made to an online repository
git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work
Well, usually it is good to avoid asynchronous file operations. Here is the short (i.e. no error handling) sync example:
var fs = require('fs');
fs.writeFileSync(targetFile, fs.readFileSync(sourceFile));
The following worked pretty well for me:
ping -s my_host_name
if your using sqlsrv_connect you have to download and install MS sql driver for your php. download it here http://www.microsoft.com/en-us/download/details.aspx?id=20098 extract it to your php folder or ext in xampp folder then add this on the end of the line in your php.ini file
extension=php_pdo_sqlsrv_55_ts.dll
extension=php_sqlsrv_55_ts.dll
im using xampp version 5.5 so its name php_pdo_sqlsrv_55_ts.dll & php_sqlsrv_55_ts.dll
if you are using xampp version 5.5 dll files is not included in the link...hope it helps
You can use also
select * from tablename where column1 ='a' and column2!='b';
In addtion to align-self
you can also consider auto margin which will do almost the same thing
.container {_x000D_
background: red;_x000D_
height: 200px;_x000D_
flex-direction: column;_x000D_
padding: 10px;_x000D_
display: flex;_x000D_
}_x000D_
a {_x000D_
margin-right:auto;_x000D_
padding: 10px 40px;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
<a href="#">Test</a>_x000D_
</div>
_x000D_
LinearLayout is a subclass of ViewGroup, which has a method called addView. The addView method should be what you are after.
Use Predefined Character Ranges
echo $words= preg_replace('/[[:digit:]]/','', $words);
Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.
The way you do this is in the UITableView
didSelectRowAtIndexPath
you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue
.
Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD
The following code snippet is an adaptation of Kendall Bennett's code for printing pdf files using the PdfiumViewer library. The main difference is that a Stream is used rather than a file.
public bool PrintPDF(
string printer,
string paperName,
int copies, Stream stream)
{
try
{
// Create the printer settings for our printer
var printerSettings = new PrinterSettings
{
PrinterName = printer,
Copies = (short)copies,
};
// Create our page settings for the paper size selected
var pageSettings = new PageSettings(printerSettings)
{
Margins = new Margins(0, 0, 0, 0),
};
foreach (PaperSize paperSize in printerSettings.PaperSizes)
{
if (paperSize.PaperName == paperName)
{
pageSettings.PaperSize = paperSize;
break;
}
}
// Now print the PDF document
using (var document = PdfiumViewer.PdfDocument.Load(stream))
{
using (var printDocument = document.CreatePrintDocument())
{
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
}
}
return true;
}
catch (System.Exception e)
{
return false;
}
}
In my case I am generating the PDF file using a library called PdfSharp and then saving the document to a Stream like so:
PdfDocument pdf = PdfGenerator.GeneratePdf(printRequest.html, PageSize.A4);
pdf.AddPage();
MemoryStream stream = new MemoryStream();
pdf.Save(stream);
MemoryStream stream2 = new MemoryStream(stream.ToArray());
One thing that I want to point out that might be helpful to other developers is that I had to install the 32 bit version of the pdfuim native dll in order for the printing to work even though I am running Windows 10 64 bit. I installed the following two NuGet packages using the NuGet package manager in Visual Studio:
This works on Windows only:
If you are trying to find all envs created using virtualenv
search for "activate_this.py" or "pip-selfcheck.json"
This gives you just the helper method without the side effects of loading every ActionView::Helpers method into your model:
ActionController::Base.helpers.sanitize(str)
Multiple posted answer here, but probably this can help who is newly using PowerShell
SO if any space is there in your directory path do not forgot to add double inverted commas "".
Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution? So, if the value includes any parts of time, it should return true too. I could NOT be able to define a array of format.
When I was in a similar situation, here is what I did:
This http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple was really helpful both for understanding as well as validation the syntax for each format.
My 2 cents if it helps....
They find a solution suboptimally without any guarantee as to the quality of solution found, it is obvious that it makes sense to the development of heuristics only polynomial. The application of these methods is suitable to solve real world problems or large problems so awkward from the computational point of view that for them there is not even an algorithm capable of finding an approximate solution in polynomial time.
is so easy You can use [phpy - library for php][1] php file
<?php
require_once "vendor/autoload.php";
use app\core\App;
$app = new App();
$python = $app->python;
$output = $python->set(your python path)->send(data..)->gen();
var_dump($ouput);
python file:
import include.library.phpy as phpy
print(phpy.get_data(number of data , first = 1 , two =2 ...))
you can see also example in github page [1]: https://github.com/Raeen123/phpy
You can call this function in beforeMount section of a Vue component: like following:
....
methods:{
getUnits: function() {...}
},
beforeMount(){
this.getUnits()
},
......
Working fiddle: https://jsfiddle.net/q83bnLrx/1/
There are different lifecycle hooks Vue provide:
I have listed few are :
vm.$el
.You can have a look at complete list here.
You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.
Python includes a function called itemgetter to return the item at a specific index in a list:
from operator import itemgetter
Pass the itemgetter() function the index of the item you want to retrieve. To retrieve the first item, you would use itemgetter(0). The important thing to understand is that itemgetter(0) itself returns a function. If you pass a list to that function, you get the specific item:
itemgetter(0)([10, 20, 30]) # Returns 10
This is useful when you combine it with map(), which takes a function as its first argument, and a list (or any other iterable) as the second argument. It returns the result of calling the function on each object in the iterable:
my_list = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
list(map(itemgetter(0), my_list)) # Returns ['a', 1, 'x']
Note that map() returns a generator, so the result is passed to list() to get an actual list. In summary, your task could be done like this:
lst2.append(list(map(itemgetter(0), lst)))
This is an alternative method to using a list comprehension, and which method to choose highly depends on context, readability, and preference.
More info: https://docs.python.org/3/library/operator.html#operator.itemgetter
In string first element search and replace
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'_x000D_
var i = str.replace('"[','[').replace(']"',']');_x000D_
console.log(i,'//first element search and replace')
_x000D_
In string global search and replace
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'_x000D_
var j = str.replace(/\"\[/g,'[').replace(/\]\"/g,']');_x000D_
console.log(j,'//global search and replace')
_x000D_
--files-from=
parameter needs trailing slash if you want to keep the absolute path intact. So your command would become something like below:
rsync -av --files-from=/path/to/file / /tmp/
This could be done like there are a large number of files and you want to copy all files to x path. So you would find the files and throw output to a file like below:
find /var/* -name *.log > file
This appears to be missing the providerName="System.Data.EntityClient"
bit. Sure you got the whole thing?
The public
keyword is used only when declaring a class method.
Since you're declaring a simple function and not a class you need to remove public
from your code.
If this is a Mac you type 'exit' then press return.
After a data connection update, some UDF's were not executing. Using a subroutine, I was trying to recalcuate a single column with:
Sheets("mysheet").Columns("D").Calculate
But above statement had no effect. None of above solutions helped, except kambeeks suggestion to replace formulas worked and was fast if manual recalc turned on during update. Below code solved my problem, even if not exactly responsible to OP "kluge" comment, it provided a fast/reliable solution to force recalculation of user-specified cells.
Application.Calculation = xlManual
DoEvents
For Each mycell In Sheets("mysheet").Range("D9:D750").Cells
mycell.Formula = mycell.Formula
Next
DoEvents
Application.Calculation = xlAutomatic
In case you are using NodeJS/Express as back-end and ReactJS/axios as front-end within a development environment in MacOS, you need to run both sides under https. Below is what it finally worked for me (after many hours of deep dive & testing):
Step 1: Create an SSL certificate
Just follow the steps from How to get HTTPS working on your local development environment in 5 minutes
You will end up with a couple of files to be used as credentials to run the https server and ReactJS web:
server.key & server.crt
You need to copy them in the root folders of both the front and back ends (in a Production environment, you might consider copying them in ./ssh for the back-end).
Step 2: Back-end setup
I read a lot of answers proposing the use of 'cors' package or even setting ('Access-Control-Allow-Origin', '*'), which is like saying: "Hackers are welcome to my website". Just do like this:
import express from 'express';
const emailRouter = require('./routes/email'); // in my case, I was sending an email through a form in ReactJS
const fs = require('fs');
const https = require('https');
const app = express();
const port = 8000;
// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', (req, res, next) => {
res.header("Access-Control-Allow-Origin", "https://localhost:3000");
next();
});
// Routes definition
app.use('/email', emailRouter);
// HTTPS server
const credentials = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(port, () => {
console.log(`Back-end running on port ${port}`);
});
In case you want to test if the https is OK, you can replace the httpsServer constant by the one below:
https.createServer(credentials, (req: any, res: any) => {
res.writeHead(200);
res.end("hello world from SSL\n");
}).listen(port, () => {
console.log(`HTTPS server listening on port ${port}...`);
});
And then access it from a web browser: https://localhost:8000/
Step 3: Front-end setup
This is the axios request from the ReactJS front-end:
await axios.get(`https://localhost:8000/email/send`, {
params: {/* whatever data you want to send */ },
headers: {
'Content-Type': 'application/json',
}
})
And now, you need to launch your ReactJS web in https mode using the credentials for SSL we already created. Type this in your MacOS terminal:
HTTPS=true SSL_CRT_FILE=server.crt SSL_KEY_FILE=server.key npm start
At this point, you are sending a request from an https connection at port 3000 from your front-end, to be received by an https connection at port 8000 by your back-end. CORS should be happy with this ;)
Markdown doesn't have a defined syntax to underline text.
I guess this is because underlined text is hard to read, and that it's usually used for hyperlinks.
@Gabe Martin-Dempesy's answer is helped to me. And I wrote a small script related to it. The usage is very simple.
Install a certificate from host:
> sudo ./java-cert-importer.sh example.com
Remove the certificate that installed already.
> sudo ./java-cert-importer.sh example.com --delete
java-cert-importer.sh
#!/usr/bin/env bash
# Exit on error
set -e
# Ensure script is running as root
if [ "$EUID" -ne 0 ]
then echo "WARN: Please run as root (sudo)"
exit 1
fi
# Check required commands
command -v openssl >/dev/null 2>&1 || { echo "Required command 'openssl' not installed. Aborting." >&2; exit 1; }
command -v keytool >/dev/null 2>&1 || { echo "Required command 'keytool' not installed. Aborting." >&2; exit 1; }
# Get command line args
host=$1; port=${2:-443}; deleteCmd=${3:-${2}}
# Check host argument
if [ ! ${host} ]; then
cat << EOF
Please enter required parameter(s)
usage: ./java-cert-importer.sh <host> [ <port> | default=443 ] [ -d | --delete ]
EOF
exit 1
fi;
if [ "$JAVA_HOME" ]; then
javahome=${JAVA_HOME}
elif [[ "$OSTYPE" == "linux-gnu" ]]; then # Linux
javahome=$(readlink -f $(which java) | sed "s:bin/java::")
elif [[ "$OSTYPE" == "darwin"* ]]; then # Mac OS X
javahome="$(/usr/libexec/java_home)/jre"
fi
if [ ! "$javahome" ]; then
echo "WARN: Java home cannot be found."
exit 1
elif [ ! -d "$javahome" ]; then
echo "WARN: Detected Java home does not exists: $javahome"
exit 1
fi
echo "Detected Java Home: $javahome"
# Set cacerts file path
cacertspath=${javahome}/lib/security/cacerts
cacertsbackup="${cacertspath}.$$.backup"
if ( [ "$deleteCmd" == "-d" ] || [ "$deleteCmd" == "--delete" ] ); then
sudo keytool -delete -alias ${host} -keystore ${cacertspath} -storepass changeit
echo "Certificate is deleted for ${host}"
exit 0
fi
# Get host info from user
#read -p "Enter server host (E.g. example.com) : " host
#read -p "Enter server port (Default 443) : " port
# create temp file
tmpfile="/tmp/${host}.$$.crt"
# Create java cacerts backup file
cp ${cacertspath} ${cacertsbackup}
echo "Java CaCerts Backup: ${cacertsbackup}"
# Get certificate from speficied host
openssl x509 -in <(openssl s_client -connect ${host}:${port} -prexit 2>/dev/null) -out ${tmpfile}
# Import certificate into java cacerts file
sudo keytool -importcert -file ${tmpfile} -alias ${host} -keystore ${cacertspath} -storepass changeit
# Remove temp certificate file
rm ${tmpfile}
# Check certificate alias name (same with host) that imported successfully
result=$(keytool -list -v -keystore ${cacertspath} -storepass changeit | grep "Alias name: ${host}")
# Show results to user
if [ "$result" ]; then
echo "Success: Certificate is imported to java cacerts for ${host}";
else
echo "Error: Something went wrong";
fi;
Referring to Spring Boot application as a Service as well, I would go for the systemd
version, since it's the easiest, least verbose, and best integrated into modern distros (and even the not-so-modern ones like CentOS 7.x).
When you execute the Java Virtual Machine (JVM) with the java
command,
java ClassName argument1 argument2 ...
When you execute your application, you specify its class name as an argument to the java command, as above
the JVM attempts to invoke the main method of the class you specify
—at this point, no objects of the class have been created.
Declaring
main
as staticallows
the JVM toinvoke
mainwithout
creating aninstance
of the class.
let's back to the command
ClassName
is a command-line argument
to the JVM that tells it which class to execute. Following the ClassName, you can also specify a list of Strings
(separated by spaces) as command-line arguments that the JVM will pass to your application. -Such arguments might be used to specify options (e.g., a filename) to run the application- this is why there is a parameter called String[] args
in the main
References:Java™ How To Program (Early Objects), Tenth Edition
I may not be so good at this, but surely strings (even though they are technically reference types and live on the heap) are passed by value, not reference?
string a = "Hello";
string b = "goodbye";
b = a; //attempt to make b point to a, won't work.
a = "testing";
Console.WriteLine(b); //this will produce "hello", NOT "testing"!!!!
This why you need ref if you want changes to exist outside of the scope of the function making them, you aren't passing a reference otherwise.
As far as I am aware you only need ref for structs/value types and string itself, as string is a reference type that pretends it is but is not a value type.
I could be completely wrong here though, I am new.
Pessimistic locking is generally not recommended and it's very costly in terms of performance on database side. The problem that you have mentioned (the code part) a few things are not clear such as:
session
object (not sure if you are using Spring)?Hibernate Session objects are NOT thread-safe. So if there are multiple threads accessing the same session and trying to update the same database entity, your code can potentially end up in an error situation like this.
So what happens here is that more than one thread tries to update the same entity, one thread succeeds and when the next thread goes to commit the data, it sees that its already been modified and ends up throwing StaleObjectStateException
.
EDIT:
There is a way to use Pessimistic Locking in Hibernate. Check out this link. But there seems to be some issue with this mechanism. I came across posting a bug in hibernate (HHH-5275), however. The scenario mentioned in the bug is as follows:
Two threads are reading the same database record; one of those threads should use pessimistic locking thereby blocking the other thread. But both threads can read the database record causing the test to fail.
This is very close to what you are facing. Please try this if this does not work, the only way I can think of is using Native SQL queries where you can achieve pessimistic locking in postgres database with SELECT FOR UPDATE
query.
A user agent style sheet is a ”default style sheet” provided by the browser (e.g., Chrome, Firefox, Edge, etc.) in order to present the page in a way that satisfies ”general presentation expectations.” For example, a default style sheet would provide base styles for things like font size, borders, and spacing between elements. It is common to employ a reset style sheet to deal with inconsistencies amongst browsers.
From the specification...
A user agent's default style sheet should present the elements of the document language in ways that satisfy general presentation expectations for the document language. ~ The Cascade.
For more information about user agents in general, see user agent.
nowadays,2017-12-17. I don't find any description about Font-property-order‘s necessity in spec. And I test in chrome always works whatever the order is.
@font-face {
font-family: 'Font Awesome 5 Free';
font-weight: 900;
src: url('#{$fa-font-path}/fa-solid-900.eot');
src: url('#{$fa-font-path}/fa-solid-900.eot?#iefix') format('embedded-opentype'),
url('#{$fa-font-path}/fa-solid-900.woff2') format('woff2'),
url('#{$fa-font-path}/fa-solid-900.woff') format('woff'),
url('#{$fa-font-path}/fa-solid-900.ttf') format('truetype'),
url('#{$fa-font-path}/fa-solid-900.svg#fontawesome') format('svg');
}
@font-face {
font-family: 'Font Awesome 5 Free';
font-weight: 400;
src: url('#{$fa-font-path}/fa-regular-400.eot');
src: url('#{$fa-font-path}/fa-regular-400.eot?#iefix') format('embedded-opentype'),
url('#{$fa-font-path}/fa-regular-400.woff2') format('woff2'),
url('#{$fa-font-path}/fa-regular-400.woff') format('woff'),
url('#{$fa-font-path}/fa-regular-400.ttf') format('truetype'),
url('#{$fa-font-path}/fa-regular-400.svg#fontawesome') format('svg');
}
Use regex and now you have two problems. I would split the thing on dots ("."), then make sure that each part is either a wildcard or set of digits (regex is perfect now). If the thing is valid, you just return correct chunk of the split.
For those looking for a general strategy for reading and writing a string to file:
First, get a file object
You'll need the storage path. For the internal storage, use:
File path = context.getFilesDir();
For the external storage (SD card), use:
File path = context.getExternalFilesDir(null);
Then create your file object:
File file = new File(path, "my-file-name.txt");
Write a string to the file
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write("text-to-write".getBytes());
} finally {
stream.close();
}
Or with Google Guava
String contents = Files.toString(file, StandardCharsets.UTF_8);
Read the file to a string
int length = (int) file.length();
byte[] bytes = new byte[length];
FileInputStream in = new FileInputStream(file);
try {
in.read(bytes);
} finally {
in.close();
}
String contents = new String(bytes);
Or if you are using Google Guava
String contents = Files.toString(file,"UTF-8");
For completeness I'll mention
String contents = new Scanner(file).useDelimiter("\\A").next();
which requires no libraries, but benchmarks 50% - 400% slower than the other options (in various tests on my Nexus 5).
Notes
For each of these strategies, you'll be asked to catch an IOException.
The default character encoding on Android is UTF-8.
If you are using external storage, you'll need to add to your manifest either:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
or
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Write permission implies read permission, so you don't need both.
Sometimes you inherit brittle code that is already expecting magic values in a lot of places. Everyone is correct, you should use NULL if possible. However, as a shortcut to make sure every reference to that value is the same, I like to put "constants" (for lack of a better name) in SQL in a scaler function and then call that function when I need the value. That way if I ever want to update them all to be something else, I can do so easily. Or if I want to change the default value moving forward, I only have one place to update it.
The following code creates the function and a table using it for the default DateTime value. Then inserts and select from the table without specifying the value for Modified. Then cleans up after itself. I hope this helps.
-- CREATE FUNCTION
CREATE FUNCTION dbo.DateTime_MinValue ( )
RETURNS DATETIME
AS
BEGIN
DECLARE @dateTime_min DATETIME ;
SET @dateTime_min = '1/1/1753 12:00:00 AM'
RETURN @dateTime_min ;
END ;
GO
-- CREATE TABLE USING FUNCTION FOR DEFAULT
CREATE TABLE TestTable
(
TestTableId INT IDENTITY(1, 1)
PRIMARY KEY CLUSTERED ,
Value VARCHAR(50) ,
Modified DATETIME DEFAULT dbo.DateTime_MinValue()
) ;
-- INSERT VALUE INTO TABLE
INSERT INTO TestTable
( Value )
VALUES ( 'Value' ) ;
-- SELECT FROM TABLE
SELECT TestTableId ,
VALUE ,
Modified
FROM TestTable ;
-- CLEANUP YOUR DB
DROP TABLE TestTable ;
DROP FUNCTION dbo.DateTime_MinValue ;
I am a beginner to screen but I find it immensely useful while restoring lost connections. Your question has already been answered but this information might serve as an add on - I use putty with putty connection manager and name my screens - "tab1", "tab2", etc. - as for me the overall picture of the 8-10 tabs is more important than each individual tab name. I use the 8th tab for connecting to db, the 7th for viewing logs, etc. So when I want to reattach my screens I have written a simple wrapper which says:
#!/bin/bash
screen -d -r tab$1
where first argument is the tab number.
Of course, this wasn't an option when the OP submitted the question, but ECMAScript 6 now also allows for constants by way of the "const" keyword:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
You can see ECMAScript 6 adoption here.