Complete example here:-
<!DOCTYPE html >
<html ng-app="dashboard">
<head>
<title>AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="./bootstrap.min.css">
<script src="./bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
</head>
<body ng-controller="myController">
<table border='1'>
<tr ng-repeat="(key,val) in collValues">
<td ng-if="!hasChildren(val)">{{key}}</td>
<td ng-if="val === 'string'">
<input type="text" name="{{key}}"></input>
</td>
<td ng-if="val === 'number'">
<input type="number" name="{{key}}"></input>
</td>
<td ng-if="hasChildren(val)" td colspan='2'>
<table border='1' ng-repeat="arrVal in val">
<tr ng-repeat="(key,val) in arrVal">
<td>{{key}}</td>
<td ng-if="val === 'string'">
<input type="text" name="{{key}}"></input>
</td>
<td ng-if="val === 'number'">
<input type="number" name="{{key}}"></input>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
<script type="text/javascript">
var app = angular.module("dashboard",[]);
app.controller("myController",function($scope){
$scope.collValues = {
'name':'string',
'id':'string',
'phone':'number',
'depart':[
{
'depart':'string',
'name':'string'
}
]
};
$scope.hasChildren = function(bigL1) {
return angular.isArray(bigL1);
}
});
</script>
</html>
public MainWindow()
{
// This button needs to exist on your form.
myButton.Click += myButton_Click;
}
void myButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Message here");
this.Close();
}
As others have said, you can't do that either using alert()
or confirm()
.
You can, however, create an external HTML document containing your error message and an OK
button, set its <title>
element to whatever you want, then display it in a modal dialog box using showModalDialog().
I used the following code to listen to changes to an array.
/* @arr array you want to listen to
@callback function that will be called on any change inside array
*/
function listenChangesinArray(arr,callback){
// Add more methods here if you want to listen to them
['pop','push','reverse','shift','unshift','splice','sort'].forEach((m)=>{
arr[m] = function(){
var res = Array.prototype[m].apply(arr, arguments); // call normal behaviour
callback.apply(arr, arguments); // finally call the callback supplied
return res;
}
});
}
Hope this was useful :)
Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship. If you want the same user record to have the possibility of having more than 1 related profile record, go with a separate primary key, otherwise stick with what you have.
You can use setattr
name = 'varname'
value = 'something'
setattr(self, name, value) #equivalent to: self.varname= 'something'
print (self.varname)
#will print 'something'
But, since you should inform an object to receive the new variable, this only works inside classes or modules.
Installation code chunks for vanilla Sublime may change in the future.
This link would be the safest place to install plugin support to Sublime Text 2.
For Sublime Text 3 this link works has the code.
I am using this to switch one branch to another anyone you can use it works for me like charm.
git switch [branchName] OR git checkout [branchName]
ex: git switch develop OR
git checkout develop
Update of @param's answer.
ICS emulator supports camera.
I found Simple Android Photo Capture, which supports webcam in android emulator.
Your xpath is just a little off:
count(//Property/long[text()=$parPropId])
Edit: Cerebrus quite rightly points out that the code in your OP (using the implicit value of a node) is absolutely fine for your purposes. In fact, since it's quite likely you want to work with the "Property" node rather than the "long" node, it's probably superior to ask for //Property[long=$parPropId]
than the text() xpath, though you could make a case for the latter on readability grounds.
What can I say, I'm a bit tired today :)
Here's a more optimized version of Mike's answer above that gets the websites Content-Type properly, supports POST and GET request, and uses your browsers User-Agent so websites can identify your proxy as a browser. You can just simply set the URL by changing url =
and it will automatically set HTTP and HTTPS stuff without manually doing it.
var express = require('express')
var app = express()
var https = require('https');
var http = require('http');
const { response } = require('express');
app.use('/', function(clientRequest, clientResponse) {
var url;
url = 'https://www.google.com'
var parsedHost = url.split('/').splice(2).splice(0, 1).join('/')
var parsedPort;
var parsedSSL;
if (url.startsWith('https://')) {
parsedPort = 443
parsedSSL = https
} else if (url.startsWith('http://')) {
parsedPort = 80
parsedSSL = http
}
var options = {
hostname: parsedHost,
port: parsedPort,
path: clientRequest.url,
method: clientRequest.method,
headers: {
'User-Agent': clientRequest.headers['user-agent']
}
};
var serverRequest = parsedSSL.request(options, function(serverResponse) {
var body = '';
if (String(serverResponse.headers['content-type']).indexOf('text/html') !== -1) {
serverResponse.on('data', function(chunk) {
body += chunk;
});
serverResponse.on('end', function() {
// Make changes to HTML files when they're done being read.
body = body.replace(`example`, `Cat!` );
clientResponse.writeHead(serverResponse.statusCode, serverResponse.headers);
clientResponse.end(body);
});
}
else {
serverResponse.pipe(clientResponse, {
end: true
});
clientResponse.contentType(serverResponse.headers['content-type'])
}
});
serverRequest.end();
});
app.listen(3000)
console.log('Running on 0.0.0.0:3000')
You want to add libraries to your project and in doing so you have two options as you yourself identified:
Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.
This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).
Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.
As for the other alernatives you have either global libraries using Library Manager
or jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager
.
See Date/Epoch Converter.
You need to ParseInt
, otherwise it wouldn't work:
if (!window.a)
window.a = new Date();
var mEpoch = parseInt(UNIX_timestamp);
if (mEpoch < 10000000000)
mEpoch *= 1000;
------
a.setTime(mEpoch);
var year = a.getFullYear();
...
return time;
Alternatively, you can use Guava's Resources object:
URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
List<String> lines = Resources.readLines(url, Charsets.UTF_8);
lines.forEach(System.out::println);
std::atomic
exists because many ISAs have direct hardware support for it
What the C++ standard says about std::atomic
has been analyzed in other answers.
So now let's see what std::atomic
compiles to to get a different kind of insight.
The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic
basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.
This support allows for faster alternatives to more general methods such as std::mutex
, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic
because std::mutex
it makes futex
system calls in Linux, which is way slower than the userland instructions emitted by std::atomic
, see also: Does std::mutex create a fence?
Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.
main.cpp
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
size_t niters;
#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif
void threadMain() {
for (size_t i = 0; i < niters; ++i) {
#if LOCK
__asm__ __volatile__ (
"lock incq %0;"
: "+m" (global),
"+g" (i) // to prevent loop unrolling
:
:
);
#else
__asm__ __volatile__ (
""
: "+g" (i) // to prevent he loop from being optimized to a single add
: "g" (global)
:
);
global++;
#endif
}
}
int main(int argc, char **argv) {
size_t nthreads;
if (argc > 1) {
nthreads = std::stoull(argv[1], NULL, 0);
} else {
nthreads = 2;
}
if (argc > 2) {
niters = std::stoull(argv[2], NULL, 0);
} else {
niters = 10;
}
std::vector<std::thread> threads(nthreads);
for (size_t i = 0; i < nthreads; ++i)
threads[i] = std::thread(threadMain);
for (size_t i = 0; i < nthreads; ++i)
threads[i].join();
uint64_t expect = nthreads * niters;
std::cout << "expect " << expect << std::endl;
std::cout << "global " << global << std::endl;
}
Compile, run and disassemble:
comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out -DLOCK $common
./main_fail.out 4 100000
./main_std_atomic.out 4 100000
./main_lock.out 4 100000
gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out
Extremely likely "wrong" race condition output for main_fail.out
:
expect 400000
global 100000
and deterministic "right" output of the others:
expect 400000
global 400000
Disassembly of main_fail.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: mov 0x29b5(%rip),%rcx # 0x5140 <niters>
0x000000000000278b <+11>: test %rcx,%rcx
0x000000000000278e <+14>: je 0x27b4 <threadMain()+52>
0x0000000000002790 <+16>: mov 0x29a1(%rip),%rdx # 0x5138 <global>
0x0000000000002797 <+23>: xor %eax,%eax
0x0000000000002799 <+25>: nopl 0x0(%rax)
0x00000000000027a0 <+32>: add $0x1,%rax
0x00000000000027a4 <+36>: add $0x1,%rdx
0x00000000000027a8 <+40>: cmp %rcx,%rax
0x00000000000027ab <+43>: jb 0x27a0 <threadMain()+32>
0x00000000000027ad <+45>: mov %rdx,0x2984(%rip) # 0x5138 <global>
0x00000000000027b4 <+52>: retq
Disassembly of main_std_atomic.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a6 <threadMain()+38>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock addq $0x1,0x299f(%rip) # 0x5138 <global>
0x0000000000002799 <+25>: add $0x1,%rax
0x000000000000279d <+29>: cmp %rax,0x299c(%rip) # 0x5140 <niters>
0x00000000000027a4 <+36>: ja 0x2790 <threadMain()+16>
0x00000000000027a6 <+38>: retq
Disassembly of main_lock.out
:
Dump of assembler code for function threadMain():
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a5 <threadMain()+37>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock incq 0x29a0(%rip) # 0x5138 <global>
0x0000000000002798 <+24>: add $0x1,%rax
0x000000000000279c <+28>: cmp %rax,0x299d(%rip) # 0x5140 <niters>
0x00000000000027a3 <+35>: ja 0x2790 <threadMain()+16>
0x00000000000027a5 <+37>: retq
Conclusions:
the non-atomic version saves the global to a register, and increments the register.
Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000
.
std::atomic
compiles to lock addq
. The LOCK prefix makes the following inc
fetch, modify and update memory atomically.
our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic
, except that our inc
is used instead of add
. Not sure why GCC chose add
, considering that our INC generated a decoding 1 byte smaller.
ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?
Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.
On line 2 change new FileWriter(my_file_name)
to new FileWriter(my_file_name, true)
so you're appending to the file rather than overwriting.
File f = new File("/path/of/the/file");
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.append(line);
bw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
This answer is not ideal any more since CSS flexbox and grid where implemented to CSS. However it is still a working solution
On a smaller screen you would probably want to keep the height auto as the col1, col2 and col3 are stacked on one another.
However after a media query breakpoint you would like cols to appear next to each other with an equal height for all columns.
1125 px is only an example of window width breakpoint after which you would want to make all columns set to the same height.
<div class="wraper">
<div class="col1">Lorem ipsum dolor sit amet.</div>
<div class="col2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eos laudantium, possimus sed, debitis amet in, explicabo dolor similique eligendi officia numquam eaque quae illo magnam distinctio odio, esse vero aspernatur.</div>
<div class="col3">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem, odio qui praesentium.</div>
</div>
You could, of course, set more breakpoints if you need to.
<script>
$(document).ready(function(){
$(window).on('load resize', function() {
let vraperH = $('.wraper').height();
if (window.innerWidth>= 1125) {
$('.col1').height(vraperH);
$('.col2').height(vraperH);
$('.col3').height(vraperH);
}
if (window.innerWidth < 1125) {
$('.col1').height('auto');
$('.col2').height('auto');
$('.col3').height('auto');
}
});
});
</script>
<head>
<script type="text/javascript">
<%=YourScript %>
function functionname1(arg1,arg2){content}
</script>
</head>
public string YourScript = "";
public string functionname(arg)
{
if (condition)
{
YourScript = "functionname1(arg1,arg2);";
}
}
This solution had the following issues:
:
label:
anywhere on a line as a labelHere's a fixed (shell-check
clean) version:
#!/bin/bash
# GOTO for bash, based upon https://stackoverflow.com/a/31269848/5353461
function goto
{
local label=$1
cmd=$(sed -En "/^[[:space:]]*#[[:space:]]*$label:[[:space:]]*#/{:a;n;p;ba};" "$0")
eval "$cmd"
exit
}
start=${1:-start}
goto "$start" # GOTO start: by default
#start:# Comments can occur after labels
echo start
goto end
# skip: # Whitespace is allowed
echo this is usually skipped
# end: #
echo end
Try this:
#foo
{
position: absolute;
top: 100%;
right: 0%;
}
This was a problem for me, too. One reason for doing this (in my case) was that I needed to convert a client-side event (a javascript variable being modified) to a server-side variable (for that variable to be used in php). Hence populating a form with a javascript variable (eg a sessionStorage key/value) and converting it to a $_POST variable.
<form name='formName'>
<input name='inputName'>
</form>
<script>
document.formName.inputName.value=var
</script>
In Spyder, go to your active shell and download nltk using below 2 commands. import nltk nltk.download() Then you should see NLTK downloader window open as below, Go to 'Models' tab in this window and click on 'punkt' and download 'punkt'
You don't need to reset all your user data to switch users. Try clicking on your name in the upper right corner then click on "Account settings". There you will get an option to sign out of the IDE. Once signed out you can sign back in as another Microsoft account.
The advice to use Graphviz is good: you can generate the dot file and it will do the hard work of measuring strings, doing the layout, etc. Plus it can output the graphs in lot of formats, including vector ones.
I found a Perl program doing precisely that, in a mailing list, but I just can't find it back! I copied the sample dot file and studied it, since I don't know much of this declarative syntax and I wanted to learn a bit more.
Problem: with latest Graphviz, I have errors (or rather, warnings, as the final diagram is generated), both in the original graph and the one I wrote (by hand). Some searches shown this error was found in old versions and disappeared in more recent versions. Looks like it is back.
I still give the file, maybe it can be a starting point for somebody, or maybe it is enough for your needs (of course, you still have to generate it).
digraph tree
{
rankdir=LR;
DirTree [label="Directory Tree" shape=box]
a_Foo_txt [shape=point]
f_Foo_txt [label="Foo.txt", shape=none]
a_Foo_txt -> f_Foo_txt
a_Foo_Bar_html [shape=point]
f_Foo_Bar_html [label="Foo Bar.html", shape=none]
a_Foo_Bar_html -> f_Foo_Bar_html
a_Bar_png [shape=point]
f_Bar_png [label="Bar.png", shape=none]
a_Bar_png -> f_Bar_png
a_Some_Dir [shape=point]
d_Some_Dir [label="Some Dir", shape=ellipse]
a_Some_Dir -> d_Some_Dir
a_VBE_C_reg [shape=point]
f_VBE_C_reg [label="VBE_C.reg", shape=none]
a_VBE_C_reg -> f_VBE_C_reg
a_P_Folder [shape=point]
d_P_Folder [label="P Folder", shape=ellipse]
a_P_Folder -> d_P_Folder
a_Processing_20081117_7z [shape=point]
f_Processing_20081117_7z [label="Processing-20081117.7z", shape=none]
a_Processing_20081117_7z -> f_Processing_20081117_7z
a_UsefulBits_lua [shape=point]
f_UsefulBits_lua [label="UsefulBits.lua", shape=none]
a_UsefulBits_lua -> f_UsefulBits_lua
a_Graphviz [shape=point]
d_Graphviz [label="Graphviz", shape=ellipse]
a_Graphviz -> d_Graphviz
a_Tree_dot [shape=point]
f_Tree_dot [label="Tree.dot", shape=none]
a_Tree_dot -> f_Tree_dot
{
rank=same;
DirTree -> a_Foo_txt -> a_Foo_Bar_html -> a_Bar_png -> a_Some_Dir -> a_Graphviz [arrowhead=none]
}
{
rank=same;
d_Some_Dir -> a_VBE_C_reg -> a_P_Folder -> a_UsefulBits_lua [arrowhead=none]
}
{
rank=same;
d_P_Folder -> a_Processing_20081117_7z [arrowhead=none]
}
{
rank=same;
d_Graphviz -> a_Tree_dot [arrowhead=none]
}
}
> dot -Tpng Tree.dot -o Tree.png
Error: lost DirTree a_Foo_txt edge
Error: lost a_Foo_txt a_Foo_Bar_html edge
Error: lost a_Foo_Bar_html a_Bar_png edge
Error: lost a_Bar_png a_Some_Dir edge
Error: lost a_Some_Dir a_Graphviz edge
Error: lost d_Some_Dir a_VBE_C_reg edge
Error: lost a_VBE_C_reg a_P_Folder edge
Error: lost a_P_Folder a_UsefulBits_lua edge
Error: lost d_P_Folder a_Processing_20081117_7z edge
Error: lost d_Graphviz a_Tree_dot edge
I will try another direction, using Cairo, which is also able to export a number of formats. It is more work (computing positions/offsets) but the structure is simple, shouldn't be too hard.
This is a new answer to an old question about a common misconception about contains()
in XPath...
Summary: contains()
means contains a substring, not contains a node.
This XPath is often misinterpreted:
//ul[contains(li, 'Model')]
Wrong interpretation:
Select those ul
elements that contain an li
element with Model
in it.
This is wrong because
contains(x,y)
expects x
to be a string, andthe XPath rule for converting multiple elements to a string is this:
A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.
Right interpretation: Select those ul
elements whose first li
child has a string-value that contains a Model
substring.
XML
<r>
<ul id="one">
<li>Model A</li>
<li>Foo</li>
</ul>
<ul id="two">
<li>Foo</li>
<li>Model A</li>
</ul>
</r>
XPaths
//ul[contains(li, 'Model')]
selects the one
ul
element.
Note: The two
ul
element is not selected because the string-value of the first li
child
of the two
ul
is Foo
, which does not contain the Model
substring.
//ul[li[contains(.,'Model')]]
selects the one
and two
ul
elements.
Note: Both ul
elements are selected because contains()
is applied to each li
individually. (Thus, the tricky multiple-element-to-string conversion rule is avoided.) Both ul
elements do have an li
child whose string value contains the Model
substring -- position of the li
element no longer matters.
Here is how to do dump the database (with just the schema):
mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql
If you also want the data, remove the --no-data
option.
What is the problem? To use multiple controllers, just use multiple ngController directives:
<div class="widget" ng-controller="widgetController">
<p>Stuff here</p>
</div>
<div class="menu" ng-controller="menuController">
<p>Other stuff here</p>
</div>
You will need to have the controllers available in your application module, as usual.
The most basic way to do it could be as simple as declaring the controller functions like this:
function widgetController($scope) {
// stuff here
}
function menuController($scope) {
// stuff here
}
Following @GregaKešpret you can make an infix operator:
`%+=%` = function(e1,e2) eval.parent(substitute(e1 <- e1 + e2))
x = 1
x %+=% 2 ; x
Remove duplicates (Keeping First)
idx = np.unique( df.index.values, return_index = True )[1]
df = df.iloc[idx]
Remove duplicates (Keeping Last)
df = df[::-1]
df = df.iloc[ np.unique( df.index.values, return_index = True )[1] ]
Tests: 10k loops using OP's data
numpy method - 3.03 seconds
df.loc[~df.index.duplicated(keep='first')] - 4.43 seconds
df.groupby(df.index).first() - 21 seconds
reset_index() method - 29 seconds
HttpWebRequest request =(HttpWebRequest)WebRequest.Create("some url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
request.Accept = "/";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
doc.Save(request.GetRequestStream());
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
Hope it helps
I used a slightly modified version:
with open(file_name, 'w', encoding = 'utf-8') as f:
for rec_index, rec in df.iterrows():
f.write(rec['<field>'] + '\n')
I had to write the contents of a dataframe field (that was delimited) as a text file.
You can increase the Heap Size by passing JVM parameters -Xms and -Xmx like below:
For Jar Files:
java -jar -Xms4096M -Xmx6144M jarFilePath.jar
For Java Files:
java -Xms4096M -Xmx6144M ClassName
The above parameters increase the InitialHeapSize (-Xms) to 4GB (4096 MB) and MaxHeapSize(-Xmx) to 6GB (6144 MB).
But, the Young Generation Heap Size will remain same and the additional HeapSize will be added to the Old Generation Heap Size. To equalize the size of Young Gen Heap and Old Gen Heap, use -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy params.
java -jar -Xms4096M -Xmx6144M -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy pathToJarFile.jar
-XX:NewRatio = Old Gen Heap Size : Young Gen HeapSize (You can play with this ratio to get your desired ratio).
It seems like overkill but you can use supervisor to start and stop your simpleHttpserver, and completely manage it as a service.
Or just run it in the foreground as suggested and kill it with control c
I've found a way where you can set the real line height (not a factor) and it even renders live in Interface Builder. Just follow the instructions below. Code is written in Swift 4.
Step #1: Create a file named DesignableLabel.swift
and insert the following code:
import UIKit
@IBDesignable
class DesignableLabel: UILabel {
@IBInspectable var lineHeight: CGFloat = 20 {
didSet {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
paragraphStyle.alignment = self.textAlignment
let attrString = NSMutableAttributedString(string: text!)
attrString.addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: attrString.length))
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attrString.length))
attributedText = attrString
}
}
}
Step #2: Place a UILabel
into a Storyboard/XIB and set its class to DesignableLabel
. Wait for your project to build (build must succeed!).
Step 3: Now you should see a new property in the properties pane named "Line Height". Just set the value you like and you should see the results immediately!
This version
controls backtracking
/(["'])((?:(?!\1)[^\\]|(?:\\\\)*\\[^\\])*)\1/
The issue is because you have a bean of type SuggestionService created through @Component annotation and also through the XML config . As explained by JB Nizet, this will lead to the creation of a bean with name 'suggestionService' created via @Component and another with name 'SuggestionService' created through XML .
When you refer SuggestionService by @Autowired, in your controller, Spring autowires "by type" by default and find two beans of type 'SuggestionService'
You could do the following
Remove @Component from your Service and depend on mapping via XML - Easiest
Remove SuggestionService from XML and autowire the dependencies - use util:map to inject the indexSearchers map.
Use @Resource instead of @Autowired to pick the bean by its name .
@Resource(name="suggestionService")
private SuggestionService service;
or
@Resource(name="SuggestionService")
private SuggestionService service;
both should work.The third is a dirty fix and it's best to resolve the bean conflict through other ways.
Set Arg = WScript.Arguments
set WshShell = createObject("Wscript.Shell")
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout
Set rs = CreateObject("ADODB.Recordset")
With rs
.Fields.Append "LineNumber", 4
.Fields.Append "Txt", 201, 5000
.Open
LineCount = 0
Do Until Inp.AtEndOfStream
LineCount = LineCount + 1
.AddNew
.Fields("LineNumber").value = LineCount
.Fields("Txt").value = Inp.readline
.UpDate
Loop
.Sort = "LineNumber ASC"
If LCase(Arg(1)) = "t" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber < " & LCase(Arg(3)) + 1
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber > " & LCase(Arg(3))
End If
ElseIf LCase(Arg(1)) = "b" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber > " & LineCount - LCase(Arg(3))
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber < " & LineCount - LCase(Arg(3)) + 1
End If
End If
Do While not .EOF
Outp.writeline .Fields("Txt").Value
.MoveNext
Loop
End With
Cut
filter cut {t|b} {i|x} NumOfLines
Cuts the number of lines from the top or bottom of file.
t - top of the file
b - bottom of the file
i - include n lines
x - exclude n lines
Example
cscript /nologo filter.vbs cut t i 5 < "%systemroot%\win.ini"
Another way This outputs lines 5001+, adapt for your use. This uses almost no memory.
Do Until Inp.AtEndOfStream
Count = Count + 1
If count > 5000 then
OutP.WriteLine Inp.Readline
End If
Loop
This can be done from the command line using the SETX
command. For example to 'move' your temporary files to another disk:
SETX TEMP d:\tmp
Both methods have different goals/responsibilities. The task of the constructor (which is a language supported feature) is to make sure that the representation invariant holds. Otherwise stated to make sure that the instance is valid by giving correct values to the members. It is up to the developer to decide what 'correct' means.
The task of the onInit() method (which is an angular concept) is to allow method invocations on a correct object (representation invariant). Each method should in turn make sure that the representation invariant holds when the method terminates.
The constructor should be used to create 'correct' objects, the onInit method gives you the opportunity to invoke method calls at a well defined instance.
According to the certification exam you should use Convert.ToXXX() whenever possible for simple conversions because it optimizes performance better than CXXX conversions.
I prefer to stop the MongoDB server using the port
command itself.
sudo port unload mongodb
And to start it again.
sudo port load mongodb
Adding overflow:auto
before setting overflow-y
seems to do the trick in Google Chrome.
{
width:249px;
height:299px;
background-color:Gray;
overflow: auto;
overflow-y: scroll;
max-width:230px;
max-height:100px;
}
it's depends on what service you're using.
if you use MySQL Workbench it wold be some thing like this :
jdbc:mysql://"host":"port number"/
String url = "jdbc:mysql://localhost:3306/";
And of course it will be different if you using SSL/SSH.
For more information follow the official link of Jetbriens (intelliJ idea) :
https://www.jetbrains.com/help/idea/connecting-to-a-database.html
Configuring database connections #
https://www.jetbrains.com/help/idea/configuring-database-connections.html
jasonmp85 is right about passing a different array to String.format
. The size of an array can't be changed once constructed, so you'd have to pass a new array instead of modifying the existing one.
Object newArgs = new Object[args.length+1];
System.arraycopy(args, 0, newArgs, 1, args.length);
newArgs[0] = extraVar;
String.format(format, extraVar, args);
Visibility : Hidden Vs Collapsed
Consider following code which only shows three Labels
and has second Label
visibility
as Collapsed
:
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Center">
<StackPanel.Resources>
<Style TargetType="Label">
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="0"/>
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="BorderThickness" Value="1" />
</Style>
</StackPanel.Resources>
<Label Width="50" Content="First"/>
<Label Width="50" Content="Second" Visibility="Collapsed"/>
<Label Width="50" Content="Third"/>
</StackPanel>
Output Collapsed:
Now change the second Label
visibility
to Hiddden
.
<Label Width="50" Content="Second" Visibility="Hidden"/>
Output Hidden:
As simple as that.
Closing a SpringApplication
basically means closing the underlying ApplicationContext
. The SpringApplication#run(String...)
method gives you that ApplicationContext
as a ConfigurableApplicationContext
. You can then close()
it yourself.
For example,
@SpringBootApplication
public class Example {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
// ...determine it's time to shut down...
ctx.close();
}
}
Alternatively, you can use the static
SpringApplication.exit(ApplicationContext, ExitCodeGenerator...)
helper method to do it for you. For example,
@SpringBootApplication
public class Example {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
// ...determine it's time to stop...
int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
@Override
public int getExitCode() {
// no errors
return 0;
}
});
// or shortened to
// int exitCode = SpringApplication.exit(ctx, () -> 0);
System.exit(exitCode);
}
}
npm install <packagename> --registry http://registry.npmjs.org/
Try specifying the registry with the install command. Solved my problem.
In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.
You mean something like this?
long key = -1L;
PreparedStatement preparedStatement = connection.prepareStatement(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setXXX(index, VALUE);
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
if (rs.next()) {
key = rs.getLong(1);
}
I was searching for a simple solution without window focus. Jayk's answer, pynput
, works perfect for me. Here is the example how I use it.
from pynput import keyboard
def on_press(key):
if key == keyboard.Key.esc:
return False # stop listener
try:
k = key.char # single-char keys
except:
k = key.name # other keys
if k in ['1', '2', 'left', 'right']: # keys of interest
# self.keys.append(k) # store it in global-like variable
print('Key pressed: ' + k)
return False # stop listener; remove this if want more keys
listener = keyboard.Listener(on_press=on_press)
listener.start() # start to listen on a separate thread
listener.join() # remove if main thread is polling self.keys
If you want the file upload control to Limit the types of files user can upload on a button click then this is the way..
<script type="text/JavaScript">
<!-- Begin
function TestFileType( fileName, fileTypes ) {
if (!fileName) return;
dots = fileName.split(".")
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];
return (fileTypes.join(".").indexOf(fileType) != -1) ?
alert('That file is OK!') :
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
}
// -->
</script>
You can then call the function from an event like the onClick of the above button, which looks like:
onClick="TestFileType(this.form.uploadfile.value, ['gif', 'jpg', 'png', 'jpeg']);"
You can change this to: PDF
and XLS
You can see it implemented over here: Demo
ngStyle
accepts a map:
$scope.myStyle = {
"width" : "900px",
"background" : "red"
};
I imagine that there are not many browsers supporting extension. Indeed, I have been interested in this question for the last year and I only found Dolphin supporting add-ons and other cool features announced few days ago. I want to test it soon.
PUT /testIndex
{
"mappings": {
"properties": { <--ADD THIS
"field1": {
"type": "integer"
},
"field2": {
"type": "integer"
},
"field3": {
"type": "string",
"index": "not_analyzed"
},
"field4": {
"type": "string",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
}
},
"settings": {
bla
bla
bla
}
}
Here's a similar command I know works:
curl -v -H "Content-Type: application/json" -H "Authorization: Basic cGC3COJ1c2Vy925hZGFJbXBvcnABCnRl" -X PUT -d '{"mappings":{"properties":{"city":{"type": "text"}}}}' https://35.80.2.21/manzanaIndex
The breakdown for the above curl command is:
PUT /manzanaIndex
{
"mappings":{
"properties":{
"city":{
"type": "text"
}
}
}
}
Since Guava 15.0 (released September 2013) there's EvictingQueue:
A non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full. An evicting queue must be configured with a maximum size. Each time an element is added to a full queue, the queue automatically removes its head element. This is different from conventional bounded queues, which either block or reject new elements when full.
This class is not thread-safe, and does not accept null elements.
Example use:
EvictingQueue<String> queue = EvictingQueue.create(2);
queue.add("a");
queue.add("b");
queue.add("c");
queue.add("d");
System.out.print(queue); //outputs [c, d]
The error message is quite clear: you have a configuration element in a web.config file in a subfolder of your web app that is not allowed at that level - OR you forgot to configure your web application as IIS application.
Example: you try to override application level settings like forms authentication parameters in a web.config in a subfolder of your application
From an accessibility perspective <a>
without a href is not tab-able, all links should be tab-able so add a tabindex='0" if you don't have a href.
based on graycrow's excellent answer...
Here's a more real world example that has two cicular divs with some filler content. I replaced the hard-coded png background with just a hex value, i.e.
-=-webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
is replaced with
-webkit-mask-image:#fff;
See this JSFiddle... http://jsfiddle.net/hqLkA/
Please try below:
DECLARE @Today DATETIME;
SET @Today = '12/5/2007';
SET LANGUAGE Italian;
SELECT DATENAME(month, @Today) AS 'Month Name';
SET LANGUAGE us_english;
SELECT DATENAME(month, @Today) AS 'Month Name' ;
GO
Reference:
https://docs.microsoft.com/en-us/sql/t-sql/statements/set-language-transact-sql
Quite simply the number is the precision of the timestamp, the fraction of a second held in the column:
SQL> create table t23
2 (ts0 timestamp(0)
3 , ts3 timestamp(3)
4 , ts6 timestamp(6)
5 )
6 /
Table created.
SQL> insert into t23 values (systimestamp, systimestamp, systimestamp)
2 /
1 row created.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
SQL>
If we don't specify a precision then the timestamp defaults to six places.
SQL> alter table t23 add ts_def timestamp;
Table altered.
SQL> update t23
2 set ts_def = systimestamp
3 /
1 row updated.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
SQL>
Note that I'm running on Linux so my TIMESTAMP
column actually gives me precision to six places i.e. microseconds. This would also be the case on most (all?) flavours of Unix. On Windows the limit is three places i.e. milliseconds. (Is this still true of the most modern flavours of Windows - citation needed).
As might be expected, the documentation covers this. Find out more.
"when you create timestamp(9) this gives you nanos right"
Only if the OS supports it. As you can see, my OEL appliance does not:
SQL> alter table t23 add ts_nano timestamp(9)
2 /
Table altered.
SQL> update t23 set ts_nano = systimestamp(9)
2 /
1 row updated.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
TS_NANO
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
24-JAN-12 08.28.03.990557000 AM
SQL>
(Those trailing zeroes could be a coincidence but they aren't.)
umh.. like that?
$newstring = substr($dynamicstring, -7);
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
You just use this code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.80">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical|start"
android:paddingBottom="5dp"
android:paddingTop="5dp">
<Spinner
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/spiner_back"
android:visibility="visible" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|end"
android:src="@drawable/ic_arrow_drop_down_black_24dp" />
</FrameLayout>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.20">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorred"
android:fontFamily="@font/raleway_extrabold"
android:text="GO"
android:textColor="@color/colorwhite" />
</LinearLayout>
</LinearLayout>
And This is background which i used...
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<solid android:color="@color/colorwhite" />
Take a look into NSColorWell class reference.
Here is a repeat-done directive that calls a specified function when true. I have found that the called function must use $timeout with interval=0 before doing DOM manipulation, such as initializing tooltips on the rendered elements. jsFiddle: http://jsfiddle.net/tQw6w/
In $scope.layoutDone, try commenting out the $timeout line and uncommenting the "NOT CORRECT!" line to see the difference in the tooltips.
<ul>
<li ng-repeat="feed in feedList" repeat-done="layoutDone()" ng-cloak>
<a href="{{feed}}" title="view at {{feed | hostName}}" data-toggle="tooltip">{{feed | strip_http}}</a>
</li>
</ul>
JS:
angular.module('Repeat_Demo', [])
.directive('repeatDone', function() {
return function(scope, element, attrs) {
if (scope.$last) { // all are rendered
scope.$eval(attrs.repeatDone);
}
}
})
.filter('strip_http', function() {
return function(str) {
var http = "http://";
return (str.indexOf(http) == 0) ? str.substr(http.length) : str;
}
})
.filter('hostName', function() {
return function(str) {
var urlParser = document.createElement('a');
urlParser.href = str;
return urlParser.hostname;
}
})
.controller('AppCtrl', function($scope, $timeout) {
$scope.feedList = [
'http://feeds.feedburner.com/TEDTalks_video',
'http://feeds.nationalgeographic.com/ng/photography/photo-of-the-day/',
'http://sfbay.craigslist.org/eng/index.rss',
'http://www.slate.com/blogs/trending.fulltext.all.10.rss',
'http://feeds.current.com/homepage/en_US.rss',
'http://feeds.current.com/items/popular.rss',
'http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml'
];
$scope.layoutDone = function() {
//$('a[data-toggle="tooltip"]').tooltip(); // NOT CORRECT!
$timeout(function() { $('a[data-toggle="tooltip"]').tooltip(); }, 0); // wait...
}
})
It's not recommended to add conda.exe path directly into the System Environment Variables at stated by anaconda installer :
For Windows Users, Open Conda Prompt Shortcut and change the Target into the Correct Address :
Something a bit more universal since this comes up on google. While the details are more specific, the title of this question is more universal.
/**
* recursively create a long directory path
*/
function createPath($path) {
if (is_dir($path)) return true;
$prev_path = substr($path, 0, strrpos($path, '/', -2) + 1 );
$return = createPath($prev_path);
return ($return && is_writable($prev_path)) ? mkdir($path) : false;
}
This will take a path, possibly with a long chain of uncreated directories, and keep going up one directory until it gets to an existing directory. Then it will attempt to create the next directory in that directory, and continue till it's created all the directories. It returns true if successful.
Could be improved by providing a stopping level so it just fails if it goes beyond user folder or something and by including permissions.
Try this:
DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null ? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;
I use these:
/* Non-Retina */
@media screen and (-webkit-max-device-pixel-ratio: 1) {
}
/* Retina */
@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (min--moz-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5) {
}
/* iPhone Portrait */
@media screen and (max-device-width: 480px) and (orientation:portrait) {
}
/* iPhone Landscape */
@media screen and (max-device-width: 480px) and (orientation:landscape) {
}
/* iPad Portrait */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
}
/* iPad Landscape */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
}
http://zsprawl.com/iOS/2012/03/css-for-iphone-ipad-and-retina-displays/
You can use use findFragmentById
in FragmentManager
.
Since you are using the Support library (you are extending FragmentActivity) you can use:
getSupportFragmentManager().findFragmentById(R.id.pageview)
If you are not using the support library (so you are on Honeycomb+ and you don't want to use the support library):
getFragmentManager().findFragmentById(R.id.pageview)
Please consider that using the support library is recommended even on Honeycomb+.
alert()
doesn't support HTML, but you have some alternatives to format your message.
You can use Unicode characters as others stated, or you can make use of the ES6 Template literals. For example:
...
.catch(function (error) {
const alertMessage = `Error retrieving resource. Please make sure:
• the resource server is accessible
• you're logged in
Error: ${error}`;
window.alert(alertMessage);
}
As you can see, it maintains the line breaks and spaces that we included in the variable, with no extra characters.
I have a function next()
which will maybe inspire you.
function queue(target) {
var array = Array.prototype;
var queueing = [];
target.queue = queue;
target.queued = queued;
return target;
function queued(action) {
return function () {
var self = this;
var args = arguments;
queue(function (next) {
action.apply(self, array.concat.apply(next, args));
});
};
}
function queue(action) {
if (!action) {
return;
}
queueing.push(action);
if (queueing.length === 1) {
next();
}
}
function next() {
queueing[0](function (err) {
if (err) {
throw err;
}
queueing = queueing.slice(1);
if (queueing.length) {
next();
}
});
}
}
As something of an aside, MAXDOP can apparently be used as a workaround to a potentially nasty bug:
Just use Apache Commons
A couple of things:
You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b
switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k
to the command line to get more or less DVD video bitrate.
You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264
as part of the command line. Otherwise -vcodec mpeg4
will also do a better job than MPEG-1, but not as well as x264.
There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.
There is another possibility that can cause this error in hibernate. You may set an unsaved reference of your object A
to an attached entity B
and want to persist object C
. Even in this case, you will get the aforementioned error.
Other answers work, but
To get the full/default price:
$product->get_price_html();
Here is what I ended up doing and it worked great.
First I moved the file input outside of the form so that it is not submitted:
<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
<input id="name" value="#{name}" />
... a few more inputs ...
</form>
Then I changed the uploadPhotos
function to handle only the resizing:
window.uploadPhotos = function(url){
// Read in file
var file = event.target.files[0];
// Ensure it's an image
if(file.type.match(/image.*/)) {
console.log('An image has been loaded');
// Load the image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
// Resize the image
var canvas = document.createElement('canvas'),
max_size = 544,// TODO : pull max size from a site config
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
var resizedImage = dataURLToBlob(dataUrl);
$.event.trigger({
type: "imageResized",
blob: resizedImage,
url: dataUrl
});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}
};
As you can see I'm using canvas.toDataURL('image/jpeg');
to change the resized image into a dataUrl adn then I call the function dataURLToBlob(dataUrl);
to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:
/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = parts[1];
return new Blob([raw], {type: contentType});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB */
Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.
/* Handle image resized events */
$(document).on("imageResized", function (event) {
var data = new FormData($("form[id*='uploadImageForm']")[0]);
if (event.blob && event.url) {
data.append('image_data', event.blob);
$.ajax({
url: event.url,
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
//handle errors...
}
});
}
});
I know this is an old thread but it might be useful for some people such as myself that months after are hitting this issue for the first time.
Here is some code that resizes the image every time you reload the image. I am aware this is not optimal at all, but I provide it as a proof of concept.
Also, sorry for using jQuery for simple selectors but I just feel too comfortable with the syntax.
$(document).on('ready', createImage);_x000D_
$(window).on('resize', createImage);_x000D_
_x000D_
var createImage = function(){_x000D_
var canvas = document.getElementById('myCanvas');_x000D_
canvas.width = window.innerWidth || $(window).width();_x000D_
canvas.height = window.innerHeight || $(window).height();_x000D_
var ctx = canvas.getContext('2d');_x000D_
img = new Image();_x000D_
img.addEventListener('load', function () {_x000D_
ctx.drawImage(this, 0, 0, w, h);_x000D_
});_x000D_
img.src = 'http://www.ruinvalor.com/Telanor/images/original.jpg';_x000D_
};
_x000D_
html, body{_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
background: #000;_x000D_
}_x000D_
canvas{_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
z-index: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Canvas Resize</title>_x000D_
</head>_x000D_
<body>_x000D_
<canvas id="myCanvas"></canvas>_x000D_
</body>_x000D_
</html>
_x000D_
My createImage function is called once when the document is loaded and after that it is called every time the window receives a resize event.
I tested it in Chrome 6 and Firefox 3.6, both on the Mac. This "technique" eats processor as it if was ice cream in the summer, but it does the trick.
Add the following to your xml:
android:clickable="true"
android:focusable="true"
android:background="?android:attr/selectableItemBackground"
And add to your adapter (if it's your case)
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val attrs = intArrayOf(R.attr.selectableItemBackground)
val typedArray = holder.itemView.context.obtainStyledAttributes(attrs)
val selectableItemBackground = typedArray.getResourceId(0, 0)
typedArray.recycle()
holder.itemView.isClickable = true
holder.itemView.isFocusable = true
holder.itemView.foreground = holder.itemView.context.getDrawable(selectableItemBackground)
}
}
git checkout foo/bar.txt
did you tried that? (without a HEAD keyword)
I usually revert my changes this way.
#!/bin/bash
process_install()
{
commands...
commands...
}
process_exit()
{
commands...
commands...
}
if [ "$choice" = "true" ] then
process_install
else
process_exit
fi
You need to have the file /root/test/devenv/openstack-rhel/pom.xml
This file need to have the followings elements:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.openstack</groupId>
<artifactId>openstack-rhel-rpms</artifactId>
<version>2012.1-SNAPSHOT</version>
<packaging>pom</packaging>
</project>
I used below regex to get that result also when its finished by a \
(\\[^\\]+)\\?$
extension NSDate {
func toMillis() -> NSNumber {
return NSNumber(longLong:Int64(timeIntervalSince1970 * 1000))
}
static func fromMillis(millis: NSNumber?) -> NSDate? {
return millis.map() { number in NSDate(timeIntervalSince1970: Double(number) / 1000)}
}
static func currentTimeInMillis() -> NSNumber {
return NSDate().toMillis()
}
}
The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?
If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:
public class MyClass
{
public void doSomething(int i)
{
...
}
public void doSomething(int i, String s)
{
...
}
public void doSomething(int i, String s, boolean b)
{
...
}
}
If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:
public MyClass
{
public void doSomething(int... integers)
{
for (int i : integers)
{
...
}
}
}
Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.
Ryan Bates uses a nice little bit of code in his Railscast on beta invitations. This produces a 40 character alphanumeric string.
Digest::SHA1.hexdigest([Time.now, rand].join)
I ran into this issue as well, but in order to use a safe pipe in my angular module, I installed the safe-pipe npm package, which you can find here. FYI, this worked in Angular 9.1.3, I haven't tried this in any other versions of Angular. Here's how you add it step by step:
Install the package via npm install safe-pipe or yarn add safe-pipe. This will store a reference to it in your dependencies in the package.json file, which you should already have from starting a new Angular project.
Add SafePipeModule module to NgModule.imports in your Angular module file like so:
import { SafePipeModule } from 'safe-pipe';
@NgModule({
imports: [ SafePipeModule ]
})
export class AppModule { }
Add the safe pipe to an element in the template for the Angular component you are importing into your NgModule this way:
<element [property]="value | safe: sanitizationType"></element>
<div [style.background-image]="'url(' + pictureUrl + ')' | safe: 'style'" class="pic bg-pic"></div>
<img [src]="pictureUrl | safe: 'url'" class="pic" alt="Logo">
<iframe [src]="catVideoEmbed | safe: 'resourceUrl'" width="640" height="390"></iframe>
<pre [innerHTML]="htmlContent | safe: 'html'"></pre>
Do you have Git information showing in your Bash prompt? If so, maybe you're inadvertently doing way too much work on every command. To test this theory try the following temporary change in Bash:
export PS1='$'
This will do what you want:
select *
from orders_products
INNER JOIN orders
ON orders_products.orders_id = orders.orders_id
where products_id in (180, 181);
Set your HTML as
<div id="body" hidden="">
<h1>Numbers</h1>
</div>
<div id="body1" hidden="hidden">
Body 1
</div>
And now set the javascript as
function changeDiv()
{
document.getElementById('body').hidden = "hidden"; // hide body div tag
document.getElementById('body1').hidden = ""; // show body1 div tag
document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked";
// display text if JavaScript worked
}
Check, it works.
Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:
Given what you wrote, I suspect whatever converts the database data to XML is broken; it's propagating non-XML characters.
Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.
If the converter output looks good, the problem is in your XML consumer; it's inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.
Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn't, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.
In C++ you would use std::find
, and check if the resultant pointer points to the end of the range, like this:
Foo array[10];
... // Init the array here
Foo *foo = std::find(std::begin(array), std::end(array), someObject);
// When the element is not found, std::find returns the end of the range
if (foo != std::end(array)) {
cerr << "Found at position " << std::distance(array, foo) << endl;
} else {
cerr << "Not found" << endl;
}
Set the following two environment variables:
NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0
where gpu_id
is the ID of your selected GPU, as seen in the host system's nvidia-smi
(a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).
You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id
parameter in nvidia-smi
run in a terminal in the guest system).
This method based on NVIDIA_VISIBLE_DEVICES
exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES
to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).
Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0
or env
in Kubernetes or Openshift.
If you want GPU load-balancing, make gpu_id
random at each guest system start.
If setting this with python, make sure you are using strings for all environment variables, including numerical ones.
You can verify that a different card is selected for each value of gpu_id
by inspecting nvidia-smi
's Bus-Id parameter (in a terminal run in the guest system).
The accepted solution based on CUDA_VISIBLE_DEVICES
alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).
This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu
), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).
This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.
You may want to try this Firebug lite extension for Chrome.
A 2d array is simply an array of arrays. The analog for lists is simply a List
of List
s.
ArrayList<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();
I'll admit, it's not a pretty solution, especially if you go for a 3 or more dimensional structure.
In Windows systems, use the command csc <filname>.cs
in the command prompt while the current directory is in Microsoft Visual Studio\<Year>\<Version>
There are two ways:
Using the command prompt:
Using Developer Command Prompt :
Start --> Developer Command Prompt for VS 2017 (Here the directory is already set to Visual Studio folder)
Use the command: csc /.cs
Hope it helps!
Converting your value in milliseconds to days is simply (MsValue / 86,400,000)
We can get 1/1/1970 as numeric value by DATE(1970,1,1)
= (MsValueCellReference / 86400000) + DATE(1970,1,1)
Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss
gives me a date and time of 19/04/2010 08:16:11
You need jQuery see bootstrap's basic template
Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;
MySQL – Temporarily disable Foreign Key Checks or Constraints
Include the fonts Copy over all the font files to a /fonts directory near your CSS.
<span class="glyphicon glyphicon-ok"></span>
Arrays are fixed in size, you cannot resize them after creating them. You can remove an existing item by setting it to null
:
objects[4] = null;
But you won't be able to delete that entire slot off the array and reduce its size by 1.
If you need a dynamically-sized array, you can use an ArrayList
. With it, you can add()
and remove()
objects, and it will grow and shrink as needed.
Because UICollectionView
is so flexible, there are multiple ways you could change the number of columns, depending on the kind of layout you use.
The UICollectionViewFlowLayout
(which is probably what you're working with) doesn't specify a number of columns directly (because it depends on the view size/orientation). The easiest way to change it would be to set the itemSize
property and/or minimumInteritemSpacing
/minimumLineSpacing
.
"Copy on write" means more or less what it sounds like: everyone has a single shared copy of the same data until it's written, and then a copy is made. Usually, copy-on-write is used to resolve concurrency sorts of problems. In ZFS, for example, data blocks on disk are allocated copy-on-write; as long as there are no changes, you keep the original blocks; a change changed only the affected blocks. This means the minimum number of new blocks are allocated.
These changes are also usually implemented to be transactional, ie, they have the ACID properties. This eliminates some concurrency issues, because then you're guaranteed that all updates are atomic.
//different declaration type
vector<int>v;
vector<int>v2(5,30); //size is 5 and fill up with 30
vector<int>v3={10,20,30};
//From C++11 and onwards
for(auto itr:v2)
cout<<"\n"<<itr;
//(pre c++11)
for(auto itr=v3.begin(); itr !=v3.end(); itr++)
cout<<"\n"<<*itr;
You need to modify the Starter-Application class as shown below.
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages="com.nice.application")
@EnableJpaRepositories("com.spring.app.repository")
public class InventoryApp extends SpringBootServletInitializer {..........
And update the Controller, Service and Repository packages structure as I mentioned below.
Example: REST-Controller
package com.nice.controller;
--> It has to be modified as
package com.nice.application.controller;
You need to follow proper package structure for all packages which are in Spring Boot MVC flow.
So, If you modify your project bundle package structures correctly then your spring boot app will work correctly.
Can't you just use a Definite Assignment Assertion? (See https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions)
i.e. declaring the property as makes!: any[];
The ! assures typescript that there definitely will be a value at runtime.
Sorry I haven't tried this in angular but it worked great for me when I was having the exact same problem in React.
shell_escape () {
printf '%s' "'${1//\'/\'\\\'\'}'"
}
Implementation explanation:
double quotes so we can easily output wrapping single quotes and use the ${...}
syntax
bash's search and replace looks like: ${varname//search/replacement}
we're replacing '
with '\''
'\''
encodes a single '
like so:
'
ends the single quoting
\'
encodes a '
(the backslash is needed because we're not inside quotes)
'
starts up single quoting again
bash automatically concatenates strings with no white space between
there's a \
before every \
and '
because that's the escaping rules for ${...//.../...}
.
string="That's "'#@$*&^`(@#'
echo "original: $string"
echo "encoded: $(shell_escape "$string")"
echo "expanded: $(bash -c "echo $(shell_escape "$string")")"
P.S. Always encode to single quoted strings because they are way simpler than double quoted strings.
To convert an integer to a string:
integer :: i
character* :: s
if (i.LE.9) then
s=char(48+i)
else if (i.GE.10) then
s=char(48+(i/10))// char(48-10*(i/10)+i)
endif
I took some help from MSDN, but this is my answer:
double number;
string localStringNumber;
string doubleNumericValueasString = "65.89875";
System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint;
if (double.TryParse(doubleNumericValueasString, style, System.Globalization.CultureInfo.InvariantCulture, out number))
Console.WriteLine("Converted '{0}' to {1}.", doubleNumericValueasString, number);
else
Console.WriteLine("Unable to convert '{0}'.", doubleNumericValueasString);
localStringNumber =number.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"));
Let's say you have a button with the text, "Click Me". What width should that button be?
First, you definitely don't want the button to be smaller than the text. Otherwise, the text would be clipped. This is the horizontal compression resistance priority.
Second, you don't want the button to be bigger than it needs to be. A button that looked like this, [ Click Me ], is obviously too big. You want the button to "hug" its contents without too much padding. This is the horizontal content hugging priority. For a button, it isn't as strong as the horizontal compression resistance priority.
You can also use web storage too if the app specs allows you that (it has support for IE8+).
It has 5M (most browsers) or 10M (IE) of memory at its disposal.
"Web Storage (Second Edition)" is the API and "HTML5 Local Storage" is a quick start.
Sounds like you got your answer. Passing by value is expensive, but gives you a copy to work with if you need it.
A Spring Boot with Thymeleaf solution could look like:
Lets say my context-path is /app/
In Thymeleaf you can get it via:
<script th:inline="javascript">
/*<![CDATA[*/
let contextPath = /*[[@{/}]]*/
/*]]>*/
</script>
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Number.isInteger()
is probably the most concise. It returns true if it is an integer, and false if it isn't.
This is a supplemental answer for those arriving here based on the question title (like I did) and don't need to deal with the security issues related to saving passwords.
User settings are generally saved locally in Android using SharedPreferences
with a key-value pair. You use the String
key to save or look up the associated value.
String key = "myInt";
int valueToSave = 10;
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, valueToSave).commit();
Use apply()
instead of commit()
to save in the background rather than immediately.
String key = "myInt";
int defaultValue = 0;
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
int savedValue = sharedPref.getInt(key, defaultValue);
The default value is used if the key isn't found.
Rather than using a local key String in multiple places like I did above, it would be better to use a constant in a single location. You could use something like this at the top of your settings activity:
final static String PREF_MY_INT_KEY = "myInt";
I used an int
in my example, but you can also use putString()
, putBoolean()
, getString()
, getBoolean()
, etc.
See the documentation for more details.
There are multiple ways to get SharedPreferences. See this answer for what to look out for.
For SQL Server 2000:
SELECT su.name,so.name,so.crdate,*
FROM sysobjects so JOIN sysusers su
ON so.uid = su.uid
WHERE xtype='U'
ORDER BY so.name
Create a BroadcastReceiver
and register it to receive ACTION_BOOT_COMPLETED. You also need RECEIVE_BOOT_COMPLETED permission.
Read: Listening For and Broadcasting Global Messages, and Setting Alarms
Try this code :
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,null); // Code for inflating xml layout_x000D_
RelativeLayout item = view.findViewById(R.id.item);
_x000D_
LinearLayout parent = findViewById(R.id.container); //parent layout._x000D_
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,parent,false); _x000D_
RelativeLayout item = view.findViewById(R.id.item); //initialize layout & By this you can also perform any event._x000D_
parent.addView(view); //adding your inflated layout in parent layout.
_x000D_
Usually it would be this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>='2010-10-01'
AND yourtimetimefield< '2010-11-01'
But because you have a unix timestamps, you'll need something like this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>=unix_timestamp('2010-10-01')
AND yourtimetimefield< unix_timestamp('2010-11-01')
I don't think that you'll like it but I made a pair port for python :) using it is some how similar to c++
pair = Pair
pair.make_pair(value1, value2)
or
pair = Pair(value1, value2)
here's the source code pair_stl_for_python
There are two types of table views cells provided to you through the storyboard, they are Dynamic Prototypes and Static Cells
1. Dynamic Prototypes
From the name, this type of cell is generated dynamically. They are controlled through your code, not the storyboard. With help of table view's delegate and data source, you can specify the number of cells, heights of cells, prototype of cells programmatically.
When you drag a cell to your table view, you are declaring a prototype of cells. You can then create any amount of cells base on this prototype and add them to the table view through cellForRow
method, programmatically. The advantage of this is that you only need to define 1 prototype instead of creating each and every cell with all views added to them by yourself (See static cell).
So in this case, you cannot connect UI elements on cell prototype to your view controller. You will have only one view controller object initiated, but you may have many cell objects initiated and added to your table view. It doesn't make sense to connect cell prototype to view controller because you cannot control multiple cells with one view controller connection. And you will get an error if you do so.
To fix this problem, you need to connect your prototype label to a UITableViewCell
object. A UITableViewCell
is also a prototype of cells and you can initiate as many cell objects as you want, each of them is then connected to a view that is generated from your storyboard table cell prototype.
Finally, in your cellForRow
method, create the custom cell from the UITableViewCell
class, and do fun stuff with the label
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier") as! YourCell
cell.label.text = "it works!"
return cell
}
2. Static Cells
On the other hand, static cells are indeed configured though storyboard. You have to drag UI elements to each and every cell to create them. You will be controlling cell numbers, heights, etc from the storyboard. In this case, you will see a table view that is exactly the same from your phone compared with what you created from the storyboard. Static cells are more often used for setting page, which the cells do not change a lot.
To control UI elements for a static cell, you will indeed need to connect them directly to your view controller, and set them up.
If you create a new repository from the Github web GUI, you sometimes get the name 'main' instead of 'master'. By using the command git status
from your terminal you'd see which location you are. In some cases, you'd see origin/main
.
If you are trying to push your app to a cloud service via CLI then use 'main', not 'master'.
example:
git push heroku main
jQuery .scrollTo(): View - Demo, API, Source
I wrote this lightweight plugin to make page/element scrolling much easier. It's flexible where you could pass in a target element or specified value. Perhaps this could be part of jQuery's next official release, what do you think?
Examples Usage:
$('body').scrollTo('#target'); // Scroll screen to target element
$('body').scrollTo(500); // Scroll screen 500 pixels down
$('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down
Options:
scrollTarget: A element, string, or number which indicates desired scroll position.
offsetTop: A number that defines additional spacing above scroll target.
duration: A string or number determining how long the animation will run.
easing: A string indicating which easing function to use for the transition.
complete: A function to call once the animation is complete.
string root = HttpContext.Current.Server.MapPath("~/App_Data");
Above Code JAVA version: Thanks @William
public static List<Rect> detectLetters(Mat img){
List<Rect> boundRect=new ArrayList<>();
Mat img_gray =new Mat(), img_sobel=new Mat(), img_threshold=new Mat(), element=new Mat();
Imgproc.cvtColor(img, img_gray, Imgproc.COLOR_RGB2GRAY);
Imgproc.Sobel(img_gray, img_sobel, CvType.CV_8U, 1, 0, 3, 1, 0, Core.BORDER_DEFAULT);
//at src, Mat dst, double thresh, double maxval, int type
Imgproc.threshold(img_sobel, img_threshold, 0, 255, 8);
element=Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(15,5));
Imgproc.morphologyEx(img_threshold, img_threshold, Imgproc.MORPH_CLOSE, element);
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
Imgproc.findContours(img_threshold, contours,hierarchy, 0, 1);
List<MatOfPoint> contours_poly = new ArrayList<MatOfPoint>(contours.size());
for( int i = 0; i < contours.size(); i++ ){
MatOfPoint2f mMOP2f1=new MatOfPoint2f();
MatOfPoint2f mMOP2f2=new MatOfPoint2f();
contours.get(i).convertTo(mMOP2f1, CvType.CV_32FC2);
Imgproc.approxPolyDP(mMOP2f1, mMOP2f2, 2, true);
mMOP2f2.convertTo(contours.get(i), CvType.CV_32S);
Rect appRect = Imgproc.boundingRect(contours.get(i));
if (appRect.width>appRect.height) {
boundRect.add(appRect);
}
}
return boundRect;
}
And use this code in practice :
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat img1=Imgcodecs.imread("abc.png");
List<Rect> letterBBoxes1=Utils.detectLetters(img1);
for(int i=0; i< letterBBoxes1.size(); i++)
Imgproc.rectangle(img1,letterBBoxes1.get(i).br(), letterBBoxes1.get(i).tl(),new Scalar(0,255,0),3,8,0);
Imgcodecs.imwrite("abc1.png", img1);
Scott S's answer worked perfectly.
I was coding a web-based phone dialpad for mobile, and every time the user would press a number on the keypad (composed of td span elements in a table), the softkeyboard would pop up. I also wanted the user to not be able to tap into the input box of the number being dialed. This actually solved both problems in 1 shot. The following was used:
<input type="text" id="phone-number" onfocus="blur();" />
I realise this answer is not a direct response to the problem described by the OP, but I found this question as a result of searching for the same error message. I thought it worth posting my experience here just in case anybody is muddling over the same thing...
You can encounter the error in question as a result of a poorly formatted for
loop over an associative array. In a fit of bone-headedness, I was using -> instead of => in my for
statement:
foreach ($object->someArray as $key->$val) {
// do something
}
Of course, I should have had:
foreach ($object->someArray as $key=>$val) {
// do something
}
I confused myself at first, thinking the reported error was referring to the someArray property!
In .Net Core (as of v2.2) it should be:
new Process
{
StartInfo = new ProcessStartInfo(@"file path")
{
UseShellExecute = true
}
}.Start();
Related github issue can be found here
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
If you need n % m
then:
int i = (n < 0) ? (m - (abs(n) % m) ) %m : (n % m);
mathematical explanation:
n = -1 * abs(n)
-> n % m = (-1 * abs(n) ) % m
-> (-1 * (abs(n) % m) ) % m
-> m - (abs(n) % m))
Sorry, didn't quite get your question. So something like this?
str.ToCharArray().Any(char.IsDigit);
Or does the value have to be an integer completely, without any additional strings?
if(str.ToCharArray().All(char.IsDigit(c));
You can't.. You would have to know:
Maybe, just maybe if the object was optically tagged with for example a QR code, and you have a code-to-loc map...
I had this issue occurring in Xcode 10.3 after I switched over to my XCTest unit test target then back to the project run time target.
Turns out I had a different Teams selected in my provisioning profile for each target.
To fix it :
Clean Build Folder
Make sure all may targets are using the same Team. See Profile Signing under the general tab.
If not using same Team for all targets, clean before switching to a build target with
different team selected.
I think you could create a separate css class that you can use in these cases:
.disable-transition {
-webkit-transition: none;
-moz-transition: none;
-o-transition: color 0 ease-in;
-ms-transition: none;
transition: none;
}
Then in jQuery you would toggle the class like so:
$('#<your-element>').addClass('disable-transition');
No luck with Code lens in Community editions.
Press Shift + F12 to find all references.
Dim a As String = Microsoft.VisualBasic.right("I will be going to school in 2011!", 5)
MsgBox("the value is:" & a)
There are no gotchas. The default construction of std::string
is ""
. But you cannot compare a string to NULL
. The closest you can get is to check whether the string is empty or not, using the std::string::empty
method..
byte[] bytes = { 1,2,3,4 };
string stringByte= BitConverter.ToString(bytes);
Console.WriteLine(stringByte);
VonC's answer is pretty thorough. In addition I'd like to add one thing that helped me. If you just want to run a cron job without tailing a file, you'd be tempted to just remove the && tail -f /var/log/cron.log
from the cron command.
However this will cause the Docker container to exit shortly after running because when the cron command completes, Docker thinks the last command has exited and hence kills the container. This can be avoided by running cron in the foreground via cron -f
.
VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.
There is currently no way to disable this behaviour.
Sometimes, we are want to get the picture but not need to download it to real files,
i.e., download the data and keep it on memory.
For example, If I use the machine learning method, train a model that can recognize an image with the number (bar code).
When I spider some websites and that have those images so I can use the model to recognize it,
and I don't want to save those pictures on my disk drive,
then you can try the below method to help you keep download data on memory.
import requests
from io import BytesIO
response = requests.get(url)
with BytesIO as io_obj:
for chunk in response.iter_content(chunk_size=4096):
io_obj.write(chunk)
basically, is like to @Ranvijay Kumar
import requests
from typing import NewType, TypeVar
from io import StringIO, BytesIO
import matplotlib.pyplot as plt
import imageio
URL = NewType('URL', str)
T_IO = TypeVar('T_IO', StringIO, BytesIO)
def download_and_keep_on_memory(url: URL, headers=None, timeout=None, **option) -> T_IO:
chunk_size = option.get('chunk_size', 4096) # default 4KB
max_size = 1024 ** 2 * option.get('max_size', -1) # MB, default will ignore.
response = requests.get(url, headers=headers, timeout=timeout)
if response.status_code != 200:
raise requests.ConnectionError(f'{response.status_code}')
instance_io = StringIO if isinstance(next(response.iter_content(chunk_size=1)), str) else BytesIO
io_obj = instance_io()
cur_size = 0
for chunk in response.iter_content(chunk_size=chunk_size):
cur_size += chunk_size
if 0 < max_size < cur_size:
break
io_obj.write(chunk)
io_obj.seek(0)
""" save it to real file.
with open('temp.png', mode='wb') as out_f:
out_f.write(io_obj.read())
"""
return io_obj
def main():
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Host': 'statics.591.com.tw',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36'
}
io_img = download_and_keep_on_memory(URL('http://statics.591.com.tw/tools/showPhone.php?info_data=rLsGZe4U%2FbphHOimi2PT%2FhxTPqI&type=rLEFMu4XrrpgEw'),
headers, # You may need this. Otherwise, some websites will send the 404 error to you.
max_size=4) # max loading < 4MB
with io_img:
plt.rc('axes.spines', top=False, bottom=False, left=False, right=False)
plt.rc(('xtick', 'ytick'), color=(1, 1, 1, 0)) # same of plt.axis('off')
plt.imshow(imageio.imread(io_img, as_gray=False, pilmode="RGB"))
plt.show()
if __name__ == '__main__':
main()
After writing
header('HTTP/1.0 404 Not Found');
add one more header for any inexisting page on your site. It works, for sure.
header("Location: http://yoursite/nowhere");
die;
One simple possibility would be to make an array of 26 ints, each is a count for a letter a-z:
int alphacount[26] = {0}; //[0] = 'a', [1] = 'b', etc
Then loop through the string and increment the count for each letter:
for(int i = 0; i<strlen(mystring); i++) //for the whole length of the string
if(isalpha(mystring[i]))
alphacount[tolower(mystring[i])-'a']++; //make the letter lower case (if it's not)
//then use it as an offset into the array
//and increment
It's a simple idea that works for A-Z, a-z. If you want to separate by capitals you just need to make the count 52 instead and subtract the correct ASCII offset
I think that this will do the trick:
table{
table-layout: fixed;
width: 300px;
}
I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.
I have to assume you are using windows because you have mentioned notepad++.
Use notepad++. Right click on the file and choose "edit with notepad++"
Use notepad Change the filename extension to .txt and double click the file.
Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"
If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.
My problem at first was:
Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.
1) I Right click on my project -> Android Tools -> Add Support Library (Run my app...Didn't work so I keep it going...) 2) Right click on my project again -> Properties -> Android -> Check Android 4.1.2 (16) on Project Build Target (Run the app again...and get this:
Unable to execute dex: Multiple dex files define Landroid/support/v4/app/BackStackState;
3) So I went to the "lib" folder on my project and delete the "old" Android.support.library.jar (Run the app and cross fingers and...)
¡IT WORKS!
Hope it helps someone...Thanks people!
I ran into a similar problem and just passed the end of the array to the ArrayList.add()
index param like so:
public class Stack {
private ArrayList<String> stringList = new ArrayList<String>();
RandomStringGenerator rsg = new RandomStringGenerator();
private void push(){
String random = rsg.randomStringGenerator();
stringList.add(stringList.size(), random);
}
}
function omit(obj, key) {
const {[key]:ignore, ...rest} = obj;
return rest;
}
You can use ES6 spread operators like this. And to remove your key simply call
const newJson = omit(myjsonobj, "otherIndustry");
Its always better if you maintain pure function when you deal with type=object
in javascript.
Your code is just fine. The reason you're getting a black screen is because there's nothing on your second view controller.
Try something like:
secondViewController.view.backgroundColor = UIColor.redColor();
Now the view controller it shows should be red.
To actually do something with secondViewController
, create a subclass of UIViewController
and instead of
let secondViewController:UIViewController = UIViewController()
create an instance of your second view controller:
//If using code
let secondViewController = MyCustomViewController.alloc()
//If using storyboard, assuming you have a view controller with storyboard ID "MyCustomViewController"
let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("MyCustomViewController") as UIViewController
I realize this is not related to OSX, but on an embedded system (Beagle Bone Angstrom) I had the exact same error message. Installing the following ipk packages solved it.
opkg install python-setuptools
opkg install python-pip
This is the only syntax that worked for me
$('input[name="assReq"][value="' + obj["AssociationReq"] + '"]').prop('checked', 'checked');
The dir
wrapper can wrap, any other step, and it all works inside a steps
block, for example:
steps {
sh "pwd"
dir('your-sub-directory') {
sh "pwd"
}
sh "pwd"
}
Try setting the type of your parameter to [bool]
:
param
(
[int]$Turn = 0
[bool]$Unity = $false
)
switch ($Unity)
{
$true { "That was true."; break }
default { "Whatever it was, it wasn't true."; break }
}
This example defaults $Unity
to $false
if no input is provided.
Usage
.\RunScript.ps1 -Turn 1 -Unity $false
Something like this should work for you. Even if there are multiple query string values then this function should return the value of your desired key.
function getQSValue(url)
{
key = 'img_id';
query_string = url.split('?');
string_values = query_string[1].split('&');
for(i=0; i < string_values.length; i++)
{
if( string_values[i].match(key))
req_value = string_values[i].split('=');
}
return req_value[1];
}
check fnAddData: https://legacy.datatables.net/ref
$(document).ready(function () {
var table = $('#example').dataTable();
var url = '/RESTApplicationTest/webresources/entity.person';
$.get(url, function (data) {
for (var i = 0; i < data.length; i++) {
table.fnAddData([data[i].idPerson, data[i].firstname, data[i].lastname, data[i].email, data[i].phone])
}
});
});
JPA is a specification to standardize ORM-APIs. Hibernate is a vendor of a JPA implementation. So if you use JPA with hibernate, you can use the standard JPA API, hibernate will be under the hood, offering some more non standard functions. See http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html_single/ and http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/
Try setting a default value in the css (to let it know where you want it to start out)
position: relative;
transition: all 2s ease 0s;
top: 0; /* start out at position 0 */
I struggled with this from behind a proxy so I thought I should post what I did. Below one is worked for me.
-> "export HTTPS_PROXY=(yourproxy)"
The easiest way, at least for me, was:
Make sure that both projects have same target framework version here: right click on project -> properties -> application (tab) -> target framework
Also, make sure that the project "logger" (which you want to include in the main project) has the output type "Class Library" in: right click on project -> properties -> application (tab) -> output type
Finally, Rebuild the solution.
That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next f()
function
create function f() returns integer as $$
select 1;
$$ language sql;
is called as
select f(1);
It will error out with
ERROR: function f(integer) does not exist
LINE 1: select f(1);
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
because there is no f()
function that takes an integer as argument.
So you need to carefully compare what you are passing to the function to what it is expecting. That long list of table columns looks like bad design.
Running the command prompt or Powershell ISE as an administrator fixed this for me.
You don't have to add a .
in getElementsByClassName
, i.e.
var multibutton = angular.element(element.getElementsByClassName("multi-files"));
However, when using angular.element
, you do have to use jquery style selectors:
angular.element('.multi-files');
should do the trick.
Also, from this documentation "If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.""
If you open your second link in a browser you'll see the source code:
#!/bin/bash
# Script to download individual .nc files from the ORNL
# Daymet server at: http://daymet.ornl.gov
[...]
# For ranges use {start..end}
# for individul vaules, use: 1 2 3 4
for year in {2002..2003}
do
for tile in {1159..1160}
do wget --limit-rate=3m http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc -O ${tile}_${year}_vp.nc
# An example using curl instead of wget
#do curl --limit-rate 3M -o ${tile}_${year}_vp.nc http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc
done
done
So it's a bash script. Got Linux?
In any case, the script is nothing but a series of HTTP retrievals. Both wget and curl are available for most operating systems and almost all language have HTTP libraries so it's fairly trivial to rewrite in any other technology. There're also some Windows ports of bash itself (git includes one). Last but not least, Windows 10 now has native support for Linux binaries.
EDIT: based on your comment and assuming that this
is the element that is cloned.
$(this).clone()
.attr( 'id', this.id + '_' + new_id )
.attr( 'name', this.name + '_' + new_id )
.val( 'test' )
.appendTo('#someElement');
Full Example
<script type="text/javascript">
var new_id = 0;
$(document).ready( function() {
$('#container > input[type=button]').click( function() {
var oldinp = $('input#inp')[0];
var newinp = $(oldinp).clone()
.attr('id',oldinp.id + new_id )
.attr('name',oldinp.name + new_id )
.val('test')
.appendTo($('#container'));
$('#container').append('<br>');
new_id++;
});
});
</script>
<div id="container">
<input type="button" value="Clone" /><br/>
<input id="inp" name="inp" type="text" value="hmmm" /><br/>
</div>
function isObject(obj) {
return obj !== null && typeof obj === 'object';
}
const isArray = Array.isArray;
function isPlainObject(obj) {
return isObject(obj) && (
obj.constructor === Object // obj = {}
|| obj.constructor === undefined // obj = Object.create(null)
);
}
function mergeDeep(target, ...sources){
if (!sources.length) return target;
const source = sources.shift();
if (isPlainObject(source) || isArray(source)) {
for (const key in source) {
if (isPlainObject(source[key]) || isArray(source[key])) {
if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
target[key] = {};
}else if (isArray(source[key]) && !isArray(target[key])) {
target[key] = [];
}
mergeDeep(target[key], source[key]);
} else if (source[key] !== undefined && source[key] !== '') {
target[key] = source[key];
}
}
}
return mergeDeep(target, ...sources);
}
// test...
var source = {b:333};
var source2 = {c:32, arr: [33,11]}
var n = mergeDeep({a:33}, source, source2);
source2.arr[1] = 22;
console.log(n.arr); // out: [33, 11]
for a in someList:
list.append(splitColon.split(a))
You can rewrite the above as:
newlist = [splitColon.split(a) for a in someList]
The java.sql.Timestamp class has no format. Its toString method generates a String with a format.
Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.
First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.
Instant instant = mySqlDate.toInstant() ;
Lose the fraction of a second you don't want.
instant = instant.truncatedTo( ChronoUnit.Seconds );
Assign the time zone to adjust from UTC used by Instant.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );
Generate a String close to your desired output. Replace its T
in the middle with a SPACE.
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );
It looks like you're using the wrong tool there. Grep isn't that sophisticated, I think you want to step up to awk as the tool for the job:
awk '/blah/ { getline; print $0 }' logfile
If you get any problems let me know, I think its well worth learning a bit of awk, its a great tool :)
p.s. This example doesn't win a 'useless use of cat award' ;) http://porkmail.org/era/unix/award.html
If you want to retrieve the form values (such as those that would be sent using an HTTP POST) you can use:
JavaScript
const formData = new FormData(document.querySelector('form'))
for (var pair of formData.entries()) {
// console.log(pair[0] + ': ' + pair[1]);
}
form-serialize (https://code.google.com/archive/p/form-serialize/)
serialize(document.forms[0]);
jQuery
$("form").serializeArray()
The ImageView "scaleType" function may help you here.
This code will keep the aspect ratio and position the image at the top:
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitStart"
Here is a great post showing the possibilities and appearances from using scaleType.
Another suggestion is using flexbox instead of tables altogether. This is a "modern browser" thing of course, but come on, it's 2016 ;)
At least this might be an alternative solution for those looking for an answer to this nowadays, since the original post was from 2010.
Here's a great guide: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
.table {_x000D_
border: 1px solid red;_x000D_
padding: 2px;_x000D_
max-width: 300px;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
}_x000D_
.table-cell {_x000D_
border: 1px solid blue;_x000D_
flex: 1 30%;_x000D_
}_x000D_
.colspan-3 {_x000D_
border: 1px solid green;_x000D_
flex: 1 100%;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="table-cell">_x000D_
row 1 - cell 1_x000D_
</div>_x000D_
<div class="table-cell">_x000D_
row 1 - cell 2_x000D_
</div>_x000D_
<div class="table-cell">_x000D_
row 1 - cell 3_x000D_
</div>_x000D_
<div class="table-cell colspan-3">_x000D_
row 2 - cell 1 (spans 3 columns)_x000D_
</div>_x000D_
</div>
_x000D_
Three ways you can do that:-
Approach 1:-
// using spread ...
let obj1 = {
...obj2
};
Approach2:-
// using Object.assign() method
let obj1 = Object.assign({}, obj2);
Approach3:-
// using JSON
let obj1 = JSON.parse(JSON.stringify(obj2));
I usually create log table with a stored procedure to log to it. The call the logging procedure wherever needed from the procedure under development.
Looking at other posts on this same question, it seems like a common practice, although there are some alternatives.
You can disable them altogether by
(setq make-backup-files nil)
For InteliJ IDEA 11.0 and above
Goto File --> Settings in the Settings window Editor --> Appearance
and tick Show line numbers check box.
I uninstalled the NDK since I didn't need it . Go to SDK manager on Android studio ( Tools -> Android -> SDK Manager ) . If NDK is installed . Just uncheck the box and click OK . The installed components will be deleted .
I implemented many automation cases based on REST Assured , a jave DSL for testing restful service. https://code.google.com/p/rest-assured/
The syntax is easy, it supports json and xml. https://code.google.com/p/rest-assured/wiki/Usage
Before that, I tried SOAPUI and had some issues with the free version. Plus the cases are in xml files which hard to extend and reuse, simply I don't like
This is the notorious floating point rounding issue. Just add a very small number, to correct the issue.
double a;
a=3669.0;
int b;
b=a+ 1e-9;
As a variant you can use third party script PID Cat by Jake Wharton. This script has two major advantages:
From documentation:
During application development you often want to only display log messages coming from your app. Unfortunately, because the process ID changes every time you deploy to the phone it becomes a challenge to grep for the right thing.
This script solves that problem by filtering by application package.
HTTPS is so powerful because it uses asymmetric cryptography. This type of cryptography not only allows you to create an encrypted tunnel but you can verify that you are talking to the right person, and not a hacker.
Here is Java source code which uses the asymmetric cipher RSA (used by PGP) to communicate: http://www.hushmail.com/services/downloads/
Normally you can't DELETE from multiple tables at once, unless you'll use JOINs as shown in other answers.
However if all yours tables starts with certain name, then this query will generate query which would do that task:
SELECT CONCAT('DELETE FROM ', GROUP_CONCAT(TABLE_NAME SEPARATOR ' WHERE user_id=123;DELETE FROM ') , 'FROM table1;' ) AS statement FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'table%'
then pipe it (in shell) into mysql command for execution.
For example it'll generate something like:
DELETE FROM table1 WHERE user_id=123;
DELETE FROM table2 WHERE user_id=123;
DELETE FROM table3 WHERE user_id=123;
More shell oriented example would be:
echo "SHOW TABLES LIKE 'table%'" | mysql | tail -n +2 | xargs -L1 -I% echo "DELETE FROM % WHERE user_id=123;" | mysql -v
If you want to use only MySQL for that, you can think of more advanced query, such as this:
SET @TABLES = (SELECT GROUP_CONCAT(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'table%');
PREPARE drop_statement FROM 'DELETE FROM @tables';
EXECUTE drop_statement USING @TABLES;
DEALLOCATE PREPARE drop_statement;
The above example is based on: MySQL – Delete/Drop all tables with specific prefix.
To clearly answer OP's question of how to determine whether a variable is set, @Lionel's answer is correct:
if test "${name+x}"; then
echo 'name is set'
else
echo 'name is not set'
fi
This question already has a lot of answers, but none of them offered bona fide boolean expressions to clearly differentiate between variables values.
Here are some unambiguous expressions that I worked out:
+-----------------------+-------------+---------+------------+
| Expression in script | name='fish' | name='' | unset name |
+-----------------------+-------------+---------+------------+
| test "$name" | TRUE | f | f |
| test -n "$name" | TRUE | f | f |
| test ! -z "$name" | TRUE | f | f |
| test ! "${name-x}" | f | TRUE | f |
| test ! "${name+x}" | f | f | TRUE |
+-----------------------+-------------+---------+------------+
By the way, these expressions are equivalent:
test <expression>
<=> [ <expression> ]
Other ambiguous expressions to be used with caution:
+----------------------+-------------+---------+------------+
| Expression in script | name='fish' | name='' | unset name |
+----------------------+-------------+---------+------------+
| test "${name+x}" | TRUE | TRUE | f |
| test "${name-x}" | TRUE | f | TRUE |
| test -z "$name" | f | TRUE | TRUE |
| test ! "$name" | f | TRUE | TRUE |
| test ! -n "$name" | f | TRUE | TRUE |
| test "$name" = '' | f | TRUE | TRUE |
+----------------------+-------------+---------+------------+
Retrieve the content pane for the frame and use the setBackground() method inherited from Component to change the color.
Example:
myJFrame.getContentPane().setBackground( desiredColor );
see nditer
import numpy as np
Y = np.array([3,4,5,6])
for y in np.nditer(Y, op_flags=['readwrite']):
y += 3
Y == np.array([6, 7, 8, 9])
y = 3
would not work, usey *= 0
andy += 3
instead.
in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().
$filedate = date_create(date("Y-m-d", filectime($file)));
becomes
$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));
that worked for me.
Complete snippet for deleting files by number of days:
$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
$extension = substr($file, -3, 3);
if ($extension == 'jpg') // in case you only want specific files deleted
{
$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));
$today = date_create(date("Y-m-d"));
$days = date_diff($filedate, $today, true);
if ($days->days > 1)
{
unlink($directory.$file);
}
}
}
You can always use CSS to constrain the width of the fieldset, which would also constrain the controls inside.
I find that I often have to constrain the width of select
controls, or else really long option text will make it totally unmanageable.
install the android SDK for me was not the problem, having the right JRE and JDK was the problem.
To solve this install the JVM 8 (the last fully compatible, for now):
sudo apt-get install openjdk-8-jre
Next use update-alternative to switch to the jre-8 version:
sudo update-alternatives --config java
You can revert JVM version when you want with the same update-alternatives
command
Note that you problably have to do the same after this with javac
also (now you have only java
command at version 8)
first do:
sudo apt-get install openjdk-8-jdk
next:
sudo update-alternatives --config javac
After this you can install android SDK that require this specific Java version
You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.
For a hint, you could possibly do something like:
Record record = new Record();
PropertyInfo[] properties = typeof(Record).GetProperties();
foreach (PropertyInfo property in properties)
{
property.SetValue(record, value);
}
Where value
is the value you're wanting to write in (so from your resultItems
array).
Open the file with a FileInputStream
, then use an InputStreamReader
with the UTF-8 Charset
to read characters from the stream, and use a BufferedReader
to read lines, e.g. via BufferedReader#readLine
, which will give you a string. Once you have the string, you can check for characters that aren't what you consider to be printable.
E.g. (without error checking), using try-with-resources (which is in vaguely modern Java version):
String line;
try (
InputStream fis = new FileInputStream("the_file_name");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
) {
while ((line = br.readLine()) != null) {
// Deal with the line
}
}
Using the native SQL Server Management Studio technique to export to CSV (as @8kb suggested) doesn't work if your values contain commas, because SSMS doesn't wrap values in double quotes. A more robust way that worked for me is to simply copy the results (click inside the grid and then CTRL-A, CTRL-C) and paste it into Excel. Then save as CSV file from Excel.
Maybe a little late to the party but why don't you use sessions to store your data?
bookingfacilities.php
session_start();
$_SESSION['form_date'] = $date;
successfulbooking.php
session_start();
$date = $_SESSION['form_date'];
Nobody will see this.
You can also do like this
// put value in intent
Intent in = new Intent(MainActivity.this, Booked.class);
in.putExtra("filter", "Booked");
startActivity(in);
// get value from intent
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String filter = bundle.getString("filter");
To include an optional minus sign and to disallow numbers like 015
(which can be mistaken for octal numbers) write:
-?(0|([1-9]\d*))(\.\d+)?