This is a state-of-the-union answer as of Windows PowerShell v5.1 / PowerShell Core v6.2.0:
Andrew Savinykh's ill-fated answer, despite being the accepted one, is, as of this writing, fundamentally flawed (I do hope it gets fixed - there's enough information in the comments - and in the edit history - to do so).
Ansgar Wiecher's helpful answer works well, but requires direct use of the .NET Framework (and reads the entire file into memory, though that could be changed). Direct use of the .NET Framework is not a problem per se, but is harder to master for novices and hard to remember in general.
A future version of PowerShell Core will have a
Convert-TextFile
cmdlet with a -LineEnding
parameter to allow in-place updating of text files with a specific newline style, as being discussed on GitHub.
In PSv5+, PowerShell-native solutions are now possible, because Set-Content
now supports the -NoNewline
switch, which prevents undesired appending of a platform-native newline[1]
:
# Convert CRLFs to LFs only.
# Note:
# * (...) around Get-Content ensures that $file is read *in full*
# up front, so that it is possible to write back the transformed content
# to the same file.
# * + "`n" ensures that the file has a *trailing LF*, which Unix platforms
# expect.
((Get-Content $file) -join "`n") + "`n" | Set-Content -NoNewline $file
The above relies on Get-Content
's ability to read a text file that uses any combination of CR-only, CRLF, and LF-only newlines line by line.
Caveats:
You need to specify the output encoding to match the input file's in order to recreate it with the same encoding. The command above does NOT specify an output encoding; to do so, use -Encoding
; without -Encoding
:
The input file's content as well as its transformed copy must fit into memory as a whole, which can be problematic with large input files.
There's a risk of file corruption, if the process of writing back to the input file gets interrupted.
[1] In fact, if there are multiple strings to write, -NoNewline
also doesn't place a newline between them; in the case at hand, however, this is irrelevant, because only one string is written.
If you're getting your timestamps from System.currentTimeMillis()
, then your time variables should be longs.
You can do it a number of ways, depending on the type of quotes you use:
echo "<a href='http://www.whatever.com/$param'>Click here</a>";
echo "<a href='http://www.whatever.com/{$param}'>Click here</a>";
echo '<a href="http://www.whatever.com/' . $param . '">Click here</a>';
echo "<a href=\"http://www.whatever.com/$param\">Click here</a>";
Double quotes allow for variables in the middle of the string, where as single quotes are string literals and, as such, interpret everything as a string of characters -- nothing more -- not even \n
will be expanded to mean the new line character, it will just be the characters \
and n
in sequence.
You need to be careful about your use of whichever type of quoting you decide. You can't use double quotes inside a double quoted string (as in your example) as you'll be ending the string early, which isn't what you want. You can escape the inner double quotes, however, by adding a backslash.
On a separate note, you might need to be careful about XSS attacks when printing unsafe variables (populated by the user) out to the browser.
Before proceeding further with the fuss of immutability, let's just take a look into the String
class and its functionality a little before coming to any conclusion.
This is how String
works:
String str = "knowledge";
This, as usual, creates a string containing "knowledge"
and assigns it a reference str
. Simple enough? Lets perform some more functions:
String s = str; // assigns a new reference to the same string "knowledge"
Lets see how the below statement works:
str = str.concat(" base");
This appends a string " base"
to str
. But wait, how is this possible, since String
objects are immutable? Well to your surprise, it is.
When the above statement is executed, the VM takes the value of String str
, i.e. "knowledge"
and appends " base"
, giving us the value "knowledge base"
. Now, since String
s are immutable, the VM can't assign this value to str
, so it creates a new String
object, gives it a value "knowledge base"
, and gives it a reference str
.
An important point to note here is that, while the String
object is immutable, its reference variable is not. So that's why, in the above example, the reference was made to refer to a newly formed String
object.
At this point in the example above, we have two String
objects: the first one we created with value "knowledge"
, pointed to by s
, and the second one "knowledge base"
, pointed to by str
. But, technically, we have three String
objects, the third one being the literal "base"
in the concat
statement.
What if we didn't have another reference s
to "knowledge"
? We would have lost that String
. However, it still would have existed, but would be considered lost due to having no references.
Look at one more example below
String s1 = "java";
s1.concat(" rules");
System.out.println("s1 refers to "+s1); // Yes, s1 still refers to "java"
What's happening:
String
"java"
and refer s1
to it.String
"java rules"
, but nothing
refers to it. So, the second String
is instantly lost. We can't reach
it.The reference variable s1
still refers to the original String
"java"
.
Almost every method, applied to a String
object in order to modify it, creates new String
object. So, where do these String
objects go? Well, these exist in memory, and one of the key goals of any programming language is to make efficient use of memory.
As applications grow, it's very common for String
literals to occupy large area of memory, which can even cause redundancy. So, in order to make Java more efficient, the JVM sets aside a special area of memory called the "String constant pool".
When the compiler sees a String
literal, it looks for the String
in the pool. If a match is found, the reference to the new literal is directed to the existing String
and no new String
object is created. The existing String
simply has one more reference. Here comes the point of making String
objects immutable:
In the String
constant pool, a String
object is likely to have one or many references. If several references point to same String
without even knowing it, it would be bad if one of the references modified that String
value. That's why String
objects are immutable.
Well, now you could say, what if someone overrides the functionality of String
class? That's the reason that the String
class is marked final
so that nobody can override the behavior of its methods.
Set body css to :
body {
background: url(../img/background.jpg) no-repeat center center fixed #000;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Try this:
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:view.bounds];
view.layer.masksToBounds = NO;
view.layer.shadowColor = [UIColor blackColor].CGColor;
view.layer.shadowOffset = CGSizeMake(0.0f, 5.0f);
view.layer.shadowOpacity = 0.5f;
view.layer.shadowPath = shadowPath.CGPath;
First of all: The UIBezierPath
used as shadowPath
is crucial. If you don't use it, you might not notice a difference at first, but the keen eye will observe a certain lag occurring during events like rotating the device and/or similar. It's an important performance tweak.
Regarding your issue specifically: The important line is view.layer.masksToBounds = NO
. It disables the clipping of the view's layer's sublayers that extend further than the view's bounds.
For those wondering what the difference between masksToBounds
(on the layer) and the view's own clipToBounds
property is: There isn't really any. Toggling one will have an effect on the other. Just a different level of abstraction.
Swift 2.2:
override func layoutSubviews()
{
super.layoutSubviews()
let shadowPath = UIBezierPath(rect: bounds)
layer.masksToBounds = false
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOffset = CGSizeMake(0.0, 5.0)
layer.shadowOpacity = 0.5
layer.shadowPath = shadowPath.CGPath
}
Swift 3:
override func layoutSubviews()
{
super.layoutSubviews()
let shadowPath = UIBezierPath(rect: bounds)
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
layer.shadowOpacity = 0.5
layer.shadowPath = shadowPath.cgPath
}
In short, they are equivalent. Let's have a history view:
(1) at first, the function looks like this.
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
(2) to make code more abstract (and more portable). A common method to get Super-Class is invented like:
super(<class>, <instance>)
And init function can be:
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
However requiring an explicit passing of both the class and instance break the DRY (Don't Repeat Yourself) rule a bit.
(3) in V3. It is more smart,
super()
is enough in most case. You can refer to http://www.python.org/dev/peps/pep-3135/
That's not possible in a portable manner in pure C++, because it depends too much on the terminal used that may be connected with stdin
(they are usually line buffered). You can, however use a library for that:
conio available with Windows compilers. Use the _getch()
function to give you a character without waiting for the Enter key. I'm not a frequent Windows developer, but I've seen my classmates just include <conio.h>
and use it. See conio.h
at Wikipedia. It lists getch()
, which is declared deprecated in Visual C++.
curses available for Linux. Compatible curses implementations are available for Windows too. It has also a getch()
function. (try man getch
to view its manpage). See Curses at Wikipedia.
I would recommend you to use curses if you aim for cross platform compatibility. That said, I'm sure there are functions that you can use to switch off line buffering (I believe that's called "raw mode", as opposed to "cooked mode" - look into man stty
). Curses would handle that for you in a portable manner, if I'm not mistaken.
Use something like the following, taking advantage of the XML output of subversion:
# parse rev from popen "svn info --xml"
dom = xml.dom.minidom.parse(os.popen('svn info --xml'))
entry = dom.getElementsByTagName('entry')[0]
revision = entry.getAttribute('revision')
Note also that, depending on what you need this for, the <commit revision=...>
entry may be more what you're looking for. That gives the "Last Changed Rev", which won't change until the code in the current tree actually changes, as opposed to "Revision" (what the above gives) which will change any time anything in the repository changes (even branches) and you do an "svn up", which is not the same thing, nor often as useful.
From the documentation:
It is necessary to keep in mind that the browsers do not know how to correctly show this error.
I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.
You can get the path via fp.name
. Example:
>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'
You might need os.path.basename
if you want only the file name:
>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'
File object docs (for Python 2) here.
You can use the readline module to read from stdin line by line:
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function(line){
console.log(line);
})
VI shows newlines (LF character, code x0A
) by showing the subsequent text on the next line.
Use the -b
switch for binary mode. Eg vi -b filename
or vim -b filename --
.
It will then show CR characters (x0D
), which are not normally used in Unix style files, as the characters ^M
.
Quoting MSDN:
When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back. When SET XACT_ABORT is OFF, in some cases only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing.
In practice this means that some of the statements might fail, leaving the transaction 'partially completed', and there might be no sign of this failure for a caller.
A simple example:
INSERT INTO t1 VALUES (1/0)
INSERT INTO t2 VALUES (1/1)
SELECT 'Everything is fine'
This code would execute 'successfully' with XACT_ABORT OFF, and will terminate with an error with XACT_ABORT ON ('INSERT INTO t2' will not be executed, and a client application will raise an exception).
As a more flexible approach, you could check @@ERROR after each statement (old school), or use TRY...CATCH blocks (MSSQL2005+). Personally I prefer to set XACT_ABORT ON whenever there is no reason for some advanced error handling.
The solution provided by BBoy works fine. But in my case I had to use
e.Graphics.DrawImage(memoryImage, e.PageBounds);
This will print only the form. When I use MarginBounds it prints the entire screen even if the form is smaller than the monitor screen. PageBounds solved that issue. Thanks to BBoy!
You could also set the timezone at the JVM level
Date date1 = new Date();
System.out.println(date1);
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// or pass in a command line arg: -Duser.timezone="UTC"
Date date2 = new Date();
System.out.println(date2);
output:
Thu Sep 05 10:11:12 EDT 2013
Thu Sep 05 14:11:12 UTC 2013
If you don't mind VBA, here is a function that will do it for you. Your call would be something like:
=CountRows(1:10)
Function CountRows(ByVal range As range) As Long
Application.ScreenUpdating = False
Dim row As range
Dim count As Long
For Each row In range.Rows
If (Application.WorksheetFunction.CountBlank(row)) - 256 <> 0 Then
count = count + 1
End If
Next
CountRows = count
Application.ScreenUpdating = True
End Function
How it works: I am exploiting the fact that there is a 256 row limit. The worksheet formula CountBlank will tell you how many cells in a row are blank. If the row has no cells with values, then it will be 256. So I just minus 256 and if it's not 0 then I know there is a cell somewhere that has some value.
full solution here:
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
</RadioGroup>
selector XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected" android:state_checked="false"/>
</selector>
If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.
var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();
Then you'll be able to access it like:
nodes.Any(n => n.Checked);
Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.
nodes.Add(new { Checked = false, /* etc */ });
Here is a prototype to convert a number to a readable string respecting the new international standards.
There are two ways to represent big numbers: You could either display them in multiples of 1000 = 10 3 (base 10) or 1024 = 2 10 (base 2). If you divide by 1000, you probably use the SI prefix names, if you divide by 1024, you probably use the IEC prefix names. The problem starts with dividing by 1024. Many applications use the SI prefix names for it and some use the IEC prefix names. The current situation is a mess. If you see SI prefix names you do not know whether the number is divided by 1000 or 1024
https://wiki.ubuntu.com/UnitsPolicy
http://en.wikipedia.org/wiki/Template:Quantities_of_bytes
Object.defineProperty(Number.prototype,'fileSize',{value:function(a,b,c,d){
return (a=a?[1e3,'k','B']:[1024,'K','iB'],b=Math,c=b.log,
d=c(this)/c(a[0])|0,this/b.pow(a[0],d)).toFixed(2)
+' '+(d?(a[1]+'MGTPEZY')[--d]+a[2]:'Bytes');
},writable:false,enumerable:false});
This function contains no loop
, and so it's probably faster than some other functions.
Usage:
IEC prefix
console.log((186457865).fileSize()); // default IEC (power 1024)
//177.82 MiB
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB
SI prefix
console.log((186457865).fileSize(1)); //1,true for SI (power 1000)
//186.46 MB
//kB,MB,GB,TB,PB,EB,ZB,YB
i set the IEC as default because i always used binary mode to calculate the size of a file... using the power of 1024
If you just want one of them in a short oneliner function:
SI
function fileSizeSI(a,b,c,d,e){
return (b=Math,c=b.log,d=1e3,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
+' '+(e?'kMGTPEZY'[--e]+'B':'Bytes')
}
//kB,MB,GB,TB,PB,EB,ZB,YB
IEC
function fileSizeIEC(a,b,c,d,e){
return (b=Math,c=b.log,d=1024,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
+' '+(e?'KMGTPEZY'[--e]+'iB':'Bytes')
}
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB
Usage:
console.log(fileSizeIEC(7412834521));
if you have some questions about the functions just ask
It could be too late. But, I encountered similar problem and in my case the project had self reference. Hence, deleting it from the References worked like a charm!!!
Just my two cents, but doesn't the following code portably work in C++17?
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main(int argc, char* argv[])
{
std::cout << "Path is " << fs::path(argv[0]).parent_path() << '\n';
}
Seems to work for me on Linux at least.
Based on the previous idea, I now have:
std::filesystem::path prepend_exe_path(const std::string& filename, const std::string& exe_path = "");
With implementation:
fs::path prepend_exe_path(const std::string& filename, const std::string& exe_path)
{
static auto exe_parent_path = fs::path(exe_path).parent_path();
return exe_parent_path / filename;
}
And initialization trick in main()
:
(void) prepend_exe_path("", argv[0]);
Thanks @Sam Redway for the argv[0] idea. And of course, I understand that C++17 was not around for many years when the OP asked the question.
Try to use the fitText plugin, because Viewport sizes isn't the solution of this problem.
Just add the library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
And change font-size for correct by settings the coefficient of text:
$("#text_div").fitText(0.8);
You can set maximum and minimum values of text:
$("#text_div").fitText(0.8, { minFontSize: '12px', maxFontSize: '36px' });
After creating virtual environment, try to use pip located in yourVirtualEnvName\Scripts
It should install a package inside Lib\site-packages in your virtual environment
The function you're after is numpy.linalg.norm
. (I reckon it should be in base numpy as a property of an array -- say x.norm()
-- but oh well).
import numpy as np
x = np.array([1,2,3,4,5])
np.linalg.norm(x)
You can also feed in an optional ord
for the nth order norm you want. Say you wanted the 1-norm:
np.linalg.norm(x,ord=1)
And so on.
A solution combining find and replace methods in a single line if statement could be:
```python
my_var = "stackoverflaw"
my_new_var = my_var.replace('a', 'o', 1) if my_var.find('s') != -1 else my_var
print(f"my_var = {my_var}") # my_var = stackoverflaw
print(f"my_new_var = {my_new_var}") # my_new_var = stackoverflow
```
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
Use ValueAnimator:
ValueAnimator expandAnimation = ValueAnimator.ofInt(mainView.getHeight(), 400);
expandAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(final ValueAnimator animation) {
int height = (Integer) animation.getAnimatedValue();
RelativeLayout.LayoutParams lp = (LayoutParams) mainView.getLayoutParams();
lp.height = height;
}
});
expandAnimation.setDuration(500);
expandAnimation.start();
For me it was the "Start In" - I accidentally left in the '.py' at the end of the name of my program. And I forgot to capitalize the name of the folder it was in ('Apps').
Easiest way to achieve this would be :
CSS :
label{ float: left; }
span
{
display: block;
overflow: hidden;
padding-right: 5px;
padding-left: 10px;
}
span > input{ width: 100%; }
HTML :
<fieldset>
<label>label</label><span><input type="text" /></span>
<label>longer label</label><span><input type="text" /></span>
</fieldset>
Looks like : http://jsfiddle.net/JwfRX/
In my case, PATH was properly SET but PATHEXT has been cleared by me by mistake with .exe extension. That why window can't find java or anything .exe application from command prompt. Hope it can help someone.
import numpy as np
# ND array list with different size
a = [[1],[2,3,4,5],[6,7,8]]
# stack them
b = np.hstack(a)
print(b)
[1 2 3 4 5 6 7 8]
for _ in {1..10}; do command; done
Note the underscore instead of using a variable.
Countdown of user input
Interface Screenshot
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
hours: 0,
minutes: 0,
seconds:0
}
this.hoursInput = React.createRef();
this.minutesInput= React.createRef();
this.secondsInput = React.createRef();
}
inputHandler = (e) => {
this.setState({[e.target.name]: e.target.value});
}
convertToSeconds = ( hours, minutes,seconds) => {
return seconds + minutes * 60 + hours * 60 * 60;
}
startTimer = () => {
this.timer = setInterval(this.countDown, 1000);
}
countDown = () => {
const { hours, minutes, seconds } = this.state;
let c_seconds = this.convertToSeconds(hours, minutes, seconds);
if(c_seconds) {
// seconds change
seconds ? this.setState({seconds: seconds-1}) : this.setState({seconds: 59});
// minutes change
if(c_seconds % 60 === 0 && minutes) {
this.setState({minutes: minutes -1});
}
// when only hours entered
if(!minutes && hours) {
this.setState({minutes: 59});
}
// hours change
if(c_seconds % 3600 === 0 && hours) {
this.setState({hours: hours-1});
}
} else {
clearInterval(this.timer);
}
}
stopTimer = () => {
clearInterval(this.timer);
}
resetTimer = () => {
this.setState({
hours: 0,
minutes: 0,
seconds: 0
});
this.hoursInput.current.value = 0;
this.minutesInput.current.value = 0;
this.secondsInput.current.value = 0;
}
render() {
const { hours, minutes, seconds } = this.state;
return (
<div className="App">
<h1 className="title"> (( React Countdown )) </h1>
<div className="inputGroup">
<h3>Hrs</h3>
<input ref={this.hoursInput} type="number" placeholder={0} name="hours" onChange={this.inputHandler} />
<h3>Min</h3>
<input ref={this.minutesInput} type="number" placeholder={0} name="minutes" onChange={this.inputHandler} />
<h3>Sec</h3>
<input ref={this.secondsInput} type="number" placeholder={0} name="seconds" onChange={this.inputHandler} />
</div>
<div>
<button onClick={this.startTimer} className="start">start</button>
<button onClick={this.stopTimer} className="stop">stop</button>
<button onClick={this.resetTimer} className="reset">reset</button>
</div>
<h1> Timer {hours}: {minutes} : {seconds} </h1>
</div>
);
}
}
export default App;
There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.
One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.
Case C) is the fastest. Having this as an extension:
Public Module MyExtensions
<Extension()> _
Public Sub Add(Of T)(ByRef arr As T(), item As T)
Array.Resize(arr, arr.Length + 1)
arr(arr.Length - 1) = item
End Sub
End Module
Usage:
Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
arr.Add(newItem)
' --> duration for adding 100.000 items: 1 msec
' --> duration for adding 100.000.000 items: 1168 msec
Close the eclipse and start the server you will able to see and run the project.
There's an illegal character at index 16. I'd say it doesn't like the space in the path. You can percent encode special characters like spaces. Replace it with a %20 in this case.
The question I linked to above suggests using URLEncoder:
String thePath = "file://E:/Program Files/IBM/SDP/runtimes/base";
thePath = URLEncoder.encode(thePath, "UTF-8");
I answered a similar question here
As @Syden said, the mixins will work. Another option is using SASS map-get
like this..
@media (min-width: map-get($grid-breakpoints, sm)){
.something {
padding: 10px;
}
}
@media (min-width: map-get($grid-breakpoints, md)){
.something {
padding: 20px;
}
}
http://www.codeply.com/go/0TU586QNlV
There are (at least) three different things you might conceive of as a "character", and consequently, three different categories of approach you might want to use.
JavaScript strings were originally invented as sequences of UTF-16 code units, back at a point in history when there was a one-to-one relationship between UTF-16 code units and Unicode code points. The .length
property of a string measures its length in UTF-16 code units, and when you do someString[i]
you get the ith UTF-16 code unit of someString
.
Consequently, you can get an array of UTF-16 code units from a string by using a C-style for-loop with an index variable...
const yourString = 'Hello, World!';_x000D_
const charArray = [];_x000D_
for (let i=0; i<=yourString.length; i++) {_x000D_
charArray.push(yourString[i]);_x000D_
}_x000D_
console.log(charArray);
_x000D_
There are also various short ways to achieve the same thing, like using .split()
with the empty string as a separator:
const charArray = 'Hello, World!'.split('');_x000D_
console.log(charArray);
_x000D_
However, if your string contains code points that are made up of multiple UTF-16 code units, this will split them into individual code units, which may not be what you want. For instance, the string ''
is made up of four unicode code points (code points 0x1D7D8 through 0x1D7DB) which, in UTF-16, are each made up of two UTF-16 code units. If we split that string using the methods above, we'll get an array of eight code units:
const yourString = '';_x000D_
console.log('First code unit:', yourString[0]);_x000D_
const charArray = yourString.split('');_x000D_
console.log('charArray:', charArray);
_x000D_
So, perhaps we want to instead split our string into Unicode Code Points! That's been possible since ECMAScript 2015 added the concept of an iterable to the language. Strings are now iterables, and when you iterate over them (e.g. with a for...of
loop), you get Unicode code points, not UTF-16 code units:
const yourString = '';_x000D_
const charArray = [];_x000D_
for (const char of yourString) {_x000D_
charArray.push(char);_x000D_
}_x000D_
console.log(charArray);
_x000D_
We can shorten this using Array.from
, which iterates over the iterable it's passed implicitly:
const yourString = '';_x000D_
const charArray = Array.from(yourString);_x000D_
console.log(charArray);
_x000D_
However, unicode code points are not the largest possible thing that could possibly be considered a "character" either. Some examples of things that could reasonably be considered a single "character" but be made up of multiple code points include:
We can see below that if we try to convert a string with such characters into an array via the iteration mechanism above, the characters end up broken up in the resulting array. (In case any of the characters don't render on your system, yourString
below consists of a capital A with an acute accent, followed by the flag of the United Kingdom, followed by a black woman.)
const yourString = 'A´';_x000D_
const charArray = Array.from(yourString);_x000D_
console.log(charArray);
_x000D_
If we want to keep each of these as a single item in our final array, then we need an array of graphemes, not code points.
JavaScript has no built-in support for this - at least not yet. So we need a library that understands and implements the Unicode rules for what combination of code points constitute a grapheme. Fortunately, one exists: orling's grapheme-splitter. You'll want to install it with npm or, if you're not using npm, download the index.js file and serve it with a <script>
tag. For this demo, I'll load it from jsDelivr.
grapheme-splitter gives us a GraphemeSplitter
class with three methods: splitGraphemes
, iterateGraphemes
, and countGraphemes
. Naturally, we want splitGraphemes
:
const splitter = new GraphemeSplitter();_x000D_
const yourString = 'A´';_x000D_
const charArray = splitter.splitGraphemes(yourString);_x000D_
console.log(charArray);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/index.js"></script>
_x000D_
And there we are - an array of three graphemes, which is probably what you wanted.
If you are using python 3 and windows 10, the best solution that I found to be working is from Giovanni Gianni. This played for me in the male voice:
import win32com.client as wincl
speak = wincl.Dispatch("SAPI.SpVoice")
speak.Speak("This is the pc voice speaking")
I also found this video on youtube so if you really want to, you can get someone you know and make your own DIY tts voice.
foreach($objectA as $k => $v) $objectB->$k = $v;
By default, Sublime Text set 'UTF8 without BOM'
, but that wasn't specified.
The only specicified things is 'UTF8 with BOM'
.
Hope this help :)
The only time you need to set it (or not) is if you need to explicitly check that a variable a
is set exactly to null
or undefined
.
if(a === null) {
}
...is not the same as:
if(a === undefined) {
}
That said, a == null && a == undefined
will return true
.
just like this :
global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);
simply your selecting all the rows then order them DESC by id , and displaying only the first
What does the trick for me is:
1) Right click on wwwroot > Add > Client Side Library
2) Typed "bootstrap" on the search box
3) Select "Choose specific files"
4) Scroll down and select a folder. In my case I chose "twitter-bootstrap"
5) Check "css" and "js"
6) Click "Install".
A few seconds later I have all of them wwwroot folder. Do the same for all client side packages that you want to add.
Try forfiles:
forfiles /p C:\Temp /m file1.txt /c "cmd /c echo @fsize"
The forfiles
command runs command c
for each file m
in directory p
.
The variable @fsize
is replaced with the size of each file.
If the file C:\Temp\file1.txt
is 27 bytes, forfiles
runs this command:
cmd /c echo 27
Which prints 27
to the screen.
As a side-effect, it clears your screen as if you had run the cls
command.
If this same scenario is not spread everywhere you can use React's context, specially if you don't want to introduce all the overhead that state management libraries introduce. Plus, it's easier to learn. But be careful, you could overuse it and start writing bad code. Basically you define a Container component (that will hold and keep that piece of state for you) making all the components interested in writing/reading that piece of data its children (not necessarily direct children)
https://reactjs.org/docs/context.html
You could also use plain React properly instead.
<Component5 onSomethingHappenedIn5={this.props.doSomethingAbout5} />
pass doSomethingAbout5 up to Component 1
<Component1>
<Component2 onSomethingHappenedIn5={somethingAbout5 => this.setState({somethingAbout5})}/>
<Component5 propThatDependsOn5={this.state.somethingAbout5}/>
<Component1/>
If this a common problem you should starting thinking moving the whole state of the application to someplace else. You have a few options, the most common are:
https://facebook.github.io/flux/
Basically, instead of managing the application state in your component you send commands when something happens to get the state updated. Components pull the state from this container as well so all the data is centralized. This doesn't mean can't use local state anymore, but that's a more advanced topic.
The HTML code is for three div align side by side and can be used for two also by some changes
<div id="wrapper">
<div id="first">first</div>
<div id="second">second</div>
<div id="third">third</div>
</div>
The CSS will be
#wrapper {
display:table;
width:100%;
}
#row {
display:table-row;
}
#first {
display:table-cell;
background-color:red;
width:33%;
}
#second {
display:table-cell;
background-color:blue;
width:33%;
}
#third {
display:table-cell;
background-color:#bada55;
width:34%;
}
This code will workup towards responsive layout as it will resize the
<div>
according to device width. Even one can silent anyone
<div>
as
<!--<div id="third">third</div> -->
and can use rest two for two
<div>
side by side.
Answer is NO. It won't affect the original/main repository where you forked from. (Functionally, it will be incorrect if such an access is provided to a non-owner).
Just wanted to add this though.
Warning: It will delete the local commits and branches you created on your forked repo. So, before deleting make sure there is a backup of that code with you if it is important.
Best way would be getting a git backup of forked repo using:
git bundle
or other methods that are familiar.
Another solution could be use the uncommit
command to exclude specific file from current commit.
hg uncommit [file/directory]
This is very helpful when you want to keep current commit and deselect some files from commit (especially helpful for files/directories
have been deleted).
This is the best way to do it, very simple.
$msg = "Hello this is a string";
$first_index_of_i = stripos($msg,'i');
$last_index_of_i = strripos($msg, 'i');
echo "First i : " . $first_index_of_i . PHP_EOL ."Last i : " . $last_index_of_i;
NOTE: This is true for the version mentioned in the question, 4.1.1.RELEASE.
Spring MVC handles a ResponseEntity
return value through HttpEntityMethodProcessor
.
When the ResponseEntity
value doesn't have a body set, as is the case in your snippet, HttpEntityMethodProcessor
tries to determine a content type for the response body from the parameterization of the ResponseEntity
return type in the signature of the @RequestMapping
handler method.
So for
public ResponseEntity<Void> taxonomyPackageExists( @PathVariable final String key ) {
that type will be Void
. HttpEntityMethodProcessor
will then loop through all its registered HttpMessageConverter
instances and find one that can write a body for a Void
type. Depending on your configuration, it may or may not find any.
If it does find any, it still needs to make sure that the corresponding body will be written with a Content-Type that matches the type(s) provided in the request's Accept
header, application/xml
in your case.
If after all these checks, no such HttpMessageConverter
exists, Spring MVC will decide that it cannot produce an acceptable response and therefore return a 406 Not Acceptable HTTP response.
With ResponseEntity<String>
, Spring will use String
as the response body and find StringHttpMessageConverter
as a handler. And since StringHttpMessageHandler
can produce content for any media type (provided in the Accept
header), it will be able to handle the application/xml
that your client is requesting.
Spring MVC has since been changed to only return 406 if the body in the ResponseEntity
is NOT null
. You won't see the behavior in the original question if you're using a more recent version of Spring MVC.
In iddy85's solution, which seems to suggest ResponseEntity<?>
, the type for the body will be inferred as Object
. If you have the correct libraries in your classpath, ie. Jackson (version > 2.5.0) and its XML extension, Spring MVC will have access to MappingJackson2XmlHttpMessageConverter
which it can use to produce application/xml
for the type Object
. Their solution only works under these conditions. Otherwise, it will fail for the same reason I've described above.
try this formula in column E:
=IF( AND( ISNUMBER(D2), D2=G2), H2, "")
your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )
you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.
I hope you understand my explanation.
Only this solution worked for me. Tried 7 8 solutions. Using Windows platform.
To load your data in WebView. Call loadData() method of WebView
webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");
You can check this example
http://developer.android.com/reference/android/webkit/WebView.html
you can try this (I don't have sql server here today so I can't verify syntax, sorry)
select attributeName
from tableName
where CONVERT(varchar,attributeName,101) BETWEEN '03/01/2009' AND '03/31/2009'
and CONVERT(varchar, attributeName,108) BETWEEN '06:00:00' AND '22:00:00'
and DATEPART(day,attributeName) BETWEEN 2 AND 4
I had the same issue. When I checked my config file I noticed that 'fetch = +refs/heads/:refs/remotes/origin/' was on the same line as 'url = Z:/GIT/REPOS/SEL.git' as shown:
[core]
repositoryformatversion = 0
filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
[remote "origin"]
url = Z:/GIT/REPOS/SEL.git fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
[gui]
wmstate = normal
geometry = 1109x563+32+32 216 255
At first I did not think that this would have mattered but after seeing the post by Magere I moved the line and that fixed the problem:
[core]
repositoryformatversion = 0
filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
[remote "origin"]
url = Z:/GIT/REPOS/SEL.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
[gui]
wmstate = normal
geometry = 1109x563+32+32 216 255
In my case It was totally different since I was not having activity to launch the service in Oreo.
Below are the steps which I used to resolve this foreground service issue -
public class SocketService extends Service {
private String TAG = this.getClass().getSimpleName();
@Override
public void onCreate() {
Log.d(TAG, "Inside onCreate() API");
if (Build.VERSION.SDK_INT >= 26) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on.
mNotificationManager.notify(100, mBuilder.build());
startForeground(100, mBuilder.mNotification);
}
Toast.makeText(getApplicationContext(), "inside onCreate()", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent resultIntent, int resultCode, int startId) {
Log.d(TAG, "inside onStartCommand() API");
return startId;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "inside onDestroy() API");
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And after that to initiate this service I triggered below cmd -
adb -s " + serial_id + " shell am startforegroundservice -n com.test.socket.sample/.SocketService
So this helps me to start service without activity on Oreo devices :)
I've a sample for multiple data with their subnode 3 list , each list has attribute and child attribute:
var list1 = {
name: "Role A",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Write",
id: 2,
selected: false
}, {
sub: "Update",
id: 3,
selected: false
}],
};
var list2 = {
name: "Role B",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Write",
id: 2,
selected: false
}],
};
var list3 = {
name: "Role B",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Update",
id: 3,
selected: false
}],
};
Add these to Array :
newArr.push(list1);
newArr.push(list2);
newArr.push(list3);
$scope.itemDisplayed = newArr;
Show them in html:
<li ng-repeat="item in itemDisplayed" class="ng-scope has-pretty-child">
<div>
<ul>
<input type="checkbox" class="checkall" ng-model="item.name_selected" ng-click="toggleAll(item)" />
<span>{{item.name}}</span>
<div>
<li ng-repeat="sub in item.subs" class="ng-scope has-pretty-child">
<input type="checkbox" kv-pretty-check="" ng-model="sub.selected" ng-change="optionToggled(item,item.subs)"><span>{{sub.sub}}</span>
</li>
</div>
</ul>
</div>
</li>
And here is the solution to check them:
$scope.toggleAll = function(item) {
var toogleStatus = !item.name_selected;
console.log(toogleStatus);
angular.forEach(item, function() {
angular.forEach(item.subs, function(sub) {
sub.selected = toogleStatus;
});
});
};
$scope.optionToggled = function(item, subs) {
item.name_selected = subs.every(function(itm) {
return itm.selected;
})
}
jsfiddle demo
Since this question is from 4 years ago new things have been implemented and among them there is a new function plt.subplots
which is very convenient:
fig, axes = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
where axes
is a numpy.ndarray
of AxesSubplot objects, making it very convenient to go through the different subplots just using array indices [i,j]
.
Take a look at the INFORMATION_SCHEMA
.TABLES
table. It contains metadata about all your tables.
Example:
SELECT * FROM `INFORMATION_SCHEMA`.`TABLES`
WHERE TABLE_NAME LIKE 'table1'
The advantage of this over other methods is that you can easily use queries like the one above as subqueries in your other queries.
In my case, I was rendering another action method for my menu section in _layout.cshtml file using @Html.Action("Menu", "Menu") whereas I forgot to create Menu controller and as layout file was being used in my current controller action's view therefore I was getting this error in my current action render request. try to look in your layout and as well as view file if you did the same mistake
I give my activity an interface that all the fragments can then use. If you have have many fragments on the same activity, this saves a lot of code re-writing and is a cleaner solution / more modular than making an individual interface for each fragment with similar functions. I also like how it is modular. The downside, is that some fragments will have access to functions they don't need.
public class MyActivity extends AppCompatActivity
implements MyActivityInterface {
private List<String> mData;
@Override
public List<String> getData(){return mData;}
@Override
public void setData(List<String> data){mData = data;}
}
public interface MyActivityInterface {
List<String> getData();
void setData(List<String> data);
}
public class MyFragment extends Fragment {
private MyActivityInterface mActivity;
private List<String> activityData;
public void onButtonPress(){
activityData = mActivity.getData()
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof MyActivityInterface) {
mActivity = (MyActivityInterface) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement MyActivityInterface");
}
}
@Override
public void onDetach() {
super.onDetach();
mActivity = null;
}
}
By default git uses uses less as pager. I normally prefer more, as it will print the first page and then allow you to scroll through the content.
Further, the content will remain in the console when done. This is usually convenient, as you often want to do something with the content after lookup (eg. email the commiter and tell him he introduced a bug in his last commit).
If you then want to pipe content, it would be inconvenient to scroll to print everything. The good thing with more is you will be able to combine it with pipeline and it will pipe through everything, eg.
# Find the commit abcdef123 in the full commit history and read author and commit message
git log |grep -C 5 'abcdef123'
Basically more is all you would ever need, unless you do not want the content to remain in the console when done. To use more instead, do as below.
git config --global core.pager 'more'
Here is a simple function I created for getting the thumbnails. It is easy to understand and use.
$link is the YouTube link copied exactly as it is in the browser, for example, https://www.youtube.com/watch?v=BQ0mxQXmLsk
function get_youtube_thumb($link){
$new = str_replace('https://www.youtube.com/watch?v=', '', $link);
$thumbnail = 'https://img.youtube.com/vi/' . $new . '/0.jpg';
return $thumbnail;
}
To get sequence id use
SELECT pg_get_serial_sequence('tableName', 'ColumnName');
This will gives you sequesce id as tableName_ColumnName_seq
To Get Last seed number use
select currval(pg_get_serial_sequence('tableName', 'ColumnName'));
or if you know sequence id already use it directly.
select currval(tableName_ColumnName_seq);
It will gives you last seed number
To Reset seed number use
ALTER SEQUENCE tableName_ColumnName_seq RESTART WITH 45
I ran S.Lott's code and produced the same 10% performance increase by preallocating. I tried Ned Batchelder's idea using a generator and was able to see the performance of the generator better than that of the doAllocate. For my project the 10% improvement matters, so thanks to everyone as this helps a bunch.
def doAppend(size=10000):
result = []
for i in range(size):
message = "some unique object %d" % ( i, )
result.append(message)
return result
def doAllocate(size=10000):
result = size*[None]
for i in range(size):
message = "some unique object %d" % ( i, )
result[i] = message
return result
def doGen(size=10000):
return list("some unique object %d" % ( i, ) for i in xrange(size))
size = 1000
@print_timing
def testAppend():
for i in xrange(size):
doAppend()
@print_timing
def testAlloc():
for i in xrange(size):
doAllocate()
@print_timing
def testGen():
for i in xrange(size):
doGen()
testAppend()
testAlloc()
testGen()
testAppend took 14440.000ms
testAlloc took 13580.000ms
testGen took 13430.000ms
An alternate to the above solutions is using Aliases for Tables:
UPDATE T1 SET T1.extrasPrice = (SELECT SUM(T2.Price) FROM BookingPitchExtras T2 WHERE T2.pitchID = T1.ID)
FROM BookingPitches T1;
Simply use the IntegerUpDown
control in the Extended.Wpf.Toolkit
You can use it like this:
Add to your XAML the following namespace:
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
In your XAML where you want the control use:
<xctk:IntegerUpDown Name="myUpDownControl" />
You can try overflow
css property.
You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:
<body oncopy="return false" oncut="return false" onpaste="return false">
How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers
A more advanced aproach:
How to detect Ctrl+V, Ctrl+C using JavaScript?
Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.
I Hope that will help
$.each(myobj, function(index, value) {
console.log(myobj[index]);
)};
Step 1
Search
→ Find
→ (goto Tab) Mark
Find what
: ^Session.*$ Bookmark line
Regular expression
(under Search Mode
)Mark All
(this will find the regex and highlights all the lines and bookmark them) Step 2
Search
→ Bookmark
→ Remove Bookmarked Lines
I had the same issue with Xcode... black screen on launching apps, no debugging and clicking would lock up Xcode.
I finally found the problem... following the lead that the simulator could not connect to Xcode I took a look at my etc/hosts file and found that months ago to solve a different issue I had edited the host file to map localhost to my fixed IP instead of the default... my value:
10.0.1.17 localhost
This should work since that is my IP, but changing it back to the default IP fixed Xcode...
127.0.0.1 localhost
Hope this helps.
I had the same problem on my EC2 instance. I think the initial cause was because I had a Node instance running when I installed Mongo. I stopped the Node service and then ran
sudo npm update
inside of the top level folder of my node project. This fixed the problem and everything was just like new
Tumblr has a public API that provides JSON. You can get a dump of posts using a simple url like http://puppygifs.tumblr.com/api/read/json
.
if($('#testElement').is(':visible')){
//what you want to do when is visible
}
Adding below line in .gitignore will ignore node modules from the entire repository.
node_modules
In addition to FLAG_ACTIVITY_CLEAR_TOP
, you may try adding Intent.FLAG_ACTIVITY_SINGLE_TOP
as well:
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Create a helper using the code I created belows and name it controller_helper.php.
Autoload your helper in the autoload.php
file under config
.
From your method call controller('name')
to load the controller.
Note that name
is the filename of the controller.
This method will append '_controller'
to your controller 'name'
. To call a method in the controller just run $this->name_controller->method();
after you load the controller as described above.
<?php
if(!function_exists('controller'))
{
function controller($name)
{
$filename = realpath(__dir__ . '/../controllers/'.$name.'.php');
if(file_exists($filename))
{
require_once $filename;
$class = ucfirst($name);
if(class_exists($class))
{
$ci =& get_instance();
if(!isset($ci->{$name.'_controller'}))
{
$ci->{$name.'_controller'} = new $class();
}
}
}
}
}
?>
Press Shift twice and a Search Everywhere dialog will appear.
How is this different from the following?
This line of code here:
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
constructs a new String object (i.e. a copy of oldString
), while this line of code:
String newString = oldString;
declares a new variable of type java.lang.String
and initializes it to refer to the same String object as the variable oldString
.
Is there any scenario in which the two lines will have different outputs?
Absolutely:
String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true
vs.
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
// isSameInstance == false (in most cases)
boolean isSameInstance = newString == oldString;
a_horse_with_no_name (see comment) is right of course. The equivalent of
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
is
String newString = new String(oldString);
minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.
If you need a single fadeIn/Out without an explicit user action (like a mouseover/mouseout) you may use a CSS3 animation
: http://codepen.io/anon/pen/bdEpwW
.elementToFadeInAndOut {
animation: fadeinout 4s linear 1 forwards;
}
@keyframes fadeinout {
0% { opacity: 0; }
50% { opacity: 1; }
100% { opacity: 0; }
}
By setting animation-fill-mode: forwards
the animation will retain its last keyframe
By setting animation-iteration-count: 1
the animation will run just once (change this value if you need to repeat the effect more than once)
final RelativeLayout llLogin = (RelativeLayout) findViewById(R.id.rl_main);
llLogin.setOnTouchListener(
new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent ev) {
InputMethodManager imm = (InputMethodManager) this.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
return false;
}
});
I just use
git remote update
git status
The latter then reports how many commits behind my local is (if any).
Then
git pull origin master
to bring my local up to date :)
sudo
is a Unix/Linux command. It's not available in Windows.
Hi instead of using hook API, you should use Higher-order component API as mentioned here
I'll modify the example in the documentation to suit your need for class component
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';
const styles = theme => ({
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
},
});
class HigherOrderComponentUsageExample extends React.Component {
render(){
const { classes } = this.props;
return (
<Button className={classes.root}>This component is passed to an HOC</Button>
);
}
}
HigherOrderComponentUsageExample.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(HigherOrderComponentUsageExample);
A 'fun' way to learn socket.io is to play BrowserQuest by mozilla and look at its source code :-)
mappedby
speaks for itself, it tells hibernate not to map this field. it's already mapped by this field [name="field"].
field is in the other entity (name of the variable in the class not the table in the database)
..
If you don't do that, hibernate will map this two relation as it's not the same relation
so we need to tell hibernate to do the mapping in one side only and co-ordinate between them.
A company insurance policy insures an employee and any dependents, the DEPENDENT cannot exist without the EMPLOYEE; that is, a person cannot get insurance coverage as a dependent unless the person is a dependent of an employee.DEPENDENT is the weak entity in the relationship "EMPLOYEE has DEPENDENT"
For anyone needing to prompt for a password, you may be interested in using encpass.sh. This is a script I wrote for similar purposes of capturing a secret at runtime and then encrypting it for subsequent occasions. Subsequent runs do not prompt for the password as it will just use the encrypted value from disk.
It stores the encrypted passwords in a hidden folder under the user's home directory or in a custom folder that you can define through the environment variable ENCPASS_HOME_DIR. It is designed to be POSIX compliant and has an MIT License, so it can be used even in corporate enterprise environments. My company, Plyint LLC, maintains the script and occasionally releases updates. Pull requests are also welcome, if you find an issue. :)
To use it in your scripts simply source encpass.sh in your script and call the get_secret function. I'm including a copy of the script below for easy visibility.
#!/bin/sh
################################################################################
# Copyright (c) 2020 Plyint, LLC <[email protected]>. All Rights Reserved.
# This file is licensed under the MIT License (MIT).
# Please see LICENSE.txt for more information.
#
# DESCRIPTION:
# This script allows a user to encrypt a password (or any other secret) at
# runtime and then use it, decrypted, within a script. This prevents shoulder
# surfing passwords and avoids storing the password in plain text, which could
# inadvertently be sent to or discovered by an individual at a later date.
#
# This script generates an AES 256 bit symmetric key for each script (or user-
# defined bucket) that stores secrets. This key will then be used to encrypt
# all secrets for that script or bucket. encpass.sh sets up a directory
# (.encpass) under the user's home directory where keys and secrets will be
# stored.
#
# For further details, see README.md or run "./encpass ?" from the command line.
#
################################################################################
encpass_checks() {
if [ -n "$ENCPASS_CHECKS" ]; then
return
fi
if [ ! -x "$(command -v openssl)" ]; then
echo "Error: OpenSSL is not installed or not accessible in the current path." \
"Please install it and try again." >&2
exit 1
fi
if [ -z "$ENCPASS_HOME_DIR" ]; then
ENCPASS_HOME_DIR=$(encpass_get_abs_filename ~)/.encpass
fi
if [ ! -d "$ENCPASS_HOME_DIR" ]; then
mkdir -m 700 "$ENCPASS_HOME_DIR"
mkdir -m 700 "$ENCPASS_HOME_DIR/keys"
mkdir -m 700 "$ENCPASS_HOME_DIR/secrets"
fi
if [ "$(basename "$0")" != "encpass.sh" ]; then
encpass_include_init "$1" "$2"
fi
ENCPASS_CHECKS=1
}
# Initializations performed when the script is included by another script
encpass_include_init() {
if [ -n "$1" ] && [ -n "$2" ]; then
ENCPASS_BUCKET=$1
ENCPASS_SECRET_NAME=$2
elif [ -n "$1" ]; then
ENCPASS_BUCKET=$(basename "$0")
ENCPASS_SECRET_NAME=$1
else
ENCPASS_BUCKET=$(basename "$0")
ENCPASS_SECRET_NAME="password"
fi
}
encpass_generate_private_key() {
ENCPASS_KEY_DIR="$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET"
if [ ! -d "$ENCPASS_KEY_DIR" ]; then
mkdir -m 700 "$ENCPASS_KEY_DIR"
fi
if [ ! -f "$ENCPASS_KEY_DIR/private.key" ]; then
(umask 0377 && printf "%s" "$(openssl rand -hex 32)" >"$ENCPASS_KEY_DIR/private.key")
fi
}
encpass_get_private_key_abs_name() {
ENCPASS_PRIVATE_KEY_ABS_NAME="$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.key"
if [ "$1" != "nogenerate" ]; then
if [ ! -f "$ENCPASS_PRIVATE_KEY_ABS_NAME" ]; then
encpass_generate_private_key
fi
fi
}
encpass_get_secret_abs_name() {
ENCPASS_SECRET_ABS_NAME="$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET/$ENCPASS_SECRET_NAME.enc"
if [ "$3" != "nocreate" ]; then
if [ ! -f "$ENCPASS_SECRET_ABS_NAME" ]; then
set_secret "$1" "$2"
fi
fi
}
get_secret() {
encpass_checks "$1" "$2"
encpass_get_private_key_abs_name
encpass_get_secret_abs_name "$1" "$2"
encpass_decrypt_secret
}
set_secret() {
encpass_checks "$1" "$2"
if [ "$3" != "reuse" ] || { [ -z "$ENCPASS_SECRET_INPUT" ] && [ -z "$ENCPASS_CSECRET_INPUT" ]; }; then
echo "Enter $ENCPASS_SECRET_NAME:" >&2
stty -echo
read -r ENCPASS_SECRET_INPUT
stty echo
echo "Confirm $ENCPASS_SECRET_NAME:" >&2
stty -echo
read -r ENCPASS_CSECRET_INPUT
stty echo
fi
if [ "$ENCPASS_SECRET_INPUT" = "$ENCPASS_CSECRET_INPUT" ]; then
encpass_get_private_key_abs_name
ENCPASS_SECRET_DIR="$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET"
if [ ! -d "$ENCPASS_SECRET_DIR" ]; then
mkdir -m 700 "$ENCPASS_SECRET_DIR"
fi
printf "%s" "$(openssl rand -hex 16)" >"$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc"
ENCPASS_OPENSSL_IV="$(cat "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc")"
echo "$ENCPASS_SECRET_INPUT" | openssl enc -aes-256-cbc -e -a -iv \
"$ENCPASS_OPENSSL_IV" -K \
"$(cat "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.key")" 1>> \
"$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc"
else
echo "Error: secrets do not match. Please try again." >&2
exit 1
fi
}
encpass_get_abs_filename() {
# $1 : relative filename
filename="$1"
parentdir="$(dirname "${filename}")"
if [ -d "${filename}" ]; then
cd "${filename}" && pwd
elif [ -d "${parentdir}" ]; then
echo "$(cd "${parentdir}" && pwd)/$(basename "${filename}")"
fi
}
encpass_decrypt_secret() {
if [ -f "$ENCPASS_PRIVATE_KEY_ABS_NAME" ]; then
ENCPASS_DECRYPT_RESULT="$(dd if="$ENCPASS_SECRET_ABS_NAME" ibs=1 skip=32 2> /dev/null | openssl enc -aes-256-cbc \
-d -a -iv "$(head -c 32 "$ENCPASS_SECRET_ABS_NAME")" -K "$(cat "$ENCPASS_PRIVATE_KEY_ABS_NAME")" 2> /dev/null)"
if [ ! -z "$ENCPASS_DECRYPT_RESULT" ]; then
echo "$ENCPASS_DECRYPT_RESULT"
else
# If a failed unlock command occurred and the user tries to show the secret
# Present either locked or decrypt command
if [ -f "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.lock" ]; then
echo "**Locked**"
else
# The locked file wasn't present as expected. Let's display a failure
echo "Error: Failed to decrypt"
fi
fi
elif [ -f "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.lock" ]; then
echo "**Locked**"
else
echo "Error: Unable to decrypt. The key file \"$ENCPASS_PRIVATE_KEY_ABS_NAME\" is not present."
fi
}
##########################################################
# COMMAND LINE MANAGEMENT SUPPORT
# -------------------------------
# If you don't need to manage the secrets for the scripts
# with encpass.sh you can delete all code below this point
# in order to significantly reduce the size of encpass.sh.
# This is useful if you want to bundle encpass.sh with
# your existing scripts and just need the retrieval
# functions.
##########################################################
encpass_show_secret() {
encpass_checks
ENCPASS_BUCKET=$1
encpass_get_private_key_abs_name "nogenerate"
if [ ! -z "$2" ]; then
ENCPASS_SECRET_NAME=$2
encpass_get_secret_abs_name "$1" "$2" "nocreate"
if [ -z "$ENCPASS_SECRET_ABS_NAME" ]; then
echo "No secret named $2 found for bucket $1."
exit 1
fi
encpass_decrypt_secret
else
ENCPASS_FILE_LIST=$(ls -1 "$ENCPASS_HOME_DIR"/secrets/"$1")
for ENCPASS_F in $ENCPASS_FILE_LIST; do
ENCPASS_SECRET_NAME=$(basename "$ENCPASS_F" .enc)
encpass_get_secret_abs_name "$1" "$ENCPASS_SECRET_NAME" "nocreate"
if [ -z "$ENCPASS_SECRET_ABS_NAME" ]; then
echo "No secret named $ENCPASS_SECRET_NAME found for bucket $1."
exit 1
fi
echo "$ENCPASS_SECRET_NAME = $(encpass_decrypt_secret)"
done
fi
}
encpass_getche() {
old=$(stty -g)
stty raw min 1 time 0
printf '%s' "$(dd bs=1 count=1 2>/dev/null)"
stty "$old"
}
encpass_remove() {
if [ ! -n "$ENCPASS_FORCE_REMOVE" ]; then
if [ ! -z "$ENCPASS_SECRET" ]; then
printf "Are you sure you want to remove the secret \"%s\" from bucket \"%s\"? [y/N]" "$ENCPASS_SECRET" "$ENCPASS_BUCKET"
else
printf "Are you sure you want to remove the bucket \"%s?\" [y/N]" "$ENCPASS_BUCKET"
fi
ENCPASS_CONFIRM="$(encpass_getche)"
printf "\n"
if [ "$ENCPASS_CONFIRM" != "Y" ] && [ "$ENCPASS_CONFIRM" != "y" ]; then
exit 0
fi
fi
if [ ! -z "$ENCPASS_SECRET" ]; then
rm -f "$1"
printf "Secret \"%s\" removed from bucket \"%s\".\n" "$ENCPASS_SECRET" "$ENCPASS_BUCKET"
else
rm -Rf "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET"
rm -Rf "$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET"
printf "Bucket \"%s\" removed.\n" "$ENCPASS_BUCKET"
fi
}
encpass_save_err() {
if read -r x; then
{ printf "%s\n" "$x"; cat; } > "$1"
elif [ "$x" != "" ]; then
printf "%s" "$x" > "$1"
fi
}
encpass_help() {
less << EOF
NAME:
encpass.sh - Use encrypted passwords in shell scripts
DESCRIPTION:
A lightweight solution for using encrypted passwords in shell scripts
using OpenSSL. It allows a user to encrypt a password (or any other secret)
at runtime and then use it, decrypted, within a script. This prevents
shoulder surfing passwords and avoids storing the password in plain text,
within a script, which could inadvertently be sent to or discovered by an
individual at a later date.
This script generates an AES 256 bit symmetric key for each script
(or user-defined bucket) that stores secrets. This key will then be used
to encrypt all secrets for that script or bucket.
Subsequent calls to retrieve a secret will not prompt for a secret to be
entered as the file with the encrypted value already exists.
Note: By default, encpass.sh sets up a directory (.encpass) under the
user's home directory where keys and secrets will be stored. This directory
can be overridden by setting the environment variable ENCPASS_HOME_DIR to a
directory of your choice.
~/.encpass (or the directory specified by ENCPASS_HOME_DIR) will contain
the following subdirectories:
- keys (Holds the private key for each script/bucket)
- secrets (Holds the secrets stored for each script/bucket)
USAGE:
To use the encpass.sh script in an existing shell script, source the script
and then call the get_secret function.
Example:
#!/bin/sh
. encpass.sh
password=\$(get_secret)
When no arguments are passed to the get_secret function,
then the bucket name is set to the name of the script and
the secret name is set to "password".
There are 2 other ways to call get_secret:
Specify the secret name:
Ex: \$(get_secret user)
- bucket name = <script name>
- secret name = "user"
Specify both the secret name and bucket name:
Ex: \$(get_secret personal user)
- bucket name = "personal"
- secret name = "user"
encpass.sh also provides a command line interface to manage the secrets.
To invoke a command, pass it as an argument to encpass.sh from the shell.
$ encpass.sh [COMMAND]
See the COMMANDS section below for a list of available commands. Wildcard
handling is implemented for secret and bucket names. This enables
performing operations like adding/removing a secret to/from multiple buckets
at once.
COMMANDS:
add [-f] <bucket> <secret>
Add a secret to the specified bucket. The bucket will be created
if it does not already exist. If a secret with the same name already
exists for the specified bucket, then the user will be prompted to
confirm overwriting the value. If the -f option is passed, then the
add operation will perform a forceful overwrite of the value. (i.e. no
prompt)
list|ls [<bucket>]
Display the names of the secrets held in the bucket. If no bucket
is specified, then the names of all existing buckets will be
displayed.
lock
Locks all keys used by encpass.sh using a password. The user
will be prompted to enter a password and confirm it. A user
should take care to securely store the password. If the password
is lost then keys can not be unlocked. When keys are locked,
secrets can not be retrieved. (e.g. the output of the values
in the "show" command will be encrypted/garbage)
remove|rm [-f] <bucket> [<secret>]
Remove a secret from the specified bucket. If only a bucket is
specified then the entire bucket (i.e. all secrets and keys) will
be removed. By default the user is asked to confirm the removal of
the secret or the bucket. If the -f option is passed then a
forceful removal will be performed. (i.e. no prompt)
show [<bucket>] [<secret>]
Show the unencrypted value of the secret from the specified bucket.
If no secret is specified then all secrets for the bucket are displayed.
update <bucket> <secret>
Updates a secret in the specified bucket. This command is similar
to using an "add -f" command, but it has a safety check to only
proceed if the specified secret exists. If the secret, does not
already exist, then an error will be reported. There is no forceable
update implemented. Use "add -f" for any required forceable update
scenarios.
unlock
Unlocks all the keys for encpass.sh. The user will be prompted to
enter the password and confirm it.
dir
Prints out the current value of the ENCPASS_HOME_DIR environment variable.
help|--help|usage|--usage|?
Display this help message.
EOF
}
# Subcommands for cli support
case "$1" in
add )
shift
while getopts ":f" ENCPASS_OPTS; do
case "$ENCPASS_OPTS" in
f ) ENCPASS_FORCE_ADD=1;;
esac
done
encpass_checks
if [ -n "$ENCPASS_FORCE_ADD" ]; then
shift $((OPTIND-1))
fi
if [ ! -z "$1" ] && [ ! -z "$2" ]; then
# Allow globbing
# shellcheck disable=SC2027,SC2086
ENCPASS_ADD_LIST="$(ls -1d "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"
if [ -z "$ENCPASS_ADD_LIST" ]; then
ENCPASS_ADD_LIST="$1"
fi
for ENCPASS_ADD_F in $ENCPASS_ADD_LIST; do
ENCPASS_ADD_DIR="$(basename "$ENCPASS_ADD_F")"
ENCPASS_BUCKET="$ENCPASS_ADD_DIR"
if [ ! -n "$ENCPASS_FORCE_ADD" ] && [ -f "$ENCPASS_ADD_F/$2.enc" ]; then
echo "Warning: A secret with the name \"$2\" already exists for bucket $ENCPASS_BUCKET."
echo "Would you like to overwrite the value? [y/N]"
ENCPASS_CONFIRM="$(encpass_getche)"
if [ "$ENCPASS_CONFIRM" != "Y" ] && [ "$ENCPASS_CONFIRM" != "y" ]; then
continue
fi
fi
ENCPASS_SECRET_NAME="$2"
echo "Adding secret \"$ENCPASS_SECRET_NAME\" to bucket \"$ENCPASS_BUCKET\"..."
set_secret "$ENCPASS_BUCKET" "$ENCPASS_SECRET_NAME" "reuse"
done
else
echo "Error: A bucket name and secret name must be provided when adding a secret."
exit 1
fi
;;
update )
shift
encpass_checks
if [ ! -z "$1" ] && [ ! -z "$2" ]; then
ENCPASS_SECRET_NAME="$2"
# Allow globbing
# shellcheck disable=SC2027,SC2086
ENCPASS_UPDATE_LIST="$(ls -1d "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"
for ENCPASS_UPDATE_F in $ENCPASS_UPDATE_LIST; do
# Allow globbing
# shellcheck disable=SC2027,SC2086
if [ -f "$ENCPASS_UPDATE_F/"$2".enc" ]; then
ENCPASS_UPDATE_DIR="$(basename "$ENCPASS_UPDATE_F")"
ENCPASS_BUCKET="$ENCPASS_UPDATE_DIR"
echo "Updating secret \"$ENCPASS_SECRET_NAME\" to bucket \"$ENCPASS_BUCKET\"..."
set_secret "$ENCPASS_BUCKET" "$ENCPASS_SECRET_NAME" "reuse"
else
echo "Error: A secret with the name \"$2\" does not exist for bucket $1."
exit 1
fi
done
else
echo "Error: A bucket name and secret name must be provided when updating a secret."
exit 1
fi
;;
rm|remove )
shift
encpass_checks
while getopts ":f" ENCPASS_OPTS; do
case "$ENCPASS_OPTS" in
f ) ENCPASS_FORCE_REMOVE=1;;
esac
done
if [ -n "$ENCPASS_FORCE_REMOVE" ]; then
shift $((OPTIND-1))
fi
if [ -z "$1" ]; then
echo "Error: A bucket must be specified for removal."
fi
# Allow globbing
# shellcheck disable=SC2027,SC2086
ENCPASS_REMOVE_BKT_LIST="$(ls -1d "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"
if [ ! -z "$ENCPASS_REMOVE_BKT_LIST" ]; then
for ENCPASS_REMOVE_B in $ENCPASS_REMOVE_BKT_LIST; do
ENCPASS_BUCKET="$(basename "$ENCPASS_REMOVE_B")"
if [ ! -z "$2" ]; then
# Removing secrets for a specified bucket
# Allow globbing
# shellcheck disable=SC2027,SC2086
ENCPASS_REMOVE_LIST="$(ls -1p "$ENCPASS_REMOVE_B/"$2".enc" 2>/dev/null)"
if [ -z "$ENCPASS_REMOVE_LIST" ]; then
echo "Error: No secrets found for $2 in bucket $ENCPASS_BUCKET."
exit 1
fi
for ENCPASS_REMOVE_F in $ENCPASS_REMOVE_LIST; do
ENCPASS_SECRET="$2"
encpass_remove "$ENCPASS_REMOVE_F"
done
else
# Removing a specified bucket
encpass_remove
fi
done
else
echo "Error: The bucket named $1 does not exist."
exit 1
fi
;;
show )
shift
encpass_checks
if [ -z "$1" ]; then
ENCPASS_SHOW_DIR="*"
else
ENCPASS_SHOW_DIR=$1
fi
if [ ! -z "$2" ]; then
# Allow globbing
# shellcheck disable=SC2027,SC2086
if [ -f "$(encpass_get_abs_filename "$ENCPASS_HOME_DIR/secrets/$ENCPASS_SHOW_DIR/"$2".enc")" ]; then
encpass_show_secret "$ENCPASS_SHOW_DIR" "$2"
fi
else
# Allow globbing
# shellcheck disable=SC2027,SC2086
ENCPASS_SHOW_LIST="$(ls -1d "$ENCPASS_HOME_DIR/secrets/"$ENCPASS_SHOW_DIR"" 2>/dev/null)"
if [ -z "$ENCPASS_SHOW_LIST" ]; then
if [ "$ENCPASS_SHOW_DIR" = "*" ]; then
echo "Error: No buckets exist."
else
echo "Error: Bucket $1 does not exist."
fi
exit 1
fi
for ENCPASS_SHOW_F in $ENCPASS_SHOW_LIST; do
ENCPASS_SHOW_DIR="$(basename "$ENCPASS_SHOW_F")"
echo "$ENCPASS_SHOW_DIR:"
encpass_show_secret "$ENCPASS_SHOW_DIR"
echo " "
done
fi
;;
ls|list )
shift
encpass_checks
if [ ! -z "$1" ]; then
# Allow globbing
# shellcheck disable=SC2027,SC2086
ENCPASS_FILE_LIST="$(ls -1p "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"
if [ -z "$ENCPASS_FILE_LIST" ]; then
# Allow globbing
# shellcheck disable=SC2027,SC2086
ENCPASS_DIR_EXISTS="$(ls -d "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"
if [ ! -z "$ENCPASS_DIR_EXISTS" ]; then
echo "Bucket $1 is empty."
else
echo "Error: Bucket $1 does not exist."
fi
exit 1
fi
ENCPASS_NL=""
for ENCPASS_F in $ENCPASS_FILE_LIST; do
if [ -d "${ENCPASS_F%:}" ]; then
printf "$ENCPASS_NL%s\n" "$(basename "$ENCPASS_F")"
ENCPASS_NL="\n"
else
printf "%s\n" "$(basename "$ENCPASS_F" .enc)"
fi
done
else
# Allow globbing
# shellcheck disable=SC2027,SC2086
ENCPASS_BUCKET_LIST="$(ls -1p "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"
for ENCPASS_C in $ENCPASS_BUCKET_LIST; do
if [ -d "${ENCPASS_C%:}" ]; then
printf "\n%s" "\n$(basename "$ENCPASS_C")"
else
basename "$ENCPASS_C" .enc
fi
done
fi
;;
lock )
shift
encpass_checks
echo "************************!!!WARNING!!!*************************" >&2
echo "* You are about to lock your keys with a password. *" >&2
echo "* You will not be able to use your secrets again until you *" >&2
echo "* unlock the keys with the same password. It is important *" >&2
echo "* that you securely store the password, so you can recall it *" >&2
echo "* in the future. If you forget your password you will no *" >&2
echo "* longer be able to access your secrets. *" >&2
echo "************************!!!WARNING!!!*************************" >&2
printf "\n%s\n" "About to lock keys held in directory $ENCPASS_HOME_DIR/keys/"
printf "\nEnter Password to lock keys:" >&2
stty -echo
read -r ENCPASS_KEY_PASS
printf "\nConfirm Password:" >&2
read -r ENCPASS_CKEY_PASS
printf "\n"
stty echo
if [ -z "$ENCPASS_KEY_PASS" ]; then
echo "Error: You must supply a password value."
exit 1
fi
if [ "$ENCPASS_KEY_PASS" = "$ENCPASS_CKEY_PASS" ]; then
ENCPASS_NUM_KEYS_LOCKED=0
ENCPASS_KEYS_LIST="$(ls -1d "$ENCPASS_HOME_DIR/keys/"*"/" 2>/dev/null)"
for ENCPASS_KEY_F in $ENCPASS_KEYS_LIST; do
if [ -d "${ENCPASS_KEY_F%:}" ]; then
ENCPASS_KEY_NAME="$(basename "$ENCPASS_KEY_F")"
ENCPASS_KEY_VALUE=""
if [ -f "$ENCPASS_KEY_F/private.key" ]; then
ENCPASS_KEY_VALUE="$(cat "$ENCPASS_KEY_F/private.key")"
if [ ! -f "$ENCPASS_KEY_F/private.lock" ]; then
echo "Locking key $ENCPASS_KEY_NAME..."
else
echo "Error: The key $ENCPASS_KEY_NAME appears to have been previously locked."
echo " The current key file may hold a bad value. Exiting to avoid encrypting"
echo " a bad value and overwriting the lock file."
exit 1
fi
else
echo "Error: Private key file ${ENCPASS_KEY_F}private.key missing for bucket $ENCPASS_KEY_NAME."
exit 1
fi
if [ ! -z "$ENCPASS_KEY_VALUE" ]; then
openssl enc -aes-256-cbc -pbkdf2 -iter 10000 -salt -in "$ENCPASS_KEY_F/private.key" -out "$ENCPASS_KEY_F/private.lock" -k "$ENCPASS_KEY_PASS"
if [ -f "$ENCPASS_KEY_F/private.key" ] && [ -f "$ENCPASS_KEY_F/private.lock" ]; then
# Both the key and lock file exist. We can remove the key file now
rm -f "$ENCPASS_KEY_F/private.key"
echo "Locked key $ENCPASS_KEY_NAME."
ENCPASS_NUM_KEYS_LOCKED=$(( ENCPASS_NUM_KEYS_LOCKED + 1 ))
else
echo "Error: The key fle and/or lock file were not found as expected for key $ENCPASS_KEY_NAME."
fi
else
echo "Error: No key value found for the $ENCPASS_KEY_NAME key."
exit 1
fi
fi
done
echo "Locked $ENCPASS_NUM_KEYS_LOCKED keys."
else
echo "Error: Passwords do not match."
fi
;;
unlock )
shift
encpass_checks
printf "%s\n" "About to unlock keys held in the $ENCPASS_HOME_DIR/keys/ directory."
printf "\nEnter Password to unlock keys: " >&2
stty -echo
read -r ENCPASS_KEY_PASS
printf "\n"
stty echo
if [ ! -z "$ENCPASS_KEY_PASS" ]; then
ENCPASS_NUM_KEYS_UNLOCKED=0
ENCPASS_KEYS_LIST="$(ls -1d "$ENCPASS_HOME_DIR/keys/"*"/" 2>/dev/null)"
for ENCPASS_KEY_F in $ENCPASS_KEYS_LIST; do
if [ -d "${ENCPASS_KEY_F%:}" ]; then
ENCPASS_KEY_NAME="$(basename "$ENCPASS_KEY_F")"
echo "Unlocking key $ENCPASS_KEY_NAME..."
if [ -f "$ENCPASS_KEY_F/private.key" ] && [ ! -f "$ENCPASS_KEY_F/private.lock" ]; then
echo "Error: Key $ENCPASS_KEY_NAME appears to be unlocked already."
exit 1
fi
if [ -f "$ENCPASS_KEY_F/private.lock" ]; then
# Remove the failed file in case previous decryption attempts were unsuccessful
rm -f "$ENCPASS_KEY_F/failed" 2>/dev/null
# Decrypt key. Log any failure to the "failed" file.
openssl enc -aes-256-cbc -d -pbkdf2 -iter 10000 -salt \
-in "$ENCPASS_KEY_F/private.lock" -out "$ENCPASS_KEY_F/private.key" \
-k "$ENCPASS_KEY_PASS" 2>&1 | encpass_save_err "$ENCPASS_KEY_F/failed"
if [ ! -f "$ENCPASS_KEY_F/failed" ]; then
# No failure has occurred.
if [ -f "$ENCPASS_KEY_F/private.key" ] && [ -f "$ENCPASS_KEY_F/private.lock" ]; then
# Both the key and lock file exist. We can remove the lock file now.
rm -f "$ENCPASS_KEY_F/private.lock"
echo "Unlocked key $ENCPASS_KEY_NAME."
ENCPASS_NUM_KEYS_UNLOCKED=$(( ENCPASS_NUM_KEYS_UNLOCKED + 1 ))
else
echo "Error: The key file and/or lock file were not found as expected for key $ENCPASS_KEY_NAME."
fi
else
printf "Error: Failed to unlock key %s.\n" "$ENCPASS_KEY_NAME"
printf " Please view %sfailed for details.\n" "$ENCPASS_KEY_F"
fi
else
echo "Error: No lock file found for the $ENCPASS_KEY_NAME key."
fi
fi
done
echo "Unlocked $ENCPASS_NUM_KEYS_UNLOCKED keys."
else
echo "No password entered."
fi
;;
dir )
shift
encpass_checks
echo "ENCPASS_HOME_DIR=$ENCPASS_HOME_DIR"
;;
help|--help|usage|--usage|\? )
encpass_checks
encpass_help
;;
* )
if [ ! -z "$1" ]; then
echo "Command not recognized. See \"encpass.sh help\" for a list commands."
exit 1
fi
;;
esac
You can find some resources related to developing web services client using Apache axis2 here.
http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html
Below posts gives good explanations about developing web services using Apache axis2.
http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({`enter code here`
url: "TextFile.txt",
dataType: "text",
success: function (data) {
var text = $('#newCheckText').val();
var str = data;
var str_array = str.split('\n');
for (var i = 0; i < str_array.length; i++) {
// Trim the excess whitespace.
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
// Add additional code here, such as:
alert(str_array[i]);
$('#checkboxes').append('<input type="checkbox" class="checkBoxClass" /> ' + str_array[i] + '<br />');
}
}
});
$("#ckbCheckAll").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
});
</script>
</head>
<body>
<div id="checkboxes">
<input type="checkbox" id="ckbCheckAll" class="checkBoxClass"/> Select All<br />
</div>
</body>
</html>
The sort package provides the building blocks if your slice is sorted or you are willing to sort it.
input := []string{"bird", "apple", "ocean", "fork", "anchor"}
sort.Strings(input)
fmt.Println(contains(input, "apple")) // true
fmt.Println(contains(input, "grow")) // false
...
func contains(s []string, searchterm string) bool {
i := sort.SearchStrings(s, searchterm)
return i < len(s) && s[i] == searchterm
}
SearchString
promises to return the index to insert x if x is not present (it could be len(a))
, so a check of that reveals whether the string is contained the sorted slice.
You need to use an iframe
.
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content" src="about:blank"></iframe>
</body>
</html
Git will even determine that it is binary if you have one super-long line in your text file. I broke up a long String, turning it into several source code lines, and suddenly the file went from being 'binary' to a text file that I could see (in SmartGit).
So don't keep typing too far to the right without hitting 'Enter' in your editor - otherwise later on Git will think you have created a binary file.
This error means that the XML file could not be found. The library needs you to pass it the full path, even though you’re probably just using a file that came with the OpenCV library.
You can use the built-in pkg_resources
module to automatically determine this for you. The following code looks up the full path to a file inside wherever the cv2
module was loaded from:
import pkg_resources
haar_xml = pkg_resources.resource_filename(
'cv2', 'data/haarcascade_frontalface_default.xml')
For me this was '/Users/andrew/.local/share/virtualenvs/foo-_b9W43ee/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml'
; yours is guaranteed to be different. Just let python’s pkg_resources
library figure it out.
classifier = cv2.CascadeClassifier(haar_xml)
faces = classifier.detectMultiScale(frame)
Success!
Our solution, adding some validations to response so we are sure we have a well formed json object in $json variable
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
if (! $result) {
return false;
}
$json = json_decode(utf8_encode($result));
if (empty($json) || json_last_error() !== JSON_ERROR_NONE) {
return false;
}
It's an encoding error - so if it's a unicode string, this ought to fix it:
text.encode("windows-1252").decode("utf-8")
If it's a plain string, you'll need an extra step:
text.decode("utf-8").encode("windows-1252").decode("utf-8")
Both of these will give you a unicode string.
By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:
>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}
Another way of doing the same but with dplyr
library(dplyr)
subdf <- df %>% filter(numbers <= 3) %>% droplevels()
str(subdf)
Edit:
Also Works ! Thanks to agenis
subdf <- df %>% filter(numbers <= 3) %>% droplevels
levels(subdf$letters)
In my experience, /var/www/ directory directive prevents subfolder virtualhost directives. So if you had tried all suggestions and still not working and you are using virtualhosts try this ;
1 - Be sure that you have
AllowOverride All
directive in
/etc/apache2/sites-available/example.com.conf
2 - Check /var/www/ Directory directives in /etc/apache2/apache2.conf
(possibly at line 164), which looks like ;
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
If there is an AllowOverride None
directive change it to
AllowOverride All
or just escape line
I think @InspiredJW did it with ES5, and as @trincot pointed out, using es6 is a better approach. But we can add a bit more sugar, by using the spread operator, and logical AND short circuit evaluation:
const a = {
...(someCondition && {b: 5})
}
You do the same way as any other character matching, but you use \uXXXX where XXXX is the unicode number of the character.
Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).
You can limit the whole search to one row by using Limit 0,1
SELECT COUNT(UserName)
FROM TableName
WHERE UserName = 'User' AND
Password = 'Pass'
LIMIT 0, 1
Yes it is possible
You can do this using only
HTML
You need to set default select optiondisabled=""
andselected=""
and select tagrequired=""
. Browser doesn't allow user to submit the form without selecting an option.
<form action="" method="POST">
<select name="in-op" required="">
<option disabled="" selected="">Select Option</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<input type="submit" value="Submit">
</form>
Add these lines in urls.py
from django.conf.urls import (
handler400, handler403, handler404, handler500
)
handler400 = 'my_app.views.bad_request'
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'
# ...
and implement our custom views in views.py.
from django.shortcuts import (
render_to_response
)
from django.template import RequestContext
# HTTP Error 400
def bad_request(request):
response = render_to_response(
'400.html',
context_instance=RequestContext(request)
)
response.status_code = 400
return response
# ...
Below are all what you want:
CTRL + M + M
CTRL + M + H
CTRL + M + O
CTRL + M + A
CTRL + M + X
CTRL + M + L
92% additional asset processing scripts-webpack-plugin× ?wdm?: Error: ENOENT: no such file or directory, open....==> if anyone faced to such error, you should do followings: 1) you should check the if the file path is correct in angular.json file.
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.js"
],
2) you should press crtl+c and re run the project.
Check filenames.
You might need to create a new database in phpmyadmin that matches the database you're trying to import.
[A-Za-z ]*
to match letters and spaces.
Naive question: Is it possible to somehow download GLIBC 2.15, put it in any folder (e.g. /tmp/myglibc) and then point to this path ONLY when executing something that needs this specific version of glibc?
Yes, it's possible.
In the second you can access the attributes of the exception object:
>>> def catch():
... try:
... asd()
... except Exception as e:
... print e.message, e.args
...
>>> catch()
global name 'asd' is not defined ("global name 'asd' is not defined",)
But it doesn't catch BaseException
or the system-exiting exceptions SystemExit
, KeyboardInterrupt
and GeneratorExit
:
>>> def catch():
... try:
... raise BaseException()
... except Exception as e:
... print e.message, e.args
...
>>> catch()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in catch
BaseException
Which a bare except does:
>>> def catch():
... try:
... raise BaseException()
... except:
... pass
...
>>> catch()
>>>
See the Built-in Exceptions section of the docs and the Errors and Exceptions section of the tutorial for more info.
If you want a less verbose hack:
void deleteDirectory(String path) {
Runtime.getRuntime().exec(String.format("rm -rf %s", path));
}
The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.
Try using headers to do authentication:
import urllib2, base64
request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662
For me this worked in WPF
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
RoutedEventArgs routedEventArgs = new RoutedEventArgs(ButtonBase.ClickEvent, Button_OK);
Button_OK.RaiseEvent(routedEventArgs);
}
}
This can be done in two ways.
JLabel Horizontal Alignment
You can use the JLabel
constructor:
JLabel(String text, int horizontalAlignment)
To align to the right:
JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);
JLabel
also has setHorizontalAlignment
:
label.setHorizontalAlignment(SwingConstants.RIGHT);
This assumes the component takes up the whole width in the container.
Using Layout
A different approach is to use the layout to actually align the component to the right, whilst ensuring they do not take the whole width. Here is an example with BoxLayout
:
Box box = Box.createVerticalBox();
JLabel label1 = new JLabel("test1, the beginning");
label1.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label1);
JLabel label2 = new JLabel("test2, some more");
label2.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label2);
JLabel label3 = new JLabel("test3");
label3.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label3);
add(box);
Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.
Having added a new view controller scene to your storyboard, you then have to:
Create a UIViewController
subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":
And then select a unique name for the new view controller subclass:
Specify this new subclass as the base class for the scene you just added to the storyboard.
Now hook up any IBOutlet
and IBAction
references for this new scene with the new view controller subclass.
The app should contain a templatetags
directory, at the same level as models.py
, views.py
, etc. If this doesn’t already exist, create it - don’t forget the __init__.py
file to ensure the directory is treated as a Python package.
define_action.py
inside of the templatetags directory with the following code:from django import template
register = template.Library()
@register.simple_tag
def define(val=None):
return val
Note: Development server won’t automatically restart. After adding the templatetags
module, you will need to restart your server before you can use the tags or filters in templates.
{% load define_action %}
{% if item %}
{% define "Edit" as action %}
{% else %}
{% define "Create" as action %}
{% endif %}
Would you like to {{action}} this item?
This issue is due to incompatible of your plugin Verison and required Gradle version; they need to match with each other. I am sharing how my problem was solved.
Required Gradle version is here
more compatibility you can see from here. Android Plugin for Gradle Release Notes
if you have the android studio version 4.0.1
then your top level gradle file must be like this
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.2'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
and the gradle version should be
and your app gradle look like this
It's impossible without CSS. In fact, the <u>
tag is simply adding text-decoration:underline
to the text with the browser's built-in CSS.
Here's what you can do:
<html>
<head>
<!-- Other head stuff here, like title or meta -->
<style type="text/css">
u {
border-bottom: 1px dotted #000;
text-decoration: none;
}
</style>
</head>
<!-- Body, content here -->
</html>
Console console = System.console();
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: ");
you can use cssSelector,
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));
Sometimes you want to change the capitalization of a lot of file names on a case insensitive filesystem (e.g. on OS X or Windows). Doing git mv
commands will tire quickly. To make things a bit easier this is what I do:
git add . -A
to remove all files.git add .
. Git should see that the files are renamed.Now you can make a commit saying you have changed the file name capitalization.
You might create a View selecting the column names required by your insert statement, add an INSTEAD OF INSERT Trigger, and insert into this view.
Kompare is fine for diff, but I use dirdiff. Although it looks ugly, dirdiff can do 3-way merge - and you can get everything done inside the tool (both diff and merge).
Keep in mind that on Linux if you have a directory with too many files, the shell may not be able to expand wildcards. I have this issue with a photo album hosted on Linux. It stores all the resized images in a single directory. While the file system can handle many files, the shell can't. Example:
-shell-3.00$ ls A*
-shell: /bin/ls: Argument list too long
or
-shell-3.00$ chmod 644 *jpg
-shell: /bin/chmod: Argument list too long
This is the code for the character you posted in your question: 
But that's not a checkbox character...
Regarding your update, about not wanting to wait for the full page to load - I think a HTTP HEAD
request is what you're looking for..
get_headers should do this - I think it only requests the headers, so will not be sent the full page content.
"PHP / Curl: HEAD Request takes a long time on some sites" describes how to do a HEAD
request using PHP/Curl
If you want to trigger the request, and not hold up the script at all, there are a few ways, of varying complexities..
"wget -O /dev/null $carefully_escaped_url"
- this will be platform specific, and you have to be really careful about escaping parameters to the commandHere is my preferred quickest and easiest solution. Works well if all slides have the same background color that you want to remove.
Step 1. In Powerpoint, "Save As" (shortcut F12) PNG, "All Slides".
Now you have a folder full of these PNG images of all your slides. The problem is that they still have a background. So now:
Step 2. Batch remove background color of all the PNG images, for example by following the steps in this SE answer.
You can do it (albeit not lightning-quickly) like so:
people.Where(p => !people.Any(q => (p != q && p.Id == q.Id)));
That is, "select all people where there isn't another different person in the list with the same ID."
Mind you, in your example, that would just select person 3. I'm not sure how to tell which you want, out of the previous two.
If the PHP file the AJAX requests has a session_start()
the session info will be retained. (baring the requests are within the same domain)
Yes, you can always use null
instead of an object. Just be careful because some methods might throw error.
It would be 1.
also null
s would be factored in in the for loop, but you could use
for(Item i : itemList) {
if (i!= null) {
//code here
}
}
I added a modal dialog in jsp and tried to open it with javascript in jsx and hit the same error: "...modal is not a function"
In my case, simply by adding the missing import to the jsx solved the problem.
`import "./../bower/bootstrap/js/modal.js"; // or import ".../bootstrap.min.js"`
you have to install python-mysqldb - Python interface to MySQL
Try
sudo apt-get install python-mysqldb
Just found a quick and simple solution to discover type of a variable.
ES6
export const isType = (type, val) => val.constructor.name.toLowerCase() === type.toLowerCase();
ES5
function isType(type, val) {
return val.constructor.name.toLowerCase() === type.toLowerCase();
}
Examples:
isType('array', [])
true
isType('array', {})
false
isType('string', '')
true
isType('string', 1)
false
isType('number', '')
false
isType('number', 1)
true
isType('boolean', 1)
false
isType('boolean', true)
true
EDIT
Improvment to prevent 'undefined' and 'null' values:
ES6
export const isType = (type, val) => !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());
ES5
function isType(type, val) {
return !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());
}
Andre Silva's answer works great for me, with one caveat in the "barplot" line:
barplot(mtcars$qsec, col="grey50",
main="",
ylab="mtcars - qsec", ylim=c(0,5+max(mtcars$qsec)),
xlab = "",
xaxt = "n",
space=1)
Notice the "xaxt" argument. Without it, the labels are drawn twice, the first time without the 60 degree rotation.
If you can't use the delay
method as Robert Harvey suggested, you can use setTimeout
.
Eg.
setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one
You can use a <div>
to cover the scrollbar if you really want it to disappear.
Although it won't work on IE6, modern browsers do let you put a <div>
on top of it.
Paths under linux are separated by colons (:
), not semi-colons (;
), as theatrus correctly used it in his example. I believe Java respects this convention.
Alternatively to what andy suggested, you may use the following form (which sets CLASSPATH for the duration of the command):
CLASSPATH=".:../somejar.jar:../mysql-connector-java-5.1.6-bin.jar" java -Xmx500m ...
whichever is more convenient to you.
Using Random function to generate number and iterating them on al
using for loop
ArrayList<Integer> al=new ArrayList<Integer>(5);
for (int i=0;i<=4;i++){
Random rand=new Random();
al.add(i,rand.nextInt(100));
System.out.println(al);
}
System.out.println(al.size());
In case the host
part is omitted it defaults to the wildcard symbol %
, allowing all hosts.
CREATE USER 'service-api';
GRANT ALL PRIVILEGES ON the_db.* TO 'service-api' IDENTIFIED BY 'the_password'
SELECT * FROM mysql.user;
SHOW GRANTS FOR 'service-api'
This error occurred to me when I was debugging the PHP header() function:
header('Location: /aaa/bbb/ccc'); // error
If I use a relative path it works:
header('Location: aaa/bbb/ccc'); // success, but not what I wanted
However when I use an absolute path like /aaa/bbb/ccc
, it gives the exact error:
Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
It appears the header function redirects internally without going HTTP at all which is weird. After some tests and trials, I found the solution of adding exit after header():
header('Location: /aaa/bbb/ccc');
exit;
And it works properly.
In Typescript, I use this algorithm to calculate framerate and frametime averages:
let getTime = () => {
return new Date().getTime();
}
let frames: any[] = [];
let previousTime = getTime();
let framerate:number = 0;
let frametime:number = 0;
let updateStats = (samples:number=60) => {
samples = Math.max(samples, 1) >> 0;
if (frames.length === samples) {
let currentTime: number = getTime() - previousTime;
frametime = currentTime / samples;
framerate = 1000 * samples / currentTime;
previousTime = getTime();
frames = [];
}
frames.push(1);
}
usage:
statsUpdate();
// Print
stats.innerHTML = Math.round(framerate) + ' FPS ' + frametime.toFixed(2) + ' ms';
Tip: If samples is 1, the result is real-time framerate and frametime.
My objective:
I needed to assign the value "{CR}{LF}"
to a string
variable delimiter
.
Code c#:
string delimiter= "{{CR}}{{LF}}";
Note: To escape special characters normally you have to use . For opening curly bracket {, use one extra like {{. For closing curly bracket }, use one extra }}.
Worked for me after I closed Visual Studio (2015 Community Edition), opened it and opened project again.Had Happened to me because I was using this project as a dependency in another project and it was opened in another instance but the changes were not imitated.
That's the Hamming weight problem, a.k.a. population count. The link mentions efficient implementations. Quoting:
With unlimited memory, we could simply create a large lookup table of the Hamming weight of every 64 bit integer
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
When using github, note that you can also target a specific commit (for example, of a fork you've made and updated) by appending its commit hash to the end of its clone url. For example:
"dependencies": {
"example": "https://github.com/owner_name/repo_name.git#9203e6166b343d7d8b3bb638775b41fe5de3524c"
}
Or you can target a git commit in your local file system if you use your project's .git directory, like so (on Windows; note the forward slashes):
"dependencies": {
"example": "file://C:/Projects/my-project/.git#9203e6166b343d7d8b3bb638775b41fe5de3524c"
}
This is one way of testing library code you've committed locally but not yet pushed to the repo.
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
1. Create class Name RecyclerTouchListener.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener
{
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
2. Call RecyclerTouchListener
recycleView.addOnItemTouchListener(new RecyclerTouchListener(this, recycleView,
new RecyclerTouchListener.ClickListener() {
@Override
public void onClick(View view, int position) {
Toast.makeText(MainActivity.this,Integer.toString(position),Toast.LENGTH_SHORT).show();
}
@Override
public void onLongClick(View view, int position) {
}
}));
In addition to the nested approach above, you can accomplish the application of theLIMIT
using JOIN
on the same table:
UPDATE `table_name`
INNER JOIN (SELECT `id` from `table_name` order by `id` limit 0,100) as t2 using (`id`)
SET `name` = 'test'
In my experience the mysql query optimizer is happier with this structure.
A char value in C is implicitly convertible to an int. e.g, char c; ... printf("%d", c)
prints the decimal ASCII value of c
, and int i = c;
puts the ASCII integer value of c
in i
. You can also explicitly convert it with (int)c
. If you mean something else, such as how to convert an ASCII digit to an int, that would be c - '0'
, which implicitly converts c
to an int and then subtracts the ASCII value of '0'
, namely 48 (in C, character constants such as '0'
are of type int, not char, for historical reasons).
This is what the res.locals object is for. Setting variables directly on the request object is not supported or documented. res.locals is guaranteed to hold state over the life of a request.
An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
app.use(function(req, res, next) {
res.locals.user = req.user;
res.locals.authenticated = !req.user.anonymous;
next();
});
To retrieve the variable in the next middleware:
app.use(function(req, res, next) {
if (res.locals.authenticated) {
console.log(res.locals.user.id);
}
next();
});
public options2 = [_x000D_
{"id": 1, "name": "a"},_x000D_
{"id": 2, "name": "b"}_x000D_
]_x000D_
_x000D_
YourFormGroup = FormGroup; _x000D_
mode: 'create' | 'update' = 'create';_x000D_
_x000D_
constructor(@Inject(MAT_DIALOG_DATA) private defaults: defautValuesCpnt,_x000D_
private fb: FormBuilder,_x000D_
private cd: ChangeDetectorRef) {_x000D_
}_x000D_
_x000D_
ngOnInit() {_x000D_
_x000D_
if (this.defaults) {_x000D_
this.mode = 'update';_x000D_
} else {_x000D_
this.defaults = {} as Cpnt;_x000D_
}_x000D_
_x000D_
this.YourFormGroup.patchValue({_x000D_
..._x000D_
fCtrlName: this.options2.find(x => x.name === this.defaults.name).id,_x000D_
... _x000D_
});_x000D_
_x000D_
this.YourFormGroup = this.fb.group({_x000D_
fCtrlName: [ , Validators.required]_x000D_
});_x000D_
_x000D_
}
_x000D_
<div>_x000D_
<mat-select formControlName="fCtrlName"> <mat-option_x000D_
*ngFor="let option of options2"_x000D_
value="{{ option.id }}">_x000D_
{{ option.name }}_x000D_
</mat-option>_x000D_
</mat-select>_x000D_
</div>
_x000D_
In my case, it happened when one table is InnoB and other is MyISAM. Changing engine of one table, through MySQL Workbench, solves for me.
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
Python is an interesting language in that while there is usually one (or two) "obvious" ways to accomplish any given task, flexibility still exists.
s = "string"
i = 0
print (s + repr(i))
The above code snippet is written in Python3 syntax but the parentheses after print were always allowed (optional) until version 3 made them mandatory.
Hope this helps.
Caitlin
You can add property to your model as follows:
public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }
and then your view will be simpler and will contain no logic at all:
<div class="details @Model.DetailsClass"/>
This will work even with many classes and will not render class if it is null:
<div class="@Model.Class1 @Model.Class2"/>
with 2 not null properties will render:
<div class="class1 class2"/>
if class1 is null
<div class=" class2"/>
Expanding on the answer by @gordon, here's an example of readable syntax and argument passing with shell/command module (these differ from the git module in that there are required but free-form arguments, as noted by @ander)
- name: "release tarball is generated" local_action: module: shell _raw_params: git archive --format zip --output release.zip HEAD chdir: "files/clones/webhooks"
apiclient
was the original name of the library.
At some point, it was switched over to be googleapiclient
.
If your code is running on Google App Engine, both should work.
If you are running the application yourself, with the google-api-python-client installed, both should work as well.
Although, if we take a look at the source code of the apiclient
package's __init__.py
module, we can see that the apiclient
module was simply kept around for backwards-compatibility.
Retain apiclient as an alias for googleapiclient.
So, you really should be using googleapiclient
in your code, since the apiclient
alias was just maintained as to not break legacy code.
# bad
from apiclient.discovery import build
# good
from googleapiclient.discovery import build
Clone is broken, so dont use it.
THE CLONE METHOD of the Object class is a somewhat magical method that does what no pure Java method could ever do: It produces an identical copy of its object. It has been present in the primordial Object superclass since the Beta-release days of the Java compiler*; and it, like all ancient magic, requires the appropriate incantation to prevent the spell from unexpectedly backfiring
Prefer a method that copies the object
Foo copyFoo (Foo foo){
Foo f = new Foo();
//for all properties in FOo
f.set(foo.get());
return f;
}
Read more http://adtmag.com/articles/2000/01/18/effective-javaeffective-cloning.aspx
Add "JsonValueProviderFactory" in global.asax :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
git clone --branch {branch-name} {repo-URI}
Example:
git clone --branch dev https://github.com/ann/cleaningmachine.git
{branch-name}
{repo-URI}
Simple use JQuery.
$(document).ready(function() {_x000D_
$("div .FormRow").focusin(function() {_x000D_
$(this).css("background-color", "#FFFFCC");_x000D_
$(this).css("border", "3px solid #555");_x000D_
});_x000D_
$("div .FormRow").focusout(function() {_x000D_
$(this).css("background-color", "#FFFFFF");_x000D_
$(this).css("border", "0px solid #555");_x000D_
});_x000D_
});
_x000D_
.FormRow {_x000D_
padding: 10px;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div style="border: 0px solid black;padding:10px;">_x000D_
<div class="FormRow">_x000D_
First Name:_x000D_
<input type="text">_x000D_
<br>_x000D_
</div>_x000D_
<div class="FormRow">_x000D_
Last Name:_x000D_
<input type="text">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<ul>_x000D_
<li><strong><em>Click an input field to get focus.</em></strong>_x000D_
</li>_x000D_
<li><strong><em>Click outside an input field to lose focus.</em></strong>_x000D_
</li>_x000D_
</ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Just a recommendation:
I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}
There's a set of useful extensions to IDLE called IDLEX that works with MacOS and Windows http://idlex.sourceforge.net/
It includes line numbering and I find it quite handy & free.
Otherwise there are a bunch of other IDEs some of which are free: https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
It can be achieved using JS. Here is a 'one-line' solution using elastic.js:
$('#note').elastic();
Updated: Seems like elastic.js is not there anymore, but if you are looking for an external library, I can recommend autosize.js by Jack Moore. This is the working example:
autosize(document.getElementById("note"));
_x000D_
textarea#note {_x000D_
width:100%;_x000D_
box-sizing:border-box;_x000D_
direction:rtl;_x000D_
display:block;_x000D_
max-width:100%;_x000D_
line-height:1.5;_x000D_
padding:15px 15px 30px;_x000D_
border-radius:3px;_x000D_
border:1px solid #F7E98D;_x000D_
font:13px Tahoma, cursive;_x000D_
transition:box-shadow 0.5s ease;_x000D_
box-shadow:0 4px 6px rgba(0,0,0,0.1);_x000D_
font-smoothing:subpixel-antialiased;_x000D_
background:linear-gradient(#F9EFAF, #F7E98D);_x000D_
background:-o-linear-gradient(#F9EFAF, #F7E98D);_x000D_
background:-ms-linear-gradient(#F9EFAF, #F7E98D);_x000D_
background:-moz-linear-gradient(#F9EFAF, #F7E98D);_x000D_
background:-webkit-linear-gradient(#F9EFAF, #F7E98D);_x000D_
}
_x000D_
<script src="https://rawgit.com/jackmoore/autosize/master/dist/autosize.min.js"></script>_x000D_
<textarea id="note">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</textarea>
_x000D_
Check this similar topics too:
Autosizing textarea using Prototype
Expanding on Abdul's answer, you can obtain a KeyedTuple
instead of a discrete collection of rows by joining the columns:
q = Session.query(*User.__table__.columns + Document.__table__.columns).\
select_from(User).\
join(Document, User.email == Document.author).\
filter(User.email == 'someemail').all()
Try this one: http://www.asp.net/downloads/essential This has web developer and VS2008 express
It is in the dist folder inside of the project, but only if "Compress WAR File" in the project settings dialog ( build / packaging) ist checked. Before I checked this checkbox there was no dist folder.
A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.
A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.
You can do this in single filter step:
requiredCars = cars.stream().filter(c -> c.getName() != null && c.getName().startsWith("M"));
If you don't want to call getName()
several times (for example, it's expensive call), you can do this:
requiredCars = cars.stream().filter(c -> {
String name = c.getName();
return name != null && name.startsWith("M");
});
Or in more sophisticated way:
requiredCars = cars.stream().filter(c ->
Optional.ofNullable(c.getName()).filter(name -> name.startsWith("M")).isPresent());
for alternative you can use as below:
if (variable >= 5 && variable <= 100) {
doSomething();
}
or the following code also works
switch (variable)
{
case 5:
case 6:
etc.
case 100:
doSomething();
break;
}
Just type ctrl+shift+I in google chrome & you will land in an isolated developer window.
Select count(*) FROM all_tables where owner='schema_name'
(question) Don't you get that info in
select * from pg_user;
or using the view pg_stat_activity:
select * from pg_stat_activity;
Added:
the view says:
One row per server process, showing database OID, database name, process ID, user OID, user name, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and client's address and port number. The columns that report data on the current query are available unless the parameter stats_command_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.
can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...
something like that.
I always use this way:
$foo = (object)null; //create an empty object
$foo->bar = "12345";
echo $foo->bar; //12345
jQuery('#masterdiv div').html('');
gravity
arranges the content inside the view. layout_gravity
arranges the view's position outside of itself.Sometimes it helps to see a picture, too. The green and blue are TextViews
and the other two background colors are LinearLayouts
.
layout_gravity
does not work for views in a RelativeLayout
. Use it for views in a LinearLayout
or FrameLayout
. See my supplemental answer for more details.gravity
won't have any effect. Thus, wrap_content
and gravity
are meaningless together.layout_gravity
won't have any effect. Thus, match_parent
and layout_gravity
are meaningless together.layout_gravity=center
looks the same as layout_gravity=center_horizontal
here because they are in a vertical linear layout. You can't center vertically in this case, so layout_gravity=center
only centers horizontally.gravity
and layout_gravity
on the views within a layout. To see what happens when you set the gravity
of the of the parent layout itself, check out the supplemental answer that I referred to above. (Summary: gravity
doesn't work well on a RelativeLayout
but can be useful with a LinearLayout
.)So remember, layout_gravity arranges a view in its layout. Gravity arranges the content inside the view.
Here is the xml for the above image for your reference:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#e3e2ad"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="24sp"
android:text="gravity=" />
<TextView
android:layout_width="200dp"
android:layout_height="40dp"
android:background="#bcf5b1"
android:gravity="left"
android:text="left" />
<TextView
android:layout_width="200dp"
android:layout_height="40dp"
android:background="#aacaff"
android:gravity="center_horizontal"
android:text="center_horizontal" />
<TextView
android:layout_width="200dp"
android:layout_height="40dp"
android:background="#bcf5b1"
android:gravity="right"
android:text="right" />
<TextView
android:layout_width="200dp"
android:layout_height="40dp"
android:background="#aacaff"
android:gravity="center"
android:text="center" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#d6c6cd"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="24sp"
android:text="layout_gravity=" />
<TextView
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_gravity="left"
android:background="#bcf5b1"
android:text="left" />
<TextView
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:background="#aacaff"
android:text="center_horizontal" />
<TextView
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_gravity="right"
android:background="#bcf5b1"
android:text="right" />
<TextView
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:background="#aacaff"
android:text="center" />
</LinearLayout>
</LinearLayout>
import datetime
from dateutil.rrule import DAILY,rrule
date=datetime.datetime(2019,1,10)
date1=datetime.datetime(2019,2,2)
for i in rrule(DAILY , dtstart=date,until=date1):
print(i.strftime('%Y%b%d'),sep='\n')
OUTPUT:
2019Jan10
2019Jan11
2019Jan12
2019Jan13
2019Jan14
2019Jan15
2019Jan16
2019Jan17
2019Jan18
2019Jan19
2019Jan20
2019Jan21
2019Jan22
2019Jan23
2019Jan24
2019Jan25
2019Jan26
2019Jan27
2019Jan28
2019Jan29
2019Jan30
2019Jan31
2019Feb01
2019Feb02
Set the digits attribute to true, which will cause it to only allow number inputs.
Then do Integer.valueOf(editText.getText())
to get an int value out.
I had same issue when first start Android Studio in Window 10, with java jdk 1.8.0_66. The solution that worked is:
Step 1: Close Android Studio
Step 2: Delete Folder C:\Users\Anna\.gradle (Anna is my username)
Step 3: Open Android Studio as Administrator
Step 4: If you are currently in an opened project, close current project by select File > Close Project.
Step 5: Now you seeing this Quick Start GUI:
Wait for gradle to build again (it would download all the dependency in your build.gradle for every module in your project)
If it has not worked till now, you could restart your computer. Do step 1 again.
This happens sometime when I changed Android Studio version or recently upgrade Window. Hope that helps !
The problem you're having running from the command line is that you don't put ".class" after your class file.
java Practice 10 12
should work - as long as you're somewhere java can find the .class file.
Classpath issues are a whole 'nother story. If java still complains that it can't find your class, go to the same directory as your .class file (and it doesn't appear you're using packages...) and try -
java -cp . Practice 10 12
Why not trying something simple and human-readable, like JSON (or XML) ?
There are many pre-made open-source implementations of JSON (or XML) for C++ - I would use one of them.
And if you want something more "binary" - try BJSON or BSON :)
You can basically do this
if(s.charAt(i)==32){
return true;
}
You must write boolean method.Whitespace char is 32.
If you are making a startup function, you can define global functions and variables this way:
function(globalScope)
{
// Define something
globalScope.something()
{
alert("It works");
};
}(window)
Because the function is invoked globally with this argument, this is global scope here. So, the something should be a global thing.
Virtual Machines (VMs) hosted in the cloud. Before the cloud, these were often called Virtual Private Servers (VPS). You'd use these the same way you'd use a physical server, where you install and configure the operating system, install your application, install the database, keep the OS up-to-date, etc. This is known as Infrastructure-as-a-Service (IaaS).
VMs are most useful when you have an existing application running on a VM or server in your datacenter, and want to easily migrate it to GCP.
App Engine hosts and runs your code, without requiring you to deal with the operating system, networking, and many of the other things you'd have to manage with a physical server or VM. Think of it as a runtime, which can automatically deploy, version, and scale your application. This is called Platform-as-a-Service (PaaS).
App Engine is most useful when you want automated deployment and automated scaling of your application. Unless your application requires custom OS configuration, App Engine is often advantageous over configuring and managing VMs by hand.
Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.
@Path("/hello")
public class Hello {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {
String input = (String) inputJsonObj.get("input");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
And, your client code should look like this:
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new LoggingFilter());
WebResource service = client.resource(getBaseURI());
JSONObject inputJsonObj = new JSONObject();
inputJsonObj.put("input", "Value");
System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));
Why not just use this?
var interopHelper = new WindowInteropHelper(System.Windows.Application.Current.MainWindow);
var activeScreen = Screen.FromHandle(interopHelper.Handle);
I use the little utility which comes with PureMPI.net called execcmd.exe
. Its syntax is as follows:
execcmd \\yourremoteserver <your command here>
Doesn't get any simpler than this :)
I was struggling with the docker push, both using the Fabric8 Maven plugin (on Windows 10), and directly calling docker push
from the command line.
Finally I solved both issues the same way.
My repo is called vgrazi/playpen. In my pom, I changed the docker image name to vgrazi/playpen, as below:
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.31.0</version>
<configuration>
<dockerHost>npipe:////./pipe/docker_engine</dockerHost>
<verbose>true</verbose>
<images>
<image>
<name>vgrazi/playpen</name>
<build>
<dockerFileDir>${project.basedir}/src/main/docker/</dockerFileDir>
...
That let me do a mvn clean package docker:build docker:push
from the command line, and at last, the image appeared in my repo, which was the problem I was trying to solve.
As an aside, to answer the OP and get this to work directly from the command line, without Maven, I did the following (PS is the PowerShell prompt, don't type that):
PS docker images
vgrazi/docker-test/docker-play playpen 0722e876ebd7 40 minutes ago 536MB
rabbitmq 3-management 68055d63a993 10 days ago 180MB
PS docker tag 0722e876ebd7 vgrazi:playpen
PS docker push vgrazi/playpen
and again, the image appeared in my docker.io: repo vgrazi/playpen
Many great answers here, but there is some additional information about why you should avoid using finalize().
If the JVM exits due to System.exit()
or Runtime.getRuntime().exit()
, finalizers will not be run by default. From Javadoc for Runtime.exit():
The virtual machine's shutdown sequence consists of two phases. In the first phase all registered shutdown hooks, if any, are started in some unspecified order and allowed to run concurrently until they finish. In the second phase all uninvoked finalizers are run if finalization-on-exit has been enabled. Once this is done the virtual machine halts.
You can call System.runFinalization()
but it only makes "a best effort to complete all outstanding finalizations" – not a guarantee.
There is a System.runFinalizersOnExit()
method, but don't use it – it's unsafe, deprecated long ago.
find /path -type f \( -iname "*.jpg" -o -name "*.jpeg" -o -iname "*gif" \)
You could use a regular expression like this
If Regex.IsMatch(number, "^[0-9 ]+$") Then
...
End If