A more contemporary way of doing it on a separate thread using Tasks and Kotlin
private val mExecutor: Executor = Executors.newSingleThreadExecutor()
private fun createHttpTask(u:String): Task<String> {
return Tasks.call(mExecutor, Callable<String>{
val url = URL(u)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.requestMethod = "GET"
conn.connectTimeout = 3000
conn.readTimeout = 3000
val rc = conn.responseCode
if ( rc != HttpURLConnection.HTTP_OK) {
throw java.lang.Exception("Error: ${rc}")
}
val inp: InputStream = BufferedInputStream(conn.inputStream)
val resp: String = inp.bufferedReader(UTF_8).use{ it.readText() }
return@Callable resp
})
}
and now you can use it like below in many places:
createHttpTask("https://google.com")
.addOnSuccessListener {
Log.d("HTTP", "Response: ${it}") // 'it' is a response string here
}
.addOnFailureListener {
Log.d("HTTP", "Error: ${it.message}") // 'it' is an Exception object here
}
I'm not 100% sure if this works in all cases (needs at least Java 1.5):
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class Main
{
public class A
{
}
public class B extends A
{
}
public Map<A, B> map = new HashMap<Main.A, Main.B>();
public static void main(String[] args)
{
try
{
Field field = Main.class.getField("map");
System.out.println("Field " + field.getName() + " is of type " + field.getType().getSimpleName());
Type genericType = field.getGenericType();
if(genericType instanceof ParameterizedType)
{
ParameterizedType type = (ParameterizedType) genericType;
Type[] typeArguments = type.getActualTypeArguments();
for(Type typeArgument : typeArguments)
{
Class<?> classType = ((Class<?>)typeArgument);
System.out.println("Field " + field.getName() + " has a parameterized type of " + classType.getSimpleName());
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This will output:
Field map is of type Map
Field map has a parameterized type of A
Field map has a parameterized type of B
Route::get('/', function () {
return view('greeting', ['name' => 'James']);
});
<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>
or
public function index($id)
{
$category = Category::find($id);
$topics = $category->getTopicPaginator();
$message = Message::find(1);
// here I would just use "->with([$category, $topics, $message])"
return View::make('category.index')->with(compact('category', 'topics', 'message'));
}
If the folder is accessible from the browser (not outside the document root of your web server), then you just need to output links to the locations of those files. If they are outside the document root, you will need to have links, buttons, whatever, that point to a PHP script that handles getting the files from their location and streaming to the response.
Creating and using the key is the way to go. The usage is free until your application reaches 25.000 calls per day on 90 consecutive days.
BTW.: In the google Developer documentation it says you shall add the api key as option {key:yourKey} when calling the API to create new instances. This however doesn't shush the console warning. You have to add the key as a parameter when including the api.
<script src="https://maps.googleapis.com/maps/api/js?key=yourKEYhere"></script>
Get the key here: GoogleApiKey Generation site
So, is that a behavior to expect, a bug
Truth be told I am not sure. It looks like parser is interpreting count
not as a column name but a function and expects following parentheses. Looks like a bug or at least a serious limitation of the parser.
is there a canonical way to go around?
Some options have been already mentioned by Herman and mattinbits so here more SQLish approach from me:
import org.apache.spark.sql.functions.count
df.groupBy("x").agg(count("*").alias("cnt")).where($"cnt" > 2)
here is a simple description of all:
Just to add to RichieHindle's answer, check out Floatutorial, which walks you through how CSS floating and clearing works.
Voila!
div {_x000D_
background-color: red;_x000D_
color: white;_x000D_
font-weight: bold;_x000D_
width: 48px;_x000D_
height: 48px; _x000D_
transform: rotate(360deg);_x000D_
transition: transform 0.5s;_x000D_
}_x000D_
_x000D_
div:active {_x000D_
transform: rotate(0deg);_x000D_
transition: 0s;_x000D_
}
_x000D_
<div></div>
_x000D_
Coming very late to the party, I found that ✓
(✓) worked in Opera. I haven't tested it on any other browsers, but it might be useful for some people.
The solution I am proposing detects if its not touch device and that the navbar-toggle
(hamburger menu) is not visible and makes the parent menu item revealing submenu on hover and and follow its link on click.
Also makes tne margin-top 0 because the gap between the navbar and the menu in some browser will not let you hover to the subitems
$(function(){_x000D_
function is_touch_device() {_x000D_
return 'ontouchstart' in window // works on most browsers _x000D_
|| navigator.maxTouchPoints; // works on IE10/11 and Surface_x000D_
};_x000D_
_x000D_
if(!is_touch_device() && $('.navbar-toggle:hidden')){_x000D_
$('.dropdown-menu', this).css('margin-top',0);_x000D_
$('.dropdown').hover(function(){ _x000D_
$('.dropdown-toggle', this).trigger('click').toggleClass("disabled"); _x000D_
}); _x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="nav" class="nav nav-pills clearfix right" role="tablist">_x000D_
<li><a href="#">menuA</a></li>_x000D_
<li><a href="#">menuB</a></li>_x000D_
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">menuC</a>_x000D_
<ul id="products-menu" class="dropdown-menu clearfix" role="menu">_x000D_
<li><a href="">A</a></li>_x000D_
<li><a href="">B</a></li>_x000D_
<li><a href="">C</a></li>_x000D_
<li><a href="">D</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">menuD</a></li>_x000D_
<li><a href="#">menuE</a></li>_x000D_
</ul>
_x000D_
$(function(){_x000D_
$("#nav .dropdown").hover(_x000D_
function() {_x000D_
$('#products-menu.dropdown-menu', this).stop( true, true ).fadeIn("fast");_x000D_
$(this).toggleClass('open');_x000D_
},_x000D_
function() {_x000D_
$('#products-menu.dropdown-menu', this).stop( true, true ).fadeOut("fast");_x000D_
$(this).toggleClass('open');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="nav" class="nav nav-pills clearfix right" role="tablist">_x000D_
<li><a href="#">menuA</a></li>_x000D_
<li><a href="#">menuB</a></li>_x000D_
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">menuC</a>_x000D_
<ul id="products-menu" class="dropdown-menu clearfix" role="menu">_x000D_
<li><a href="">A</a></li>_x000D_
<li><a href="">B</a></li>_x000D_
<li><a href="">C</a></li>_x000D_
<li><a href="">D</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">menuD</a></li>_x000D_
<li><a href="#">menuE</a></li>_x000D_
</ul>
_x000D_
I never faced such an issue with any device as I've had one codebase for all, without any hardcoded values. What I do is to have the maximum sized image as resource instead of one for each device. For example, I would have one for retina display and show it as aspect fit so it will be views as is on every device. Coming to deciding the frame of button, for instance, at run time. For this I use the % value of the patent view, example , if I want the width to be half of parent view take 50 % of parent and same applies for height and center.
With this I don't even need the xibs.
Short answer:
ALTER SCHEMA new_schema TRANSFER old_schema.table_name
I can confirm that the data in the table remains intact, which is probably quite important :)
Long answer as per MSDN docs,
ALTER SCHEMA schema_name
TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]
If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.
I'd like to add that TypeGuards only work on strings or numbers, if you want to compare an object use instanceof
if(task.id instanceof UUID) {
//foo
}
There is a plugin, flutter_launcher_name.
Write file pubspec.yaml:
dev_dependencies:
flutter_launcher_name: "^0.0.1"
flutter_launcher_name:
name: "yourNewAppLauncherName"
And run:
flutter pub get
flutter pub run flutter_launcher_name:main
You can get the same result as editing AndroidManifes.xml
and Info.plist
.
You have to disable all triggers
and constraints
first.
EXEC sp_MSforeachtable @command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"
EXEC sp_MSforeachtable @command1="ALTER TABLE ? DISABLE TRIGGER ALL"
After that you can generate the scripts for deleting the objects as
SELECT 'Drop Table '+name FROM sys.tables WHERE type='U';
SELECT 'Drop Procedure '+name FROM sys.procedures WHERE type='P';
Execute the statements generated.
lvalue
means "left value" -- it should be assignable. You cannot change the value of text
since it is an array, not a pointer.
Either declare it as char pointer (in this case it's better to declare it as const char*
):
const char *text;
if(number == 2)
text = "awesome";
else
text = "you fail";
Or use strcpy:
char text[60];
if(number == 2)
strcpy(text, "awesome");
else
strcpy(text, "you fail");
As Artem Bilan said, this problem occures because MappingJackson2HttpMessageConverter
supports response with application/json content-type only. If you can't change server code, but can change client code(I had such case), you can change content-type header with interceptor:
restTemplate.getInterceptors().add((request, body, execution) -> {
ClientHttpResponse response = execution.execute(request,body);
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return response;
});
Try this:
String result = "34.1 -118.33\n<!--ABCDEFG-->";
result = result.substring(0, result.indexOf("\n"));
Processes with open files are the usual culprits. Display them:
lsof +f -- <mountpoint or device>
There is an advantage to using /dev/<device>
rather than /mountpoint
: a mountpoint will disappear after an umount -l
, or it may be hidden by an overlaid mount.
fuser
can also be used, but to my mind lsof
has a more useful output. However fuser
is useful when it comes to killing the processes causing your dramas so you can get on with your life.
List files on <mountpoint>
(see caveat above):
fuser -vmM <mountpoint>
Interactively kill only processes with files open for writing:
fuser -vmMkiw <mountpoint>
After remounting read-only (mount -o remount,ro <mountpoint>
), it is safe(r) to kill all remaining processes:
fuser -vmMk <mountpoint>
The culprit can be the kernel itself. Another filesystem mounted on the filesystem you are trying to umount
will cause grief. Check with:
mount | grep <mountpoint>/
For loopback mounts, also check the output of:
losetup -la
Anonymous inodes can be created by:
open
with O_TMPFILE
)These are the most elusive type of pokemon, and appear in lsof
's TYPE
column as a_inode
(which is undocumented in the lsof
man page).
They won't appear in lsof +f -- /dev/<device>
, so you'll need to:
lsof | grep a_inode
For killing processes holding anonymous inodes, see: List current inotify watches (pathname, PID).
Just in case if you can't change HTML. Very primitive but short & works. (It will empty the parent div hence the child divs will be removed)
$('#one').text('Hi I am replace');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="one">_x000D_
<div class="first"></div>_x000D_
"Hi I am text"_x000D_
<div class="second"></div>_x000D_
<div class="third"></div>_x000D_
</div>
_x000D_
You can first append elements to the initialized array and then for convenience, you can convert it into a numpy array.
import numpy as np
a = [] # declare null array
a.append(['aa1']) # append elements
a.append(['aa2'])
a.append(['aa3'])
print(a)
a_np = np.asarray(a) # convert to numpy array
print(a_np)
Exists = IsObject(CurrentDb.TableDefs(tablename))
My answer is very simple>i have created password and confirm password validation using template driiven in angular 6
My html file
<div class="form-group">
<label class="label-sm">Confirm Password</label>
<input class="form-control" placeholder="Enter Password" type="password" #confirm_password="ngModel" [(ngModel)]="userModel.confirm_password" name="confirm_password" required (keyup)="checkPassword($event)" />
<div *ngIf="confirm_password.errors && (confirm_password.dirty||confirm_password.touched||signup.submitted)">
<div class="error" *ngIf="confirm_password.errors.required">Please confirm your password</div>
</div>
<div *ngIf="i" class='error'>Password does not match</div>
</div>
My typescript file
public i: boolean;
checkPassword(event) {
const password = this.userModel.password;
const confirm_new_password = event.target.value;
if (password !== undefined) {
if (confirm_new_password !== password) {
this.i = true;
} else {
this.i = false;
}
}
}
when clicking on submit button i check whether value of i is true or false
if true
if (this.i) {
return false;
}
else{
**form submitted code comes here**
}
try
Calendar c = Calendar.getInstance(); // this takes current date
c.set(Calendar.DAY_OF_MONTH, 1);
System.out.println(c.getTime()); // this returns java.util.Date
Updated (Since Java 8):
import java.time.LocalDate;
LocalDate todaydate = LocalDate.now();
System.out.println("Months first date in yyyy-mm-dd: " +todaydate.withDayOfMonth(1));
you can use the query options {raw: true}
to return the raw result. Your query should like follows:
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw: true,
})
also if you have associations with include
that gets flattened. So, we can use another parameter nest:true
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw: true,
nest: true,
})
I would suggest using the members of string, but with an explicit encoding:
byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");
By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes()
etc:
EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.
Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.
EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset
instead. Using Guava I'd really use:
byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);
Use the Filter() method as shown here - https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/filter-function
Probably you have this:
const db = mongoose.connect('mongodb://localhost:27017/db');
// Do some stuff
db.disconnect();
but you can also have something like this:
mongoose.connect('mongodb://localhost:27017/db');
const model = mongoose.model('Model', ModelSchema);
model.find().then(doc => {
console.log(doc);
}
you cannot call db.disconnect()
but you can close the connection after you use it.
model.find().then(doc => {
console.log(doc);
}).then(() => {
mongoose.connection.close();
});
An easier way to check for a process already executing is the pidof
command.
if pidof -x "abc.sh" >/dev/null; then
echo "Process already running"
fi
Alternatively, have your script create a PID file when it executes. It's then a simple exercise of checking for the presence of the PID file to determine if the process is already running.
#!/bin/bash
# abc.sh
mypidfile=/var/run/abc.sh.pid
# Could add check for existence of mypidfile here if interlock is
# needed in the shell script itself.
# Ensure PID file is removed on program exit.
trap "rm -f -- '$mypidfile'" EXIT
# Create a file with current PID to indicate that process is running.
echo $$ > "$mypidfile"
...
Update:
The question has now changed to check from the script itself. In this case, we would expect to always see at least one abc.sh
running. If there is more than one abc.sh
, then we know that process is still running. I'd still suggest use of the pidof
command which would return 2 PIDs if the process was already running. You could use grep
to filter out the current PID, loop in the shell or even revert to just counting PIDs with wc
to detect multiple processes.
Here's an example:
#!/bin/bash
for pid in $(pidof -x abc.sh); do
if [ $pid != $$ ]; then
echo "[$(date)] : abc.sh : Process is already running with PID $pid"
exit 1
fi
done
As Hogan notes above, use an AND
instead of &
. See this tutorial for more info.
I tried few of the above solutions but they didn't worked for me. Here is a link to the page which worked for me automatically click a link
Above link has many solutions and here's the one which worked for me,
<button onclick="fun();">Magic button</button>
<!--The link you want to automatically click-->
<a href='http://www.ercafe.com' id="myAnchor">My website</a>
Now within the <script>
tags,
<script>
function fun(){
actuateLink(document.getElementById('myAnchor'));
}
function actuateLink(link)
{
var allowDefaultAction = true;
if (link.click)
{
link.click();
return;
}
else if (document.createEvent)
{
var e = document.createEvent('MouseEvents');
e.initEvent(
'click' // event type
,true // can bubble?
,true // cancelable?
);
allowDefaultAction = link.dispatchEvent(e);
}
if (allowDefaultAction)
{
var f = document.createElement('form');
f.action = link.href;
document.body.appendChild(f);
f.submit();
}
}
</script>
Copy paste the above code and click on clicking the 'Magic button'
button, you will be redirected to ErCafe.com
.
Just see /etc/php5/php-fpm.conf
pid = /var/run/php5-fpm.pid
IS PID file
In file /etc/php5/fpm/pool.d/www.conf
listen = /var/run/php5-fpm.sock
IS SOCKET file
if you pid equal listen (pid = /var/run/php5-fpm.sock and listen = /var/run/php5-fpm.sock
) -> wrong settings
and finish sett /etc/php5/fpm/pool.d/www.conf
user = nginx
group = nginx
listen.owner = nginx
listen.group = nginx
listen.mode = 0660
I agree with Jeremy Young's comment on Phils answer:
I have found that this can be a problem associated with migrating from php 5 to php 7. php 5 was more tolerant of amibiguity in whether a variable was an array or not than php 7 is. In most cases the solution is to declare the array explicitly, as explained in this answer.
I was just trouble shooting a Wordpress plugin after the migration of php5 to php7. Since the plugin code was relying on user input, and it was intrinsically used in the code either as string, or as array, I added the following code in to prevent a fatal error:
if(is_array($variable_either_string_or_array)){
// if it's an array, declaration is allowed:
$variable_either_string_or_array[]=$additionalInfoData[$i];
}else{
// if it's not an array, declaration it as follows:
$variable_either_string_or_array=$additionalInfoData[$i];
}
This was the only modification I needed to add to make the plugin php7-proof. Obviously not "best practices", I'd rather read and understand the full code.. but a quick fix was needed.
The super keyword can be used to call the superclass constructor and to refer to a member of the superclass
When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.
At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.
public class Box {
int width;
int height;
int depth;
Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
public static void main(String[] args){
HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
}
}
class HeavyBox extends Box {
int weight;
HeavyBox(int w, int h, int d, int m) {
//call the superclass constructor
super(w, h, d);
weight = m;
}
}
I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.
The best way to combat this is to call the .always
chain method and do a bit of cleaning up. Here is my code.
$.ajax({
...
}).always(function(data, textStatus, xhr) {
var responseCode = null;
if (textStatus === "error") {
// data variable is actually xhr
responseCode = data.status;
if (data.responseText) {
try {
data = JSON.parse(data.responseText);
} catch (e) {
// Ignore
}
}
} else {
responseCode = xhr.status;
}
console.log("Response code", responseCode);
console.log("JSON Data", data);
});
Try the below code:
Sub opendfiles()
Dim myfile As Variant
Dim counter As Integer
Dim path As String
myfolder = "D:\temp\"
ChDir myfolder
myfile = Application.GetOpenFilename(, , , , True)
counter = 1
If IsNumeric(myfile) = True Then
MsgBox "No files selected"
End If
While counter <= UBound(myfile)
path = myfile(counter)
Workbooks.Open path
counter = counter + 1
Wend
End Sub
please try to do
make clean
(instead of make
), then
make
again.
You can set the minlength
option to some big value or you can do it by css like this,
.ui-autocomplete { height: 200px; overflow-y: scroll; overflow-x: hidden;}
Dictionary is faster than hashtable as dictionary is a generic strong type. Hashtable is slower as it takes object as data type which leads to boxing and unboxing.
var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;
function changeIframe() {
$('#frame')[0].src = sites[index++];
index = index >= sites.length ? 0 : index;
}
It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.
I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.
With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:
from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/forward/", methods=['POST'])
def move_forward():
#Moving forward code
forward_message = "Moving Forward..."
return render_template('index.html', forward_message=forward_message);
Then in your html, use this:
<form action="/forward/" method="post">
<button name="forwardBtn" type="submit">Forward</button>
</form>
...To execute your moving forward code. And include this:
{{ forward_message }}
... where you want the moving forward message to appear on your template.
This will cause your page to reload, which is inevitable without using AJAX and Javascript.
As written in the comments the old code is not "best practice". You should use a keygeneration algorithm like PBKDF2 with a high iteration count. You also should use at least partly a non static (meaning for each "identity" exclusive) salt. If possible randomly generated and stored together with the ciphertext.
SecureRandom sr = SecureRandom.getInstanceStrong();
byte[] salt = new byte[16];
sr.nextBytes(salt);
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1000, 128 * 8);
SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);
Cipher aes = Cipher.getInstance("AES");
aes.init(Cipher.ENCRYPT_MODE, key);
===========
You should use SHA-1 to generate a hash from your key and trim the result to 128 bit (16 bytes).
Additionally don't generate byte arrays from Strings through getBytes() it uses the platform default Charset. So the password "blaöä" results in different byte array on different platforms.
byte[] key = (SALT2 + username + password).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Edit: If you need 256 bit as key sizes you need to download the "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" Oracle download link, use SHA-256 as hash and remove the Arrays.copyOf line. "ECB" is the default Cipher Mode and "PKCS5Padding" the default padding. You could use different Cipher Modes and Padding Modes through the Cipher.getInstance string using following format: "Cipher/Mode/Padding"
For AES using CTS and PKCS5Padding the string is: "AES/CTS/PKCS5Padding"
You just need to 'capture' the bit between the brackets.
\[(.*?)\]
To capture you put it inside parentheses. You do not say which language this is using. In Perl for example, you would access this using the $1 variable.
my $string ='This is the match [more or less]';
$string =~ /\[(.*?)\]/;
print "match:$1\n";
Other languages will have different mechanisms. C#, for example, uses the Match collection class, I believe.
In general use serialize()
on the form element.
Please be mindful that multiple <select> options are serialized under the same key, e.g.
<select id="foo" name="foo" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
will result in a query string that includes multiple occurences of the same query parameter:
[path]?foo=1&foo=2&foo=3&someotherparams...
which may not be what you want in the backend.
I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):
function compress(data) {
data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}
which turns the above into:
[path]?foo=1,2,3&someotherparams...
In your JS code you'd call it like this:
var inputs = compress($("#your-form").serialize());
Hope that helps.
Another nice way to put your logic in data is something like this:
# Initialization.
CAR_TYPES = {
foo_type: ['honda', 'acura', 'mercedes'],
bar_type: ['toyota', 'lexus']
# More...
}
@type_for_name = {}
CAR_TYPES.each { |type, names| names.each { |name| @type_for_name[type] = name } }
case @type_for_name[car]
when :foo_type
# do foo things
when :bar_type
# do bar things
end
I would suggest a very simple way:
import numpy as np
l = [10, 22, 8, 8, 11]
print(np.argmax(l))
print(np.argmin(l))
Hope it helps.
You can try this:
CommandArgument='<%# "scrapid=" + Eval("ScrapId")+"&"+"UserId="+ Eval("UserId")%>'
The make
uses the $
for its own variable expansions. E.g. single character variable $A
or variable with a long name - ${VAR}
and $(VAR)
.
To put the $
into a command, use the $$
, for example:
all:
@echo "Please execute next commands:"
@echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'
Also note that to make
the ""
and ''
(double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @
sign to see what make
sends to shell.) To prevent the shell from expanding $PATH
, second line uses the ''
.
You can effectively remove scientific notation in printing with this code:
options(scipen=999)
Here is what I do to remove the validate password plugin:
mysql -h localhost -u root -p
uninstall plugin validate_password;
UNINSTALL COMPONENT 'file://component_validate_password';
I would not recommend this solution for a production system. I used this solution on a local mysql instance for development purposes only.
Just create a class or structure that has two members, one List(Of OneItem)
and the other Integer
and send in an instance of that class.
Edit: Sorry, missed that you had problems with one parameter as well. Just look at Thread Constructor (ParameterizedThreadStart) and that page includes a simple sample.
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources
In you specific case:
version: "3"
services:
node:
image: USER/Your-Pre-Built-Image
environment:
- VIRTUAL_HOST=localhost
volumes:
- logs:/app/out/
command: ["npm","start"]
cap_drop:
- NET_ADMIN
- SYS_ADMIN
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
volumes:
- logs
networks:
default:
driver: overlay
Note:
Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:
ports:
- 80:80
You can easily create a static object that represents a NULL return.
class Attr;
extern Attr AttrNull;
class Node {
....
Attr& getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return attributes[i];
//if not found
return AttrNull;
}
bool IsNull(const Attr& test) const {
return &test == &AttrNull;
}
private:
vector<Attr> attributes;
};
And somewhere in a source file:
static Attr AttrNull;
If you only need to prevent line-breaks on space characters, you can use
entities between words:
No line break
instead of
<span style="white-space:nowrap">No line break</span>
<location path="ForAll/Demo.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
In Addition: If you want to write something on that folder through website , you have to give IIS_User permission to the folder
You at least need to add the .java
extension to the file name in this line:
javac -cp /home/manish.yadav/Desktop/JCuda-All-0.3.2-bin-linux-x86_64 EnumDevices
From the official faq:
Class names, 'HelloWorldApp', are only accepted if annotation processing is explicitly requested
If you receive this error, you forgot to include the .java suffix when compiling the program. Remember, the command is javac HelloWorldApp.java not javac HelloWorldApp.
Also, in your second javac-example, (in which you actually included .java
) you need to include the all required .jar-files needed for compilation.
Following on from jpw it might be good to encapsulate his solution in a small subroutine to save on having lots of lines of code:
Private Sub CommandButton1_Click()
Dim i As Integer
Dim a As Integer
a = 15
For i = 11 To 32
If Worksheets(1).Cells(i, 3) <> "" Then
call copValuesAndFormat(i,3,a,15)
call copValuesAndFormat(i,5,a,17)
call copValuesAndFormat(i,6,a,18)
call copValuesAndFormat(i,7,a,19)
call copValuesAndFormat(i,8,a,20)
call copValuesAndFormat(i,9,a,21)
a = a + 1
End If
Next i
end sub
sub copValuesAndFormat(x1 as integer, y1 as integer, x2 as integer, y2 as integer)
Worksheets(1).Cells(x1, y1).Copy
Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteFormats
Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteValues
end sub
(I do not have Excel in current location so please excuse bugs as not tested)
The following works for me:
function decodeHtml(html) {
let areaElement = document.createElement("textarea");
areaElement.innerHTML = html;
return areaElement.value;
}
f=open(file,"r")
lines=f.readlines()
result=[]
for x in lines:
result.append(x.split(' ')[1])
f.close()
You can do the same using a list comprehension
print([x.split(' ')[1] for x in open(file).readlines()])
Docs on split()
string.split(s[, sep[, maxsplit]])
Return a list of the words of the string
s
. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string.
So, you can omit the space I used and do just x.split()
but this will also remove tabs and newlines, be aware of that.
Using CSS, you set the logo div to position absolute, and set the z-order to be above the second div.
#logo
{
position: absolute:
z-index: 2000;
left: 100px;
width: 100px;
height: 50px;
}
I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!!
use close(fd)
system call after you finished working on a file.
var fileName = 'file.txt';
// Getting Extension
var ext = fileName.split('.')[1];
// OR
var ext = fileName.split('.').pop();
How about doing this?
import string
def isAscii(s):
for c in s:
if c not in string.ascii_letters:
return False
return True
But again main doubt why TextView resource id it needs?
Look at the constructor and the params.
public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)
Added in API level 1 Constructor
Parameters
context
The current context.
resource
The resource ID for a layout file containing a layout to use when instantiating views.
textViewResourceId
The id of the TextView within the layout resource to be populated objects The objects to represent in theListView
.
android.R.id.text1
refers to the id of text in android resource. So you need not have the one in your activity.
Here's the full list
http://developer.android.com/reference/android/R.id.html
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
this
refers to activity context
android.R.layout.simple_list_item_1
simple_list_item_1 is the layout in android.R.layout.
android.R.id.text1
refers to the android resource id.
values
is a string array from the link you provided
http://developer.android.com/reference/android/R.layout.html
To come full circle and include all versions of Visual Studio, @Myster originally stated that;
Pre Visual Studio 2015 the paths to applicationhost.config were:
%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config
Visual Studio 2015/2017 path can be found at: (credit: @Talon)
$(solutionDir)\.vs\config\applicationhost.config
Visual Studio 2019 path can be found at: (credit: @Talon)
$(solutionDir)\.vs\config\$(ProjectName)\applicationhost.config
But the part that might get some people is that the project settings in the .sln file can repopulate the applicationhost.config for Visual Studio 2015+. (credit: @Lex Li)
So, if you make a change in the applicationhost.config you also have to make sure your changes match here:
$(solutionDir)\ProjectName.sln
The two important settings should look like:
Project("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") = "ProjectName", "ProjectPath\", "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
and
VWDPort = "Port#"
What is important here is that the two settings in the .sln must match the name and bindingInformation respectively in the applicationhost.config file if you plan on making changes. There may be more places that link these two files and I will update as I find more links either by comments or more experience.
I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.
Sub CleanTheTable()
Application.ScreenUpdating = False
Sheets("Data").Select
ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
'Remove the filters if one exists.
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If
'Clear all lines but the first one in the table leaving formulas for the next go round.
With Worksheets("Data").ListObjects("TestTable")
.Range.AutoFilter
On Error Resume Next
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
.DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
ActiveWindow.SmallScroll Down:=-10000
End With
Application.ScreenUpdating = True
End Sub
For coffeescript lovers
expect( => someMethodCall(arg1, arg2)).toThrow()
As stated in the previous answers,
git push <remote-name> <local-branch-name>:<remote-branch-name>
is enough for pushing a local branch.
Your colleagues, can pull all remote branches (including new ones) with this command:
git remote update
Then, to make changes on the branch, the usual flow:
git checkout -b <local-branch-name> <remote-name>/<remote-branch-name>
If you have lodash you can use its .get
method
_.get(a, 'b.c.d.e')
or give it a default value
_.get(a, 'b.c.d.e', default)
In Oracle 12c you can use the function STANDARD_HASH. It does not require any additional privileges.
select standard_hash('foo', 'MD5') from dual;
The dbms_obfuscation_toolkit is deprecated (see Note here). You can use DBMS_CRYPTO directly:
select rawtohex(
DBMS_CRYPTO.Hash (
UTL_I18N.STRING_TO_RAW ('foo', 'AL32UTF8'),
2)
) from dual;
Output:
ACBD18DB4CC2F85CEDEF654FCCC4A4D8
Add a lower function call if needed. More on DBMS_CRYPTO.
Use concat() function instead of +
like this:
select concat(firstname, lastname) as "Name" from test.student
Below Code May Be Help You :
<html>
<head>
<script>
function printPage(id)
{
var html="<html>";
html+= document.getElementById(id).innerHTML;
html+="</html>";
var printWin = window.open('','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status =0');
printWin.document.write(html);
printWin.document.close();
printWin.focus();
printWin.print();
printWin.close();
}
</script>
</head>
<body>
<div id="block1">
<table border="1" >
</tr>
<th colspan="3">Block 1</th>
</tr>
<tr>
<th>1</th><th>XYZ</th><th>athock</th>
</tr>
</table>
</div>
<div id="block2">
This is Block 2 content
</div>
<input type="button" value="Print Block 1" onclick="printPage('block1');"></input>
<input type="button" value="Print Block 2" onclick="printPage('block2');"></input>
</body>
</html>
For SQL Server 2012 and up , with leading zeroes:
SELECT FORMAT(GETDATE(),'MM')
without:
SELECT MONTH(GETDATE())
Doing an static import of the GestureTypes and then using the valuesOf() method could make it look much cleaner:
enum GestureTypes{ROCK,PAPER,SCISSORS};
and
import static com.example.GestureTypes.*;
public class GestureFactory {
public static Gesture getInstance(final String gesture) {
if (ROCK == valueOf(gesture))
//do somthing
if (PAPER == valueOf(gesture))
//do somthing
}
}
In my case, There were new code branch and old code branch was deployed locally in IIS. So it was pointing to old branch code that was not available. So i had deployed my code to IIS with new branch and it is working now.
To me, it is better to put the transition codes with the original/minimum selectors than with the :hover or any other additional selectors:
#content #nav a {_x000D_
background-color: #FF0;_x000D_
_x000D_
-webkit-transition: background-color 1000ms linear;_x000D_
-moz-transition: background-color 1000ms linear;_x000D_
-o-transition: background-color 1000ms linear;_x000D_
-ms-transition: background-color 1000ms linear;_x000D_
transition: background-color 1000ms linear;_x000D_
}_x000D_
_x000D_
#content #nav a:hover {_x000D_
background-color: #AD310B;_x000D_
}
_x000D_
<div id="content">_x000D_
<div id="nav">_x000D_
<a href="#link1">Link 1</a>_x000D_
</div>_x000D_
</div>
_x000D_
numpy.savetxt
saves an array to a text file.
import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("foo.csv", a, delimiter=",")
Try numpy.array_split
.
From the documentation:
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
Identical to numpy.split
, but won't raise an exception if the groups aren't equal length.
If number of chunks > len(array) you get blank arrays nested inside, to address that - if your split array is saved in a
, then you can remove empty arrays by:
[x for x in a if x.size > 0]
Just save that back in a
if you wish.
I wrote a decorator which you can use on any method to make it so that all of the arguments passed in, or any defaults, are assigned to the instance.
def argumentsToAttributes(method):
argumentNames = method.func_code.co_varnames[1:]
# Generate a dictionary of default values:
defaultsDict = {}
defaults = method.func_defaults if method.func_defaults else ()
for i, default in enumerate(defaults, start = len(argumentNames) - len(defaults)):
defaultsDict[argumentNames[i]] = default
def newMethod(self, *args, **kwargs):
# Use the positional arguments.
for name, value in zip(argumentNames, args):
setattr(self, name, value)
# Add the key word arguments. If anything is missing, use the default.
for name in argumentNames[len(args):]:
setattr(self, name, kwargs.get(name, defaultsDict[name]))
# Run whatever else the method needs to do.
method(self, *args, **kwargs)
return newMethod
A quick demonstration. Note that I use a positional argument a
, use the default value for b
, and a named argument c
. I then print all 3 referencing self
, to show that they've been properly assigned before the method is entered.
class A(object):
@argumentsToAttributes
def __init__(self, a, b = 'Invisible', c = 'Hello'):
print(self.a)
print(self.b)
print(self.c)
A('Why', c = 'Nothing')
Note that my decorator should work with any method, not just __init__
.
According to the API, the headers can all be passed in using requests.get
:
import requests
r=requests.get("http://www.example.com/", headers={"content-type":"text"})
You can give a try to Apache Commons Collections.
There is a class CollectionUtils that allows you to select or filter items by custom Predicate.
Your code would be like this:
Predicate condition = new Predicate() {
boolean evaluate(Object sample) {
return ((Sample)sample).value3.equals("three");
}
};
List result = CollectionUtils.select( list, condition );
Update:
In java8, using Lambdas and StreamAPI this should be:
List<Sample> result = list.stream()
.filter(item -> item.value3.equals("three"))
.collect(Collectors.toList());
much nicer!
If your plan is to do this as part of a query, please don't do that (a). Seriously, it's a performance killer. There may be situations where you don't care about performance (such as one-off migration jobs to split the fields allowing better performance in future) but, if you're doing this regularly for anything other than a mickey-mouse database, you're wasting resources.
If you ever find yourself having to process only part of a column in some way, your DB design is flawed. It may well work okay on a home address book or recipe application or any of myriad other small databases but it will not be scalable to "real" systems.
Store the components of the name in separate columns. It's almost invariably a lot faster to join columns together with a simple concatenation (when you need the full name) than it is to split them apart with a character search.
If, for some reason you cannot split the field, at least put in the extra columns and use an insert/update trigger to populate them. While not 3NF, this will guarantee that the data is still consistent and will massively speed up your queries. You could also ensure that the extra columns are lower-cased (and indexed if you're searching on them) at the same time so as to not have to fiddle around with case issues.
And, if you cannot even add the columns and triggers, be aware (and make your client aware, if it's for a client) that it is not scalable.
(a) Of course, if your intent is to use this query to fix the schema so that the names are placed into separate columns in the table rather than the query, I'd consider that to be a valid use. But I reiterate, doing it in the query is not really a good idea.
This is what I've made of it. In the stretch class, I simply changed the height to auto
. This way your background picture has always got the same size as the width of the screen and the height will allways have the right size.
#background {
width: 100%;
height: 100%;
position: absolute;
margin-left: 0px;
margin-top: 0px;
z-index: 0;
}
.stretch {
width:100%;
height:auto;
}
Generally, you can use the func(*tuple)
syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])
This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
Use the str_starts_with function:
str_starts_with('http://www.google.com', 'http')
Use the substr function to return a part of a string.
substr( $string_n, 0, 4 ) === "http"
If you're trying to make sure it's not another protocol. I'd use http://
instead, since https would also match, and other things such as http-protocol.com.
substr( $string_n, 0, 7 ) === "http://"
And in general:
substr($string, 0, strlen($query)) === $query
You need the actual instance of the WindowSettings
that's open, not a new one.
Currently, you are creating a new instance of WindowSettings
and calling Close
on that. That doesn't do anything because that new instance never has been shown.
Instead, when showing DialogSettingsCancel
set the current instance of WindowSettings
as the parent.
Something like this:
In WindowSettings
:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel();
dialogSettingsCancel.OwningWindowSettings = this;
dialogSettingsCancel.Show();
}
In DialogSettingsCancel
:
public WindowSettings OwningWindowSettings { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.Close();
if(OwningWindowSettings != null)
OwningWindowSettings.Close();
}
This approach takes into account, that a DialogSettingsCancel
could potentially be opened without a WindowsSettings
as parent.
If the two are always connected, you should instead use a constructor parameter:
In WindowSettings
:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel(this);
dialogSettingsCancel.Show();
}
In DialogSettingsCancel
:
WindowSettings _owningWindowSettings;
public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
if(owningWindowSettings == null)
throw new ArgumentNullException("owningWindowSettings");
_owningWindowSettings = owningWindowSettings;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
_owningWindowSettings.Close();
}
You can create an In Project Repository, so you don't have to run mvn install:install-file
every time you work on a new computer
<repository>
<id>in-project</id>
<name>In Project Repo</name>
<url>file://${project.basedir}/libs</url>
</repository>
<dependency>
<groupId>dropbox</groupId>
<artifactId>dropbox-sdk</artifactId>
<version>1.3.1</version>
</dependency>
/groupId/artifactId/version/artifactId-verion.jar
detail read this blog post
https://web.archive.org/web/20121026021311/charlie.cu.cc/2012/06/how-add-external-libraries-maven
in parent window put :
<script>
function ifDoneChildFrame(val)
{
$('#parentPrice').html(val);
}
</script>
and in iframe src file put :
<script>window.parent.ifDoneChildFrame('Your value here');</script>
To force a reload of the php.ini you should restart apache.
Try sudo service apache2 restart
from the command line.
Or sudo /etc/init.d/apache2 restart
You can specify you format Gson gson = builder.setDateFormat("yyyy-MM-dd").create();
in this method instead of yyyy-MM-dd
you can use anyother formats
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
Gson gson = builder.setDateFormat("yyyy-MM-dd").create();
Install XAMPP. If you're running MS Windows, WAMP is also an option.
Create a new class that wraps your Blog object and provides the equality/hashcode method you need. For maximum efficiency I would add two static methods on the wrapper, one to convert Blogs list -> Blog Wrapper list and the other to convert Blog Wrapper list -> Blog list. Then you would:
Code for Blog Wrapper would be something like this:
import java.util.ArrayList;
import java.util.List;
public class BlogWrapper {
public static List<Blog> unwrappedList(List<BlogWrapper> blogWrapperList) {
if (blogWrapperList == null)
return new ArrayList<Blog>(0);
List<Blog> blogList = new ArrayList<Blog>(blogWrapperList.size());
for (BlogWrapper bW : blogWrapperList) {
blogList.add(bW.getBlog());
}
return blogList;
}
public static List<BlogWrapper> wrappedList(List<Blog> blogList) {
if (blogList == null)
return new ArrayList<BlogWrapper>(0);
List<BlogWrapper> blogWrapperList = new ArrayList<BlogWrapper>(blogList
.size());
for (Blog b : blogList) {
blogWrapperList.add(new BlogWrapper(b));
}
return blogWrapperList;
}
private Blog blog = null;
public BlogWrapper() {
super();
}
public BlogWrapper(Blog aBlog) {
super();
setBlog(aBlog);
}
public boolean equals(Object other) {
// Your equality logic here
return super.equals(other);
}
public Blog getBlog() {
return blog;
}
public int hashCode() {
// Your hashcode logic here
return super.hashCode();
}
public void setBlog(Blog blog) {
this.blog = blog;
}
}
And you could use this like so:
List<BlogWrapper> myBlogWrappers = BlogWrapper.wrappedList(your blog list here);
Set<BlogWrapper> noDupWrapSet = new HashSet<BlogWrapper>(myBlogWrappers);
List<BlogWrapper> noDupWrapList = new ArrayList<BlogWrapper>(noDupSet);
List<Blog> noDupList = BlogWrapper.unwrappedList(noDupWrapList);
Quite obviously you can make the above code more efficient, particularly by making the wrap and unwrap methods on Blog Wrapper take collections instead of Lists.
An alternative route to wrapping the Blog class would be to use a byte code manipulation library like BCEL to actually change the equals and hashcode method for Blog. But of course, that could have unintended consequences to the rest of your code if they require the original equals/hashcode behaviour.
Windows solution: Control + C.
Macbook solution: Control (^) + C.
Another way is to open a terminal, type top
, write down the PID
of the process that you would like to kill and then type on the terminal: kill -9 <pid>
You don't mention the API version, but since API 11 there's the method WebViewClient.shouldInterceptRequest
Maybe this could help?
Yes, and no. There are min and max attributes in HTML 5, but
The max attribute will not work for dates and time in Internet Explorer 10+ or Firefox, since IE 10+ and Firefox does not support these input types.
EDIT: Firefox now does support it
So if you are confused by the documentation of that attributes, yet it doesn't work, that's why.
See the W3 page for the versions.
I find it easiest to use Javascript, s the other answers say, since you can just use a pre-made module. Also, many Javascript date picker libraries have a min/max setting and have that nice calendar look.
SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer
I'm certain there are better ways of doing this, but I have in the past used a method something like the following to serialize an object into a string that I can log:
private string ObjectToXml(object output)
{
string objectAsXmlString;
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(output.GetType());
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
try
{
xs.Serialize(sw, output);
objectAsXmlString = sw.ToString();
}
catch (Exception ex)
{
objectAsXmlString = ex.ToString();
}
}
return objectAsXmlString;
}
You'll see that the method might also return the exception rather than the serialized object, so you'll want to ensure that the objects you want to log are serializable.
You're synchronizing twice, which is pointless and possibly slows down the code: changes while iterating over the list need a synchronnization over the entire operation, which you are doing with synchronized (in_queue_list)
Using Collections.synchronizedList()
is superfluous in that case (it creates a wrapper that synchronizes individual operations).
However, since you are emptying the list completely, the iterated removal of the first element is the worst possible way to do it, sice for each element all following elements have to be copied, making this an O(n^2) operation - horribly slow for larger lists.
Instead, simply call clear()
- no iteration needed.
Edit:
If you need the single-method synchronization of Collections.synchronizedList()
later on, then this is the correct way:
List<Record> in_queue_list = Collections.synchronizedList(in_queue);
in_queue_list.clear(); // synchronized implicitly,
But in many cases, the single-method synchronization is insufficient (e.g. for all iteration, or when you get a value, do computations based on it, and replace it with the result). In that case, you have to use manual synchronization anyway, so Collections.synchronizedList()
is just useless additional overhead.
Some time this error in Joomla appear because some thing incorrect with SESSION or coockie. That may because incorrect HTTPd server setting or because some before CURL or Server http requests
so PHP code like:
curl_setopt($ch, CURLOPT_URL, $url_page);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_REFERER, $url_page);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
will need replace to PHP code
curl_setopt($ch, CURLOPT_URL, $url_page);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_REFERER, $url_page);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
//if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
May be some body reply how this options connected with "Curl error: Operation timed out after .."
For some of the cases where you can affect the source number representation, you can represent them as fractions instead of floats, using integer numerator and denominator. That way you can have exact comparisons.
See Fraction from fractions module for details.
I just ran into this the other day.
What I did, which seems easier than the above, is to set the pattern on a variable on the scope and refer to it in ng-pattern in the view.
When "the checkbox is unchecked" I simply set the regex value to /.*/ on the onChanged callback (if going to unchecked). ng-pattern picks that change up and says "OK, your value is fine". Form is now valid. I would also remove the bad data from the field so you don't have an apparent bad phone # sitting there.
I had additional issues around ng-required, and did the same thing. Worked like a charm.
echo stat | nc localhost 2181 | grep Mode
echo srvr | nc localhost 2181 | grep Mode #(From 3.3.0 onwards)
Above will work in whichever modes Zookeeper is running (standalone or embedded).
If zookeeper is running in standalone mode, its a JVM process. so -
jps | grep Quorum
will display list of jvm processes; something like this for zookeeper with process ID
HQuorumPeer
From the blog Managing Hierarchical Data in MySQL
Table structure
+-------------+----------------------+--------+
| category_id | name | parent |
+-------------+----------------------+--------+
| 1 | ELECTRONICS | NULL |
| 2 | TELEVISIONS | 1 |
| 3 | TUBE | 2 |
| 4 | LCD | 2 |
| 5 | PLASMA | 2 |
| 6 | PORTABLE ELECTRONICS | 1 |
| 7 | MP3 PLAYERS | 6 |
| 8 | FLASH | 7 |
| 9 | CD PLAYERS | 6 |
| 10 | 2 WAY RADIOS | 6 |
+-------------+----------------------+--------+
Query:
SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
WHERE t1.name = 'ELECTRONICS';
Output
+-------------+----------------------+--------------+-------+
| lev1 | lev2 | lev3 | lev4 |
+-------------+----------------------+--------------+-------+
| ELECTRONICS | TELEVISIONS | TUBE | NULL |
| ELECTRONICS | TELEVISIONS | LCD | NULL |
| ELECTRONICS | TELEVISIONS | PLASMA | NULL |
| ELECTRONICS | PORTABLE ELECTRONICS | MP3 PLAYERS | FLASH |
| ELECTRONICS | PORTABLE ELECTRONICS | CD PLAYERS | NULL |
| ELECTRONICS | PORTABLE ELECTRONICS | 2 WAY RADIOS | NULL |
+-------------+----------------------+--------------+-------+
Most users at one time or another have dealt with hierarchical data in a SQL database and no doubt learned that the management of hierarchical data is not what a relational database is intended for. The tables of a relational database are not hierarchical (like XML), but are simply a flat list. Hierarchical data has a parent-child relationship that is not naturally represented in a relational database table. Read more
Refer the blog for more details.
EDIT:
select @pv:=category_id as category_id, name, parent from category
join
(select @pv:=19)tmp
where parent=@pv
Output:
category_id name parent
19 category1 0
20 category2 19
21 category3 20
22 category4 21
The method you want is BigInteger#valueOf(long val).
E.g.,
BigInteger bi = BigInteger.valueOf(myInteger.intValue());
Making a String first is unnecessary and undesired.
I dont know what is the exact reason but I solved the problem running:
app/console cache:clear --env=prod
import java.io.*;
class Main
{
public static void main(String args[]) throws IOException
{
int n1,n2,n3,l;
n1=Integer.parseInt(args[0]);
n2=Integer.parseInt(args[1]);
n3=Integer.parseInt(args[2]);
if(n1>n2)
{
l=n1;
}
else
{
l=n2;
}
if(l<n3)
{
System.out.println("largest no is "+n3);
}
else
{
System.out.println("largest no is "+l);
}
}}
Consider above program, in this program I want to pass 3 no's from Command Line, to do so.
Step 1 : Right Click on Cup and Saucer icon, u'll see this window
Step 2: Click on Properties
Step 3: Click Run _> Arguments _> type three no's eg. 32 98 16 then click OK. Plz add space between two arguments. See here
Step 4: Run the Program by using F6.
Yes: Source
switch(shape)
{
case Circle c:
WriteLine($"circle with radius {c.Radius}");
break;
case Rectangle s when (s.Length == s.Height):
WriteLine($"{s.Length} x {s.Height} square");
break;
case Rectangle r:
WriteLine($"{r.Length} x {r.Height} rectangle");
break;
default:
WriteLine("<unknown shape>");
break;
case null:
throw new ArgumentNullException(nameof(shape));
}
No.
http://blogs.msdn.com/b/peterhal/archive/2005/07/05/435760.aspx
We get a lot of requests for addditions to the C# language and today I'm going to talk about one of the more common ones - switch on type. Switch on type looks like a pretty useful and straightforward feature: Add a switch-like construct which switches on the type of the expression, rather than the value. This might look something like this:
switch typeof(e) {
case int: ... break;
case string: ... break;
case double: ... break;
default: ... break;
}
This kind of statement would be extremely useful for adding virtual method like dispatch over a disjoint type hierarchy, or over a type hierarchy containing types that you don't own. Seeing an example like this, you could easily conclude that the feature would be straightforward and useful. It might even get you thinking "Why don't those #*&%$ lazy C# language designers just make my life easier and add this simple, timesaving language feature?"
Unfortunately, like many 'simple' language features, type switch is not as simple as it first appears. The troubles start when you look at a more significant, and no less important, example like this:
class C {}
interface I {}
class D : C, I {}
switch typeof(e) {
case C: … break;
case I: … break;
default: … break;
}
Link: https://blogs.msdn.microsoft.com/peterhal/2005/07/05/many-questions-switch-on-type/
My situation is my project uses a legacy (non-JSR) JSON parser that does not support pretty printing. However, I needed to produce pretty-printed JSON samples; this is possible without having to add any extra libraries as long as you are using Java 7 and above:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine scriptEngine = manager.getEngineByName("JavaScript");
scriptEngine.put("jsonString", jsonStringNoWhitespace);
scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)");
String prettyPrintedJson = (String) scriptEngine.get("result");
Following line should be called before you add your component
pnlButton.setLayout(null);
Above will set your content panel to use absolute layout. This means you'd always have to set your component's bounds explicitly by using setBounds
method.
In general I wouldn't recommend using absolute layout.
For the sake of completeness, Ron van der Heijden's solution in pure JavaScript:
<button onclick="document.querySelector('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">
I would do it like this:
SELECT top(100)* into #tmpFerdeen
FROM Customers
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerEurope
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAsia
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAmericas
This should give you a list of all the tables in your database
SELECT Distinct TABLE_NAME FROM information_schema.TABLES
So you can use it similar to your database check.
If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table')
BEGIN
--CREATE TABLE Your_Table
END
GO
Oneliner plain ruby, it works only with ruby > 1.9.x:
1.9.3p0 :002 > h = {:a => 1, :b => 2}
=> {:a=>1, :b=>2}
1.9.3p0 :003 > h.tap { |hs| hs.delete(:a) }
=> {:b=>2}
Tap method always return the object on which is invoked...
Otherwise if you have required active_support/core_ext/hash
(which is automatically required in every Rails application) you can use one of the following methods depending on your needs:
? ~ irb
1.9.3p125 :001 > require 'active_support/core_ext/hash' => true
1.9.3p125 :002 > h = {:a => 1, :b => 2, :c => 3}
=> {:a=>1, :b=>2, :c=>3}
1.9.3p125 :003 > h.except(:a)
=> {:b=>2, :c=>3}
1.9.3p125 :004 > h.slice(:a)
=> {:a=>1}
except uses a blacklist approach, so it removes all the keys listed as args, while slice uses a whitelist approach, so it removes all keys that aren't listed as arguments. There also exist the bang version of those method (except!
and slice!
) which modify the given hash but their return value is different both of them return an hash. It represents the removed keys for slice!
and the keys that are kept for the except!
:
1.9.3p125 :011 > {:a => 1, :b => 2, :c => 3}.except!(:a)
=> {:b=>2, :c=>3}
1.9.3p125 :012 > {:a => 1, :b => 2, :c => 3}.slice!(:a)
=> {:b=>2, :c=>3}
I don't Know you use any Bootstrap version but the useful helper class for centering and block an element in center it is .center-block
because this class contain margin
and display
CSS properties but the .text-center
class only contain the text-align
property
My Table didn't have primary key then I had time out error. after set key sloved.
Using the == operator will compare the references to the strings not the string themselves.
Ok, you have to toString() the Editable. I loaded up some of the code I had before that dealt with this situation.
String passwd1Text = passw1.getText().toString();
String passwd2Text = passw2.getText().toString();
if (passwd1Text.equals(passwd2Text))
{
}
I have made an attempt with illustrative pictures and working code in Java,
http://tech.bragboy.com/2010/02/least-common-ancestor-without-using.html
Netbeans Problem: For apache Tomcat server Authentication required dialog box requesting user name and password
This dialog box appear If a user role and his credentials are not set or is incorrect for Tomcat startup via NetBeans IDE,
OR when user/pass set in IDE is not matches with user/pass in "canf/tomcat-user.xml" file
1..Need to check user name and password set in IDE tools-->server
2..Check \CATALINA_BASE\conf\tomcat-users.xml. whether user and his role is defined or not. If not add these lines
<user username="ide" password="EiWnNlBG" roles="manager-script,admin"/>
</tomcat-users>
3.. set the same user/pass in IDE tools->server
Source: http://ohmjavaclasses.blogspot.com/2011/12/netbeans-problem-for-apache-tomcat.html
Try [attr.style]="changeBackground()"
"Renaming" a remote branch is actually a 2 step process (not necessarily ordered):
git push [space]:<old_name>
as ksrb explained);I use TortoiseGit and when I first tried to delete the branch through the command line, I got this:
$ git push origin :in
fatal: 'origin' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.
This was likely due to pageant not having the private key loaded (which TortoiseGit loads automatically into pageant). Moreover, I noticed that TortoiseGit commands do not have the origin
ref in them (e.g. git.exe push --progress "my_project" interesting_local:interesting
).
I am also using Bitbucket and, as others web-based online git managers of the sort (GitHub, GitLab), I was able to delete the remote branch directly through their interface (branches page):
However, in TortoiseGit you may also delete remote branches through Browse References:
By right-clicking on a remote branch (remotes list) the Delete remote branch option shows up:
After deleting the old remote branch I pushed directly into a new remote branch through TortoiseGit just by typing the new name in the Remote: field of the Push window and this branch was automatically created and visible in Bitbucket.
However, if you still prefer to do it manually, a point that has not been mentioned yet in this thread is that -u
= --set-upstream
.
From git push
docs, -u
is just an alias of --set-upstream
, so the commands in the answers of Sylvain (-set-upstream new-branch
) and Shashank (-u origin new_branch
) are equivalent, since the remote ref defaults to origin
if no other ref was previously defined:
git push origin -u new_branch
= git push -u new_branch
from the docs description:
If the configuration is missing, it defaults to
origin
.
In the end, I did not manually type in or used any of the commands suggested by the other answers in here, so perhaps this might be useful to others in a similar situation.
If it takes a long time to fail, then enlarge the wait_timeout
variable.
If it fails right away, enlarge the max_allowed_packet
variable; it it still doesn't work, make sure the command is valid SQL. Mine had unescaped quotes which screwed everything up.
Also, if feasible, consider limiting the number of inserts of a single SQL command to, say, 1000. You can create a script that creates multiple statements out of a single one by reintroducing the INSERT... part every n inserts.
$scope.item = {
"id": "3",
"name": "ALL",
};
$scope.CategoryLst = [
{ id: '1', name: 'MD' },
{ id: '2', name: 'CRNA' },
{ id: '3', name: 'ALL' }];
<select ng-model="item.id" ng-selected="3" ng-options="i.id as i.name for i in CategoryLst"></select>
DataSource
– setCurrentSchema
When instantiating a DataSource
implementation, look for a method to set the current/default schema.
For example, on the PGSimpleDataSource
class call setCurrentSchema
.
org.postgresql.ds.PGSimpleDataSource dataSource = new org.postgresql.ds.PGSimpleDataSource ( );
dataSource.setServerName ( "localhost" );
dataSource.setDatabaseName ( "your_db_here_" );
dataSource.setPortNumber ( 5432 );
dataSource.setUser ( "postgres" );
dataSource.setPassword ( "your_password_here" );
dataSource.setCurrentSchema ( "your_schema_name_here_" ); // <----------
If you leave the schema unspecified, Postgres defaults to a schema named public
within the database. See the manual, section 5.9.2 The Public Schema. To quote hat manual:
In the previous sections we created tables without specifying any schema names. By default such tables (and other objects) are automatically put into a schema named “public”. Every new database contains such a schema.
You mixed the keys and the values.
Hashmap <Integer,String> hashmap = new HashMap<Integer, String>();
hashmap.put(100, "one");
hashmap.put(200, "two");
Afterwards a
hashmap.get(100);
will give you "one"
On a generic note, you can use a combination of ng-if and ng-style incorporate conditional changes with change in background image.
<span ng-if="selectedItem==item.id"
ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_active.png)',
'background-size':'52px 57px',
'padding-top':'70px',
'background-repeat':'no-repeat',
'background-position': 'center'}">
</span>
<span ng-if="selectedItem!=item.id"
ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_deactivated.png)',
'background-size':'52px 57px',
'padding-top':'70px',
'background-repeat':'no-repeat',
'background-position': 'center'}">
</span>
You can use this VSCode Extension called Reload
That Exception is thrown if there is already a key in the dictionary when you try to add the new one.
There must be more than one line in rct3Lines
with the same first word. You can't have 2 entries in the same dictionary with the same key.
You need to decide what you want to happen if the key already exists - if you want to just update the value where the key exists you can simply
rct3Features[items[0]]=items[1]
but, if not you may want to test if the key already exists with:
if(rect3Features.ContainsKey(items[0]))
{
//Do something
}
else
{
//Do something else
}
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
I work with asp.net core 2.2 and jquery and have to submit a complex object ('main class') from a view to a controller with simple data fields and some array's.
As soon as I have added the array in the c# 'main class' definition (see below) and submitted the (correct filled) array over ajax (post), the whole object was null in the controller.
First, I thought, the missing "traditional: true," to my ajax call was the reason, but this is not the case.
In my case the reason was the definition in the c# 'main class'.
In the 'main class', I had:
public List<EreignisTagNeu> oEreignistageNeu { get; set; }
and EreignisTagNeu was defined as:
public class EreignisTagNeu
{
public int iHME_Key { get; set; }
}
I had to change the definition in the 'main class' to:
public List<int> oEreignistageNeu { get; set; }
Now it works.
So... for me it seems as asp.net core has a problem (with post), if the list for an array is not defined completely in the 'main class'.
Note:
In my case this works with or without "traditional: true," to the ajax call
Get container name or short container id:
$ docker ps
Get full container id:
$ docker inspect -f '{{.Id}}' SHORT_CONTAINER_ID-or-CONTAINER_NAME
Copy file:
$ sudo cp path-file-host /var/lib/docker/aufs/mnt/FULL_CONTAINER_ID/PATH-NEW-FILE
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d8e703d7e303 solidleon/ssh:latest /usr/sbin/sshd -D cranky_pare
$ docker inspect -f '{{.Id}}' cranky_pare
or
$ docker inspect -f '{{.Id}}' d8e703d7e303
d8e703d7e3039a6df6d01bd7fb58d1882e592a85059eb16c4b83cf91847f88e5
$ sudo cp file.txt /var/lib/docker/aufs/mnt/**d8e703d7e3039a6df6d01bd7fb58d1882e592a85059eb16c4b83cf91847f88e5**/root/file.txt
I met the same problem. I found the solution in the solution from kb.vmware.com.
It works for me by adding
usb.quirks.device0 = "0xvid:0xpid skip-refresh"
Detail as below:
vmx | USB: Found device [name:Apple\ IR\ Receiver vid:05ac pid:8240 path:13/7/2 speed:full family:hid]
The line has the name of the USB device and its vid and pid information. Make a note of the vid and pid values.
usb.quirks.device0 = "0xvid:0xpid skip-reset"
For example, for the Apple device found in step 2, this line is:
usb.quirks.device0 = "0x05ac:0x8240 skip-reset"
usb.quirks.device0 = "0xvid:0xpid skip-refresh"
usb.quirks.device0 = "0xvid:0xpid skip-setconfig"
usb.quirks.device0 = "0xvid:0xpid skip-reset, skip-refresh, skip-setconfig"
Notes:
Refer this to see in detail.
Curious, what happens if you use straight net.sockets
instead? Here's some sample code I put together for testing purposes:
var net = require('net');
function HttpRequest(host, port, path, method) {
return {
headers: [],
port: 80,
path: "/",
method: "GET",
socket: null,
_setDefaultHeaders: function() {
this.headers.push(this.method + " " + this.path + " HTTP/1.1");
this.headers.push("Host: " + this.host);
},
SetHeaders: function(headers) {
for (var i = 0; i < headers.length; i++) {
this.headers.push(headers[i]);
}
},
WriteHeaders: function() {
if(this.socket) {
this.socket.write(this.headers.join("\r\n"));
this.socket.write("\r\n\r\n"); // to signal headers are complete
}
},
MakeRequest: function(data) {
if(data) {
this.socket.write(data);
}
this.socket.end();
},
SetupRequest: function() {
this.host = host;
if(path) {
this.path = path;
}
if(port) {
this.port = port;
}
if(method) {
this.method = method;
}
this._setDefaultHeaders();
this.socket = net.createConnection(this.port, this.host);
}
}
};
var request = HttpRequest("www.somesite.com");
request.SetupRequest();
request.socket.setTimeout(30000, function(){
console.error("Connection timed out.");
});
request.socket.on("data", function(data) {
console.log(data.toString('utf8'));
});
request.WriteHeaders();
request.MakeRequest();
(a little bit late, but could be useful)
Only trust PHP_INT_MAX and PHP_INT_SIZE, this value vary on your arch (32/64 bits) and your OS...
Any other "guess" or "hint" can be false.
Generally speaking, it's recommended to use MSI-based installations on Windows. Thus, if you're ready to invest a fair bit of time, WiX is the way to go.
If you want something which is much more simpler, go with InnoSetup.
Why not use the Database Helper ? This will have a nice onCreate which is only called the first time the app is started. This will help those people who want to track this after there initial app has been installed without tracking.
Remove existing files from the repository:
find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch
Add the line
.DS_Store
to the file .gitignore
, which can be found at the top level of your repository (or created if it isn't there already). You can do this easily with this command in the top directory
echo .DS_Store >> .gitignore
Then
git add .gitignore
git commit -m '.DS_Store banished!'
I always place the path in double quotes when I am creating a .bat file. (I just added the PAUSE so it wont close the screen.)
For example:
"C:\Program Files\PageTech\PCLReader64_131\PCLReader64.exe"
PAUSE
You should first make a String that holds all of the letters/numbers that you want.
Then, make a Random. e. g. Random rnd = new Random;
Finally, make something that actually gets a random character from your String containing your alphabet.
For example,
import java.util.Random;
public class randomCharacter {
public static void main(String[] args) {
String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ?/.,";
Random rnd = new Random();
char char = alphabet.charAt(rnd.nextInt(alphabet.length()));
// do whatever you want with the character
}
}
See this.
It's where I got this info from.
reload(module)
, but only if it's completely stand-alone. If anything else has a reference to the module (or any object belonging to the module), then you'll get subtle and curious errors caused by the old code hanging around longer than you expected, and things like isinstance
not working across different versions of the same code.
If you have one-way dependencies, you must also reload all modules that depend on the reloaded module to get rid of all the references to the old code. And then reload modules that depend on the reloaded modules, recursively.
If you have circular dependencies, which is very common for example when you are dealing with reloading a package, you must unload all the modules in the group in one go. You can't do this with reload()
because it will re-import each module before its dependencies have been refreshed, allowing old references to creep into new modules.
The only way to do it in this case is to hack sys.modules
, which is kind of unsupported. You'd have to go through and delete each sys.modules
entry you wanted to be reloaded on next import, and also delete entries whose values are None
to deal with an implementation issue to do with caching failed relative imports. It's not terribly nice but as long as you have a fully self-contained set of dependencies that doesn't leave references outside its codebase, it's workable.
It's probably best to restart the server. :-)
This should work:
Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + "/myFolder/");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");
if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
{
startActivity(intent);
}
else
{
// if you reach this place, it means there is no any file
// explorer app installed on your device
}
Please, be sure that you have any file explorer app installed on your device.
EDIT: added a shantanu's recommendation from the comment.
LIBRARIES: You can also have a look at the following libraries https://android-arsenal.com/tag/35 if the current solution doesn't help you.
If you want to know the user version in your code, then you can use using app()
helper function
app()->version();
It is defined in this file ../src/Illuminate/Foundation/Application.php
Hope it will help :)
You have three options:
Use a StringBuilder:
StringBuilder zText = new StringBuilder ();
void fillString(StringBuilder zText) { zText.append ("foo"); }
Create a container class and pass an instance of the container to your method:
public class Container { public String data; }
void fillString(Container c) { c.data += "foo"; }
Create an array:
new String[] zText = new String[1];
zText[0] = "";
void fillString(String[] zText) { zText[0] += "foo"; }
From a performance point of view, the StringBuilder is usually the best option.
If you're trying this with GitHub, you can do this with your SSH entered:
git clone https://[email protected]/username/repository
.nav-link {
color: blue !important;
}
Worked for me. Bootstrap v4.3.1
Based on luttken's answer. Thought I'd add my twist :)
function dateIsInBetween(\DateTime $from, \DateTime $to, \DateTime $subject)
{
return $subject->getTimestamp() > $from->getTimestamp() && $subject->getTimestamp() < $to->getTimestamp() ? true : false;
}
$paymentDate = new \DateTime('now');
$contractDateBegin = new \DateTime('01/01/2001');
$contractDateEnd = new \DateTime('01/01/2016');
echo dateIsInBetween($contractDateBegin, $contractDateEnd, $paymentDate) ? "is between" : "NO GO!";
A simple solution is to install jshon
library :
jshon -l < /tmp/test.json
2
You can get just the edition name by using the following steps.
Java implementations typically use a two-step compilation process. Java source code is compiled down to bytecode by the Java compiler. The bytecode is executed by a Java Virtual Machine (JVM). Modern JVMs use a technique called Just-in-Time (JIT) compilation to compile the bytecode to native instructions understood by hardware CPU on the fly at runtime.
Some implementations of JVM may choose to interpret the bytecode instead of JIT compiling it to machine code, and running it directly. While this is still considered an "interpreter," It's quite different from interpreters that read and execute the high level source code (i.e. in this case, Java source code is not interpreted directly, the bytecode, output of Java compiler, is.)
It is technically possible to compile Java down to native code ahead-of-time and run the resulting binary. It is also possible to interpret the Java code directly.
To summarize, depending on the execution environment, bytecode can be:
Generally, you don't need all those levels, SEVERE, WARNING, INFO, FINE might be enough. We're using Log4J (not java.util.logging directly) and the following levels (which might differ in name from other logging frameworks):
ERROR: Any error/exception that is or might be critical. Our Logger automatically sends an email for each such message on our servers (usage: logger.error("message");
)
WARN: Any message that might warn us of potential problems, e.g. when a user tried to log in with wrong credentials - which might indicate an attack if that happens often or in short periods of time (usage: logger.warn("message");
)
INFO: Anything that we want to know when looking at the log files, e.g. when a scheduled job started/ended (usage: logger.info("message");
)
DEBUG: As the name says, debug messages that we only rarely turn on. (usage: logger.debug("message");
)
The beauty of this is that if you set the log level to WARN, info and debug messages have next to no performance impact. If you need to get additional information from a production system you just can lower the level to INFO or DEBUG for a short period of time (since you'd get much more log entries which make your log files bigger and harder to read). Adjusting log levels etc. can normally be done at runtime (our JBoss instance checks for changes in that config every minute or so).
It's hard for us to bind a specific USB device to a docker container which is also specific. As you can see, the recommended way to achieve is:
docker run -t -i --privileged -v /dev/bus/usb:/dev/bus/usb ubuntu bash
It will bind all the devices to this container. It's unsafe. Every containers were granted to operate all of them.
Another way is binding devices by devpath. It may looks like:
docker run -t -i --privileged -v /dev/bus/usb/001/002:/dev/bus/usb/001/002 ubuntu bash
or --device
(better, no privileged
):
docker run -t -i --device /dev/bus/usb/001/002 ubuntu bash
Much safer. But actually it is hard to know what the devpath of a specific device is.
I have wrote this repo to solve this problem.
https://github.com/williamfzc/usb2container
After deploying this server, you can easily get all the connected devices' information via HTTP request:
curl 127.0.0.1:9410/api/device
and get:
{
"/devices/pci0000:00/0000:00:14.0/usb1/1-13": {
"ACTION": "add",
"DEVPATH": "/devices/pci0000:00/0000:00:14.0/usb1/1-13",
"DEVTYPE": "usb_device",
"DRIVER": "usb",
"ID_BUS": "usb",
"ID_FOR_SEAT": "xxxxx",
"ID_MODEL": "xxxxx",
"ID_MODEL_ID": "xxxxx",
"ID_PATH": "xxxxx",
"ID_PATH_TAG": "xxxxx",
"ID_REVISION": "xxxxx",
"ID_SERIAL": "xxxxx",
"ID_SERIAL_SHORT": "xxxxx",
"ID_USB_INTERFACES": "xxxxx",
"ID_VENDOR": "xxxxx",
"ID_VENDOR_ENC": "xxxxx",
"ID_VENDOR_FROM_DATABASE": "",
"ID_VENDOR_ID": "xxxxx",
"INTERFACE": "",
"MAJOR": "189",
"MINOR": "119",
"MODALIAS": "",
"PRODUCT": "xxxxx",
"SEQNUM": "xxxxx",
"SUBSYSTEM": "usb",
"TAGS": "",
"TYPE": "0/0/0",
"USEC_INITIALIZED": "xxxxx",
"adb_user": "",
"_empty": false,
"DEVNAME": "/dev/bus/usb/001/120",
"BUSNUM": "001",
"DEVNUM": "120",
"ID_MODEL_ENC": "xxxxx"
},
...
}
and bind them to your containers. For example, you can see the DEVNAME of this device is /dev/bus/usb/001/120
:
docker run -t -i --device /dev/bus/usb/001/120 ubuntu bash
Maybe it will help.
This probably isn't exactly the answer you're looking for, but having struggled with this myself and having issues with suggested answers, I decided to make it uncontrolled instead.
When editable
prop is false
, I use text
prop as is, but when it is true
, I switch to editing mode in which text
has no effect (but at least browser doesn't freak out). During this time onChange
are fired by the control. Finally, when I change editable
back to false
, it fills HTML with whatever was passed in text
:
/** @jsx React.DOM */
'use strict';
var React = require('react'),
escapeTextForBrowser = require('react/lib/escapeTextForBrowser'),
{ PropTypes } = React;
var UncontrolledContentEditable = React.createClass({
propTypes: {
component: PropTypes.func,
onChange: PropTypes.func.isRequired,
text: PropTypes.string,
placeholder: PropTypes.string,
editable: PropTypes.bool
},
getDefaultProps() {
return {
component: React.DOM.div,
editable: false
};
},
getInitialState() {
return {
initialText: this.props.text
};
},
componentWillReceiveProps(nextProps) {
if (nextProps.editable && !this.props.editable) {
this.setState({
initialText: nextProps.text
});
}
},
componentWillUpdate(nextProps) {
if (!nextProps.editable && this.props.editable) {
this.getDOMNode().innerHTML = escapeTextForBrowser(this.state.initialText);
}
},
render() {
var html = escapeTextForBrowser(this.props.editable ?
this.state.initialText :
this.props.text
);
return (
<this.props.component onInput={this.handleChange}
onBlur={this.handleChange}
contentEditable={this.props.editable}
dangerouslySetInnerHTML={{__html: html}} />
);
},
handleChange(e) {
if (!e.target.textContent.trim().length) {
e.target.innerHTML = '';
}
this.props.onChange(e);
}
});
module.exports = UncontrolledContentEditable;
If you declare your callback as mentioned by @lex82 like
callback = "callback(item.id, arg2)"
You can call the callback method in the directive scope with object map and it would do the binding correctly. Like
scope.callback({arg2:"some value"});
without requiring for $parse. See my fiddle(console log) http://jsfiddle.net/k7czc/2/
Update: There is a small example of this in the documentation:
& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).
You can't: It's a security feature in all modern browsers.
For IE8, it's off by default, but can be reactivated using a security setting:
When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.
The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.
In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.
More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.
One way that the Scala community can help ease the fear of programmers new to Scala is to focus on practice and to teach by example--a lot of examples that start small and grow gradually larger. Here are a few sites that take this approach:
After spending some time on these sites, one quickly realizes that Scala and its libraries, though perhaps difficult to design and implement, are not so difficult to use, especially in the common cases.
You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet
of Note
s, where you need to pass in a single Note
.
You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
From Bootstrap 4
.carousel-item{
height: 200px;
}
.carousel-item img{
height: 200px;
}
You should just use android studio for this process. It is just simpler. But first run this command in your react native app directory:
For Newer version of react-native(e.g. react native 0.49.0 & so on...)
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
For Older Version of react-native (0.49.0 & below)
react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/
Then Use android studio to open the 'android' folder in you react native app directory, it will ask to upgrade gradle and some other stuff. go to build-> Generate signed APK and follow the instructions from there. It's really straight forward.
In NetBeans,
properties
rub
tabmysql-connector-java.jar
and applyI use this property for hibernate in config xml
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/bookshop?serverTimezone=UTC&useSSL=false
</property>
without - serverTimezone=UTC - it doesn't work
Some big picture perspective to add to the other useful but more detail-centric answers:
In Swift, the exclamation point appears in several contexts:
let name = nameLabel!.text
var logo: UIImageView!
logo.image = thing as! UIImage
try! NSJSONSerialization.JSONObjectWithData(data, [])
Every one of these is a different language construct with a different meaning, but they all have three important things in common:
When you use !
in Swift, you are essentially saying, “Hey, compiler, I know you think an error could happen here, but I know with total certainty that it never will.”
Not all valid code fits into the box of Swift’s compile-time type system — or any language’s static type checking, for that matter. There are situations where you can logically prove that an error will never happen, but you can’t prove it to the compiler. That’s why Swift’s designers added these features in the first place.
However, whenever you use !
, you’re ruling out having a recovery path for an error, which means that…
An exclamation point also says, “Hey Swift, I am so certain that this error can never happen that it’s better for you to crash my whole app than it is for me to code a recovery path for it.”
That’s a dangerous assertion. It can be the correct one: in mission-critical code where you have thought hard about your code’s invariants, it may be that bogus output is worse than a crash.
However, when I see !
in the wild, it's rarely used so mindfully. Instead, it too often means, “this value was optional and I didn’t really think too hard about why it could be nil or how to properly handle that situation, but adding !
made it compile … so my code is correct, right?”
Beware the arrogance of the exclamation point. Instead…
Every one of these !
constructs has a ?
counterpart that forces you to deal with the error/nil case:
if let name = nameLabel?.text { ... }
var logo: UIImageView?
logo.image = thing as? UIImage
try? NSJSONSerialization.JSONObjectWithData(data, [])
If you are tempted to use !
, it is always good to consider carefully why you are not using ?
instead. Is crashing your program really the best option if the !
operation fails? Why is that value optional/failable?
Is there a reasonable recovery path your code could take in the nil/error case? If so, code it.
If it can’t possibly be nil, if the error can never happen, then is there a reasonable way to rework your logic so that the compiler knows that? If so, do it; your code will be less error-prone.
There are times when there is no reasonable way to handle an error, and simply ignoring the error — and thus proceeding with wrong data — would be worse than crashing. Those are the times to use force unwrapping.
I periodically search my entire codebase for !
and audit every use of it. Very few usages stand up to scrutiny. (As of this writing, the entire Siesta framework has exactly two instances of it.)
That’s not to say you should never use !
in your code — just that you should use it mindfully, and never make it the default option.
In general, you must have a file handle before opening the stream. You have a fileOutputStream handle before createNewFile() in the else block. The stream does not create the file if it doesn't exist.
Not really android specific, but that's a lot IO for this purpose. What if you do many "write" operations one after another? You will be reading the entire contents and writing the entire contents, taking time, and more importantly, battery life.
I suggest using java.io.RandomAccessFile, seek()'ing to the end, then writeChars() to append. It will be much cleaner code and likely much faster.
Use them all the time to process long-running operations asynchronously. A web user won't want to wait for more than 5 seconds for a request to process. If you have one that runs longer than that, one design is to submit the request to a queue and immediately send back a URL that the user can check to see when the job is finished.
Publish/subscribe is another good technique for decoupling senders from many receivers. It's a flexible architecture, because subscribers can come and go as needed.
iOS 10 update
The ban on autoplay has been lifted as of iOS 10 - but with some restrictions (e.g. A can be autoplayed if there is no audio track).
To see a full list of these restrictions, see the official docs: https://webkit.org/blog/6784/new-video-policies-for-ios/
iOS 9 and before
As of iOS 6.1, it is no longer possible to auto-play videos on the iPad.
My assumption as to why they've disabled the auto-play feature?
Well, as many device owners have data usage/bandwidth limits on their devices, I think Apple felt that the user themselves should decide when they initiate bandwidth usage.
After a bit of research I found the following extract in the Apple documentation in regard to auto-play on iOS devices to confirm my assumption:
"Apple has made the decision to disable the automatic playing of video on iOS devices, through both script and attribute implementations.
In Safari, on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and auto-play are disabled. No data is loaded until the user initiates it." - Apple documentation.
Here is a separate warning featured on the Safari HTML5 Reference page about why embedded media cannot be played in Safari on iOS:
Warning: To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript.
What this means (in terms of code) is that Javascript's play()
and load()
methods are inactive until the user initiates playback, unless the play()
or load()
method is triggered by user action (e.g. a click event).
Basically, a user-initiated play button works, but
an onLoad="play()"
event does not.
For example, this would play the movie:
<input type="button" value="Play" onclick="document.myMovie.play()">
Whereas the following would do nothing on iOS:
<body onload="document.myMovie.play()">
Bootstrap select has an noneSelectedText
option. You can set it via data-none-selected-text
attribute.
Documentation.
Simply try to multiply by one as following:
"00123" * 1; // Get as number
"00123" * 1 + ""; // Get as string
You could have a redirect servlet. In you web.xml you'd have:
<servlet>
<servlet-name>images</servlet-name>
<servlet-class>com.example.images.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>images</servlet-name>
<url-pattern>/images/*</url-pattern>
</servlet-mapping>
All your images would be in "/images", which would be intercepted by the servlet. It would then read in the relevant file in whatever folder and serve it right back out. For example, say you have a gif in your images folder, c:\Server_Images\smilie.gif. In the web page would be <img src="http:/example.com/app/images/smilie.gif"...
. In the servlet, HttpServletRequest.getPathInfo()
would yield "/smilie.gif". Which the servlet would find in the folder.
You can use Multiline Search and Replace in Visual Studio macro which provides nice GUI for the task.
public class MyArray : List<string> { }
services.Configure<ShipmentDetailsDisplayGidRoles>(Configuration.GetSection("MyArray"));
public SomeController(IOptions<MyArray> myArrayOptions)
{
myArray = myArrayOptions.Value;
}
Wikipedia points to the term Canonicalization.
A process for converting data that has more than one possible representation into a "standard" canonical representation. This can be done to compare different representations for equivalence, to count the number of distinct data structures, to improve the efficiency of various algorithms by eliminating repeated calculations, or to make it possible to impose a meaningful sorting order.
The Unicode example made the most sense to me:
Variable-length encodings in the Unicode standard, in particular UTF-8, have more than one possible encoding for most common characters. This makes string validation more complicated, since every possible encoding of each string character must be considered. A software implementation which does not consider all character encodings runs the risk of accepting strings considered invalid in the application design, which could cause bugs or allow attacks. The solution is to allow a single encoding for each character. Canonicalization is then the process of translating every string character to its single allowed encoding. An alternative is for software to determine whether a string is canonicalized, and then reject it if it is not. In this case, in a client/server context, the canonicalization would be the responsibility of the client.
In summary, a standard form of representation for data. From this form you can then convert to any representation you may need.
Specifically, the MySQLi extension provides the following extremely useful benefits over the old MySQL extension..
OOP Interface (in addition to procedural) Prepared Statement Support Transaction + Stored Procedure Support Nicer Syntax Speed Improvements Enhanced Debugging
PDO Extension
PHP Data Objects extension is a Database Abstraction Layer. Specifically, this is not a MySQL interface, as it provides drivers for many database engines (of course including MYSQL).
PDO aims to provide a consistent API that means when a database engine is changed, the code changes to reflect this should be minimal. When using PDO, your code will normally "just work" across many database engines, simply by changing the driver you're using.
In addition to being cross-database compatible, PDO also supports prepared statements, stored procedures and more, whilst using the MySQL Driver.
The “user is currently connected to it” might be SQL Server Management Studio window itself. Try selecting the master database and running the ALTER
query again.
This one works best to reset the form.
import React, { Component } from 'react'
class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
inputVal: props.inputValue
}
// preserve the initial state in a new object
this.baseState = this.state ///>>>>>>>>> note this one.
}
resetForm = () => {
this.setState(this.baseState) ///>>>>>>>>> note this one.
}
submitForm = () => {
// submit the form logic
}
updateInput = val => this.setState({ inputVal: val })
render() {
return (
<form>
<input
onChange={this.updateInput}
type="text
value={this.state.inputVal} />
<button
onClick={this.resetForm}
type="button">Cancel</button>
<button
onClick={this.submitForm}
type="submit">Submit</button>
</form>
)
}
}
def read_file(file, delete_after = false)
# code
end
Following code may work in this situation including ECMAScript 6 (ES6) as well as earlier versions.
function read_file(file, delete_after) {_x000D_
if(delete_after == undefined)_x000D_
delete_after = false;//default value_x000D_
_x000D_
console.log('delete_after =',delete_after);_x000D_
}_x000D_
read_file('text1.txt',true);_x000D_
read_file('text2.txt');
_x000D_
as default value in languages works when the function's parameter value is skipped when calling, in JavaScript it is assigned to undefined. This approach doesn't look attractive programmatically but have backward compatibility.
background: url(../images/backgroundImage.jpg) no-repeat center center fixed;
this should help
.aspx is a rendered page. If you need a view, use an .aspx page. If all you need is backend functionality but will be staying on the same view, use an .ashx page.
The way I think about it is that you use flatMap
when the function you wanted to put inside of map()
returns an Observable
. In which case you might still try to use map()
but it would be unpractical. Let me try to explain why.
If in such case you decided to stick with map
, you would get an Observable<Observable<Something>>
. For example in your case, if we used an imaginary RxGson library, that returned an Observable<String>
from it's toJson()
method (instead of simply returning a String
) it would look like this:
Observable.from(jsonFile).map(new Func1<File, Observable<String>>() {
@Override public Observable<String>> call(File file) {
return new RxGson().toJson(new FileReader(file), Object.class);
}
}); // you get Observable<Observable<String>> here
At this point it would be pretty tricky to subscribe()
to such an observable. Inside of it you would get an Observable<String>
to which you would again need to subscribe()
to get the value. Which is not practical or nice to look at.
So to make it useful one idea is to "flatten" this observable of observables (you might start to see where the name _flat_Map comes from). RxJava provides a few ways to flatten observables and for sake of simplicity lets assume merge is what we want. Merge basically takes a bunch of observables and emits whenever any of them emits. (Lots of people would argue switch would be a better default. But if you're emitting just one value, it doesn't matter anyway.)
So amending our previous snippet we would get:
Observable.from(jsonFile).map(new Func1<File, Observable<String>>() {
@Override public Observable<String>> call(File file) {
return new RxGson().toJson(new FileReader(file), Object.class);
}
}).merge(); // you get Observable<String> here
This is a lot more useful, because subscribing to that (or mapping, or filtering, or...) you just get the String
value. (Also, mind you, such variant of merge()
does not exist in RxJava, but if you understand the idea of merge then I hope you also understand how that would work.)
So basically because such merge()
should probably only ever be useful when it succeeds a map()
returning an observable and so you don't have to type this over and over again, flatMap()
was created as a shorthand. It applies the mapping function just as a normal map()
would, but later instead of emitting the returned values it also "flattens" (or merges) them.
That's the general use case. It is most useful in a codebase that uses Rx allover the place and you've got many methods returning observables, which you want to chain with other methods returning observables.
In your use case it happens to be useful as well, because map()
can only transform one value emitted in onNext()
into another value emitted in onNext()
. But it cannot transform it into multiple values, no value at all or an error. And as akarnokd wrote in his answer (and mind you he's much smarter than me, probably in general, but at least when it comes to RxJava) you shouldn't throw exceptions from your map()
. So instead you can use flatMap()
and
return Observable.just(value);
when all goes well, but
return Observable.error(exception);
when something fails.
See his answer for a complete snippet: https://stackoverflow.com/a/30330772/1402641
In a php section before the HTML section, use sprinf() to create a constant string from the variables:
$mystuff = sprinf("My name is %s and my mother's name is %s","Suzy","Caroline");
Then in the HTML section you can do whatever you like, such as:
<p>$mystuff</p>
The compiler should make them all the same in the long run. Pick a standard so that your code will be easy to read, and stick with it.
I simply:
rm -rf ~/anaconda3
...this removed conda also.
Then:
mousepad ~/.bashrc
...and removed the path line added at the very bottom (clearly identified by Anaconda as 'added by Anaconda'.
Worth noting that anaconda3 created a backup of my .bashrc file before modification, and named it as:
./bashrc-anaconda3.bak
...so I could always have just renamed this and deleted my modified .bashrc
Why not get rid of the inline javascript and do something like this instead?
Inline javascript is considered bad practice as it is outdated.
Notes
Why use addEventListener?
addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:
It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used. It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling) It works on any DOM element, not just HTML elements.
<a id="back" href="www.mypage.com"> Link </a>
document.getElementById("back").addEventListener("click", window.history.back, false);
On jsfiddle
One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.
One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).
Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.
-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
ID INT IDENTITY(1, 1) NOT NULL,
CallTime DATETIME NOT NULL DEFAULT GETDATE(),
CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
ID INT IDENTITY(1, 1) NOT NULL,
CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
Subject VARCHAR(250) NOT NULL,
Notes VARCHAR(8000) NOT NULL,
Completed BIT NOT NULL DEFAULT 0
)
-- This table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
PhoneCallID INT NOT NULL,
TicketID INT NOT NULL
)
I think you are looking for the Dictionary object, found in the Microsoft Scripting Runtime library. (Add a reference to your project from the Tools...References menu in the VBE.)
It pretty much works with any simple value that can fit in a variant (Keys can't be arrays, and trying to make them objects doesn't make much sense. See comment from @Nile below.):
Dim d As dictionary
Set d = New dictionary
d("x") = 42
d(42) = "forty-two"
d(CVErr(xlErrValue)) = "Excel #VALUE!"
Set d(101) = New Collection
You can also use the VBA Collection object if your needs are simpler and you just want string keys.
I don't know if either actually hashes on anything, so you might want to dig further if you need hashtable-like performance. (EDIT: Scripting.Dictionary does use a hash table internally.)
I have recently started working on a project using Vue JS, JSON Schema. I am trying to access nested JSON Objects from a JSON Schema file in the Vue app. I tried the below code and now I can load different JSON objects inside different Vue template tags. In the script tag add the below code
import {JsonObject1name, JsonObject2name} from 'your Json file path';
Now you can access JsonObject1,2 names in data section of export default part as below:
data: () => ({
schema: JsonObject1name,
schema1: JsonObject2name,
model: {}
}),
Now you can load the schema, schema1 data inside Vue template according to your requirement. See below code for example :
<SchemaForm id="unique name representing your Json object1" class="form" v-model="model" :schema="schema" :components="components">
</SchemaForm>
<SchemaForm id="unique name representing your Json object2" class="form" v-model="model" :schema="schema1" :components="components">
</SchemaForm>
SchemaForm is the local variable name for @formSchema/native library. I have implemented the data of different JSON objects through forms in different CSS tabs.
I hope this answer helps someone. I can help if there are any questions.
An alternate I would suggest in this use case is to use the MAX(t_stamp) to get the latest row ... e.g.
select t.* from raceway_input_labo t
where t.t_stamp = (select max(t_stamp) from raceway_input_labo)
limit 1
My coding pattern preference (perhaps) - reliable, generally performs at or better than trying to select the 1st row from a sorted list - also the intent is more explicitly readable.
Hope this helps ...
SQLer
Just a shot in the dark(since you did not share the compiler
initialization code with us): the way you retrieve the compiler
causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools hence, results in NPE
.
Assuming your "states" collection is like:
{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
The query to find states with null cities would be:
db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
It is a common mistake to query for nulls as:
db.states.find({"cities.name" : null});
because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.
You can bind the mouseenter
and mouseleave
events and jQuery will emulate those where they are not native.
$("div.system_box").on('mouseenter', function(){
//enter
})
.on('mouseleave', function(){
//leave
});
note: do not use hover as that is deprecated
I create a file named __partials__.scss
in the same directory of partials
|- __partials__.scss
|- /partials
|- __header__.scss
|- __viewport__.scss
|- ....
In __partials__.scss
, I wrote these:
@import "partials/header";
@import "partials/viewport";
@import "partials/footer";
@import "partials/forms";
....
So, when I want import the whole partials
, just write @import "partials"
. If I want import any of them, I can also write @import "partials/header"
.
To move a table from database A to database B at your local setup, use the following command:
pg_dump -h localhost -U owner-name -p 5432 -C -t table-name database1 | psql -U owner-name -h localhost -p 5432 database2
While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.
@{Model.RequiredProperty = "default";}
@Html.HiddenFor(model => model.RequiredProperty)
For completeness, write_csv()
from the readr
package is faster and never writes row names
# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")
If you need to write big data out, use fwrite()
from the data.table
package. It's much faster than both write.csv
and write_csv
# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")
Below is a benchmark that Edouard published on his site
microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
write_csv(data, "readr_file.csv"),
fwrite(data, "datatable_file.csv"),
times = 10, unit = "s")
## Unit: seconds
## expr min lq mean median uq max neval
## write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311 10
## write_csv(data, "readr_file.csv") 3.6742610 3.7999409 3.8572456 3.8690681 3.8991995 4.0637453 10
## fwrite(data, "datatable_file.csv") 0.3976728 0.4014872 0.4097876 0.4061506 0.4159007 0.4355469 10
EDIT ouch, too late... I know read your comment stating that you want to keep the feature-x changeset around, so the cloning approach here doesn't work.
I'll still let the answer here for it may help others.
If you want to completely get rid of "feature X", because, for example, it didn't work, you can clone. This is one of the method explained in the article and it does work, and it talks specifically about heads.
As far as I understand you have this and want to get rid of the "feature-x" head once and for all:
@ changeset: 7:00a7f69c8335
|\ tag: tip
| | parent: 4:31b6f976956b
| | parent: 2:0a834fa43688
| | summary: merge
| |
| | o changeset: 5:013a3e954cfd
| |/ summary: Closed branch feature-x
| |
| o changeset: 4:31b6f976956b
| | summary: Changeset2
| |
| o changeset: 3:5cb34be9e777
| | parent: 1:1cc843e7f4b5
| | summary: Changeset 1
| |
o | changeset: 2:0a834fa43688
|/ summary: Changeset C
|
o changeset: 1:1cc843e7f4b5
| summary: Changeset B
|
o changeset: 0:a9afb25eaede
summary: Changeset A
So you do this:
hg clone . ../cleanedrepo --rev 7
And you'll have the following, and you'll see that feature-x is indeed gone:
@ changeset: 5:00a7f69c8335
|\ tag: tip
| | parent: 4:31b6f976956b
| | parent: 2:0a834fa43688
| | summary: merge
| |
| o changeset: 4:31b6f976956b
| | summary: Changeset2
| |
| o changeset: 3:5cb34be9e777
| | parent: 1:1cc843e7f4b5
| | summary: Changeset 1
| |
o | changeset: 2:0a834fa43688
|/ summary: Changeset C
|
o changeset: 1:1cc843e7f4b5
| summary: Changeset B
|
o changeset: 0:a9afb25eaede
summary: Changeset A
I may have misunderstood what you wanted but please don't mod down, I took time reproducing your use case : )
Use WORKSPACE environment variable to change workspace directory.
If doing using Jenkinsfile, use following code :
dir("${env.WORKSPACE}/aQA"){
sh "pwd"
}
In Visual Studio without mouse: Alt+Shift+{ Arrow }.