When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.
In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.
It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.
As a note for the future: if you need a sentence parsed out and tag it as linguistics
(and syntax
or whatnot, if that's available), someone can probably parse it out for you and guide you through it.
After, or in-between your text, use the
(non-breaking space) extended HTML character.
EG 1 :
This is an example paragraph.
This is the next line.
JVM : A specification which describes the the way/resources to run a java program. Actually executes the byte code and make java platform independent. In doing so, it is different for different platform. JVM for windows cannot work as JVM for UNIX.
JRE : Implementation of JVM. (JVM + run time libraries)
JDK : JRE + java compiler and other essential tools to build a java program from scratch
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
I figure you fixed your problem, but I don't see the solution here that helped me, so here it is.
Type in terminal:
echo "" > ~/.ssh/known_hosts
That will empty your known_hosts
file, and you'll have to add every host you used and have connected to, but it solved the problem.
The best solution is the word-spacing
property.
Add the <p>
in a container with a specific size (example 300px
) and after you have to add that size as the value in the word-spacing.
HTML
<div>
<p>Sentence Here</p>
</div>
CSS
div {
width: 300px;
}
p {
width: auto;
text-align: center;
word-spacing: 300px;
}
In this way, your sentence will be always broken and set in a column, but the with of the paragraph will be dynamic.
Here an example Codepen
We can do it by searching the text in options of dropdown list and then by setting selected attribute to true.
This code is run in every environment.
$("#numbers option:contains(" + inputText + ")").attr('selected', 'selected');
You can use ExecutorService.invokeAll
method, It will execute all task and wait till all threads finished their task.
Here is complete javadoc
You can also user overloaded version of this method to specify the timeout.
Here is sample code with ExecutorService.invokeAll
public class Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService service = Executors.newFixedThreadPool(3);
List<Callable<String>> taskList = new ArrayList<>();
taskList.add(new Task1());
taskList.add(new Task2());
List<Future<String>> results = service.invokeAll(taskList);
for (Future<String> f : results) {
System.out.println(f.get());
}
}
}
class Task1 implements Callable<String> {
@Override
public String call() throws Exception {
try {
Thread.sleep(2000);
return "Task 1 done";
} catch (Exception e) {
e.printStackTrace();
return " error in task1";
}
}
}
class Task2 implements Callable<String> {
@Override
public String call() throws Exception {
try {
Thread.sleep(3000);
return "Task 2 done";
} catch (Exception e) {
e.printStackTrace();
return " error in task2";
}
}
}
You could use .find("is")
, it would return position of "is" in the string
or use .start() from re
>>> re.search("is", String).start()
2
Actually its match "is" from "This"
If you need to match per word, you should use \b
before and after "is", \b
is the word boundary.
>>> re.search(r"\bis\b", String).start()
5
>>>
for more info about python regular expressions, docs here
My preference is to encode all non-alphaumeric characters as HTML numeric character entities. Since almost, if not all attacks require non-alphuneric characters (like <, ", etc) this should eliminate a large chunk of dangerous output.
Format is &#N;, where N is the numeric value of the character (you can just cast the character to an int and concatenate with a string to get a decimal value). For example:
// java-ish pseudocode StringBuffer safestrbuf = new StringBuffer(string.length()*4); foreach(char c : string.split() ){ if( Character.isAlphaNumeric(c) ) safestrbuf.append(c); else safestrbuf.append(""+(int)symbol);
You will also need to be sure that you are encoding immediately before outputting to the browser, to avoid double-encoding, or encoding for HTML but sending to a different location.
You can separate multiple classes with the space:
$("p").addClass("myClass yourClass");
/** length should be less than 4 (for int) **/
public long byteToInt(byte[] bytes, int length) {
int val = 0;
if(length>4) throw new RuntimeException("Too big to fit in int");
for (int i = 0; i < length; i++) {
val=val<<8;
val=val|(bytes[i] & 0xFF);
}
return val;
}
When we insert any line break with a programming language the char code for this is "\n". php does output that but html can't display that due to htmls line break is
. so easy way to do this job is replacing all the "\n" with "
". so the code should be
str_replace("\n","<br/>",$str);
after adding this code you wont have to use pre tag for all the output oparation.
Normal behaviour with NULL is that any operation including a NULL yields a NULL...
- 9 * NULL = NULL
- NULL + '' = NULL
- etc
To overcome this use ISNULL or COALESCE to replace any instances of NULL with something else..
SELECT (ISNULL(field1,'') + '' + ISNULL(field2,'') + '' + ISNULL(field3,'')) FROM table1
You might no be able to HIDE it, but if you are looking for the extra space, what I did and seems to work is a very simple thing, the address bar has 60px height, so this is my solution.
@media only screen and (max-width: 1024px){ // only from ipads down
body{
padding-bottom: 60px; // push your whole site same height upwards. ;)
}
}
For a DATE
column you can use:
NULLS last:
ORDER BY IFNULL(`myDate`, '9999-12-31') ASC
Blanks last:
ORDER BY IF(`myDate` = '', '9999-12-31', `myDate`) ASC
If you want to use class, you can do this.
Helper.js
function x(){}
function y(){}
export default class Helper{
static x(){ x(); }
static y(){ y(); }
}
App.js
import Helper from 'helper.js';
/****/
Helper.x
TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).
As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.
BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.
RetrofitHelper library written in kotlin, will let you make API calls, using a few lines of code.
Add headers in your application class like this :
class Application : Application() {
override fun onCreate() {
super.onCreate()
retrofitClient = RetrofitClient.instance
//api url
.setBaseUrl("https://reqres.in/")
//you can set multiple urls
// .setUrl("example","http://ngrok.io/api/")
//set timeouts
.setConnectionTimeout(4)
.setReadingTimeout(15)
//enable cache
.enableCaching(this)
//add Headers
.addHeader("Content-Type", "application/json")
.addHeader("client", "android")
.addHeader("language", Locale.getDefault().language)
.addHeader("os", android.os.Build.VERSION.RELEASE)
}
companion object {
lateinit var retrofitClient: RetrofitClient
}
}
And then make your call:
retrofitClient.Get<GetResponseModel>()
//set path
.setPath("api/users/2")
//set url params Key-Value or HashMap
.setUrlParams("KEY","Value")
// you can add header here
.addHeaders("key","value")
.setResponseHandler(GetResponseModel::class.java,
object : ResponseHandler<GetResponseModel>() {
override fun onSuccess(response: Response<GetResponseModel>) {
super.onSuccess(response)
//handle response
}
}).run(this)
For more information see the documentation
We can use another way to edit files inside working containers (this won't work if container is stoped).
Logic is to:
-)copy file from container to host
-)edit file on host using its host editor
-)copy file back to container
We can do all this steps manualy, but i have written simple bash script to make this easy by one call.
/bin/dmcedit:
#!/bin/sh
set -e
CONTAINER=$1
FILEPATH=$2
BASE=$(basename $FILEPATH)
DIR=$(dirname $FILEPATH)
TMPDIR=/tmp/m_docker_$(date +%s)/
mkdir $TMPDIR
cd $TMPDIR
docker cp $CONTAINER:$FILEPATH ./$DIR
mcedit ./$FILEPATH
docker cp ./$FILEPATH $CONTAINER:$FILEPATH
rm -rf $TMPDIR
echo 'END'
exit 1;
Usage example:
dmcedit CONTAINERNAME /path/to/file/in/container
The script is very easy, but it's working fine for me.
Any suggestions are appreciated.
The best way to do this is to open the file in text mode, read each line with ReadLine(), and then write it to a new file with WriteLine(), skipping the one line you want to delete.
There is no generic delete-a-line-from-file function, as far as I know.
You can try this
var x, y, space = "",
star = "",
n = 4,
m = n - 1;
for (x = 1; x <= n; x++) {
for (y = m; y >= 1; y--) {
space = space + (" ");
}
m--;
for (let k = 1; k <= x * 2 - 1; k++) {
star = star + "*"
}
console.log(space + star)
space = '';
star = "";
}
The camprocessor available on Sourceforge.net will do xml test case generation for any XSD. There is a tutorial available to show you how to generate your own test examples - including using content hints to ensure realistic examples, not just random junk ones.
The tutorial is available here: http://www.oasis-open.org/committees/download.php/29661/XSD%20and%20jCAM%20tutorial.pdf
And more information on the tool - which is using the OASIS Content Assembly Mechanism (CAM) standard to refactor your XSD into a more XSLT friendly structure - can be found from the resource website - http://www.jcam.org.uk
Enjoy, DW
I find such a function named is_sequence in tensorflow.
def is_sequence(seq):
"""Returns a true if its input is a collections.Sequence (except strings).
Args:
seq: an input sequence.
Returns:
True if the sequence is a not a string and is a collections.Sequence.
"""
return (isinstance(seq, collections.Sequence)
and not isinstance(seq, six.string_types))
And I have verified that it meets your needs.
The message that you are getting is not for the default Exception of Python:
For a fresh python list, IndexError
is thrown only on index not being in range (even docs say so).
>>> l = []
>>> l[1]
IndexError: list index out of range
If we try passing multiple items to list, or some other value, we get the TypeError
:
>>> l[1, 2]
TypeError: list indices must be integers, not tuple
>>> l[float('NaN')]
TypeError: list indices must be integers, not float
However, here, you seem to be using matplotlib
that internally uses numpy
for handling arrays. On digging deeper through the codebase for numpy
, we see:
static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
npy_intp n, i;
n = PyTuple_GET_SIZE(index);
if (n > result_n) {
PyErr_SetString(PyExc_IndexError,
"too many indices for array");
return -1;
}
for (i = 0; i < n; i++) {
result[i] = PyTuple_GET_ITEM(index, i);
Py_INCREF(result[i]);
}
return n;
}
where, the unpack method will throw an error if it the size of the index is greater than that of the results.
So, Unlike Python which raises a TypeError
on incorrect Indexes, Numpy raises the IndexError
because it supports multidimensional arrays.
NSLog
below code somewhere in "AppDelegate", run your project and follow the path. This will be easy for you to get to the documents rather than searching randomly inside "~/Library/Developer/CoreSimulator/Devices/"
Objective-C
NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
Swift
If you are using Swift 1.2, use the code below which will only output in development when using the Simulator because of the #if
#endif
block:
#if arch(i386) || arch(x86_64)
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
NSLog("Document Path: %@", documentsPath)
#endif
Copy your path from "/Users/ankur/Library/Developer/CoreSimulator/Devices/7BA821..." go to "Finder" and then "Go to Folder" or command + shift + g and paste your path, let the mac take you to your documents directory :)
Actually you are right: it runs another instance of make. A possible solution would be:
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : clean clearscr all
clearscr:
clear
By calling make fresh
you get first the clean
target, then the clearscreen
which runs clear
and finally all
which does the job.
EDIT Aug 4
What happens in the case of parallel builds with make’s -j
option?
There's a way of fixing the order. From the make manual, section 4.2:
Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites
The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).
Hence the makefile becomes
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : | clean clearscr all
clearscr:
clear
EDIT Dec 5
It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.
log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
install:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
command1 # this line will be a subshell
command2 # this line will be another subshell
@command3 # Use `@` to hide the command line
$(call log_error, "It works, yey!")
uninstall:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
....
$(call log_error, "Nuked!")
For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />
Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.
If databinding you will need to insert the "Please select" value afterwards as follows
this.ddl1.Items.Insert(0, "Please select");
Yesterday Date in PHP:
echo date("Y-m-d", strtotime("yesterday"));
document.getElementById('drpSelectSourceLibrary').value = 'Seven';
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
My problem was in web.config: UnobtrusiveJavaScriptEnabled was turned off
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="false" />
</appSettings>
I changed to and now works:
`<add key="UnobtrusiveJavaScriptEnabled" value="true" />`
use Sqlit delete function with last two null parameters.
db.delete(TABLE_NAME,null,null)
Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay
. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.
The key excerpt to look at is:
# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)
learning_rate = tf.train.exponential_decay(
0.01, # Base learning rate.
batch * BATCH_SIZE, # Current index into the dataset.
train_size, # Decay step.
0.95, # Decay rate.
staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
0.9).minimize(loss,
global_step=batch)
Note the global_step=batch
parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.
Here is an example that I used:
def volume(self):
return round(pi * self.radius ** 2 * self.height, 2)
def surface_area(self):
return round((2 * pi * self.radius * self.height) + (2 * pi * self.radius ** 2), 2)
const setAttributes = (el, attrs) =>
Object.entries(attrs)
.forEach(args =>
el.setAttribute(...args))
You can also put the tooltip onto one line by removing the "title":
this.chart = new Chart(ctx, {
type: this.props.horizontal ? 'horizontalBar' : 'bar',
options: {
legend: {
display: false,
},
tooltips: {
callbacks: {
label: tooltipItem => `${tooltipItem.yLabel}: ${tooltipItem.xLabel}`,
title: () => null,
}
},
},
});
redis-cli shutdown
is most effective. The accepted answer does not work for me (OSX Lion). Thanks, @JesseBuesking.
Yes, they are all the same.
We can review the interpreted machine code to confirm that that they're all doing the exact same thing.
import dis
def f1():
print "Hello World"
return None
def f2():
print "Hello World"
return
def f3():
print "Hello World"
dis.dis(f1)
4 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 5 LOAD_CONST 0 (None)
8 RETURN_VALUE
dis.dis(f2)
9 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
10 5 LOAD_CONST 0 (None)
8 RETURN_VALUE
dis.dis(f3)
14 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (None)
8 RETURN_VALUE
Depends on how your data is distributed. For a simple counter, the simplest function
f(i) = i
will be good (I suspect optimal, but I can't prove it).
I am suggesting a much simpler utility I just wrote. It's currently called par, but will be renamed soon to either parl or pll, haven't decided yet.
API is as simple as:
par "script1.sh" "script2.sh" "script3.sh"
Prefixing commands can be done via:
par "PARPREFIX=[script1] script1.sh" "script2.sh" "script3.sh"
My suggestion is to leverage the hidden/collapse attribute. Try with this example:
<select>
<option value="echo $row[month]" selected disabled hidden><? echo $row[month] ?></option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
</select>
in case of null for $row[month]
the selected item is blank and with data, it would contain less codes for many options and always working for HTML5 and bootstrap etc...
I realise this is a little late but you could add the following to your code. This won't work for transparent pngs though, you'd need a cropping mask for that. Which I'm now going to see about.
outerLink {
overflow: hidden;
position: relative;
}
outerLink:hover:after {
background: #000;
content: "";
display: block;
height: 100%;
left: 0;
opacity: 0.5;
position: absolute;
top: 0;
width: 100%;
}
if ( (strlen($ownerID) == 0) || ($ownerID == '0') || (empty($ownerID )) )
if $ownerID is NULL it will be triggered by the empty() test
This is quoted from Android official doc, I've tested it on Android 4.4, and works perfectly. See more examples at https://developer.android.com/guide/components/intents-common.html#Email
public void composeEmail(String[] addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
Try using rowMeans
:
z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
Try using RegisterScriptBlock. Example from the link:
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
String csname2 = "ButtonClickScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
{
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
cstext2.Append("Form1.Message.value='Text from client script.'} </");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
}
}
I faced same issue, I uploaded ipa via Xcode7 and it get stuck for 48hrs. Number of times I mail to apple support but it won't work so I uploaded ipa multiple times, but no use then I made change in version number e.g. 2.2(33) to 2.3(1) and it works for me. So try at your side may be this will help you.
There are 4 methods you can use:
Consider the following sample TABLE
with test data:
/** Create test table */
CREATE TEMPORARY TABLE dupes(word text, num int, id int);
/** Add test data with duplicates */
INSERT INTO dupes(word, num, id)
VALUES ('aaa', 100, 1)
,('bbb', 200, 2)
,('ccc', 300, 3)
,('bbb', 400, 4)
,('bbb', 200, 5) -- duplicate
,('ccc', 300, 6) -- duplicate
,('ddd', 400, 7)
,('bbb', 400, 8) -- duplicate
,('aaa', 100, 9) -- duplicate
,('ccc', 300, 10); -- duplicate
This is the most simple and straight forward, but also the most limited way:
SELECT DISTINCT word, num
FROM dupes
ORDER BY word, num;
/*
word|num|
----|---|
aaa |100|
bbb |200|
bbb |400|
ccc |300|
ddd |400|
*/
Grouping allows you to add aggregated data, like the min(id)
, max(id)
, count(*)
, etc:
SELECT word, num, min(id), max(id), count(*)
FROM dupes
GROUP BY word, num
ORDER BY word, num;
/*
word|num|min|max|count|
----|---|---|---|-----|
aaa |100| 1| 9| 2|
bbb |200| 2| 5| 2|
bbb |400| 4| 8| 2|
ccc |300| 3| 10| 3|
ddd |400| 7| 7| 1|
*/
Using a subquery, you can first identify the duplicate rows to ignore, and then filter them out in the outer query with the WHERE NOT IN (subquery)
construct:
/** Find the higher id values of duplicates, distinct only added for clarity */
SELECT distinct d2.id
FROM dupes d1
INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
WHERE d2.id > d1.id
/*
id|
--|
5|
6|
8|
9|
10|
*/
/** Use the previous query in a subquery to exclude the dupliates with higher id values */
SELECT *
FROM dupes
WHERE id NOT IN (
SELECT d2.id
FROM dupes d1
INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
WHERE d2.id > d1.id
)
ORDER BY word, num;
/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/
In the Common Table Expression (CTE), select the ROW_NUMBER(), partitioned by the group column and ordered in the desired order. Then SELECT only the records that have ROW_NUMBER() = 1
:
WITH CTE AS (
SELECT *
,row_number() OVER(PARTITION BY word, num ORDER BY id) AS row_num
FROM dupes
)
SELECT word, num, id
FROM cte
WHERE row_num = 1
ORDER BY word, num;
/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/
hi friend in this case you can use the
AppendDataBound="true"
and after this use the list item. for e.g.:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
but the problem in this is after second time select data are append with old data.
import sys
sys.path
The best two options are BufferedReader
and Scanner
.
The most widely used method is Scanner
and I personally prefer it because of its simplicity and easy implementation, as well as its powerful utility to parse text into primitive data.
Advantages of Using Scanner
Scanner
classAdvantages of BufferedInputStream
Scanner
between threads)Overall each input method has different purposes.
If you are inputting large amount of data BufferedReader
might be
better for you
If you are inputting lots of numbers Scanner
does automatic parsing
which is very convenient
For more basic uses I would recommend the Scanner
because it is easier to use and easier to write programs with. Here is a quick example of how to create a Scanner
. I will provide a comprehensive example below of how to use the Scanner
Scanner scanner = new Scanner (System.in); // create scanner
System.out.print("Enter your name"); // prompt user
name = scanner.next(); // get user input
(For more info about BufferedReader
see How to use a BufferedReader and see Reading lines of Chars)
import java.util.InputMismatchException; // import the exception catching class
import java.util.Scanner; // import the scanner class
public class RunScanner {
// main method which will run your program
public static void main(String args[]) {
// create your new scanner
// Note: since scanner is opened to "System.in" closing it will close "System.in".
// Do not close scanner until you no longer want to use it at all.
Scanner scanner = new Scanner(System.in);
// PROMPT THE USER
// Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println"
System.out.println("Please enter a number");
// use "try" to catch invalid inputs
try {
// get integer with "nextInt()"
int n = scanner.nextInt();
System.out.println("Please enter a decimal"); // PROMPT
// get decimal with "nextFloat()"
float f = scanner.nextFloat();
System.out.println("Please enter a word"); // PROMPT
// get single word with "next()"
String s = scanner.next();
// ---- Note: Scanner.nextInt() does not consume a nextLine character /n
// ---- In order to read a new line we first need to clear the current nextLine by reading it:
scanner.nextLine();
// ----
System.out.println("Please enter a line"); // PROMPT
// get line with "nextLine()"
String l = scanner.nextLine();
// do something with the input
System.out.println("The number entered was: " + n);
System.out.println("The decimal entered was: " + f);
System.out.println("The word entered was: " + s);
System.out.println("The line entered was: " + l);
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input entered. Please enter the specified input");
}
scanner.close(); // close the scanner so it doesn't leak
}
}
Note: Other classes such as Console
and DataInputStream
are also viable alternatives.
Console
has some powerful features such as ability to read passwords, however, is not available in all IDE's (such as Eclipse). The reason this occurs is because Eclipse runs your application as a background process and not as a top-level process with a system console. Here is a link to a useful example on how to implement the Console
class.
DataInputStream
is primarily used for reading input as a primitive datatype, from an underlying input stream, in a machine-independent way. DataInputStream
is usually used for reading binary data. It also provides convenience methods for reading certain data types. For example, it has a method to read a UTF String which can contain any number of lines within them.
However, it is a more complicated class and harder to implement so not recommended for beginners. Here is a link to a useful example how to implement a DataInputStream
.
Using the date helper worked for me
$this->load->helper('date');
You can find documentation for date_helper
here.
$data = array(
'created' => now(),
'modified' => now()
);
$this->db->insert('TABLENAME', $data);
Here is one possiblity for you if you are using Bootstrap 3
live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/
edit view: http://jsfiddle.net/panchroma/vPH8N/
I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive
ie:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
Take a look at the FormData object: https://developer.mozilla.org/en/docs/Web/API/FormData
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
You can use the .Clear method:
Sheets("Zeros").UsedRange.Clear
Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.
You have to pass a function to expect
. Like this:
expect(model.get.bind(model, 'z')).to.throw('Property does not exist in model schema.');
expect(model.get.bind(model, 'z')).to.throw(new Error('Property does not exist in model schema.'));
The way you are doing it, you are passing to expect
the result of calling model.get('z')
. But to test whether something is thrown, you have to pass a function to expect
, which expect
will call itself. The bind
method used above creates a new function which when called will call model.get
with this
set to the value of model
and the first argument set to 'z'
.
A good explanation of bind
can be found here.
After you shelled to the Docker container, just type:
apt-get update
apt-get install nano
Please find in the below code which enables to perform the date validation for any of the supplied format or based on user locale to validate start/from and end/to dates. There could be some better approaches but have come up with this. Have tested it for the formats like: MM/dd/yyyy, dd/MM/yyyy, yyyy-MM-dd, yyyy.MM.dd, yyyy/MM/dd and dd-MM-yyyy.
Note supplied date format and date string go hand in hand.
<script type="text/javascript">
function validate(format) {
if(isAfterCurrentDate(document.getElementById('start').value, format)) {
alert('Date is after the current date.');
} else {
alert('Date is not after the current date.');
}
if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
alert('Date is before current date.');
} else {
alert('Date is not before current date.');
}
if(isCurrentDate(document.getElementById('start').value, format)) {
alert('Date is current date.');
} else {
alert('Date is not a current date.');
}
if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Start/Effective Date cannot be greater than End/Expiration Date');
} else {
alert('Valid dates...');
}
if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('End/Expiration Date cannot be less than Start/Effective Date');
} else {
alert('Valid dates...');
}
if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Dates are equals...');
} else {
alert('Dates are not equals...');
}
if (isDate(document.getElementById('start').value, format)) {
alert('Is valid date...');
} else {
alert('Is invalid date...');
}
}
/**
* This method gets the year index from the supplied format
*/
function getYearIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'YYYY'
|| tokens[0] === 'yyyy') {
return 0;
} else if (tokens[1]=== 'YYYY'
|| tokens[1] === 'yyyy') {
return 1;
} else if (tokens[2] === 'YYYY'
|| tokens[2] === 'yyyy') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the year string located at the supplied index
*/
function getYear(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the month index from the supplied format
*/
function getMonthIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'MM'
|| tokens[0] === 'mm') {
return 0;
} else if (tokens[1] === 'MM'
|| tokens[1] === 'mm') {
return 1;
} else if (tokens[2] === 'MM'
|| tokens[2] === 'mm') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the month string located at the supplied index
*/
function getMonth(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the date index from the supplied format
*/
function getDateIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'DD'
|| tokens[0] === 'dd') {
return 0;
} else if (tokens[1] === 'DD'
|| tokens[1] === 'dd') {
return 1;
} else if (tokens[2] === 'DD'
|| tokens[2] === 'dd') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the date string located at the supplied index
*/
function getDate(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method returns true if date1 is before date2 else return false
*/
function isBefore(date1, date2, format) {
// Validating if date1 date is greater than the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
> new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method returns true if date1 is after date2 else return false
*/
function isAfter(date1, date2, format) {
// Validating if date2 date is less than the date1 date
if (new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()
< new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
) {
return true;
}
return false;
}
/**
* This method returns true if date1 is equals to date2 else return false
*/
function isEquals(date1, date2, format) {
// Validating if date1 date is equals to the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
=== new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date is
* equals to the current date.
*/
function isCurrentDate(date, format) {
// Validating if the supplied date is the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
=== new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is before the current date.
*/
function isBeforeCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
< new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is after the current date.
*/
function isAfterCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
> new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method splits the supplied date OR format based
* on non alpha numeric characters in the supplied string.
*/
function splitDateFormat(dateFormat) {
// Spliting the supplied string based on non characters
return dateFormat.split(/\W/);
}
/*
* This method validates if the supplied value is a valid date.
*/
function isDate(date, format) {
// Validating if the supplied date string is valid and not a NaN (Not a Number)
if (!isNaN(new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))))) {
return true;
}
return false;
}
Below is the HTML snippet
<input type="text" name="start" id="start" size="10" value="05/31/2016" />
<br/>
<input type="text" name="end" id="end" size="10" value="04/28/2016" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate('MM/dd/yyyy');" />
Try:
git format-patch -1 <sha>
or
git format-patch -1 HEAD
According to the documentation link above, the -1
flag tells git how many commits should be included in the patch;
-<n>
Prepare patches from the topmost commits.
Apply the patch with the command:
git am < file.patch
You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...
Try the following:
color.gradient <- function(x, colors=c("red","yellow","green"), colsteps=100) {
return( colorRampPalette(colors) (colsteps) [ findInterval(x, seq(min(x),max(x), length.out=colsteps)) ] )
}
x <- c((1:100)^2, (100:1)^2)
plot(x,col=color.gradient(x), pch=19,cex=2)
In my case I got rid of the exception by replacing SetDataAndType
with just SetData
.
Either as most people answered: the file doesn't exist / you're not specifying the path correctly.
Or, you're simply writing the syntax wrong (which you can't know unless you know what it should be like, right?, especially when in the "help" itself, it's wrong).
For gnuplot 4.6.0 on windows 7, terminal type set to windows
Make sure you specify the file's whole path to avoid looking for it where it's not (default seems to be "documents")
Make sure you use this syntax:
plot 'path\path\desireddatafile.txt'
NOT
plot "< path\path\desireddatafile.txt>"
NOR
plot "path\path\desireddatafile.txt"
also make sure your file is in the right format, like for .txt file format ANSI, not Unicode and such.
another way to create a data url from blob url may be using canvas.
var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)
as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)
With C++17 str::string
receives data()
overload that returns a pointer to modifieable buffer so string can be used in strtok
directly without any hacks:
#include <string>
#include <iostream>
#include <cstring>
#include <cstdlib>
int main()
{
::std::string text{"pop dop rop"};
char const * const psz_delimiter{" "};
char * psz_token{::std::strtok(text.data(), psz_delimiter)};
while(nullptr != psz_token)
{
::std::cout << psz_token << ::std::endl;
psz_token = std::strtok(nullptr, psz_delimiter);
}
return EXIT_SUCCESS;
}
output
pop
dop
rop
by XML:
<EditText
android:id="@+id/search_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/search"
android:imeOptions="actionSearch"
android:inputType="text" />
By Java:
editText.clearFocus();
InputMethodManager in = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
The latest version of core-js lib provides the polyfills from a different path. so use the following in the polyfills.js. And also change the target
value to es5
in the tsconfig.base.json
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es/symbol';
import 'core-js/es/object';
import 'core-js/es/function';
import 'core-js/es/parse-int';
import 'core-js/es/parse-float';
import 'core-js/es/number';
import 'core-js/es/math';
import 'core-js/es/string';
import 'core-js/es/date';
import 'core-js/es/array';
import 'core-js/es/regexp';
import 'core-js/es/map';
To complement the version of Leo Dabus, I added support for projects written Swift and Objective-C, also added support for the optional milliseconds, probably isn't the best but you would get the point:
Xcode 8 and Swift 3
extension Date {
struct Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
}
var iso8601: String {
return Formatter.iso8601.string(from: self)
}
}
extension String {
var dateFromISO8601: Date? {
var data = self
if self.range(of: ".") == nil {
// Case where the string doesn't contain the optional milliseconds
data = data.replacingOccurrences(of: "Z", with: ".000000Z")
}
return Date.Formatter.iso8601.date(from: data)
}
}
extension NSString {
var dateFromISO8601: Date? {
return (self as String).dateFromISO8601
}
}
func mimeTypeForPath(path: String) -> String {
let url = NSURL(fileURLWithPath: path)
let pathExtension = url.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream"
}
For those who code-golf, an unreliable test with fewest characters:
function isArray(a) {
return a.map;
}
This is commonly used when traversing/flattening a hierarchy:
function golf(a) {
return a.map?[].concat.apply([],a.map(golf)):a;
}
input: [1,2,[3,4,[5],6],[7,[8,[9]]]]
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
I found the most easiest way to find sum of all the elements of a vector
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<int>v(10,1);
int sum=0;
for(int i=0;i<v.size();i++)
{
sum+=v[i];
}
cout<<sum<<endl;
}
In this program, I have a vector of size 10 and are initialized by 1. I have calculated the sum by a simple loop like in array.
INTERNAL : Table is created First and Data is loaded later
EXTERNAL : Data is present and Table is created on top of it.
Simple! The folder named ..
is the parent folder, so you can make the path to the file you need as such
var foobar = require('../config/dev/foobar.json');
If you needed to go up two levels, you would write ../../
etc
Some more details about this in this SO answer and it's comments
as ehogue said, put this in your CREATE TABLE
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
alternatively, if you already have the table created, use an ALTER TABLE command:
ALTER TABLE `accounts`
ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;
One good way to start learning these commands is using the MySQL GUI Tools, which give you a more "visual" interface for working with your database. The real benefit to that (over Access's method), is that after designing your table via the GUI, it shows you the SQL it's going to run, and hence you can learn from that.
mvn install primary jobs are to 1)Download The Dependencies and 2)Build The Project
while job 1 is nowadays taken care by IDs like intellij (they download for any dependency at POM)
mvn install is majorly now used for job 2.
Same thing is happening for me. And yes, as @Joao Leme said, it seems it is related to a user bookmarking a site to their device homescreen.
However, I noticed that even though there is an error in the log, it's happening behind the scenes and the user never sees the error. I assume the device makes a request for the touch-icon specific to its resolution (which isn't there) until defaulting to the general apple-touch-icon
or apple-touch-icon-precomposed
, if present, or else generates a small screenshot of the current page.
FWIW, put the icons in the /public directory.
For the example given, I prefer the ternary or condition operator (?
) for a specific reason: I can clearly see that assigning a
is not optional. With a simple example, it's not too hard to scan the if-else block to see that a
is assigned in each clause, but imagine several assignments in each clause:
if (i == 0)
{
a = 10;
b = 6;
c = 3;
}
else
{
a = 5;
b = 4;
d = 1;
}
a = (i == 0) ? 10 : 5;
b = (i == 0) ? 6 : 4;
c = (i == 0) ? 3 : 9;
d = (i == 0) ? 12 : 1;
I prefer the latter so that you know you haven't missed an assignment.
You could use my JavaScript hash table implementation, jshashtable. It allows any object to be used as a key, not just strings.
Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.
Here are the commands to retrieve key value:
<key>
<key>
<key> <start> <end>
<key>
<key> <min> <max>
Use the TYPE
command to check the type of value a key is mapping to:
<key>
From Java 1.5 it's always a good Idea to consider java.util.concurrent package. They are the state of the art locking mechanism in java right now. The synchronize mechanism is more heavyweight that the java.util.concurrent classes.
The example would look something like this:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Sample {
private final Lock lock = new ReentrantLock();
private String message = null;
public void newmsg(String msg) {
lock.lock();
try {
message = msg;
} finally {
lock.unlock();
}
}
public String getmsg() {
lock.lock();
try {
String temp = message;
message = null;
return temp;
} finally {
lock.unlock();
}
}
}
Do it like this:
TextField(
decoration: new InputDecoration.collapsed(
hintText: 'Username'
),
),
or if you need other stuff like icon, set the border with InputBorder.none
InputDecoration(
border: InputBorder.none,
hintText: 'Username',
),
),
I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.
<form id="form">
...
<button type="submit"></button>
</form>
<script>
$(document).ready(function() {
$("#form_selector").submit(function() {
$.ajax({
type: "POST",
url: "form_handler.php",
data: $(this).serialize(),
success: function() {
// callback code here
}
})
})
})
</script>
What you have will find a space anywhere in the string, not just between words.
If you want to find any kind of whitespace, you can use this, which uses a regular expression:
if (/\s/.test(str)) {
// It has any kind of whitespace
}
\s
means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.
According to MDN, \s
is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000]
.
For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...
If you mean literally spaces, a regex can do it:
if (/^ *$/.test(str)) {
// It has only spaces, or is empty
}
That says: Match the beginning of the string (^
) followed by zero or more space characters followed by the end of the string ($
). Change the *
to a +
if you don't want to match an empty string.
If you mean whitespace as a general concept:
if (/^\s*$/.test(str)) {
// It has only whitespace
}
That uses \s
(whitespace) rather than the space, but is otherwise the same. (And again, change *
to +
if you don't want to match an empty string.)
You can use ESCAPE
:
WHERE columnName LIKE '%\%%' ESCAPE '\'
Find out if an enumerable contains any duplicate :
var anyDuplicate = enumerable.GroupBy(x => x.Key).Any(g => g.Count() > 1);
Find out if all values in an enumerable are unique :
var allUnique = enumerable.GroupBy(x => x.Key).All(g => g.Count() == 1);
These 2 commands have several subtle differences if the file in question is already in the repo and under version control (previously committed etc.):
git reset HEAD <file>
unstages the file in the current commit.git rm --cached <file>
will unstage the file for future commits also. It's unstaged untill it gets added again with git add <file>
.And there's one more important difference:
git rm --cached <file>
and push your branch to the remote, anyone pulling your branch from the remote will get the file ACTUALLY deleted from their folder, even though in your local working set the file just becomes untracked (i.e. not physically deleted from the folder).This last difference is important for projects which include a config file where each developer on the team has a different config (i.e. different base url, ip or port setting) so if you're using git rm --cached <file>
anyone who pulls your branch will have to manually re-create the config, or you can send them yours and they can re-edit it back to their ip settings (etc.), because the delete only effects people pulling your branch from the remote.
You can do exactly the same thing in R with two more characters:
x <- 0:9
x[-5:-1]
[1] 5 6 7 8 9
or
x[-(1:5)]
The answer about going under "Other Users" was close, but not nearly explicit enough, so I felt the need to add this answer, below.
In Oracle, it will only show you tables that belong to schemas (databases in MS SQL Server) that are owned by the account you are logged in with. If the account owns/has created nothing, you will see nothing, even if you have rights/permissions to everything in the database! (This is contrary to MS SQL Server Management Studio, where you can see anything you have rights on and the owner is always "dbo", barring some admin going in and changing it for some unforeseeable reason.)
The owner will be the only one who will see those tables under "Tables" in the tree. If you do not see them because you are not their owner, you will have to go under "Other Users" and expand each user until you find out who created/owns that schema, if you do not know it, already. It will not matter if your account has permissions to the tables or not, you still have to go under "Other Users" and find that user that owns it to see it, under "Tables"!
One thing that can help you: when you write queries, you actually specify in the nomenclature who that owner is, ex.
Select * from admin.mytable
indicates that "admin" is the user that owns it, so you go under "Other Users > Admin" and expand "Tables" and there it is.
You have different choices to handle this. It seem like its taking us back to old good plain SQL days :)
Read this: http://www.javacodegeeks.com/2012/07/four-solutions-to-lazyinitializationexc_05.html
1)A primary key
is a set of one or more attributes that uniquely identifies tuple within relation.
2)A foreign key
is a set of attributes from a relation scheme which can be uniquely identify tuples fron another relation scheme.
Not tested, but I think this will be close?
SELECT m1.id
FROM mytable m1
INNER JOIN mytable m2 ON m1.id < m2.id
GROUP BY m1.id
HAVING SUM(m1.cash) > 500
ORDER BY m1.id
LIMIT 1,2
The idea is to SUM up all the previous rows, get only the ones where the sum of the previous rows is > 500, then skip one and return the next one.
A portable approach that works equally well on Linux or Windows (where there is no /dev/null):
echo | gcc -dM -E -
For c++ you may use (replace c++11
with whatever version you use):
echo | gcc -x c++ -std=c++11 -dM -E -
It works by telling gcc to preprocess stdin (which is produced by echo) and print all preprocessor defines (search for -dletters
). If you want to know what defines are added when you include a header file you can use -dD
option which is similar to -dM but does not include predefined macros:
echo "#include <stdlib.h>" | gcc -x c++ -std=c++11 -dD -E -
Note, however, that empty input still produces lots of defines with -dD
option.
If you want connect to user@'%'
from localhost use mysql -h192.168.0.1 -uuser -p
.
One word: Don't.
OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?
You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).
I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)
It doesn't. It makes 0 <= r < 1
, but your original is 0 <= r <= 1
.
Note that this can lead to undefined behavior if RAND_MAX + 1
overflows.
Why not write one? Something like this may satisfy your requirements:
def FixCase(st):
return ' '.join(''.join([w[0].upper(), w[1:].lower()]) for w in st.split())
I would say everything probably works except that the column idx
doesn't actually exist in the table you're selecting from. Maybe you meant to select from @Practitioner
:
WHILE (@i <= (SELECT MAX(idx) FROM @Practitioner))
because that's defined in the code above like that:
DECLARE @Practitioner TABLE (
idx smallint Primary Key IDENTITY(1,1)
, PractitionerId int
)
If you doesn't want to touch the config object, you just hide the grid by css:
.chart-container .highcharts-grid {
display: none;
}
I liked the (C#) code in the following which sets the registry settings for your app. Not sure if it will cut it after installation though if permissions are required. For me it solved an issue with WebSocket not being available inside a WebBrowser control in WPF.
In general terms (and in normal English usage) the terms mean the same thing.
In the specific context of HTML / Javascript the terms get confused because the HTML representation of a DOM element has attributes (that being the term used in XML for the key/value pairs contained within a tag) but when represented as a JavaScript object those attributes appear as object properties.
To further confuse things, changes to the properties will typically update the attributes.
For example, changing the element.href
property will update the href
attribute on the element, and that'll be reflected in a call to element.getAttribute('href')
.
However if you subsequently read that property, it will have been normalised to an absolute URL, even though the attribute might be a relative URL!
Yes. You know that you can put any Object
into the Object
parameter of most JOptionPane.showXXX methods
, and often that Object
happens to be a JPanel
.
In your situation, perhaps you could use a JPanel
that has several JTextFields
in it:
import javax.swing.*;
public class JOptionPaneMultiInput {
public static void main(String[] args) {
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("x:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("y:"));
myPanel.add(yField);
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
System.out.println("x value: " + xField.getText());
System.out.println("y value: " + yField.getText());
}
}
}
This is compact and universal
# exit if another instance of this script is running
for pid in $(pidof -x `basename $0`); do
[ $pid != $$ ] && { exit 1; }
done
Answer : document.body.scroll = 'no';
<script>
function getFontsByScreenWidth(actuallFontSize, maxScreenWidth){
return (actualFontSize / maxScreenWidth) * window.innerWidth;
}
// Example:
fontSize = 18;
maxScreenWidth = 1080;
fontSize = getFontsByScreenWidth(fontSize, maxScreenWidth)
</script>
I hope this will help. I am using this formula for my Phase game.
I was having the same problem, although I solved out by creating the table using a script query instead of doing it graphically. See the snipped below:
USE [Database_Name]
GO
CREATE TABLE [dbo].[Table_Name](
[tableID] [int] IDENTITY(1,1) NOT NULL,
[column_2] [datatype] NOT NULL,
[column_3] [datatype] NOT NULL,
CONSTRAINT [PK_Table_Name] PRIMARY KEY CLUSTERED
(
[tableID] ASC
)
)
echo basename(__DIR__); will return the current directory name only
echo basename(__FILE__); will return the current file name only
figure;
plot(something);
or
figure(2);
plot(something);
...
figure(3);
plot(something else);
...
etc.
The answer code allow only to localhost:8888. This code can't be deployed to the production, or different server and port name.
To get it working for all sources, use this instead:
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
You should possibly make data
a keyword parameter with a default value of empty dictionary:
class DHT:
def __init__(self, data=dict()):
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
if __name__ == '__main__':
DHT().showData()
If you want to create a new A
you can use INTO
;
select * into A from dbo.myView
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
The method match() searches a string for a match and returns an Array object.
// Original string
var str = "My cow always gives milk";
// Using index [0] would return<br/>
// "**cow always gives milk**"
str.match(/cow(.*)milk/)**[0]**
// Using index **[1]** would return
// "**always gives**"
str.match(/cow(.*)milk/)[1]
Read these:
These articles will help you understand how to pass data between two activities in Android.
If your database is small enough (or if you add enough memory) your database will effectively run in memory since it your data will be cached after the first request.
Changing the database table definitions to use the memory engine is probably more complicated than you need.
If you have enough memory to load the tables into memory with the MEMORY
engine, you have enough to tune the innodb settings to cache everything anyway.
Thanks to Mike's comment, I've re-read the doc and I've realised that my current user (i.e. userA that already has the create privilege) wasn't a direct/indirect member of the new owning role...
So the solution was quite simple - I've just done this grant:
grant userB to userA;
That's all folks ;-)
Another requirement is that the object has to be owned by user userA before altering it...
You might try following function:
<script type="text/javascript">
function open(url)
{
var popup = window.open(url, "_blank", "width=200, height=200") ;
popup.location = URL;
}
</script>
The HTML code for execution:
<a href="#" onclick="open('http://www.google.com')">google search</a>
Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax()
method. Or if you wanted to do it using plain javascript, here's a tutorial.
I have a WinForms application with a single project in the solution.
Targeting .NET Framework 4.0
Using SharpDevelop 4.3
as my IDE
Sounds silly, but I happened to have the Logical Name
property set to "Resources"
on my "Resources.resx"
file. Once I cleared that property, all works hunky-dory.
Normally, when you add random files as EmbeddedResource
, you generally want to set the Logical Name
to something reasonable, for some reason, I did the same on the Resources.resx
file and that screwed it all up...
Hope this helps someone.
Something like this will work, using Linq:
string result = "12345"
var intList = result.Select(digit => int.Parse(digit.ToString()));
This will give you an IEnumerable list of ints.
If you want an IEnumerable of strings:
var intList = result.Select(digit => digit.ToString());
or if you want a List of strings:
var intList = result.ToList();
My answer was different and came along with the message:
resource fork, Finder information, or similar detritus not allowed
The solution was to do with generated graphics:
$('.line').click(function() {_x000D_
$(this).toggleClass('red');_x000D_
});
_x000D_
.line {_x000D_
border: 0;_x000D_
background-color: #000;_x000D_
height: 3px;_x000D_
cursor: pointer;_x000D_
}_x000D_
.red {_x000D_
background-color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<hr class="line"></hr>_x000D_
<p>click the line</p>
_x000D_
You don't require broadcast receiver. If one would take some pain copy one of the api(serviceconnection) from above example by Stephen Donecker and paste it in google you would get this, https://www.concretepage.com/android/android-local-bound-service-example-with-binder-and-serviceconnection
Hi for example if you have split and replace in String 07:05:45PM
var hour = time.replace("PM", "").split(":");
Result
[ '07', '05', '45' ]
Run the path in cmd C:\Program Files (x86)\Microsoft Visual Studio\Installer>vswhere.exe
This is just an indentation problem since Python is very strict when it comes to it.
If you are using Sublime, you can select all, click on the lower right beside 'Python' and make sure you check 'Indent using spaces' and choose your Tab Width to be consistent, then Convert Indentation to Spaces to convert all tabs to spaces.
In terminal, log into MySQL as root. You may have created a root password when you installed MySQL for the first time or the password could be blank, in which case you can just press ENTER when prompted for a password.
sudo mysql -p -u root
Now add a new MySQL user with the username of your choice. In this example we are calling it pmauser (for phpmyadmin user). Make sure to replace password_here with your own. You can generate a password here. The % symbol here tells MySQL to allow this user to log in from anywhere remotely. If you wanted heightened security, you could replace this with an IP address.
CREATE USER 'pmauser'@'%' IDENTIFIED BY 'password_here';
Now we will grant superuser privilege to our new user.
GRANT ALL PRIVILEGES ON *.* TO 'pmauser'@'%' WITH GRANT OPTION;
Then go to config.inc.php ( in ubuntu, /etc/phpmyadmin/config.inc.php )
/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pmauser';
$cfg['Servers'][$i]['controlpass'] = 'password_here';
Super simple:
var state = false;
$("a").click(function () {
state = !state;
$("select").prop("size", state ? $("option").length : 1);
});
The above examples work but don't go so far as to really deal with a real world example (i.e. when you process data coming in multiple chunks. One thing you need to make sure of is that you have an 'on chunk' handler that push's the data into an array (fastest way to do this in JS) and an 'on end' handler that joins them all together so you can return it.
This is especially necessary when you're working with big requests (5000+ lines) and the server sends a bunch of data at you.
Here's an example in one of my programs (coffeescript): https://gist.github.com/1105888
Try this:
df.my_channel = df.my_channel.where(df.my_channel <= 20000, other= 0)
or
df.my_channel = df.my_channel.mask(df.my_channel > 20000, other= 0)
As answered by RafaelC, Python 3 renamed dict.iteritems -> dict.items. Try a different package version. This will list available packages:
python -m pip install yourOwnPackageHere==
Then rerun with the version you will try after == to install/switch version
A small word of caution, if "do some stuff" means updating the value of the actual property that you visit AND if there is a struct type property along the path from root object to the visited property, the change you made on the property will not be reflected on the root object.
Oracle
's locking concept is quite different from that of the other systems.
When a row in Oracle
gets locked, the record itself is updated with the new value (if any) and, in addition, a lock (which is essentially a pointer to transaction lock that resides in the rollback segment) is placed right into the record.
This means that locking a record in Oracle
means updating the record's metadata and issuing a logical page write. For instance, you cannot do SELECT FOR UPDATE
on a read only tablespace.
More than that, the records themselves are not updated after commit: instead, the rollback segment is updated.
This means that each record holds some information about the transaction that last updated it, even if the transaction itself has long since died. To find out if the transaction is alive or not (and, hence, if the record is alive or not), it is required to visit the rollback segment.
Oracle does not have a traditional lock manager, and this means that obtaining a list of all locks requires scanning all records in all objects. This would take too long.
You can obtain some special locks, like locked metadata objects (using v$locked_object
), lock waits (using v$session
) etc, but not the list of all locks on all objects in the database.
I have had trouble myself displaying Snackbar until now.
Here is the simplest way to display a Snackbar. To display it as your Main Activity Starts, just put these two lines inside your OnCreate()
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Welcome To Main Activity", Snackbar.LENGTH_LONG);
snackbar.show();
P.S. Just make sure you have imported the Android Design Support.(As mentioned in the question).
For Kotlin,
Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_SHORT).show()
You have to do the following:
a=a.replace("\n"," ");
a=a.trim();
String b[]=a.split("+");
int k=Integer.ValueOf(b[0]);
int l=Integer.ValueOf(b[1]);
int sum=k+l;
All you have to do is set the selection style on the UITableViewCell
instance using either:
Objective-C:
cell.selectionStyle = UITableViewCellSelectionStyleNone;
or
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
Swift 2:
cell.selectionStyle = UITableViewCellSelectionStyle.None
Swift 3 and 4.x:
cell.selectionStyle = .none
Further, make sure you either don't implement -tableView:didSelectRowAtIndexPath:
in your table view delegate or explicitly exclude the cells you want to have no action if you do implement it.
More info here and here
Similar to Tamas's answer, here is a one-liner for Mac OS X to fetch all of the files for app with your.app.id
from your device and save them to (in this case) ~/Desktop/your.app.id
:
(
id=your.app.id &&
dest=~/Desktop &&
adb shell "run-as $id cp -r /data/data/$id /sdcard" &&
adb -d pull "/sdcard/$id" "$dest" &&
if [ -n "$id" ]; then adb shell "rm -rf /sdcard/$id"; fi
)
-d
to pull from emulatorI know it's late, but maybe this helps others. I have created a class NotifyObservableCollection
, that solves the problem of missing notification to item itself, when a property of the item changes. The usage is as simple as ObservableCollection
.
public class NotifyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
private void Handle(object sender, PropertyChangedEventArgs args)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null));
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null) {
foreach (object t in e.NewItems) {
((T) t).PropertyChanged += Handle;
}
}
if (e.OldItems != null) {
foreach (object t in e.OldItems) {
((T) t).PropertyChanged -= Handle;
}
}
base.OnCollectionChanged(e);
}
While Items are added or removed the class forwards the items PropertyChanged
event to the collections PropertyChanged
event.
usage:
public abstract class ParameterBase : INotifyPropertyChanged
{
protected readonly CultureInfo Ci = new CultureInfo("en-US");
private string _value;
public string Value {
get { return _value; }
set {
if (value == _value) return;
_value = value;
OnPropertyChanged();
}
}
}
public class AItem {
public NotifyObservableCollection<ParameterBase> Parameters {
get { return _parameters; }
set {
NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
if (_parameters != null) _parameters.CollectionChanged -= cceh;
_parameters = value;
//needed for Binding to AItem at xaml directly
_parameters.CollectionChanged += cceh;
}
}
public NotifyObservableCollection<ParameterBase> DefaultParameters {
get { return _defaultParameters; }
set {
NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
if (_defaultParameters != null) _defaultParameters.CollectionChanged -= cceh;
_defaultParameters = value;
//needed for Binding to AItem at xaml directly
_defaultParameters.CollectionChanged += cceh;
}
}
public class MyViewModel {
public NotifyObservableCollection<AItem> DataItems { get; set; }
}
If now a property of an item in DataItems
changes, the following xaml will get a notification, though it binds to Parameters[0]
or to the item itself except to the changing property Value
of the item (Converters at Triggers are called reliable on every change).
<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding DataItems}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Parameters[0].Value}" Header="P1">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="Aqua" />
<Style.Triggers>
<DataTrigger Value="False">
<!-- Bind to Items with changing properties -->
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource ParameterCompareConverter}">
<Binding Path="DefaultParameters[0]" />
<Binding Path="Parameters[0]" />
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="DeepPink" />
</DataTrigger>
<!-- Binds to AItem directly -->
<DataTrigger Value="True" Binding="{Binding Converter={StaticResource CheckParametersConverter}}">
<Setter Property="FontWeight" Value="ExtraBold" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure
Unless you can get PHP to label that element with a class you are better to use jQuery.
jQuery(document).ready(function () {
$count = jQuery("ul li").size() - 1;
alert($count);
jQuery("ul li:nth-child("+$count+")").css("color","red");
});
I encountered this error since my encoded image started with data:image/png;base64,iVBORw0...
.
This answer led me to the solution:
String partSeparator = ",";
if (data.contains(partSeparator)) {
String encodedImg = data.split(partSeparator)[1];
byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
Files.write(destinationFile, decodedImg);
}
Get all the checked checkbox value in an array - one liner
const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);_x000D_
console.log(data);
_x000D_
<div class="row">_x000D_
<input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option1</label>_x000D_
<input class="custom-control-input inp" type="checkbox" id="inlineCheckbox1" value="option2"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option2</label>_x000D_
<input class="custom-control-input inp" Checked type="checkbox" id="inlineCheckbox1" value="option3"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option3</label>_x000D_
</div>
_x000D_
You can await on Promise.all()
:
await Promise.all([someCall(), anotherCall()]);
To store the results:
let [someResult, anotherResult] = await Promise.all([someCall(), anotherCall()]);
Note that Promise.all
fails fast, which means that as soon as one of the promises supplied to it rejects, then the entire thing rejects.
const happy = (v, ms) => new Promise((resolve) => setTimeout(() => resolve(v), ms))
const sad = (v, ms) => new Promise((_, reject) => setTimeout(() => reject(v), ms))
Promise.all([happy('happy', 100), sad('sad', 50)])
.then(console.log).catch(console.log) // 'sad'
_x000D_
If, instead, you want to wait for all the promises to either fulfill or reject, then you can use Promise.allSettled
. Note that Internet Explorer does not natively support this method.
const happy = (v, ms) => new Promise((resolve) => setTimeout(() => resolve(v), ms))
const sad = (v, ms) => new Promise((_, reject) => setTimeout(() => reject(v), ms))
Promise.allSettled([happy('happy', 100), sad('sad', 50)])
.then(console.log) // [{ "status":"fulfilled", "value":"happy" }, { "status":"rejected", "reason":"sad" }]
_x000D_
Note: If you use
Promise.all
actions that managed to finish before rejection happen are not rolled back, so you may need to take care of such situation. For example if you have 5 actions, 4 quick, 1 slow and slow rejects. Those 4 actions may be already executed so you may need to roll back. In such situation consider usingPromise.allSettled
while it will provide exact detail which action failed and which not.
The na.omit
function is what a lot of the regression routines use internally:
vec <- 1:1000
vec[runif(200, 1, 1000)] <- NA
max(vec)
#[1] NA
max( na.omit(vec) )
#[1] 1000
Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.
Having added a new view controller scene to your storyboard, you then have to:
Create a UIViewController
subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":
And then select a unique name for the new view controller subclass:
Specify this new subclass as the base class for the scene you just added to the storyboard.
Now hook up any IBOutlet
and IBAction
references for this new scene with the new view controller subclass.
var el = document.getElementById('foo');
el.parentNode.innerHTML;
Got my own answer: Using this function from the data from the textarea solves the problem:
function mynl2br($text) {
return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />'));
}
More here: http://php.net/nl2br
As tricky solution you can use Package Manager Console to execute cmd or PowerShell commends
Shortcut for Package Manager Console Alt T N O
Tested on Visual Studio 2017 Community Version
Also its available now as part of Visual Studio version 16.3 Preview 3
Shortcut Ctrl+` same as Visual Studio Code
It's simply the domain that your "facebook" application (wich means application visible on facebook but hosted on the website www.xyz.com) will be hosted. So you can put App Domain = www.xyz.com
I like jQuery Token input. Actually prefer the UI over some of the other options mentioned above.
http://loopj.com/jquery-tokeninput/
Also see: http://railscasts.com/episodes/258-token-fields for an explanation
16kb is about right; if you're using gigabit ethernet, each packet could be 9kb in size.
Let df be the data frame with 2 fields A and B
Case 1: if your field A and B are numeric
df[order(df[,1],df[,2]),] - sorts fields A and B in ascending order
df[order(df[,1],-df[,2]),] - sorts fields A in ascending and B in descending order
priority is given to A.
Case 2: if field A or B is non numeric say factor or character
In our case if B is character and we want to sort in reverse order
df[order(df[,1],-as.numeric(as.factor(df[,2]))),] -> this sorts field A(numerical) in ascending and field B(character) in descending.
priority is given to A.
The idea is that you can apply -sign in order function ony on numericals. So for sorting character strings in descending order you have to coerce them to numericals.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
});
$("input:checked")
$("input:unchecked")
To show:
<img src="//graph.facebook.com/{{fid}}/picture">
<img src="//graph.facebook.com/{{fid}}/picture?type=large">
NOTE: Don't use this. See @Foreever's comment below.
$img = file_get_contents('https://graph.facebook.com/'.$fid.'/picture?type=large');
$file = dirname(__file__).'/avatar/'.$fid.'.jpg';
file_put_contents($file, $img);
Where $fid is your user id on Facebook.
NOTE: In case of images marked as "18+" you will need a valid access_token from a 18+ user:
<img src="//graph.facebook.com/{{fid}}/picture?access_token={{access_token}}">
Graph API v2.0 can't be queried using usernames, you should use userId
always.
SQLite has a printf
function which does exactly that:
SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
Description
Settings.ACTION_APPLICATION_DETAILS_SETTINGS
Opens Details setting page for App. From here user have to manually assign desired permission.
Intent.FLAG_ACTIVITY_NEW_TASK
Optional. If set then opens Settings Screen(Activity) as new activity. Otherwise, it will be opened in currently running activity.
Uri.fromParts("package", getPackageName(), null)
Prepares or creates URI, whereas, getPackageName() - returns name of your application package.
intent.setData(uri)
Don't forget to set this. Otherwise, you will get android.content.ActivityNotFoundException
. Because you have set your intent as Settings.ACTION_APPLICATION_DETAILS_SETTINGS
and android expects some name to search.
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class ConcurrentHashSet<E> extends AbstractSet<E> implements Set<E>{
private final ConcurrentMap<E, Object> theMap;
private static final Object dummy = new Object();
public ConcurrentHashSet(){
theMap = new ConcurrentHashMap<E, Object>();
}
@Override
public int size() {
return theMap.size();
}
@Override
public Iterator<E> iterator(){
return theMap.keySet().iterator();
}
@Override
public boolean isEmpty(){
return theMap.isEmpty();
}
@Override
public boolean add(final E o){
return theMap.put(o, ConcurrentHashSet.dummy) == null;
}
@Override
public boolean contains(final Object o){
return theMap.containsKey(o);
}
@Override
public void clear(){
theMap.clear();
}
@Override
public boolean remove(final Object o){
return theMap.remove(o) == ConcurrentHashSet.dummy;
}
public boolean addIfAbsent(final E o){
Object obj = theMap.putIfAbsent(o, ConcurrentHashSet.dummy);
return obj == null;
}
}
Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.
git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67
Then, abort the rebase again.
D = {}
is a dictionary not set.
>>> d = {}
>>> type(d)
<type 'dict'>
Use D = set()
:
>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])
background: url(../images/backgroundImage.jpg) no-repeat center center fixed;
this should help
I really needed this in C# and found Center MessageBox C#
Here's a nicely formatted version
using System;
using System.Windows.Forms;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;
public class MessageBoxEx
{
private static IWin32Window _owner;
private static HookProc _hookProc;
private static IntPtr _hHook;
public static DialogResult Show(string text)
{
Initialize();
return MessageBox.Show(text);
}
public static DialogResult Show(string text, string caption)
{
Initialize();
return MessageBox.Show(text, caption);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons)
{
Initialize();
return MessageBox.Show(text, caption, buttons);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon, defButton);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon, defButton, options);
}
public static DialogResult Show(IWin32Window owner, string text)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text);
}
public static DialogResult Show(IWin32Window owner, string text, string caption)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon, defButton);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon,
defButton, options);
}
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);
public const int WH_CALLWNDPROCRET = 12;
public enum CbtHookAction : int
{
HCBT_MOVESIZE = 0,
HCBT_MINMAX = 1,
HCBT_QS = 2,
HCBT_CREATEWND = 3,
HCBT_DESTROYWND = 4,
HCBT_ACTIVATE = 5,
HCBT_CLICKSKIPPED = 6,
HCBT_KEYSKIPPED = 7,
HCBT_SYSCOMMAND = 8,
HCBT_SETFOCUS = 9
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("User32.dll")]
public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);
[DllImport("User32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
public static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
} ;
static MessageBoxEx()
{
_hookProc = new HookProc(MessageBoxHookProc);
_hHook = IntPtr.Zero;
}
private static void Initialize()
{
if (_hHook != IntPtr.Zero)
{
throw new NotSupportedException("multiple calls are not supported");
}
if (_owner != null)
{
_hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, _hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
}
}
private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
{
return CallNextHookEx(_hHook, nCode, wParam, lParam);
}
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = _hHook;
if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
{
try
{
CenterWindow(msg.hwnd);
}
finally
{
UnhookWindowsHookEx(_hHook);
_hHook = IntPtr.Zero;
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
private static void CenterWindow(IntPtr hChildWnd)
{
Rectangle recChild = new Rectangle(0, 0, 0, 0);
bool success = GetWindowRect(hChildWnd, ref recChild);
int width = recChild.Width - recChild.X;
int height = recChild.Height - recChild.Y;
Rectangle recParent = new Rectangle(0, 0, 0, 0);
success = GetWindowRect(_owner.Handle, ref recParent);
Point ptCenter = new Point(0, 0);
ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);
Point ptStart = new Point(0, 0);
ptStart.X = (ptCenter.X - (width / 2));
ptStart.Y = (ptCenter.Y - (height / 2));
ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X;
ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y;
int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width,
height, false);
}
}
this would help.. from google apis demos
private List<Marker> markerList = new ArrayList<>();
Marker marker = mGoogleMap.addMarker(new MarkerOptions().position(geoLatLng)
.title(title));
markerList.add(marker);
// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.
final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
if (mapView!=null) {
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@SuppressWarnings("deprecation") // We use the new method when supported
@SuppressLint("NewApi") // We check which build version we are using.
@Override
public void onGlobalLayout() {
//Calculate the markers to get their position
LatLngBounds.Builder b = new LatLngBounds.Builder();
for (Marker m : markerList) {
b.include(m.getPosition());
}
// also include current location to include in the view
b.include(new LatLng(mLocation.getLatitude(),mLocation.getLongitude()));
LatLngBounds bounds = b.build();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
}
});
}
}
for clear info look at this url. https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/MarkerDemoActivity.java
If you would like to use awk
then this would work too
awk -F= '{$2="xxx";print}' OFS="\=" filename
As long as method parameters (number (or) type) are different, yes they can. It is called overloading.
Overloaded methods are differentiated by the number and the type of the arguments passed into the method
public static void main(String[] args)
only main method with single String[]
(or) String...
as param will be considered as entry point for the program.
Based on @Nick keets answer, here is a more complete example:
extension String: Error {} // Enables you to throw a string
extension String: LocalizedError { // Adds error.localizedDescription to Error instances
public var errorDescription: String? { return self }
}
func test(color: NSColor) throws{
if color == .red {
throw "I don't like red"
}else if color == .green {
throw "I'm not into green"
}else {
throw "I like all other colors"
}
}
do {
try test(color: .green)
} catch let error where error.localizedDescription == "I don't like red"{
Swift.print ("Error: \(error)") // "I don't like red"
}catch let error {
Swift.print ("Other cases: Error: \(error.localizedDescription)") // I like all other colors
}
Originally published on my swift blog: http://eon.codes/blog/2017/09/01/throwing-simple-errors/
You can use the BigInteger
class for integers and BigDecimal
for numbers with decimal digits. Both classes are defined in java.math
package.
Example:
BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);
You can't save things to Hibernate until you've also told Hibernate about all the other objects referenced by this newly saved object. So in this case, you're telling Hibernate about a User
, but haven't told it about the Country
.
You can solve problems like this in two ways.
Manually
Call session.save(country)
before you save the User
.
CascadeType
You can specify to Hibernate that this relationship should propagate some operations using CascadeType. In this case CascadeType.PERSIST would do the job, as would CascadeType.ALL.
Referencing existing countries
Based on your response to @zerocool though, you have a second problem, which is that when you have two User
objects with the same Country
, you are not making sure it's the same Country
. To do this, you have to get the appropriate Country
from the database, set it on the new user, and then save the User
. Then, both of your User
objects will refer to the same Country
, not just two Country
instances that happen to have the same name. Review the Criteria
API as one way of fetching existing instances.
There is no google play store in avd emulator. But you can install it manually.
Install Google APIs System Image, so you will have google services already (without play store)
Create AVD based on Google APIs image
Download smallest archive from http://opengapps.org/ and extract Phonesky.apk from it
Push Phonesky.apk to /system/priv-app/ on avd.
Restart avd. Google play should be there.
Recently I've just tried to do it by myself and you can find detailed tutorial on my blog: http://linuxoidchannel.blogspot.com/2017/01/how-to-install-google-play-store-on.html
With dplyr 0.7.2
, you can use the very useful case_when
function :
x=read.table(
text="V1 V2 V3 V4
1 1 2 3 5
2 2 4 4 1
3 1 4 1 1
4 4 5 1 3
5 5 5 5 4")
x$V5 = case_when(x$V1==1 & x$V2!=4 ~ 1,
x$V2==4 & x$V3!=1 ~ 2,
TRUE ~ 0)
Expressed with dplyr::mutate
, it gives:
x = x %>% mutate(
V5 = case_when(
V1==1 & V2!=4 ~ 1,
V2==4 & V3!=1 ~ 2,
TRUE ~ 0
)
)
Please note that NA
are not treated specially, as it can be misleading. The function will return NA
only when no condition is matched. If you put a line with TRUE ~ ...
, like I did in my example, the return value will then never be NA
.
Therefore, you have to expressively tell case_when
to put NA
where it belongs by adding a statement like is.na(x$V1) | is.na(x$V3) ~ NA_integer_
. Hint: the dplyr::coalesce()
function can be really useful here sometimes!
Moreover, please note that NA
alone will usually not work, you have to put special NA
values : NA_integer_
, NA_character_
or NA_real_
.
I had some trouble putting together all the pieces for doing a jQuery regular expression validator, but I got it to work... Here is a complete working example. It uses the 'Validation' plugin which can be found in jQuery Validation Plugin
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://YOURJQUERYPATH/js/jquery.js" type="text/javascript"></script>
<script src="http://YOURJQUERYPATH/js/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() {
$.validator.addMethod("EMAIL", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
}, "Email Address is invalid: Please enter a valid email address.");
$.validator.addMethod("PASSWORD",function(value,element){
return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
},"Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");
$.validator.addMethod("SUBMIT",function(value,element){
return this.optional(element) || /[^ ]/i.test(value);
},"You did not click the submit button.");
// Validate signup form on keyup and submit
$("#LOGIN").validate({
rules: {
EMAIL: "required EMAIL",
PASSWORD: "required PASSWORD",
SUBMIT: "required SUBMIT",
},
});
});
</script>
</head>
<body>
<div id="LOGIN_FORM" class="form">
<form id="LOGIN" name="LOGIN" method="post" action="/index/secure/authentication?action=login">
<h1>Log In</h1>
<div id="LOGIN_EMAIL">
<label for="EMAIL">Email Address</label>
<input id="EMAIL" name="EMAIL" type="text" value="" tabindex="1" />
</div>
<div id="LOGIN_PASSWORD">
<label for="PASSWORD">Password</label>
<input id="PASSWORD" name="PASSWORD" type="password" value="" tabindex="2" />
</div>
<div id="LOGIN_SUBMIT">
<input id="SUBMIT" name="SUBMIT" type="submit" value="Submit" tabindex="3" />
</div>
</form>
</div>
</body>
</html>
A ListView
is basically like a ListBox
(and inherits from it), but it also has a View
property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView
, but you can easily create your own.
Another difference is the default selection mode: it's Single
for a ListBox
, but Extended
for a ListView
I'm using varchar(15)
so far everything is working for me. Insert, Update, Select. I have just started an app that has IP Addresses, though I have not done much dev work yet.
Here is the select statement:
select * From dbo.Server
where [IP] = ('132.46.151.181')
Go
Another one solution: html:
<div class="background">
<div class="container">Hello world!</div>
</div>
css:
.background {
position: relative;
width: 50px;
height: 50px;
border-right: 150px solid lightgreen;
border-bottom: 150px solid lightgreen;
border-radius: 10px;
}
.background::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
border: 25px solid lightgreen;
border-top-color: transparent;
border-left-color: transparent;
}
.container {
position: absolute;
padding-left: 25px;
padding-top: 25px;
font-size: 38px;
font-weight: bolder;
}
If anyone is still unable to solve the issue, please check following thread and follow callmebob's answer.
PHPMailer - SMTP ERROR: Password command failed when send mail from my server
blazeroni already made it pretty clear, I just want to add few points.
<merge>
is used for optimizing layouts.It is used for reducing unnecessary nesting. <merge>
tag is added into another layout,the <merge>
node is removed and its child view is added directly to the new parent.you'd use any of these:
JSTL c:forEach varStatus properties
Property Getter Description
current getCurrent() The item (from the collection) for the current round of iteration.
index getIndex() The zero-based index for the current round of iteration.
count getCount() The one-based count for the current round of iteration
last isLast() Flag indicating whether the current round is the last pass through the iteration
begin getBegin() The value of the begin attribute
end getEnd() The value of the end attribute
step getStep() The value of the step attribute
I agree with above answer. But here is another way of CSS compression.
You can concat your CSS by using YUI compressor:
module.exports = function(grunt) {
var exec = require('child_process').exec;
grunt.registerTask('cssmin', function() {
var cmd = 'java -jar -Xss2048k '
+ __dirname + '/../yuicompressor-2.4.7.jar --type css '
+ grunt.template.process('/css/style.css') + ' -o '
+ grunt.template.process('/css/style.min.css')
exec(cmd, function(err, stdout, stderr) {
if(err) throw err;
});
});
};
Here is a possible solution the solution #3 on my comments to blubill's answer:
yourscript.php
========================
<?php
$dir = '/home/user/Pictures';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false)
{
echo 'Directory "', $dir, '" not found!';
}
else
{
$dir_contents = scandir($dir);
foreach ($dir_contents as $file)
{
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true)
{
$name = basename($file);
echo "<img src='img.php?name={$name}' />";
}
}
}
?>
img.php
========================
<?php
$name = $_GET['name'];
$mimes = array
(
'jpg' => 'image/jpg',
'jpeg' => 'image/jpg',
'gif' => 'image/gif',
'png' => 'image/png'
);
$ext = strtolower(end(explode('.', $name)));
$file = '/home/users/Pictures/'.$name;
header('content-type: '. $mimes[$ext]);
header('content-disposition: inline; filename="'.$name.'";');
readfile($file);
?>
I tried several approaches.
# BY {dplyr}
data.table(ID = c(rep("A", 5), rep("B",5)),
Quarter = c(1:5, 1:5),
value = rnorm(10)) -> df1
df1 %<>% dplyr::mutate(ID = as.factor(ID),
Quarter = as.character(Quarter))
# check classes
dplyr::glimpse(df1)
# Observations: 10
# Variables: 3
# $ ID (fctr) A, A, A, A, A, B, B, B, B, B
# $ Quarter (chr) "1", "2", "3", "4", "5", "1", "2", "3", "4", "5"
# $ value (dbl) -0.07676732, 0.25376110, 2.47192852, 0.84929175, -0.13567312, -0.94224435, 0.80213218, -0.89652819...
, or otherwise
# from list to data.table using data.table::setDT
list(ID = as.factor(c(rep("A", 5), rep("B",5))),
Quarter = as.character(c(1:5, 1:5)),
value = rnorm(10)) %>% setDT(list.df) -> df2
class(df2)
# [1] "data.table" "data.frame"
ALTER TABLE provider ADD PRIMARY KEY(person,place,thing);
If a primary key already exists then you want to do this
ALTER TABLE provider DROP PRIMARY KEY, ADD PRIMARY KEY(person, place, thing);
The CSS code would be:
box-shadow: 0 0 10px 5px white;
That will shadow the entire DIV no matter its shape!
You need to use the new
operator when creating the object
Contacts.add(new Data(name, address, contact)); // Creating a new object and adding it to list - single step
or else
Data objt = new Data(name, address, contact); // Creating a new object
Contacts.add(objt); // Adding it to the list
and your constructor shouldn't contain void
. Else it becomes a method in your class.
public Data(String n, String a, String c) { // Constructor has the same name as the class and no return type as such
I recommend using .htaccess
. You only need to add:
DirectoryIndex home.php
or whatever page name you want to have for it.
EDIT: basic htaccess tutorial.
1) Create .htaccess
file in the directory where you want to change the index file.
.
in front, to ensure it is a "hidden" fileEnter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.
2) Set server to allow reading of .htaccess
files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)
Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default
for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:
sudo service apache2 restart
Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.
Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess
file in that sub-site's root and it will overwrite the declaration in the parent.
you could do so:
<button onclick="location.href='page'">
you could change the action attribute of the form on click the button:
<button class="float-left submit-button" onclick='myFun()'>Home</button>
<script>
myFun(){
$('form').attr('action','new path');
}
</script>
The SQLite3 PDO driver is named SQLite, not SQLite3, so you can do:
new SQLite("database");
For a SQLite2 database:
new SQLite2("database");
For everybody who uses Rider you have to select your project>Right Click>Properties>Configurations Then select Debug and Release and check "Allow unsafe code" for both.
Yes it is. Use Data Validation from the Data panel. Select Allow: List and pick those cells on the other sheet as your source.
Zenity is really the exact tool that I think that you are looking for.
or
zenity --help
Walkthrough on using MySQL's LOAD DATA command:
Create your table:
CREATE TABLE foo(myid INT, mymessage VARCHAR(255), mydecimal DECIMAL(8,4));
Create your tab delimited file (note there are tabs between the columns):
1 Heart disease kills 1.2
2 one out of every two 2.3
3 people in America. 4.5
Use the load data command:
LOAD DATA LOCAL INFILE '/tmp/foo.txt'
INTO TABLE foo COLUMNS TERMINATED BY '\t';
If you get a warning that this command can't be run, then you have to enable the --local-infile=1
parameter described here: How can I correct MySQL Load Error
The rows get inserted:
Query OK, 3 rows affected (0.00 sec)
Records: 3 Deleted: 0 Skipped: 0 Warnings: 0
Check if it worked:
mysql> select * from foo;
+------+----------------------+-----------+
| myid | mymessage | mydecimal |
+------+----------------------+-----------+
| 1 | Heart disease kills | 1.2000 |
| 2 | one out of every two | 2.3000 |
| 3 | people in America. | 4.5000 |
+------+----------------------+-----------+
3 rows in set (0.00 sec)
How to specify which columns to load your text file columns into:
Like this:
LOAD DATA LOCAL INFILE '/tmp/foo.txt' INTO TABLE foo
FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'
(@col1,@col2,@col3) set myid=@col1,mydecimal=@col3;
The file contents get put into variables @col1, @col2, @col3. myid gets column 1, and mydecimal gets column 3. If this were run, it would omit the second row:
mysql> select * from foo;
+------+-----------+-----------+
| myid | mymessage | mydecimal |
+------+-----------+-----------+
| 1 | NULL | 1.2000 |
| 2 | NULL | 2.3000 |
| 3 | NULL | 4.5000 |
+------+-----------+-----------+
3 rows in set (0.00 sec)
the case above is for a new project. I hit upon this error while editing a fork of a well established library.
the typedef was included in the file I was editing but the struct wasn't.
The end result being that I was attempting to edit the struct in the wrong place.
If you run into this in a similar way look for other places where the struct is edited and try it there.
Here is a dplyr
based option:
newV = df %>% slice(1) %>% unlist(use.names = FALSE)
# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()
Here is a list of formatters used with String.format()
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
The simplest answer:
A mutable variable is one whose value may change in place, whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable.
Example:
>>>x = 5
Will create a value 5 referenced by x
x -> 5
>>>y = x
This statement will make y refer to 5 of x
x -------------> 5 <-----------y
>>>x = x + y
As x being an integer (immutable type) has been rebuild.
In the statement, the expression on RHS will result into value 10 and when this is assigned to LHS (x), x will rebuild to 10. So now
x--------->10
y--------->5
http://code.google.com/apis/visualization/documentation/gallery.html
Has very cool interactive options including maps, gauges, and charts.
Object - An instance of a class that has its own state and access to all of the behaviour defined by its class.
Instance - Reference to an memory area for that particular class.
If you use ng-model, you don't want to also use ng-checked. Instead just initialize the model variable to true. Normally you would do this in a controller that is managing your page (add one). In your fiddle I just did the initialization in an ng-init attribute for demonstration purposes.
<div ng-app="">
Send to Office: <input type="checkbox" ng-model="checked" ng-init="checked=true"><br/>
<select id="transferTo" ng-disabled="checked">
<option>Tech1</option>
<option>Tech2</option>
</select>
</div>
Yes, you can! There's a Visual Studio for macs and there's Visual Studio Code if you only need a text editor like Sublime Text.
In your .htaccess file , if you are using apache you can try with
Rule for Error Page - 404ErrorDocument 404 http://www.domain.com/notFound.html
here you can specify whichever field you want in your output and also which you don't.
POST index_name/_search
{
"_source": {
"includes": [ "field_name", "field_name" ],
"excludes": [ "field_name" ]
},
"query" : {
"match" : { "field_name" : "value" }
}
}
Update your environment variables
Ensure the reference to java/bin is up to date in 'Path'; This may be automatic if you have JAVA_HOME or equivalent set. If JAVA_HOME is set, simply update it to refer to the older JRE installation.
what i did was a quick fix by converting readlines to string but i do not recommencement it but it works and i dont know if there are limitations or not
`def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
readlines = str(readfile.readlines())
Type = readlines.split(",")
x = Type[1]
y = Type[2]
for points in Type:
print(x,y)
getQuakeData()`
Check your windows task manager and make sure you kill all chrome processes before running the command.
Try giving 5 ',' in every line, similar to line number 4.
My answer is similar to the accepted answer, but it also check for Null and Empty String.
DECLARE @String VARCHAR(100)
SET @String = 'asdfsdf1'
-- If string is null return null, else if string is empty return as it is, else chop off the end character
SET @String = Case @String when null then null else (case LEN(@String) when 0 then @String else LEFT(@String, LEN(@String) - 1) end ) end
SELECT @String
You can do as follows
ifconfig <Interface ex:eth0,eth1> | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'
Also you can get MAC for all interface as follows
cat /sys/class/net/*/address
For particular interface like for eth0
cat /sys/class/net/eth0/address
For another approach, you can take a file like this:
From: Sunday <[email protected]>
To: Monday <[email protected]>
Subject: Day
Tuesday Wednesday
and send like this:
<?php
$a1 = ['[email protected]'];
$r1 = fopen('a.txt', 'r');
$r2 = curl_init('smtps://smtp.gmail.com');
curl_setopt($r2, CURLOPT_MAIL_RCPT, $a1);
curl_setopt($r2, CURLOPT_NETRC, true);
curl_setopt($r2, CURLOPT_READDATA, $r1);
curl_setopt($r2, CURLOPT_UPLOAD, true);
curl_exec($r2);
Programatically this can be achieved with SCHTASKS:
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=1074)]]" /EC Security /tn on_shutdown_normal /tr "c:\some.bat"
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6006)]]" /EC Security /tn on_shutdown_6006 /tr "c:\some.bat"
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6008)]]" /EC Security /tn on_shutdown_6008 /tr "c:\some.bat"