Maybe this will help.
var inputVal = $(this).closest('tr').find("td:eq(x) input").val();
Use the following:
WHERE datex BETWEEN GETDATE() AND DATEADD(DAY, -7, GETDATE())
Hope this helps.
The only similarities are that malloc
/new
both return a pointer which addresses some memory on the heap, and they both guarantee that once such a block of memory has been returned, it won't be returned again unless you free/delete it first. That is, they both "allocate" memory.
However, new
/delete
perform arbitrary other work in addition, via constructors, destructors and operator overloading. malloc
/free
only ever allocate and free memory.
In fact, new
is sufficiently customisable that it doesn't necessarily return memory from the heap, or even allocate memory at all. However the default new
does.
If you want to read a CSV File with encoding utf-8, a minimalistic approach that I recommend you is to use something like this:
with open(file_name, encoding="utf8") as csv_file:
With that statement, you can use later a CSV reader to work with.
Try this:
myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))
giving:
V1 V2 V3 V4 V5
1 1 2 3 5 1
2 2 4 4 1 2
3 1 4 1 1 0
4 4 5 1 3 0
5 5 5 5 4 0
or this:
myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))
giving:
V1 V2 V3 V4 V5
1 1 2 3 5 1
2 2 4 4 1 2
3 1 4 1 1 0
4 4 5 1 3 0
5 5 5 5 4 0
Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.
Above used this input:
myfile <-
structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L,
5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))
Update 1 Since originally posted dplyr has changed %.%
to %>%
so have modified answer accordingly.
Update 2 dplyr now has case_when
which provides another solution:
myfile %>%
mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1,
V2 == 4 & V3 != 1 ~ 2,
TRUE ~ 0))
One important thing to mention as well is the security improvement that comes with the package-lock file. Since it keeps all the hashes of the packages if someone would tamper with the public npm registry and change the source code of a package without even changing the version of the package itself it would be detected by the package-lock file.
You could use actionLayout
from the support library.
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/button_item"
android:title=""
app:actionLayout="@layout/button_layout"
app:showAsAction="always"
/>
</menu>
button_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Activity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.button_item);
Button btn = item.getActionView().findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Toolbar Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
return true;
}
Here is how I created an infinite loop with a delay that breaks on a certain condition:
// Now continuously check the app status until it's completed,
// failed or times out. The isFinished() will throw exception if
// there is a failure.
while (true) {
let status = await this.api.getStatus(appId);
if (isFinished(status)) {
break;
} else {
// Delay before running the next loop iteration:
await new Promise(resolve => setTimeout(resolve, 3000));
}
}
The key here is to create a new Promise that resolves by timeout, and to await for its resolution.
Obviously you need async/await support for that. Works in Node 8.
You need to CAST
the ParentId
as an nvarchar
, so that the output is always the same data type.
SELECT Id 'PatientId',
ISNULL(CAST(ParentId as nvarchar(100)),'') 'ParentId'
FROM Patients
For now, until there is something new from EFCore I would used a command and map it manually
using (var command = this.DbContext.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "SELECT ... WHERE ...> @p1)";
command.CommandType = CommandType.Text;
var parameter = new SqlParameter("@p1",...);
command.Parameters.Add(parameter);
this.DbContext.Database.OpenConnection();
using (var result = command.ExecuteReader())
{
while (result.Read())
{
.... // Map to your entity
}
}
}
Try to SqlParameter to avoid Sql Injection.
dbData.Product.FromSql("SQL SCRIPT");
FromSql doesn't work with full query. Example if you want to include a WHERE clause it will be ignored.
Some Links:
public bool IsNumeric(string value)
{
return value.All(char.IsNumber);
}
Have you tried?
var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;
// "2013-10-10T22:10:00"
dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern);
// "2013-10-10 22:10:00Z"
dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern)
Also try using parameters when you store the c# datetime value in the mySql database, this might help.
Use below code to change background color of edit-text's border.
Create new XML file under drawable.
abc.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#00000000" />
<stroke android:width="1dip" android:color="#ffffff" />
</shape>
and add it as background of your edit-text
android:background="@drawable/abc"
Try getPrameterValues()
for getting values from multiple checkboxes.
If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:
Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:
In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.
Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx
I know this question is already answered but I have one solution for this same.
You can also use Object.keys()
inside of *ngFor
to get required result.
I have created a demo on stackblitz. I hope this will help/guide to you/others.
CODE SNIPPET
HTML Code
<div *ngFor="let key of Object.keys(myObj)">
<p>Key-> {{key}} and value is -> {{myObj[key]}}</p>
</div>
.ts file code
Object = Object;
myObj = {
"id": 834,
"first_name": "GS",
"last_name": "Shahid",
"phone": "1234567890",
"role": null,
"email": "[email protected]",
"picture": {
"url": null,
"thumb": {
"url": null
}
},
"address": "XYZ Colony",
"city_id": 2,
"provider": "email",
"uid": "[email protected]"
}
Try with <button type="submit">
you can perform the functionality of submitform()
by doing <form ....... onsubmit="submitform()">
Here is my function:
using System;
using System.Collections.Generic;
class HexadecimalToDecimal
{
static Dictionary<char, int> hexdecval = new Dictionary<char, int>{
{'0', 0},
{'1', 1},
{'2', 2},
{'3', 3},
{'4', 4},
{'5', 5},
{'6', 6},
{'7', 7},
{'8', 8},
{'9', 9},
{'a', 10},
{'b', 11},
{'c', 12},
{'d', 13},
{'e', 14},
{'f', 15},
};
static decimal HexToDec(string hex)
{
decimal result = 0;
hex = hex.ToLower();
for (int i = 0; i < hex.Length; i++)
{
char valAt = hex[hex.Length - 1 - i];
result += hexdecval[valAt] * (int)Math.Pow(16, i);
}
return result;
}
static void Main()
{
Console.WriteLine("Enter Hexadecimal value");
string hex = Console.ReadLine().Trim();
//string hex = "29A";
Console.WriteLine("Hex {0} is dec {1}", hex, HexToDec(hex));
Console.ReadKey();
}
}
I got this error after change a loop in my program, let`s see:
for ...
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:
for ...
x_batch = []
y_batch = []
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
Then, check if you are using np.asarray() or something like that.
A simple one would be
\d{4}-\d{2}-\d{2}
but this does not restrict month to 1-12 and days from 1 to 31.
There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.
I have reproduced the issue in my system,
postgres=# alter user my-sys with password 'pass11';
ERROR: syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
^
Here is the issue,
psql is asking for input and you have given again the alter query see postgres-#
That's why it's giving error at alter
postgres-# alter user "my-sys" with password 'pass11';
ERROR: syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
^
Solution is as simple as the error,
postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE
You need to login to your mysql terminal first using
mysql -u username -p password
Then use this:
SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;
output will be like this:
STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB
You can also set sql mode by this:
SET GLOBAL sql_mode=TRADITIONAL;
Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point
$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ #remove "hell" from "hello-world" if "hell" is found at the beginning.
$ prefix_removed_string=${string/#$prefix}
$ #remove "ld" from "o-world" if "ld" is found at the end.
$ suffix_removed_String=${prefix_removed_string/%$suffix}
$ echo $suffix_removed_String
o-wor
#$prefix : adding # makes sure that substring "hell" is removed only if it is found in beginning. %$suffix : adding % makes sure that substring "ld" is removed only if it is found in end.
Without these, the substrings "hell" and "ld" will get removed everywhere, even it is found in the middle.
When you include a string literal in a query, you can enclose the string in either single or double quotes; Access' database engine will accept either. So double quotes will avoid the problem with a string which contains a single quote.
SELECT * FROM tblStudents WHERE [name] Like "Daniel O'Neal";
If you want to keep the single quotes around your string, you can double up the single quote within it, as mentioned in other answers.
SELECT * FROM tblStudents WHERE [name] Like 'Daniel O''Neal';
Notice the square brackets surrounding name. I used the brackets to lessen the chance of confusing the database engine because name is a reserved word.
It's not clear why you're using the Like comparison in your query. Based on what you've shown, this should work instead.
SELECT * FROM tblStudents WHERE [name] = "Daniel O'Neal";
You can also use the constant service as such. Defining the function outside of the constant call allows it to be recursive as well.
function doSomething( a, b ) {
return a + b;
};
angular.module('moduleName',[])
// Define
.constant('$doSomething', doSomething)
// Usage
.controller( 'SomeController', function( $doSomething ) {
$scope.added = $doSomething( 100, 200 );
})
;
export const a = 1;
export const b = 2;
export const c = 3;
This will work w/ Babel transforms today and should take advantage of all the benefits of ES2016 modules whenever that feature actually lands in a browser.
You can also add export default {a, b, c};
which will allow you to import all the values as an object w/o the * as
, i.e. import myModule from 'my-module';
Sources:
C++, O(n):
long long prod = accumulate(in.begin(), in.end(), 1LL, multiplies<int>());
transform(in.begin(), in.end(), back_inserter(res),
bind1st(divides<long long>(), prod));
just use like this to make anything to center
android:layout_gravity="center"
android:gravity="center"
updated :
android:layout_gravity="center|right"
android:gravity="center|right"
Updated : Just remove MarginBottom from your textview.. Do like this.. for your textView
<LinearLayout
android:id="@+id/linearLayout5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" >
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center|right"
android:text="hello"
android:textSize="20dp" />
</LinearLayout>
Visual studio 2019 version:
The drop down menu was moved to:
Z=np.array([1.0,1.0,1.0,1.0])
def func(TempLake,Z):
A=TempLake
B=Z
return A*B
Nlayers=Z.size
N=3
TempLake=np.zeros((N+1,Nlayers))
kOUT=np.vectorize(func)(TempLake,Z)
This works too , instead of looping , just vectorize however read below notes from the scipy documentation : https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html
The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.
If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if cache is True to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive.
@Column
AnnotationThe nullable
attribute of the @Column
annotation has two purposes:
The HBM2DDL schema generation tool translates the @Column(nullable = false)
entity attribute to a NOT NULL
constraint for the associated table column when generating the CREATE TABLE
statement.
As I explained in the Hibernate User Guide, it's better to use a tool like Flyway instead of relying on the HBM2DDL mechanism for generating the database schema.
When flushing the Persistence Context, Hibernate ORM also uses the @Column(nullable = false)
entity attribute:
new Nullability( session ).checkNullability( values, persister, true );
If the validation fails, Hibernate will throw a PropertyValueException
, and prevents the INSERT or UPDATE statement to be executed needesly:
if ( !nullability[i] && value == null ) {
//check basic level one nullablilty
throw new PropertyValueException(
"not-null property references a null or transient value",
persister.getEntityName(),
persister.getPropertyNames()[i]
);
}
@NotNull
AnnotationThe @NotNull
annotation is defined by Bean Validation and, just like Hibernate ORM is the most popular JPA implementation, the most popular Bean Validation implementation is the Hibernate Validator framework.
When using Hibernate Validator along with Hibernate ORM, Hibernate Validator will throw a ConstraintViolation
when validating the entity.
Adding the following to your css should hide the text element for users and keep FB Happy
.connect_widget_not_connected_text
{
display:none !important; /*in your stylesheets to hide the counter!*/
}
-- Update
Try using a different approach.
Use
var jsDate = $('#your_datepicker_id').datepicker('getDate');
if (jsDate !== null) { // if any date selected in datepicker
jsDate instanceof Date; // -> true
jsDate.getDate();
jsDate.getMonth();
jsDate.getFullYear();
}
You can set a control variable in vars files located in group_vars/
or directly in hosts file like this:
[vagrant:vars]
test_var=true
[location-1]
192.168.33.10 hostname=apollo
[location-2]
192.168.33.20 hostname=zeus
[vagrant:children]
location-1
location-2
And run tasks like this:
- name: "test"
command: "echo {{test_var}}"
when: test_var is defined and test_var
To set it programmatically in Activity.java:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.MyTheme); // (for Custom theme)
setTheme(android.R.style.Theme_Holo); // (for Android Built In Theme)
this.setContentView(R.layout.myactivity);
To set in Application scope in Manifest.xml (all activities):
<application
android:theme="@android:style/Theme.Holo"
android:theme="@style/MyTheme">
To set in Activity scope in Manifest.xml (single activity):
<activity
android:theme="@android:style/Theme.Holo"
android:theme="@style/MyTheme">
To build a custom theme, you will have to declare theme in themes.xml file, and set styles in styles.xml file.
String double_string = "100.215";
Double double = Double.parseDouble(double_string);
If you're using DecimalFormat
to convert double
to String
, it's very straightforward:
DecimalFormat formatter = new DecimalFormat("0.0##");
formatter.setRoundingMode(RoundingMode.HALF_UP);
double num = 1.234567;
return formatter.format(num);
There are several RoundingMode
enum values to select from, depending upon the behaviour you require.
As said @v.ladynev, it works with JDK 1.7
With Eclipse, to be able to perform a "Run As" maven install
with the TLS command-line parameter, just configure the JDK you're using.
Open the dialog through Window > Preferences > Java > Installed JREs.
Then highlight the one you're using (should be a JDK, not a JRE), click on Edit. In the field "Default VM arguments", fill the value -Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2
. As shown below:
Clean the project (maybe optional), then re-run a maven install
.
select * from tableName where columnName is null
This is a simple example of what I used for a recent test. You need to make sure that your security settings are the same on the server and client.
var myBinding = new BasicHttpBinding();
myBinding.Security.Mode = BasicHttpSecurityMode.None;
var myEndpointAddress = new EndpointAddress("http://servername:8732/TestService/");
client = new ClientTest(myBinding, myEndpointAddress);
client.someCall();
Double click on the .edmx file then right_click anywhere on the screen and choose "Update Modle From DB". In the new window go to the "Refresh" tab and choose the changed table/view and click Finish.
Alternative which I did programming Angular:
<div class="form-row">
<div class="form-group col-md-7">
Left
</div>
<div class="form-group col-md-5">
Right
</div>
</div>
I use this function:
function formatcell($data, $num, $fill=" ") {
$data = trim($data);
$data=str_replace(chr(13),' ',$data);
$data=str_replace(chr(10),' ',$data);
// translate UTF8 to English characters
$data = iconv('UTF-8', 'ASCII//TRANSLIT', $data);
$data = preg_replace("/[\'\"\^\~\`]/i", '', $data);
// fill it up with spaces
for ($i = strlen($data); $i < $num; $i++) {
$data .= $fill;
}
// limit string to num characters
$data = substr($data, 0, $num);
return $data;
}
echo formatcell("YES UTF8 String Zürich", 25, 'x'); //YES UTF8 String Zürichxxx
echo formatcell("NON UTF8 String Zurich", 25, 'x'); //NON UTF8 String Zurichxxx
Check out my function in my blog http://www.unexpectedit.com/php/php-handling-non-english-characters-utf8
You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:
try:
import datetime
import foo
import sys
except ImportError:
pass
Let's say foo
doesn't exist. Then only datetime
will be imported.
What you can do is import the sys module at the beginning of the file, before the try/except statement:
import sys
try:
import numpy as np
import pyfits as pf
import scipy.ndimage as nd
import pylab as pl
import os
import heapq
from scipy.optimize import leastsq
except ImportError:
print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
sys.exit()
eliminate all the whitespace from a string, on both ends, and in between words.
>>> import re
>>> re.sub("\s+", # one or more repetition of whitespace
'', # replace with empty string (->remove)
''' hello
... apple
... ''')
'helloapple'
Python docs:
This is very late, but I thought it could be useful to someone should they reference this question. I beleive the below JS will do what is asked.
<script>
$(document).ready(function()
{
document.getElementById('select').size=3;
});
</script>
I got this error quite a lot, so now I do a batch removal of all unused containers at once:
docker container prune
add -f
to force removal without prompt.
To list all unused containers (without removal):
docker container ls -a --filter status=exited --filter status=created
See here more examples how to prune other objects (networks, volumes, etc.).
You may find set lbr
useful; with set wrap
on this will wrap but only cutting the line on whitespace and not in the middle of a word.
e.g.
without lbr the li
ne can be split on
a word
and
with lbr on the
line will be
split on
whitespace only
You can also use references on foreach
values:
foreach($array as $elementKey => &$element) {
// $element is the same than &$array[$elementKey]
if (isset($element['id']) and $element['id'] == 'searched_value') {
unset($element);
}
}
No need to import any library:
>>> bytearray.fromhex("7061756c").decode()
'paul'
What you are looking for can be found here. It may exist a more elegant way to accomplish that, but one possible approach is
final Duration timeout = Duration.ofSeconds(30);
ExecutorService executor = Executors.newSingleThreadExecutor();
final Future<String> handler = executor.submit(new Callable() {
@Override
public String call() throws Exception {
return requestDataFromModem();
}
});
try {
handler.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
handler.cancel(true);
}
executor.shutdownNow();
final Duration timeout = Duration.ofSeconds(30);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
final Future<String> handler = executor.submit(new Callable() {
@Override
public String call() throws Exception {
return requestDataFromModem();
}
});
executor.schedule(new Runnable() {
@Override
public void run(){
handler.cancel(true);
}
}, timeout.toMillis(), TimeUnit.MILLISECONDS);
executor.shutdownNow();
Those are only a draft so that you can get the main idea.
Effective January 15, 2020, The Central Repository no longer supports insecure communication over plain HTTP and requires that all requests to the repository are encrypted over HTTPS.
If you're receiving this error, then you need to replace all URL references to Maven Central with their canonical HTTPS counterparts.
(source)
We have made the following changes in my project's build.gradle:
Old:
repositories {
maven { url "http://repo.maven.apache.org/maven2" }
}
New:
repositories {
maven { url "https://repo.maven.apache.org/maven2" }
}
Oracle/MySQL provides an official, pure Python DBAPI driver: http://dev.mysql.com/downloads/connector/python/
I have used it with Python 3.3 and found it to work great. Also works with SQLAlchemy.
See also this question: Is it still too early to hop aboard the Python 3 train?
A good example of this casting is using *= or /=
byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57
or
byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40
or
char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'
or
char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'
The shortcut is: CTRL+_
Have a look here http://ubuntuforums.org/showthread.php?t=1005737
Another easy method to sort an array of strings consists by using the NSString description
property this way:
NSSortDescriptor *valueDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
arrayOfSortedStrings = [arrayOfNotSortedStrings sortedArrayUsingDescriptors:@[valueDescriptor]];
Power has more precedence than multiply, so:
2**2*3 = (2^2)*3
2*2*3 = 2*2*3
Change your clean
so rm
will not complain:
clean:
rm -f .lambda .lambda_t .activity .activity_t_lambda
If I'm starting a long-running process like a copy or hash and I want to know later how long it took, I just do this:
$ date; sha1sum reallybigfile.txt; date
Which will result in the following output:
Tue Jun 2 21:16:03 PDT 2015
5089a8e475cc41b2672982f690e5221469390bc0 reallybigfile.txt
Tue Jun 2 21:33:54 PDT 2015
Granted, as implemented here it isn't very precise and doesn't calculate the elapsed time. But it's dirt simple and sometimes all you need.
My approach was:
openssl version
OpenSSL 1.0.1e 11 Feb 2013
wget https://www.openssl.org/source/openssl-1.0.2a.tar.gz
wget http://www.linuxfromscratch.org/patches/blfs/svn/openssl-1.0.2a-fix_parallel_build-1.patch
tar xzf openssl-1.0.2a.tar.gz
cd openssl-1.0.2a
patch -Np1 -i ../openssl-1.0.2a-fix_parallel_build-1.patch
./config --prefix=/usr --openssldir=/etc/ssl --libdir=lib shared zlib-dynamic
make
make install
openssl version
OpenSSL 1.0.2a 19 Mar 2015
Installing specific laravel version with composer create-project
composer global require laravel/installer
Then, if you want install specific version then just edit version values "6." , "5.8."
composer create-project --prefer-dist laravel/laravel Projectname "6.*"
Run Local Development Server
php artisan serve
OMG... It's not only a problem of "jQuery Library" and "getElementById".
Sure, jQuery helps us to put cross-browser problems aside, but using the traditional way without libraries can still work well, if you really understand JavaScript ENOUGH!!!
Both @Már Örlygsson and @Darryl Hein gave you good ALTARNATIVES(I'd say, they're just altarnatives, not anwsers), where the former used the traditional way, and the latter jQuery way. But do you really know the answer to your problem? What is wrong with your code?
First, .click
is a jQuery way. If you want to use traditional way, use .onclick instead. Or I recommend you concentrating on learning to use jQuery only, in case of confusing. jQuery is a good tool to use without knowing DOM enough.
The second problem, also the critical one, new function(){}
is a very bad syntax, or say it is a wrong syntax.
No matter whether you want to go with jQuery or without it, you need to clarify it.
There are 3 basic ways declaring function:
function name () {code}
... = function() {code} // known as anonymous function or function literal
... = new Function("code") // Function Object
Note that javascript is case-sensitive, so new function()
is not a standard syntax of javascript. Browsers may misunderstand the meaning.
Thus your code can be modified using the second way as
= function(){alert();}
Or using the third way as
= new Function("alert();");
Elaborating on it, the second way works almost the same as the third way, and the second way is very common, while the third is rare. Both of your best answers use the second way.
However, the third way can do something that the second can't do, because of "runtime" and "compile time". I just hope you know new Function()
can be useful sometimes. One day you meet problems using function(){}
, don't forget new Function()
.
To understand more, you are recommended read << JavaScript: The Definitive Guide, 6th Edition >>, O'Reilly.
Your syntax is incorrect, you should either specify a hash:
hash = {abc: true, def: true, ghi: true};
Or an array:
arr = ['abc','def','ghi'];
You can effectively remove an item from a hash by simply setting it to null:
hash['def'] = null;
hash.def = null;
Or removing it entirely:
delete hash.def;
To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:
arr.splice(arr.indexOf("def"), 1);
This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:
arr.filter(function(item) { return item !== 'def'; });
This will create a new array with only elements that are not 'def'.
It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.
I'm happy to add Moo as an option, although clearly I'm biased towards it: http://geoffreywiseman.github.com/Moo/
It's very easy to use for simple cases, reasonable capable for more complex cases, although there are still some areas where I can imagine enhancing it for even further complexities.
Actually, you can process the find
command output in a copy command in two ways:
If the find
command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:
Syntax:
find <Path> <Conditions> | xargs cp -t <copy file path>
Example:
find -mtime -1 -type f | xargs cp -t inner/
But our production data files might contain spaces, so most of time this command is effective:
Syntax:
find <path> <condition> -exec cp '{}' <copy path> \;
Example
find -mtime -1 -type f -exec cp '{}' inner/ \;
In the second example, the last part, the semi-colon is also considered as part of the find
command, and should be escaped before pressing Enter. Otherwise you will get an error something like:
find: missing argument to `-exec'
For anyone still looking for a simpler method to transfer repos from Gitlab to Github while preserving all history.
Step 1. Login to Github, create a private repo with the exact same name as the repo you would like to transfer.
Step 2. Under "push an existing repository from the command" copy the link of the new repo, it will look something like this:
[email protected]:your-name/name-of-repo.git
Step 3. Open up your local project and look for the folder .git
typically this will be a hidden folder. Inside the .git
folder open up config
.
The config file will contain something like:
[remote "origin"]
url = [email protected]:your-name/name-of-repo.git
fetch = +refs/heads/:refs/remotes/origin/
Under [remote "origin"]
, change the URL to the one that you copied on Github.
Step 4. Open your project folder in the terminal and run: git push --all
. This will push your code to Github as well as all the commit history.
Step 5. To make sure everything is working as expected, make changes, commit, push and new commits should appear on the newly created Github repo.
Step 6. As a last step, you can now archive your Gitlab repo or set it to read only.
Try putting anchor tag inside and adding a{display:block;}....it will work fine
If you know that your strings are mostly ASCII you could convert them to UTF-8.
byte[] bytes = string.getBytes("UTF-8");
This may reduce the memory size by about 50%. However, you will get a byte array out and not a string. If you are writing it to a file though, that should not be a problem.
To convert back to a String:
private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
...
String s = new String(bytes, UTF8_CHARSET);
As mentioned by others in this thread, don't forget to explicitly set the width and height attributes in the svg like so:
<svg id="some_id" data-name="some_name" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 26 42"
width="26px" height="42px">
if you don't do that no js manipulation can help you as gmaps will not have a frame of reference and always use a standard size.
(i know it has been mentioned in some comments, but they are easy to miss. This information helped me in various cases)
Your example code is wrong. This works:
import datetime
datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.
Please follow the way like below:
.selectParent {_x000D_
width:120px;_x000D_
overflow:hidden; _x000D_
}_x000D_
.selectParent select { _x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 2px 25px 2px 2px; _x000D_
border: none; _x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
appearance: none; _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
direction: rtl;_x000D_
padding: 2px 2px 2px 25px;_x000D_
background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>
_x000D_
It doesn't make a lot of sense, the original GAC was already quite capable of storing different versions of assemblies. And there's little reason to assume a program will ever accidentally reference the wrong assembly, all the .NET 4 assemblies got the [AssemblyVersion] bumped up to 4.0.0.0. The new in-process side-by-side feature should not change this.
My guess: there were already too many .NET projects out there that broke the "never reference anything in the GAC directly" rule. I've seen it done on this site several times.
Only one way to avoid breaking those projects: move the GAC. Back-compat is sacred at Microsoft.
There are many ways to remove a key from a hash and get the remaining hash in Ruby.
.slice
=> It will return selected keys and not delete them from the original hash. Use slice!
if you want to remove the keys permanently else use simple slice
.
2.2.2 :074 > hash = {"one"=>1, "two"=>2, "three"=>3}
=> {"one"=>1, "two"=>2, "three"=>3}
2.2.2 :075 > hash.slice("one","two")
=> {"one"=>1, "two"=>2}
2.2.2 :076 > hash
=> {"one"=>1, "two"=>2, "three"=>3}
.delete
=> It will delete the selected keys from the original hash(it can accept only one key and not more than one).
2.2.2 :094 > hash = {"one"=>1, "two"=>2, "three"=>3}
=> {"one"=>1, "two"=>2, "three"=>3}
2.2.2 :095 > hash.delete("one")
=> 1
2.2.2 :096 > hash
=> {"two"=>2, "three"=>3}
.except
=> It will return the remaining keys but not delete anything from the original hash. Use except!
if you want to remove the keys permanently else use simple except
.
2.2.2 :097 > hash = {"one"=>1, "two"=>2, "three"=>3}
=> {"one"=>1, "two"=>2, "three"=>3}
2.2.2 :098 > hash.except("one","two")
=> {"three"=>3}
2.2.2 :099 > hash
=> {"one"=>1, "two"=>2, "three"=>3}
.delete_if
=> In case you need to remove a key based on a value. It will obviously remove the matching keys from the original hash.
2.2.2 :115 > hash = {"one"=>1, "two"=>2, "three"=>3, "one_again"=>1}
=> {"one"=>1, "two"=>2, "three"=>3, "one_again"=>1}
2.2.2 :116 > value = 1
=> 1
2.2.2 :117 > hash.delete_if { |k,v| v == value }
=> {"two"=>2, "three"=>3}
2.2.2 :118 > hash
=> {"two"=>2, "three"=>3}
.compact
=> It is used to remove all nil
values from the hash. Use compact!
if you want to remove the nil
values permanently else use simple compact
.
2.2.2 :119 > hash = {"one"=>1, "two"=>2, "three"=>3, "nothing"=>nil, "no_value"=>nil}
=> {"one"=>1, "two"=>2, "three"=>3, "nothing"=>nil, "no_value"=>nil}
2.2.2 :120 > hash.compact
=> {"one"=>1, "two"=>2, "three"=>3}
Results based on Ruby 2.2.2.
In the START menu type "regedit" to open the Registry editor
Go to "HKEY_LOCAL_MACHINE" on the left-hand side registry explorer/tree menu
Click "SOFTWARE" within the "HKEY_LOCAL_MACHINE" registries
Click "JavaSoft" within the "SOFTWARE" registries
Click "Java Runtime Environment" within the "JavaSoft" list of registries here you can see different versions of installed java
Click "Java Runtime Environment"- On right hand side you will get 4-5 rows . Please select "CurrentVersion" and right Click( select modify option) Change version to "1.7"
Now the magic has been completed
I'm really late to this party but here's how I did it:
SELECT SCN_TO_TIMESTAMP(MAX(ora_rowscn)) from myTable;
It's close enough for my purposes.
To avoid freezing when you call a function somewhere down the call stack that tries to re-join the current thread (which is stuck in a Wait), you need to do the following:
class Program
{
static void Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
List<TvChannel> list = Task.Run((Func<Task<List<TvChannel>>>)bs.GetList).Result;
}
}
(the cast is only required to resolve ambiguity)
The syntax for using an alias in an update statement on SQL Server is as follows:
UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;
The alias should not be necessary here though.
I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway)
There is package called rimraf that is very handy. It is the UNIX command rm -rf for node.
Nevertheless, it can be too powerful too because you can delete folders very easily using it. The following commands will delete the files inside the folder. If you remove the *, you will remove the log folder.
const rimraf = require('rimraf');
rimraf('./log/*', function () { console.log('done'); });
You should have a look at the scalax library : http://scalax.scalaforge.org/ In this library, there is a Logging trait, using sl4j as backend. By using this trait, you can log quite easily (just use the logger field in the class inheriting the trait).
have you tried:
C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\Backup
Script to get all backups in the last week can be found at:
http://wraithnath.blogspot.com/2010/12/how-to-find-all-database-backups-in.html
I have plenty more backup SQL scripts there also at
You can just sum
and set param axis=1
to sum the rows, this will ignore none numeric columns:
In [91]:
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
a b c d e
0 1 2 dd 5 8
1 2 3 ee 9 14
2 3 4 ff 1 8
If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:
In [98]:
col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:
df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
a b c d e
0 1 2 dd 5 3
1 2 3 ee 9 5
2 3 4 ff 1 7
try $conn = mysql_connect("localhost", "root")
or $conn = mysql_connect("localhost", "root", "")
You could create a color using the static FromArgb method:
Color redColor = Color.FromArgb(255, 0, 0);
You can also specify the alpha using the following overload.
You can use as below and also can use various color just assign
myLabel.textColor = UIColor.yourChoiceOfColor
Ex:
Swift
myLabel.textColor = UIColor.red
Objective-C
[myLabel setTextColor:[UIColor redColor]];
or you can click here to Choose the color,
https://www.ralfebert.de/ios-examples/uikit/swift-uicolor-picker/
You've probably tried this, but are your specifications such that you can do this?
DECLARE @city varchar(75)
DECLARE @count INT
SET @city = 'London'
SELECT @count = COUNT(*) FROM customers WHERE City = @city
//Inside the folder,
svn cleanup
svn update
//If are viewing any conflicts,
svn revert --depth infinity conflicted_filename
svn update conflicted_filename
svn update
I had to decide between the parseFloat() and Number() conversions before I could make toFixed() call. Here's an example of a number formatting post-capturing user input.
HTML:
<input type="number" class="dec-number" min="0" step="0.01" />
Event handler:
$('.dec-number').on('change', function () {
const value = $(this).val();
$(this).val(value.toFixed(2));
});
The above code will result in TypeError exception. Note that although the html input type is "number", the user input is actually a "string" data type. However, toFixed() function may only be invoked on an object that is a Number.
My final code would look as follows:
$('.dec-number').on('change', function () {
const value = Number($(this).val());
$(this).val(value.toFixed(2));
});
The reason I favor to cast with Number() vs. parseFloat() is because I don't have to perform an extra validation neither for an empty input string, nor NaN value. The Number() function would automatically handle an empty string and covert it to zero.
Use a close button in modal, this method is working fine:
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel" id="close_model">
After success use:
$('#model_form').trigger("reset"); // for cleaning a modal form
$('#close_model').click(); // for closing a modal with backdrop
You should not use the viewport meta tag at all if your design is not responsive. Misusing this tag may lead to broken layouts. You may read this article for documentation about why you should'n use this tag unless you know what you're doing. http://blog.javierusobiaga.com/stop-using-the-viewport-tag-until-you-know-ho
"user-scalable=no" also helps to prevent the zoom-in effect on iOS input boxes.
// Page.aspx //
// To count checklist item
int a = ChkMonth.Items.Count;
int count = 0;
for (var i = 0; i < a; i++)
{
if (ChkMonth.Items[i].Selected == true)
{
count++;
}
}
// Page.aspx.cs //
// To access checkbox list item's value //
string YrStrList = "";
foreach (ListItem listItem in ChkMonth.Items)
{
if (listItem.Selected)
{
YrStrList = YrStrList + "'" + listItem.Value + "'" + ",";
}
}
sMonthStr = YrStrList.ToString();
You can do it the DOM way as well:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}
Now in modern browsers, console.log()
can be used by pressing F12 key. The picture will be helpful to understand the concept clearly.
Dictionaries in python have no order. You could use a list of tuples as your data structure instead.
d = { 'a': 10, 'b': 20, 'c': 30}
newd = [('a',10), ('b',20), ('c',30)]
Then this code could be used to find the locations of keys with a specific value
locations = [i for i, t in enumerate(newd) if t[0]=='b']
>>> [1]
If you can't/won't use iterators and if you can't/won't use std::size_t
for the loop index, make a .size()
to int
conversion function that documents the assumption and does the conversion explicitly to silence the compiler warning.
#include <cassert>
#include <cstddef>
#include <limits>
// When using int loop indexes, use size_as_int(container) instead of
// container.size() in order to document the inherent assumption that the size
// of the container can be represented by an int.
template <typename ContainerType>
/* constexpr */ int size_as_int(const ContainerType &c) {
const auto size = c.size(); // if no auto, use `typename ContainerType::size_type`
assert(size <= static_cast<std::size_t>(std::numeric_limits<int>::max()));
return static_cast<int>(size);
}
Then you write your loops like this:
for (int i = 0; i < size_as_int(things); ++i) { ... }
The instantiation of this function template will almost certainly be inlined. In debug builds, the assumption will be checked. In release builds, it won't be and the code will be as fast as if you called size() directly. Neither version will produce a compiler warning, and it's only a slight modification to the idiomatic loop.
If you want to catch assumption failures in the release version as well, you can replace the assertion with an if statement that throws something like std::out_of_range("container size exceeds range of int")
.
Note that this solves both the signed/unsigned comparison as well as the potential sizeof(int)
!= sizeof(Container::size_type)
problem. You can leave all your warnings enabled and use them to catch real bugs in other parts of your code.
If you are new in JSP/Tomcat don't modify tomcat's xml files.
I assume you have already deployed web application. But to be sure, try these steps: - right click on your web application - select Run As / Run on Server, choose your Tomcat 7
These steps will deploy and run in the browser your application. Another idea to check if your Tomcat works correctly is to find path where tomcat exists (in eclipse plugin), and copy some working WAR file to webapps (not to wtpwebapps), and then try to run the app.
SOAP - Simple Object Access Protocol is a protocol!
REST - REpresentational State Transfer is an architectural style!
SOAP
is an XML protocol used to transfer messages, typically over HTTP
REST
and SOAP
are arguably not mutually exclusive. A RESTful architecture might use HTTP
or SOAP
or some other communication protocol. REST
is optimized for the web and thus HTTP
is a perfect choice. HTTP
is also the only protocol discussed in Roy Fielding's paper.
Although REST and SOAP are clearly very different, the question does illuminate the fact that REST
and HTTP
are often used in tandem. This is primarily due to the simplicity of HTTP and its very natural mapping to RESTful principles.
Client-Server Communication
Client-server architectures have a very distinct separation of concerns. All applications built in the RESTful style must also be client-server in princple.
Stateless
Each each client request to the server requires that its state be fully represented. The server must be able to completely understand the client request without using any server context or server session state. It follows that all state must be kept on the client. We will discuss stateless representation in more detail later.
Cacheable
Cache constraints may be used, thus enabling response data to to be marked as cacheable or not-cachable. Any data marked as cacheable may be reused as the response to the same subsequent request.
Uniform Interface
All components must interact through a single uniform interface. Because all component interaction occurs via this interface, interaction with different services is very simple. The interface is the same! This also means that implementation changes can be made in isolation. Such changes, will not affect fundamental component interaction because the uniform interface is always unchanged. One disadvantage is that you are stuck with the interface. If an optimization could be provided to a specific service by changing the interface, you are out of luck as REST prohibits this. On the bright side, however, REST is optimized for the web, hence incredible popularity of REST over HTTP!
The above concepts represent defining characteristics of REST and differentiate the REST architecture from other architectures like web services. It is useful to note that a REST service is a web service, but a web service is not necessarily a REST service.
See this blog post on REST Design Principals for more details on REST and the above stated bullets.
//====Single Class Reference used to retrieve object for fields and initial values. Performance enhancing only====
Class<?> reference = vector.get(0).getClass();
Object obj = reference.newInstance();
Field[] objFields = obj.getClass().getFields();
1
$("ul.rootlist > target-element")
2 $("ul.rootlist").find(target-element).eq(0) (only one instance)
3 $("ul.rootlist").children(target-element)
there are probably many other ways
os.path
provides many functions for manipulating paths/filenames. (docs)
os.path.splitext
takes a path and splits the file extension from the end of it.
import os
filepaths = ["/folder/soundfile.mp3", "folder1/folder/soundfile.flac"]
for fp in filepaths:
# Split the extension from the path and normalise it to lowercase.
ext = os.path.splitext(fp)[-1].lower()
# Now we can simply use == to check for equality, no need for wildcards.
if ext == ".mp3":
print fp, "is an mp3!"
elif ext == ".flac":
print fp, "is a flac file!"
else:
print fp, "is an unknown file format."
Gives:
/folder/soundfile.mp3 is an mp3! folder1/folder/soundfile.flac is a flac file!
CLI has some limit when ouput is displayed. I suggest to export output into local file:
$hive -e 'show partitions table;' > partitions
In this situation I would try:
$(document).on('click','.addproduct', function(){
//your code here
});
then, if you need to perform something in the other elements with the same class on click on one ot them you can loop through the elements:
$(document).on('click','.addproduct', function(){
$('.addproduct').each( function(){
//your code here
}
);
}
);
One thing not clearly covered is that microsoft sql is creating in the background an unique index for the added constraint
create table Customer ( id int primary key identity (1,1) , name nvarchar(128) )
--Commands completed successfully.
sp_help Customer
---> index
--index_name index_description index_keys
--PK__Customer__3213E83FCC4A1DFA clustered, unique, primary key located on PRIMARY id
---> constraint
--constraint_type constraint_name delete_action update_action status_enabled status_for_replication constraint_keys
--PRIMARY KEY (clustered) PK__Customer__3213E83FCC4A1DFA (n/a) (n/a) (n/a) (n/a) id
---- now adding the unique constraint
ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)
-- Commands completed successfully.
sp_help Customer
---> index
---index_name index_description index_keys
---PK__Customer__3213E83FCC4A1DFA clustered, unique, primary key located on PRIMARY id
---U_Name nonclustered, unique, unique key located on PRIMARY name
---> constraint
---constraint_type constraint_name delete_action update_action status_enabled status_for_replication constraint_keys
---PRIMARY KEY (clustered) PK__Customer__3213E83FCC4A1DFA (n/a) (n/a) (n/a) (n/a) id
---UNIQUE (non-clustered) U_Name (n/a) (n/a) (n/a) (n/a) name
as you can see , there is a new constraint and a new index U_Name
I think a more fundamental question should be asked is that why are you trying to test the private method in the first place. That is a code smell that you're trying to test the private method through that class' public interface whereas that method is private for a reason as it's an implementation detail. One should only be concerned with the behaviour of the public interface not on how it's implemented under the covers.
If I want to test the behaviour of the private method, by using common refactorings, I can extract its code into another class (maybe with package level visibility so ensure it's not part of a public API). I can then test its behaviour in isolation.
The product of the refactoring means that private method is now a separate class that has become a collaborator to the original class. Its behaviour will have become well understood via its own unit tests.
I can then mock its behaviour when I try to test the original class so that I can then concentrate on test the behaviour of that class' public interface rather than having to test a combinatorial explosion of the public interface and the behaviour of all its private methods.
I see this analogous to driving a car. When I drive a car I don't drive with the bonnet up so I can see that the engine is working. I rely on the interface the car provides, namely the rev counter and the speedometer to know the engine is working. I rely on the fact that the car actually moves when I press the gas pedal. If I want to test the engine I can do checks on that in isolation. :D
Of course testing private methods directly may be a last resort if you have a legacy application but I would prefer that legacy code is refactored to enable better testing. Michael Feathers has written a great book on this very subject. http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052
I would use list comprehension :
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
cart_prod = [(a,b,c) for a in somelists[0] for b in somelists[1] for c in somelists[2]]
None of the above solved this issue.
Someone had one project in my solution set to use x64 CPU in the build configuration. Changing it to Any CPU caused the build to use a new folder. I still don't know what process had (has) a lock on that file.
This can also happen if your package name is invalid.
For example, if your "package" is com.my-company
(which is not a valid Java package name due to the dash), IntelliJ will prevent you from creating a Java Class in that package.
While "".join is more pythonic, and the correct answer for this problem, it is indeed possible to use a for loop.
If this is a homework assignment (please add a tag if this is so!), and you are required to use a for loop then what will work (although is not pythonic, and shouldn't really be done this way if you are a professional programmer writing python) is this:
endstring = ""
mylist = ['first', 'second', 'other']
for word in mylist:
print "This is the word I am adding: " + word
endstring = endstring + word
print "This is the answer I get: " + endstring
You don't need the 'prints', I just threw them in there so you can see what is happening.
One could simply use this
MyControl.Margin = new System.Windows.Thickness(10, 0, 5, 0);
You could do it a couple of ways:
1. Use the forceUpdate()
method:
There are some glitches that may happen when using the forceUpdate()
method. One example is that it ignores the shouldComponentUpdate()
method and will re-render the view regardless of whether shouldComponentUpdate()
returns false. Because of this using forceUpdate() should be avoided when at all possible.
2. Passing this.state to the setState()
method
The following line of code overcomes the problem with the previous example:
this.setState(this.state);
Really all this is doing is overwriting the current state with the current state which triggers a re-rendering. This still isn't necessarily the best way to do things, but it does overcome some of the glitches you might encounter using the forceUpdate() method.
var xxxx : { [key:number]: MyType };
Difference between a Spy and a Mock
When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.
In the following example – we create a mock of the ArrayList class:
@Test
public void whenCreateMock_thenCreated() {
List mockedList = Mockito.mock(ArrayList.class);
mockedList.add("one");
Mockito.verify(mockedList).add("one");
assertEquals(0, mockedList.size());
}
As you can see – adding an element into the mocked list doesn’t actually add anything – it just calls the method with no other side-effect. A spy on the other hand will behave differently – it will actually call the real implementation of the add method and add the element to the underlying list:
@Test
public void whenCreateSpy_thenCreate() {
List spyList = Mockito.spy(new ArrayList());
spyList.add("one");
Mockito.verify(spyList).add("one");
assertEquals(1, spyList.size());
}
Here we can surely say that the real internal method of the object was called because when you call the size() method you get the size as 1, but this size() method isn’t been mocked! So where does 1 come from? The internal real size() method is called as size() isn’t mocked (or stubbed) and hence we can say that the entry was added to the real object.
Source: http://www.baeldung.com/mockito-spy + self notes.
As of XCode 7 this has become much easier.
Apple has documented the process on their site: https://developer.apple.com/library/ios/recipes/xcode_help-project_editor/RenamingaProject/RenamingaProject.html
Update: XCode 8 link: http://help.apple.com/xcode/mac/8.0/#/dev3db3afe4f
(Xcode 5 iOS 7) Universal App example for iOS 7 and Xcode 5. It is an open source project / example located here: Link to SimpleWebView (Project Zip and Source Code Example)
You can also use CASE - my code below checks for both null values and empty strings, and adds a seperator only if there is a value to follow:
SELECT OrganisationName,
'Address' =
CASE WHEN Addr1 IS NULL OR Addr1 = '' THEN '' ELSE Addr1 END +
CASE WHEN Addr2 IS NULL OR Addr2 = '' THEN '' ELSE ', ' + Addr2 END +
CASE WHEN Addr3 IS NULL OR Addr3 = '' THEN '' ELSE ', ' + Addr3 END +
CASE WHEN County IS NULL OR County = '' THEN '' ELSE ', ' + County END
FROM Organisations
This can be done without explicitly using hooks provided you add a prop to your component and a state to the stateless component's parent component:
const ParentComponent = props => {
const [updateNow, setUpdateNow] = useState(true)
const updateFunc = () => {
setUpdateNow(!updateNow)
}
const MyComponent = props => {
return (<div> .... </div>)
}
const MyButtonComponent = props => {
return (<div> <input type="button" onClick={props.updateFunc} />.... </div>)
}
return (
<div>
<MyComponent updateMe={updateNow} />
<MyButtonComponent updateFunc={updateFunc}/>
</div>
)
}
Your code concatenates three strings, then converts the result to a number.
You need to convert each variable to a number by calling parseFloat()
around each one.
total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);
I use Eclipse for cross compiling and I have to add the explicit directories for some of the standard C++ libraries. Right click your project and select Properties. You'll get the dialog shown in the image. Follow the image and use the + icon to explicitly add the paths to your C++ libraries.
Source : http://git-scm.com/book/en/Git-Basics-Undoing-Things
git checkout -- modifiedfile.java
1)$ git status
you will see the modified file
2)$git checkout -- modifiedfile.java
3)$git status
I tried many ways to find the file type I wanted, and here are my results when done.
public static void main( String args[]){
final String dir2 = System.getProperty("user.name"); \\get user name
String path = "C:\\Users\\" + dir2;
digFile(new File(path)); \\ path is file start to dig
for (int i = 0; i < StringFile.size(); i++) {
System.out.println(StringFile.get(i));
}
}
private void digFile(File dir) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".mp4");
}
};
String[] children = dir.list(filter);
if (children == null) {
return;
} else {
for (int i = 0; i < children.length; i++) {
StringFile.add(dir+"\\"+children[i]);
}
}
File[] directories;
directories = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory();
}
public boolean accept(File dir, String name) {
return !name.endsWith(".mp4");
}
});
if(directories!=null)
{
for (File directory : directories) {
digFile(directory);
}
}
}
Much like the manual, use an equals (=
) sign in your definition of the parameters:
function dosomething($var1, $var2, $var3 = 'somevalue'){
// Rest of function here...
}
Try this:
SELECT CUSTOMER_ID, MAX(FIRSTNAME) AS FIRSTNAME, MAX(LASTNAME) AS LASTNAME ...
FROM
(
SELECT CUSTOMER_ID,
CASE WHEN DBCOLUMNNAME='FirstName' then DATA ELSE NULL END AS FIRSTNAME,
CASE WHEN DBCOLUMNNAME='LastName' then DATA ELSE NULL END AS LASTNAME,
... and so on ...
GROUP BY CUSTOMER_ID
) TEMP
GROUP BY CUSTOMER_ID
Just want to add (since I googled for this problem, and this question popped first) IE6 and other versions render PNG transparency very ugly. If you have PNG image that is alpha transparent (32bit) and want to show it over some complex background, you can never do this simply in IE. But you can display it correctly over a single colour background as long as you set that PNG images (or divs) CSS attribute background-color
to be the same as the parents background-color
.
So this will render black where image should be alpha transparent, and transparent where alpha byte is 0:
<div style="background-color: white;">
<div style="background-image: url(image.png);"/>
</div>
And this will render correctly (note the background-color attribute in the inner div):
<div style="background-color: white;">
<div style="background-color: white; background-image: url(image.png);"/>
</div>
Complex alternative to this which enables alpha image over a complex background is to use AlphaImageLoader
to load up and render image of the certain opacity. This works until you want to change that opacity... Problem in detail and its solution (javascript) can be found HERE.
I wanted to downgrade from API 23 to 22 and got this error. I had to change all build.gradle
files in a project in order to compile.
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.yourapp.app"
minSdkVersion 14
targetSdkVersion 22
}
...
dependencies {
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:design:22.2.1'
compile 'com.google.android.gms:play-services-gcm:10.0.1'
}
To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:
Open Source:
Paid:
** - means I didn't try those so I can't really recommend it but other users suggested it..
This worked for me:
export _JAVA_OPTIONS="-Xmx1g"
It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:
java -XshowSettings:vm
and it will tell you:
Picked up _JAVA_OPTIONS: -Xmx1g
labelName.font = labelName.font.withSize(15)
You must use OverridePendingTransition method to achieve it, which is in the Activity class. Sample Animations in the apidemos example's res/anim folder. Check it. More than check the demo in ApiDemos/App/Activity/animation.
Example:
@Override
public void onResume(){
// TODO LC: preliminary support for views transitions
this.overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}
You cannot use the SQL Server agent in SQL Server Express. The way I have done it before is to create a SQL Script, and then run it as a scheduled task each day, you could have multiple scheduled tasks to fit in with your backup schedule/retention. The command I use in the scheduled task is:
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -i"c:\path\to\sqlbackupScript.sql"
You can use the unicode of a non breaking space :
p:before { content: "\00a0 "; }
See JSfiddle demo
[style improved by @Jason Sperske]
I am using other way to do that and it sounds realistic. What I do is i got the PID of the process by getpid() function and then I use /proc/pid/stat file. I believe the 23rd column of the stat file is the vmsize (look at the Don post). You may read the vmsize from the file wherever you need in the code. In case you wonder how much a snippet of a code may use memory, you may read that file once before that snippet and once after and you can subtract them from each other.
For Multiple columns you can use code similar to one given below.I was just going through this and found answer to check multiple columns in Datatable.
private bool IsAllColumnExist(DataTable tableNameToCheck, List<string> columnsNames)
{
bool iscolumnExist = true;
try
{
if (null != tableNameToCheck && tableNameToCheck.Columns != null)
{
foreach (string columnName in columnsNames)
{
if (!tableNameToCheck.Columns.Contains(columnName))
{
iscolumnExist = false;
break;
}
}
}
else
{
iscolumnExist = false;
}
}
catch (Exception ex)
{
}
return iscolumnExist;
}
Not sure if you've fixed it but in your httpd.conf
Check to see your User/Group settings. Usually it will be set to
User www Group www
If so change it to your name/group
User Greg group staff
i = Your_int_value
Write bytes value like this for example:
the_file.write(i.to_bytes(2,"little"))
Depend of you int value size and the bit order your prefer
If you don't need to display exact result "running" / "not runnuning", you could simply:
ps notepad -ErrorAction SilentlyContinue | kill -PassThru
If the process was not running, you'll get no results. If it was running, you'll receive get-process
output, and the process will be stopped.
I found following way which can be used if you KNOW name of lock
select IS_USED_LOCK('lockname');
however i not found any info about how to list all names.
RichTextBox rtf = new RichTextBox();
System.IO.MemoryStream stream = new System.IO.MemoryStream(ASCIIEncoding.Default.GetBytes(yourText));
rtf.Selection.Load(stream, DataFormats.Rtf);
OR
rtf.Selection.Text = yourText;
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
If you want a video first frame as a thumbnail, than you can use
Add #t=0.1 to your video source, like below
<video width="320" height="240" controls>
<source src="video.mp4#t=0.1" type="video/mp4">
</video>
NOTE: make sure about your video type(ex: mp4, ogg, webm etc)
I met same problem, though I didn't what caused this. Whatever, i find some clues and fixed finally.
When I open SDK and AVD manager, but find the AVD version(2.3.3) is not same with android lib version(2.3). So I create a new AVD with 2.3.
I fixed it by the following steps: 1. Open windows task manager and kill adb.exe process. 2. Close eclipse and restart it. Then it works.
Hope it helps.
Here is how to get the selected object and object matching code for the double clicked listview item in a WPF listview:
/// <summary>
/// Get the object from the selected listview item.
/// </summary>
/// <param name="LV"></param>
/// <param name="originalSource"></param>
/// <returns></returns>
private object GetListViewItemObject(ListView LV, object originalSource)
{
DependencyObject dep = (DependencyObject)originalSource;
while ((dep != null) && !(dep.GetType() == typeof(ListViewItem)))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return null;
object obj = (Object)LV.ItemContainerGenerator.ItemFromContainer(dep);
return obj;
}
private void lvFiles_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
object obj = GetListViewItemObject(lvFiles, e.OriginalSource);
if (obj.GetType() == typeof(MyObject))
{
MyObject MyObject = (MyObject)obj;
// Add the rest of your logic here.
}
}
The Collection interface includes the toArray() method to convert a new collection into an array. There are two forms of this method. The no argument version will return the elements of the collection in an Object array: public Object[ ] toArray(). The returned array cannot cast to any other data type. This is the simplest version. The second version requires you to pass in the data type of the array you’d like to return: public Object [ ] toArray(Object type[ ]).
public static void main(String[] args) {
List<String> l=new ArrayList<String>();
l.add("A");
l.add("B");
l.add("C");
Object arr[]=l.toArray();
for(Object a:arr)
{
String str=(String)a;
System.out.println(str);
}
}
for reference, refer this link http://techno-terminal.blogspot.in/2015/11/how-to-obtain-array-from-arraylist.html
Maps never take into consideration the whole map. My guess is:- 1. According to your location, they load a place and the landmarks on that place. 2. When you search the destination, thats when they load the other part of the map and make a graph out of two places and then apply the shortest path algorithms.
Also, there is an important technique Dynamic programming which i suspect is used in the calculation of shortest paths. You can refer to that as well.
I went through the answers above. The "as_matrix()" method works but its obsolete now. For me, What worked was ".to_numpy()".
This returns a multidimensional array. I'll prefer using this method if you're reading data from excel sheet and you need to access data from any index. Hope this helps :)
Since everything is an expression, and thus results in a value, you can just use if/else
.
a = if true then 5 else 10
a = if false then 5 else 10
You can see more about expression examples here.
You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key]
you know whether the dictionary contains the key, because the Optional that you get back is not nil
(and it contains the value).
So, if you just want to answer the question whether the dictionary contains the key, ask:
let keyExists = dict[key] != nil
If you want the value and you know the dictionary contains the key, say:
let val = dict[key]!
But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let
:
if let val = dict[key] {
// now val is not nil and the Optional has been unwrapped, so use it
}
If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149
To summarize, open up a Terminal window and type the following command:
defaults write NSGlobalDomain KeyRepeat -int 0
More detail from the article:
Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:
defaults write NSGlobalDomain KeyRepeat -int 0
Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.
You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.
The python error says that wordInput
is not an iterable -> it is of NoneType.
If you print wordInput
before the offending line, you will see that wordInput
is None
.
Since wordInput
is None
, that means that the argument passed to the function is also None
. In this case word
. You assign the result of pickEasy
to word
.
The problem is that your pickEasy
function does not return anything. In Python, a method that didn't return anything returns a NoneType.
I think you wanted to return a word
, so this will suffice:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
You could wrap the not-bold text into a span and give the span the following properties:
.notbold{
font-weight:normal
}?
and
<h1>**This text should be bold**, <span class='notbold'>but this text should not</span></h1>
See: http://jsfiddle.net/MRcpa/1/
Use <span>
when you want to change the style of elements without placing them in a new block-level element in the document.
You will use the following query:
SELECT * FROM [table] GROUP BY NUMBER;
Where [table]
is the name of the table.
This provides a unique listing for the NUMBER
column however the other columns may be meaningless depending on the vendor implementation; which is to say they may not together correspond to a specific row or rows.
From sourcetree gui click on working directoy, right-click the file(s) that you want to discard, then click on Discard
In many cases you're better off using CSS transitions for this, and in old browsers the easing will simply be instant. Most animations (like fade in/out) are very trivial to implement and the browser does all the legwork for you. https://developer.mozilla.org/en/docs/Web/CSS/transition
Here answer for your code as whole:
key =10
files = ("ME%i.txt" % i for i in range(key))
#opening
files = [ open(filename, 'w') for filename in files]
# processing
for i, file in zip(range(key),files):
file.write(str(i))
# closing
for openfile in files:
openfile.close()
// Store original location in loc like: http://test.com/one/ (ending slash)
var loc = location.href;
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
targetValue = one
If your url looks like:
or
or
Then loc ends up looking like: http://test.com/one
Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
The few lines you posted from your script look okay to me. It's probably something a bit deeper.
You need to find which line is giving you this error. Add set -xv
to the top of your script. This will print out the line number and the command that's being executed to STDERR. This will help you identify where in your script you're getting this particular error.
BTW, do you have a shebang at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had #! /bin/bash
on top, but your bash interpreter is located in /usr/bin/bash
, you'll see this error.
New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
Two ways:
Tank´s Yogihosting
I have in my database one goups of tables from Open Streep Maps and I tested successful.
Distance work fine in meters.
SET @orig_lat=-8.116137;
SET @orig_lon=-34.897488;
SET @dist=1000;
SELECT *,(((acos(sin((@orig_lat*pi()/180)) * sin((dest.latitude*pi()/180))+cos((@orig_lat*pi()/180))*cos((dest.latitude*pi()/180))*cos(((@orig_lon-dest.longitude)*pi()/180))))*180/pi())*60*1.1515*1609.344) as distance FROM nodes AS dest HAVING distance < @dist ORDER BY distance ASC LIMIT 100;
Well, it's unfortunate that you didn't post your own code too, so that it could be corrected.
Anyway, here's my own solution to this:
@echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=result.txt
>nul copy nul %OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
set SERVER_ADDRESS=ADDRESS N/A
for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS=%%y
if %%x==Reply set SERVER_ADDRESS=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
)
The outer loop iterates through the hosts and the inner loop parses the ping
output. The first two if
statements handle the two possible cases of IP address resolution:
If the host IP address cannot be resolved, the address is set to "ADDRESS N/A".
Hope this helps.
If you can create a string xml you can easily transform it to the xml document object e.g. -
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
e.printStackTrace();
}
You can use the document object and xml parsing libraries or xpath to get back the ip address.
To use ASCII with accents:
var str = str.replace(/[^\x00-\xFF]/g, "");
Edited to show a possibility not mentioned here, because my original answer was far from related to the OP's question.
preg_match(); Is possible to use. However, in most applications it will be much more heavy to use than other answers here.
if (preg_match("/true/i", "true PHP is a web scripting language of choice.")) {
echo "<br><br>Returned true";
} else {
echo "<br><br>Returned False";
}
/(?:true)|(?:1)/i
Can also be used if needed in certain situations. It will not return correctly when it evaluates a string containing both "false" and "1".
Here's a slightly more compact solution to the problem:
const typeSizes = {
"undefined": () => 0,
"boolean": () => 4,
"number": () => 8,
"string": item => 2 * item.length,
"object": item => !item ? 0 : Object
.keys(item)
.reduce((total, key) => sizeOf(key) + sizeOf(item[key]) + total, 0)
};
const sizeOf = value => typeSizes[typeof value](value);
The answer given by H Dog is great, but this approach was actually giving me some modal flicker in Internet Explorer 11. Bootstrap will first hide the modal removing the 'modal-open' class, and then (using H Dogs solution) we add the 'modal-open' class again. I suspect this is somehow causing the flicker I was seeing, maybe due to some slow HTML/CSS rendering.
Another solution is to prevent bootstrap in removing the 'modal-open' class from the body element in the first place. Using Bootstrap 3.3.7, this override of the internal hideModal function works perfectly for me.
$.fn.modal.Constructor.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
if ($(".modal:visible").length === 0) {
that.$body.removeClass('modal-open')
}
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
In this override, the 'modal-open' class is only removed when there are no visible modals on the screen. And you prevent one frame of removing and adding a class to the body element.
Just include the override after bootstrap have been loaded.
If you get some compile errors for example:
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
.
private void methodThatRequiresAPI11() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.ARGB_8888; // API Level 1
options.inSampleSize = 8; // API Level 1
options.inBitmap = bitmap; // **API Level 11**
//...
}
You get compile error:
Field requires API level 11 (current min is 10): android.graphics.BitmapFactory$Options#inBitmap
Since version 17 of Android Development Tools (ADT) there is one new and very useful annotation @TargetApi
that can fix this very easily. Add it before the method that is enclosing the problematic declaration:
@TargetApi
private void methodThatRequiresAPI11() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.ARGB_8888; // API Level 1
options.inSampleSize = 8; // API Level 1
// This will avoid exception NoSuchFieldError (or NoSuchMethodError) at runtime.
if (Integer.valueOf(android.os.Build.VERSION.SDK) >= android.os.Build.VERSION_CODES.HONEYCOMB) {
options.inBitmap = bitmap; // **API Level 11**
//...
}
}
No compile errors now and it will run !
EDIT: This will result in runtime error on API level lower than 11. On 11 or higher it will run without problems. So you must be sure you call this method on an execution path guarded by version check. TargetApi just allows you to compile it but you run it on your own risk.
I had Java 7 and 8 installed and I want to redirect to java 7 but the java version in my cmd prompt window shows Java 8.
Added Java 7 bin directory path (C:\Program Files\Java\jdk1.7.0_10\bin) to PATH variable at the end, but did not work out and shows Java 8. So I changed the Java 7 path to the starting of the path value and it worked.
Opened a new cmd prompt window and checked my java version and now it shows Java 7
Merge a branch into new one (squash) and remove the files not needed:
git checkout master
git checkout -b <branch>
git merge --squash <source-branch-with-many-commits>
git reset HEAD <not-needed-file-1>
git checkout -- <not-needed-file-1>
git reset HEAD <not-needed-file-2>
git checkout -- <not-needed-file-2>
git commit
Well, no. Why there should be? Just discard the string if you don't need it anymore.
&str
is more useful than String
when you need to only read a string, because it is only a view into the original piece of data, not its owner. You can pass it around more easily than String
, and it is copyable, so it is not consumed by the invoked methods. In this regard it is more general: if you have a String
, you can pass it to where an &str
is expected, but if you have &str
, you can only pass it to functions expecting String
if you make a new allocation.
You can find more on the differences between these two and when to use them in the official strings guide.
Another approach is to use pickle. See this answer to a duplicate of this question.
File outputfile = new File("image.jpg");
ImageIO.write(bufferedImage, "jpg", outputfile);
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
Imports System.Net.NetworkInformation
Public Function PingHost(ByVal nameOrAddress As String) As Boolean
Dim pingable As Boolean = False
Dim pinger As Ping
Dim lPingReply As PingReply
Try
pinger = New Ping()
lPingReply = pinger.Send(nameOrAddress)
MessageBox.Show(lPingReply.Status)
If lPingReply.Status = IPStatus.Success Then
pingable = True
Else
pingable = False
End If
Catch PingException As Exception
pingable = False
End Try
Return pingable
End Function
This regex is very short and sweet for working.
/^([+]\d{2})?\d{10}$/
Ex: +910123456789 or 0123456789
-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length
This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.
if you want to add the space between than you can use the
[ ]
here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex
/^([+]\d{2}[ ])?\d{10}$/
Ex: +91 0123456789
Thanks ask any question if you have.
There is no such method as java.util.Random.getRandomDigits
.
To get a random number use nextInt:
return random.nextInt(10 ** num)
Also you should create the random object once when your application starts:
Random random = new Random()
You should not create a new random object every time you want a new random number. Doing this destroys the randomness.
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
Please just go to your terminal then type:
$rm __pycache__
and it will be removed.
Servlet is a java class to respond a HTTP request and produce a HTTP response...... when we make a page with the use of HTML then it would be a static page so to make it dynamic we use SERVLET {in simple words one can understand} To make use of servlet is overcomed by JSP it uses the code and HTML tag both in itself..
If you want to write this compactly all you need is:
var i = 0;
for (;yourElement.parentNode[i]!==yourElement;i++){}
indexOfYourElement = i;
We just cycle through the elements in the parent node, stopping when we find your element.
You can also easily do:
for (;yourElement.parentNode.getElementsByTagName("li")[i]!==yourElement;i++){}
if that's all you want to look through.
just go to the window bottom tray click on wamp icon ,click mysql->my.ini,then there is option ;sql-mode="" uncomment this make it like sql-mode="" and restart wamp worked for me
I found solution for Spring 3.1. with using @ResponseBody annotation. Here is example of controller using Json output:
@RequestMapping(value = "/getDealers", method = RequestMethod.GET,
produces = "application/json; charset=utf-8")
@ResponseBody
public String sendMobileData() {
}
You can update your python version to 3.8 in conda using the command
conda install -c anaconda python=3.8
as per https://anaconda.org/anaconda/python. Though not all packages support 3.8 yet, running
conda update --all
may resolve some dependency failures. You can also create a new environment called py38 using this command
conda create -n py38 python=3.8
Edit - note that the conda install
option will potentially take a while to solve the environment, and if you try to abort this midway through you will lose your Python installation (usually this means it will resort to non-conda pre-installed system Python installation).
I use this query here to get all relevant info (relevant for me, at least :-)) from SQL Server:
SELECT
SERVERPROPERTY('productversion') as 'Product Version',
SERVERPROPERTY('productlevel') as 'Product Level',
SERVERPROPERTY('edition') as 'Product Edition',
SERVERPROPERTY('buildclrversion') as 'CLR Version',
SERVERPROPERTY('collation') as 'Default Collation',
SERVERPROPERTY('instancename') as 'Instance',
SERVERPROPERTY('lcid') as 'LCID',
SERVERPROPERTY('servername') as 'Server Name'
That gives you an output something like this:
Product Version Product Level Product Edition CLR Version
10.0.2531.0 SP1 Developer Edition (64-bit) v2.0.50727
Default Collation Instance LCID Server Name
Latin1_General_CI_AS NULL 1033 *********
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
Another way to replace all instances of a string is to use the new (as of August 2020) String.prototype.replaceAll()
method.
It accepts either a string or RegEx as its first argument, and replaces all matches found with its second parameter, either a string or a function to generate the string.
As far as support goes, at time of writing, this method has adoption in current versions of all major desktop browsers* (even Opera!), except IE. For mobile, iOS SafariiOS 13.7+, Android Chromev85+, and Android Firefoxv79+ are all supported as well.
* This includes Edge/ Chrome v85+, Firefox v77+, Safari 13.1+, and Opera v71+
It'll take time for users to update to supported browser versions, but now that there's wide browser support, time is the only obstacle.
References:
You can test your current browser in the snippet below:
//Example coutesy of MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
const regex = /dog/gi;
try {
console.log(p.replaceAll(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
console.log(p.replaceAll('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
console.log('Your browser is supported!');
} catch (e) {
console.log('Your browser is unsupported! :(');
}
_x000D_
.as-console-wrapper: {
max-height: 100% !important;
}
_x000D_
You cannot - a XSD describes the DATA aspects e.g. of a webservice - the WSDL describes the FUNCTIONS of the web services (method calls). You cannot typically figure out the method calls from your data alone.
These are really two separate, distinctive parts of the equation. For simplicity's sake you would often import your XSD definitions into the WSDL in the <wsdl:types>
tag.
(thanks to Cheeso for pointing out my inaccurate usage of terms)
Solution using just POST - no $_SESSION
page1.php
<form action="page2.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
page2.php
<?php
// this page outputs the contents of the textarea if posted
$textarea1 = ""; // set var to avoid errors
if(isset($_POST['textarea1'])){
$textarea1 = $_POST['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
Solution using $_SESSION and POST
page1.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
$textarea1 = "";
if(isset($_POST['textarea1'])){
$_SESSION['textarea1'] = $_POST['textarea1'];
}
?>
<form action="page1.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>
page2.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
// this page outputs the textarea1 from the session IF it exists
$textarea1 = ""; // set var to avoid errors
if(isset($_SESSION['textarea1'])){
$textarea1 = $_SESSION['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
WARNING!!! - This contains no validation!!!
Assuming that your table name is city
and your existing Primary Key is pk_city
, you should be able to do the following:
ALTER TABLE city
DROP CONSTRAINT pk_city;
ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);
Make sure that there are no records where time
is NULL
, otherwise you won't be able to re-create the constraint.
I can't speak for the 2nd or 3rd, but if you install Node first, Sublime-HTMLPrettify works pretty well. You have to setup your own key shortcut once it is installed. One thing I noticed on Windows, you may need to edit your path for Node in the %PATH% variable if it is already long (I think the limit is 1024 for the %PATH% variable, and anything after that is ignored.)
There is a Windows bug, but in the issues there is a fix for it. You'll need to edit the HTMLPrettify.py file - https://github.com/victorporof/Sublime-HTMLPrettify/issues/12
Disclaimer: This is not a solution, it is more of a hack to test out something. User-defined functions cannot be used to perform actions that modify the database state.
I found one way to make insert or update using sqlcmd.exe so you need just to replace the code inside @sql
variable.
CREATE FUNCTION [dbo].[_tmp_func](@orderID NVARCHAR(50))
RETURNS INT
AS
BEGIN
DECLARE @sql varchar(4000), @cmd varchar(4000)
SELECT @sql = 'INSERT INTO _ord (ord_Code) VALUES (''' + @orderID + ''') '
SELECT @cmd = 'sqlcmd -S ' + @@servername +
' -d ' + db_name() + ' -Q "' + @sql + '"'
EXEC master..xp_cmdshell @cmd, 'no_output'
RETURN 1
END
I created a workaround with directive:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}]);
And the input tag becomes:
<input type="file" fileread="vm.uploadme" />
Or if just the file definition is needed:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
scope.$apply(function () {
scope.fileread = changeEvent.target.files[0];
// or all selected files:
// scope.fileread = changeEvent.target.files;
});
});
}
}
}]);
You can't tell from the JAR file itself, necessarily.
Download a hex editor and open one of the class files inside the JAR and look at byte offsets 4 through 7. The version information is built in.
http://en.wikipedia.org/wiki/Java_class_file
Note: As mentioned in the comment below,
those bytes tell you what version the class has been compiled FOR, not what version compiled it.
There are lot of wonderful answers on this thread already. However I wanted to share my experience when I tried to solve "remove nth element from array" in ES5 context.
JavaScript arrays have different methods to add/remove elements from start or end. These are:
arr.push(ele) - To add element(s) at the end of the array
arr.unshift(ele) - To add element(s) at the beginning of the array
arr.pop() - To remove last element from the array
arr.shift() - To remove first element from the array
Essentially none of the above methods can be used directly to remove nth element from the array.
A fact worth noting is that this is in contrast with java iterator's using which it is possible to remove nth element for a collection while iterating.
This basically leaves us with only one array method Array.splice
to perform removal of nth element (there are other things you could do with these methods as well, but in the context of this question I am focusing on removal of elements):
Array.splice(index,1) - removes the element at the index
Here is the code copied from original answer (with comments):
var arr = ["one", "two", "three", "four"];_x000D_
var i = arr.length; //initialize counter to array length _x000D_
_x000D_
while (i--) //decrement counter else it would run into IndexOutBounds exception_x000D_
{_x000D_
if (arr[i] === "four" || arr[i] === "two") {_x000D_
//splice modifies the original array_x000D_
arr.splice(i, 1); //never runs into IndexOutBounds exception _x000D_
console.log("Element removed. arr: ");_x000D_
_x000D_
} else {_x000D_
console.log("Element not removed. arr: ");_x000D_
}_x000D_
console.log(arr);_x000D_
}
_x000D_
Another noteworthy method is Array.slice
. However the return type of this method is the removed elements. Also this doesn't modify original array. Modified code snippet as follows:
var arr = ["one", "two", "three", "four"];_x000D_
var i = arr.length; //initialize counter to array length _x000D_
_x000D_
while (i--) //decrement counter _x000D_
{_x000D_
if (arr[i] === "four" || arr[i] === "two") {_x000D_
console.log("Element removed. arr: ");_x000D_
console.log(arr.slice(i, i + 1));_x000D_
console.log("Original array: ");_x000D_
console.log(arr);_x000D_
}_x000D_
}
_x000D_
Having said that, we can still use Array.slice
to remove nth element as shown below. However it is lot more code (hence inefficient)
var arr = ["one", "two", "three", "four"];_x000D_
var i = arr.length; //initialize counter to array length _x000D_
_x000D_
while (i--) //decrement counter _x000D_
{_x000D_
if (arr[i] === "four" || arr[i] === "two") {_x000D_
console.log("Array after removal of ith element: ");_x000D_
arr = arr.slice(0, i).concat(arr.slice(i + 1));_x000D_
console.log(arr);_x000D_
}_x000D_
_x000D_
}
_x000D_
The
Array.slice
method is extremely important to achieve immutability in functional programming à la redux
This site has an example: Using Powershell for MD5 Checksums. It uses the .NET framework to instantiate an instance of the MD5 hash algorithm to calculate the hash.
Here's the code from the article, incorporating Stephen's comment:
param
(
$file
)
$algo = [System.Security.Cryptography.HashAlgorithm]::Create("MD5")
$stream = New-Object System.IO.FileStream($Path, [System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read)
$md5StringBuilder = New-Object System.Text.StringBuilder
$algo.ComputeHash($stream) | % { [void] $md5StringBuilder.Append($_.ToString("x2")) }
$md5StringBuilder.ToString()
$stream.Dispose()
I think stash -p
is probably the choice you want, but just in case you run into other even more tricky things in the future, remember that:
Stash
is really just a very simple alternative to the only slightly more complex branch
sets. Stash is very useful for moving things around quickly, but you can accomplish more complex things with branches without that much more headache and work.
# git checkout -b tmpbranch
# git add the_file
# git commit -m "stashing the_file"
# git checkout master
go about and do what you want, and then later simply rebase
and/or merge
the tmpbranch. It really isn't that much extra work when you need to do more careful tracking than stash will allow.
A simple working code to download a file with SSH.NET library is:
using (Stream fileStream = File.Create(@"C:\target\local\path\file.zip"))
{
sftp.DownloadFile("/source/remote/path/file.zip", fileStream);
}
See also Downloading a directory using SSH.NET SFTP in C#.
To explain, why your code does not work:
The second parameter of SftpClient.DownloadFile
is a stream to write a downloaded contents to.
You are passing in a read stream instead of a write stream. And moreover the path you are opening read stream with is a remote path, what cannot work with File
class operating on local files only.
Just discard the File.OpenRead
line and use a result of previous File.OpenWrite
call instead (that you are not using at all now):
Stream file1 = File.OpenWrite(localFileName);
sftp.DownloadFile(file.FullName, file1);
Or even better, use File.Create
to discard any previous contents that the local file may have.
I'm not sure if your localFileName
is supposed to hold full path, or just file name. So you may need to add a path too, if necessary (combine localFileName
with sDir
?)
ResultSet rs = ps.executeQuery();
int rowcount = 0;
if (rs.last()) {
rowcount = rs.getRow();
rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
}
while (rs.next()) {
// do your standard per row stuff
}
I wrote an open source library called AlgoKit, available via NuGet. It contains:
The code has been extensively tested. I definitely recommend you to give it a try.
var comparer = Comparer<int>.Default;
var heap = new PairingHeap<int, string>(comparer);
heap.Add(3, "your");
heap.Add(5, "of");
heap.Add(7, "disturbing.");
heap.Add(2, "find");
heap.Add(1, "I");
heap.Add(6, "faith");
heap.Add(4, "lack");
while (!heap.IsEmpty)
Console.WriteLine(heap.Pop().Value);
The optimal choice of implementation is strongly input-dependent — as Larkin, Sen, and Tarjan show in A back-to-basics empirical study of priority queues, arXiv:1403.0252v1 [cs.DS]. They tested implicit d-ary heaps, pairing heaps, Fibonacci heaps, binomial heaps, explicit d-ary heaps, rank-pairing heaps, quake heaps, violation heaps, rank-relaxed weak heaps, and strict Fibonacci heaps.
AlgoKit features three types of heaps that appeared to be most efficient among those tested.
For a relatively small number of elements, you would likely be interested in using implicit heaps, especially quaternary heaps (implicit 4-ary). In case of operating on larger heap sizes, amortized structures like binomial heaps and pairing heaps should perform better.
I use a combination of json.get() and instanceof to read in values that might be either integers or integer strings.
These three test cases illustrate:
int val;
Object obj;
JSONObject json = new JSONObject();
json.put("number", 1);
json.put("string", "10");
json.put("other", "tree");
obj = json.get("number");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);
obj = json.get("string");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);
try {
obj = json.get("other");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
} catch (Exception e) {
// throws exception
}
For Windows users looking for solution of same problem. I just repleced
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"
in my /conf/extra/http?-xampp.conf