When we try to drop a column which is depended upon then we see this kind of error:
The object 'DF__*' is dependent on column ''.
drop the constraint which is dependent on that column with:
ALTER TABLE TableName DROP CONSTRAINT dependent_constraint;
Example:
Msg 5074, Level 16, State 1, Line 1
The object 'DF__Employees__Colf__1273C1CD' is dependent on column 'Colf'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE DROP COLUMN Colf failed because one or more objects access this column.
Drop Constraint(DF__Employees__Colf__1273C1CD):
ALTER TABLE Employees DROP CONSTRAINT DF__Employees__Colf__1273C1CD;
Then you can Drop Column:
Alter Table TableName Drop column ColumnName
You can also do this with Swift 3.
Perform the function after delay like so.
override func viewDidLoad() {
super.viewDidLoad()
self.perform(#selector(ClassName.performAction), with: nil, afterDelay: 2.0)
}
@objc func performAction() {
//This function will perform after 2 seconds
print("Delayed")
}
cout << "Enter amount of spaces you would like (integer)" << endl;
cin >> n;
//print n spaces
for (int i = 0; i < n; ++i)
{
cout << " " ;
}
cout <<endl;
Typically sites that do this by loading content via ajax and listening to the readystatechanged
event to update the DOM with a loading GIF or the content.
How are you currently loading your content?
The code would be similar to this:
function load(url) {
// display loading image here...
document.getElementById('loadingImg').visible = true;
// request your data...
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
// content is loaded...hide the gif and display the content...
if (req.responseText) {
document.getElementById('content').innerHTML = req.responseText;
document.getElementById('loadingImg').visible = false;
}
}
};
request.send(vars);
}
There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.
I found this catered for dates in 21st Century that could be entered as dd/mm or dd/mm/yy. It is intended to print an attendance register and asks for the meeting date to start with.
Sub Print_Register()
Dim MeetingDate, Answer
Sheets("Register").Select
Range("A1").Select
GetDate:
MeetingDate = DateValue(InputBox("Enter the date of the meeting." & Chr(13) & _
"Note Format" & Chr(13) & "Format DD/MM/YY or DD/MM", "Meeting Date", , 10000, 10000))
If MeetingDate = "" Then GoTo TheEnd
If MeetingDate < 36526 Then MeetingDate = MeetingDate + 36526
Range("Current_Meeting_Date") = MeetingDate
Answer = MsgBox("Date OK?", 3)
If Answer = 2 Then GoTo TheEnd
If Answer = 7 Then GoTo GetDate
ExecuteExcel4Macro "PRINT(1,,,1,,,,,,,,2,,,TRUE,,FALSE)"
TheEnd:
End Sub
SELECT a.file_name,
substr(A.tablespace_name,1,14) tablespace_name,
trunc(decode(A.autoextensible,'YES',A.MAXSIZE-A.bytes+b.free,'NO',b.free)/1024/1024) free_mb,
trunc(a.bytes/1024/1024) allocated_mb,
trunc(A.MAXSIZE/1024/1024) capacity,
a.autoextensible ae
FROM (
SELECT file_id, file_name,
tablespace_name,
autoextensible,
bytes,
decode(autoextensible,'YES',maxbytes,bytes) maxsize
FROM dba_data_files
GROUP BY file_id, file_name,
tablespace_name,
autoextensible,
bytes,
decode(autoextensible,'YES',maxbytes,bytes)
) a,
(SELECT file_id,
tablespace_name,
sum(bytes) free
FROM dba_free_space
GROUP BY file_id,
tablespace_name
) b
WHERE a.file_id=b.file_id(+)
AND A.tablespace_name=b.tablespace_name(+)
ORDER BY A.tablespace_name ASC;
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
(1) Is it possible to pass a JSON object to the url like in Ex.2?
No, because http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"}
is not a valid URL.
If you want to do it the RESTful way, use http://localhost:8080/api/v1/mno/objectKey/1/Saif
, and defined your method like this:
@RequestMapping(path = "/mno/objectKey/{id}/{name}", method = RequestMethod.GET)
public Book getBook(@PathVariable int id, @PathVariable String name) {
// code here
}
(2) How can we pass and parse the parameters in Ex.1?
Just add two request parameters, and give the correct path.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.GET)
public Book getBook(@RequestParam int id, @RequestParam String name) {
// code here
}
UPDATE (from comment)
What if we have a complicated parameter structure ?
"A": [ { "B": 37181, "timestamp": 1160100436, "categories": [ { "categoryID": 2653, "timestamp": 1158555774 }, { "categoryID": 4453, "timestamp": 1158555774 } ] } ]
Send that as a POST
with the JSON data in the request body, not in the URL, and specify a content type of application/json
.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.POST, consumes = "application/json")
public Book getBook(@RequestBody ObjectKey objectKey) {
// code here
}
You can wrap all tasks which can fail in block, and use ignore_errors: yes
with that block.
tasks:
- name: ls
command: ls -la
- name: pwd
command: pwd
- block:
- name: ls non-existing txt file
command: ls -la no_file.txt
- name: ls non-existing pic
command: ls -la no_pic.jpg
ignore_errors: yes
Read more about error handling in blocks here.
I had a similar issue which i solved by making two changes
added below entry in application.yaml file
spring:
jackson:
serialization.write_dates_as_timestamps: false
add below two annotations in pojo
sample example
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class Customer {
//your fields ...
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
protected LocalDate birthdate;
}
then the following json requests worked for me
{
"birthdate": "2019-11-28"
}
{
"birthdate":[2019,11,18]
}
Hope it helps!!
The other answers explain how to produce a string formatted like in your example, but if all you need to do is to print
that stuff you could simply write:
first = 10
second = 20
print "First number is", first, "and second number is", second
From: http://news.ycombinator.com/item?id=1726074
For RHEL-based i386 distributions:
yum install ImageMagick.i386
yum install ImageMagick-devel.i386
pecl install imagick
echo "extension=imagick.so" > /etc/php.d/imagick.ini
service httpd restart
This may also work on other i386 distributions using yum package manager. For x86_64, just replace .i386 with .x86_64
I've tried everything suggested here but didn't work for me. So in case I can help anyone with a similar issue, every single tutorial I've checked is not updated to work with version 4.
Here is what I've done to make it work
import React from 'react';
import App from './App';
import ReactDOM from 'react-dom';
import {
HashRouter,
Route
} from 'react-router-dom';
ReactDOM.render((
<HashRouter>
<div>
<Route path="/" render={()=><App items={temasArray}/>}/>
</div>
</HashRouter >
), document.getElementById('root'));
That's the only way I have managed to make it work without any errors or warnings.
In case you want to pass props to your component for me the easiest way is this one:
<Route path="/" render={()=><App items={temasArray}/>}/>
This might be useful for refreshing also. But if you want to keep track of position on the page before you click on a same position.. The following code will help.
Also added a data-confirm for prompting the user if they really want to do that..
Note: I'm using jQuery and js-cookie.js to store cookie info.
$(document).ready(function() {
// make all links with data-confirm prompt the user first.
$('[data-confirm]').on("click", function (e) {
e.preventDefault();
var msg = $(this).data("confirm");
if(confirm(msg)==true) {
var url = this.href;
if(url.length>0) window.location = url;
return true;
}
return false;
});
// on certain links save the scroll postion.
$('.saveScrollPostion').on("click", function (e) {
e.preventDefault();
var currentYOffset = window.pageYOffset; // save current page postion.
Cookies.set('jumpToScrollPostion', currentYOffset);
if(!$(this).attr("data-confirm")) { // if there is no data-confirm on this link then trigger the click. else we have issues.
var url = this.href;
window.location = url;
//$(this).trigger('click'); // continue with click event.
}
});
// check if we should jump to postion.
if(Cookies.get('jumpToScrollPostion') !== "undefined") {
var jumpTo = Cookies.get('jumpToScrollPostion');
window.scrollTo(0, jumpTo);
Cookies.remove('jumpToScrollPostion'); // and delete cookie so we don't jump again.
}
});
A example of using it like this.
<a href='gotopage.html' class='saveScrollPostion' data-confirm='Are you sure?'>Goto what the heck</a>
i believe this would be the fastest way, by a lookup table:
private static final long[] FACTORIAL_TABLE = initFactorialTable();
private static long[] initFactorialTable() {
final long[] factorialTable = new long[21];
factorialTable[0] = 1;
for (int i=1; i<factorialTable.length; i++)
factorialTable[i] = factorialTable[i-1] * i;
return factorialTable;
}
/**
* Actually, even for {@code long}, it works only until 20 inclusively.
*/
public static long factorial(final int n) {
if ((n < 0) || (n > 20))
throw new OutOfRangeException("n", 0, 20);
return FACTORIAL_TABLE[n];
}
For the native type long
(8 bytes), it can only hold up to 20!
20! = 2432902008176640000(10) = 0x 21C3 677C 82B4 0000
Obviously, 21!
will cause overflow.
Therefore, for native type long
, only a maximum of 20!
is allowed, meaningful, and correct.
Your code looks great, the only thing i see is that you did not include the collapsed class in your button selector. http://www.bootply.com/cpHugxg2f8 Note: Requires JavaScript plugin If JavaScript is disabled and the viewport is narrow enough that the navbar collapses, it will be impossible to expand the navbar and view the content within the .navbar-collapse.
The responsive navbar requires the collapse plugin to be included in your version of Bootstrap.
<div class="navbar-wrapper">
<div class="container">
<nav class="navbar navbar-inverse navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="">Page 1</a>
</li>
<li><a href="">Page 2</a>
</li>
<li><a href="">Page 3</a>
</li>
</ul>
</div>
</div>
</nav>
</div>
</div>
This is very similar to another stackoverflow article, Bind a function to Twitter Bootstrap Modal Close. Assuming you are using some version of Bootstap v3 or v4, you can do something like the following:
$("#myModal").on("hidden.bs.modal", function () {
// put your default event here
});
Separate classes by white space
$('element').removeClass('class1 class2');
Besides what other said, a common problem is to declare the types of the same function that is overloaded. Typical case is EventEmitter on() method which will accept multiple kind of listeners. Similar could happen When working with redux actions - and there you use the action type as literal to mark the overloading, In case of EventEmitters, you use the event name literal type:
interface MyEmitter extends EventEmitter {
on(name:'click', l: ClickListener):void
on(name:'move', l: MoveListener):void
on(name:'die', l: DieListener):void
//and a generic one
on(name:string, l:(...a:any[])=>any):void
}
type ClickListener = (e:ClickEvent)=>void
type MoveListener = (e:MoveEvent)=>void
... etc
// will type check the correct listener when writing something like:
myEmitter.on('click', e=>...<--- autocompletion
I would like to add an answer here, because this worked for me. I used time delays, while loops, everything I could think of.
I had the Windows Explorer window of the output folder open. I closed it, and everything worked like a charm.
I hope this helps someone.
java 6
export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-amd64
or java 7
export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-amd64
It's not relative to performance...
You set async to false, when you need that ajax request to be completed before the browser passes to other codes:
<script>
// ...
$.ajax(... async: false ...); // Hey browser! first complete this request,
// then go for other codes
$.ajax(...); // Executed after the completion of the previous async:false request.
</script>
If you're facing this problem with Eclipse, I've been following many different solutions but the one that worked for me is this:
Right click your project folder and open up Properties.
From the right panel, select Java Build Path then go to Libraries tab.
Select Add External JARs to import the mysql driver.
From the right panel, select Deployment Assembly.
Select Add..., then select Java Build Path Entries and click Next.
You should see the sql driver on the list. Select it and click first.
And that's it! Try to run it again! Cheers!
Alright, before I go into the solution, lets be on the same line about this one fact: Javascript is Event Based. So you'll usually have to setup callbacks to be able to do procedures.
Based on your comment I assumed you have a trigger that will do the logic that launched the function depending if the element is clicked; for sake of demonstration I made it a "submit button"; but this can be a timer or something else.
var the_action = function(type) {
switch(type) {
case 'a':
console.log('Case A');
break;
case 'b':
console.log('Case B');
break;
}
};
$('.clickme').click(function() {
console.log('Clicked');
$(this).data('clicked', true);
});
$('.submit').click(function() {
// All your logic can go here if you want.
if($('.clickme').data('clicked') == true) {
the_action('a');
} else {
the_action('b');
}
});
Live Example: http://jsfiddle.net/kuroir/6MCVJ/
If the same key and initialization vector are used for encoding and decoding, this issue does not come from data decoding but from data encoding.
After you called Write method on a CryptoStream object, you must ALWAYS call FlushFinalBlock method before Close method.
MSDN documentation on CryptoStream.FlushFinalBlock method says:
"Calling the Close method will call FlushFinalBlock ..."
https://msdn.microsoft.com/en-US/library/system.security.cryptography.cryptostream.flushfinalblock(v=vs.110).aspx
This is wrong. Calling Close method just closes the CryptoStream and the output Stream.
If you do not call FlushFinalBlock before Close after you wrote data to be encrypted, when decrypting data, a call to Read or CopyTo method on your CryptoStream object will raise a CryptographicException exception (message: "Padding is invalid and cannot be removed").
This is probably true for all encryption algorithms derived from SymmetricAlgorithm (Aes, DES, RC2, Rijndael, TripleDES), although I just verified that for AesManaged and a MemoryStream as output Stream.
So, if you receive this CryptographicException exception on decryption, read your output Stream Length property value after you wrote your data to be encrypted, then call FlushFinalBlock and read its value again. If it has changed, you know that calling FlushFinalBlock is NOT optional.
And you do not need to perform any padding programmatically, or choose another Padding property value. Padding is FlushFinalBlock method job.
.........
Additional remark for Kevin:
Yes, CryptoStream calls FlushFinalBlock before calling Close, but it is too late: when CryptoStream Close method is called, the output stream is also closed.
If your output stream is a MemoryStream, you cannot read its data after it is closed. So you need to call FlushFinalBlock on your CryptoStream before using the encrypted data written on the MemoryStream.
If your output stream is a FileStream, things are worse because writing is buffered. The consequence is last written bytes may not be written to the file if you close the output stream before calling Flush on FileStream. So before calling Close on CryptoStream you first need to call FlushFinalBlock on your CryptoStream then call Flush on your FileStream.
I guess you will get ORA-01741: illegal zero-length identifier if you use the following
SELECT "" AS Contact FROM Customers;
And if you use the following 2 statements, you will be getting the same null value populated in the column.
SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;
The reason in my case was the target build was not the same between project debugger and test runner. To unify those elements:
After they are identical, rebuild your solution then test methods will appear for you.
Another option is to use the Aggregate extension rather than Join:
String s = myDict.Select(x => x.Key + "=" + x.Value).Aggregate((s1, s2) => s1 + ";" + s2);
use this tag {!! description text !!}
You've specifically mentioned a "variable-length array" in your question, so neither of the existing two answers (as I write this) are quite right.
Java doesn't have any concept of a "variable-length array", but it does have Collections, which serve in this capacity. Any collection (technically any "Iterable", a supertype of Collections) can be looped over as simply as this:
Collection<Thing> things = ...;
for (Thing t : things) {
System.out.println(t);
}
EDIT: it's possible I misunderstood what he meant by 'variable-length'. He might have just meant it's a fixed length but not every instance is the same fixed length. In which case the existing answers would be fine. I'm not sure what was meant.
HAVING
is used to filter on aggregations in your GROUP BY
.
For example, to check for duplicate names:
SELECT Name FROM Usernames
GROUP BY Name
HAVING COUNT(*) > 1
For remove in NestJS need to add option to Shema() decorator
@Schema({ versionKey: false })
You can avoid the loop and cut etc by using:
awk -F ':' '{system("ping " $1);}' config.txt
However it would be better if you post a snippet of your config.txt
Rather than use "d", why not "p". I am not sure if the "p *" will work. I didn't try that. You can; however use the following script"
#!/bin/bash
#
MAIL_INDEX=$(printf 'h a\nq\n' | mail | egrep -o '[0-9]* unread' | awk '{print $1}')
markAllRead=
for (( i=1; i<=$MAIL_INDEX; i++ ))
do
markAllRead=$markAllRead"p $i\n"
done
markAllRead=$markAllRead"q\n"
printf "$markAllRead" | mail
This code will do that
<?php
$string = 'abc-123-xyz-789';
$output = explode("-",$string);
echo $output[count($output)-1];
?>
If you are using Angular UI Router, you can listen for the $viewContentLoaded
event.
"$viewContentLoaded - fired once the view is loaded, after the DOM is rendered. The '$scope' of the view emits the event." - Link
$scope.$on('$viewContentLoaded',
function(event){ ... });
A void*
does not mean anything. It is a pointer, but the type that it points to is not known.
It's not that it can return "anything". A function that returns a void*
generally is doing one of the following:
operator new
and malloc
return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void
.This construct is nothing like dynamic
or object
in C#. Those tools actually know what the original type is; void*
does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one.
And on a personal note, if you see code that uses void*
's "often", you should rethink what code you're looking at. void*
usage, especially in C++, should be rare, used primary for dealing in raw memory.
If you have a single Buffer
you can use its toString
method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8
if you don't provide a parameter, but I've explicitly set the encoding in this example.
var req = http.request(reqOptions, function(res) {
...
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// process utf8 text chunk
});
});
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8
-character may be contained in the first Buffer
(chunk) and the second byte in the second Buffer
then you should use a StringDecoder
. :
var StringDecoder = require('string_decoder').StringDecoder;
var req = http.request(reqOptions, function(res) {
...
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
var textChunk = decoder.write(chunk);
// process utf8 text chunk
});
});
This way bytes of incomplete characters are buffered by the StringDecoder
until all required bytes were written to the decoder.
I see the other answer just posted, but I think you are interactive with clients playing your game, so I may pose another approach (while BufferedReader is definitely valid in some cases).
If you wanted to... you could delegate the "registration" responsibility to the client. I.e. you would have a collection of connected users with a timestamp on the last message received from each... if a client times out, you would force a re-registration of the client, but that leads to the quote and idea below.
I have read that to actually determine whether or not a socket has been closed data must be written to the output stream and an exception must be caught. This seems like a really unclean way to handle this situation.
If your Java code did not close/disconnect the Socket, then how else would you be notified that the remote host closed your connection? Ultimately, your try/catch is doing roughly the same thing that a poller listening for events on the ACTUAL socket would be doing. Consider the following:
I think one of the features of the abstracted languages is that you are abstracted from the minutia. Think of the using keyword in C# (try/finally) for SqlConnection s or whatever... it's just the cost of doing business... I think that try/catch/finally is the accepted and necesary pattern for Socket use.
here is an utility which is up to transform json2object or Object2json, whatever your pojo (entity T)
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
*
* @author TIAGO.MEDICI
*
*/
public class JsonUtils {
public static boolean isJSONValid(String jsonInString) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonInString);
return true;
} catch (IOException e) {
return false;
}
}
public static String serializeAsJsonString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
StringWriter sw = new StringWriter();
objMapper.writeValue(sw, object);
return sw.toString();
}
public static String serializeAsJsonString(Object object, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
if (indent == true) {
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
StringWriter stringWriter = new StringWriter();
objMapper.writeValue(stringWriter, object);
return stringWriter.toString();
}
public static <T> T jsonStringToObject(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper objMapper = new ObjectMapper();
obj = objMapper.readValue(content, clazz);
return obj;
}
@SuppressWarnings("rawtypes")
public static <T> T jsonStringToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
obj = mapper.readValue(content, new TypeReference<List>() {
});
return obj;
}
public static <T> T jsonStringToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
return obj;
}
Just in case if you have a loop or a json string that need to insert in the database. Try to replace the string with a single quote . here is my solution. example if you have a string that contain's a single quote.
String mystring = "Sample's";
String myfinalstring = mystring.replace("'","''");
String query = "INSERT INTO "+table name+" ("+field1+") values ('"+myfinalstring+"')";
this works for me in c# and java
We use a.b.c.d where
Ancient question, but here is my take on it.
Lexical (static) scope refers to the scope of a variable in the source code.
In a language like JavaScript, where functions can be passed around and attached and re-attached to miscellaneous objects, you might have though that scope would depend on who’s calling the function at the time, but it doesn’t. Changing the scope that way would be dynamic scope, and JavaScript doesn’t do that, except possibly with the this
object reference.
To illustrate the point:
var a='apple';_x000D_
_x000D_
function doit() {_x000D_
var a='aardvark';_x000D_
return function() {_x000D_
alert(a);_x000D_
}_x000D_
}_x000D_
_x000D_
var test=doit();_x000D_
test();
_x000D_
In the example, the variable a
is defined globally, but shadowed in the doit()
function. This function returns another function which, as you see, relies on the a
variable outside of its own scope.
If you run this, you will find that the value used is aardvark
, not apple
which, though it is in the scope of the test()
function, is not in the lexical scope of the original function. That is, the scope used is the scope as it appears in the source code, not the scope where the function is actually used.
This fact can have annoying consequences. For example, you might decide that it’s easier to organise your functions separately, and then use them when the time comes, such as in an event handler:
var a='apple',b='banana';_x000D_
_x000D_
function init() {_x000D_
var a='aardvark',b='bandicoot';_x000D_
document.querySelector('button#a').onclick=function(event) {_x000D_
alert(a);_x000D_
}_x000D_
document.querySelector('button#b').onclick=doB;_x000D_
}_x000D_
_x000D_
function doB(event) {_x000D_
alert(b);_x000D_
}_x000D_
_x000D_
init();
_x000D_
<button id="a">A</button>_x000D_
<button id="b">B</button>
_x000D_
This code sample does one of each. You can see that because of lexical scoping, button A
uses the inner variable, while button B
doesn’t. You may end up nesting functions more than you would have liked.
By the way, in both examples, you will also notice that the inner lexically scoped variables persist even though the containing function function has run its course. This is called closure, and refers to a nested function’s access to outer variables, even if the outer function has finished. JavaScript needs to be smart enough to determine whether those variables are no longer needed, and if not, can garbage collect them.
Have you tried:
SELECT Cast( 2.555 as decimal(53,8))
This would return 2.55500000
. Is that what you want?
UPDATE:
Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:
SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')
returns 8|7
You may be able to use this in your conversion process...
For those who like me doing same mistake. Here is the elaborated answer Tested in Laravel 5.7
UserFile::orderBy('created_at','desc')->get()->toArray();
Array
(
[0] => Array
(
[id] => 2073
[type] => 'DL'
[url] => 'https://i.picsum.photos/12/884/200/300.jpg'
[created_at] => 2020-08-05 17:16:48
[updated_at] => 2020-08-06 18:08:38
)
[1] => Array
(
[id] => 2074
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 17:20:06
[updated_at] => 2020-08-06 18:08:38
)
[2] => Array
(
[id] => 2076
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 17:22:01
[updated_at] => 2020-08-06 18:08:38
)
[3] => Array
(
[id] => 2086
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 19:22:41
[updated_at] => 2020-08-06 18:08:38
)
)
UserFile::select('type','url','updated_at)->distinct('type')->get()->toArray();
Array
(
[0] => Array
(
[type] => 'DL'
[url] => 'https://i.picsum.photos/12/884/200/300.jpg'
[updated_at] => 2020-08-06 18:08:38
)
[1] => Array
(
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[updated_at] => 2020-08-06 18:08:38
)
)
So Pass only those columns in "select()"
, values of which are same.
For example: 'type','url'
. You can add more columns provided they have same value like 'updated_at'
.
If you try to pass "created_at"
or "id"
in "select()"
, then you will get the records same as A.
Because they are different for each row in DB.
in my case it was just an intermittent issues it seems, didn't work for a few tries, then looked at https://registry.npmjs.org (webpage worked fine), tried again, tried again and then it worked.
If you dont want to hard-code the cell addresses you can use the ROW()
function.
eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))
Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.
file_get_contents(php://input) - gets the raw POST data and you need to use this when you write APIs and need XML/JSON/... input that cannot be decoded to $_POST by PHP some example :
send by post JSON string
<input type="button" value= "click" onclick="fn()">
<script>
function fn(){
var js_obj = {plugin: 'jquery-json', version: 2.3};
var encoded = JSON.stringify( js_obj );
var data= encoded
$.ajax({
type: "POST",
url: '1.php',
data: data,
success: function(data){
console.log(data);
}
});
}
</script>
1.php
//print_r($_POST); //empty!!! don't work ...
var_dump( file_get_contents('php://input'));
There are 3 parts to using Font-Awesome in Angular Projects
Installation
Install from NPM and save to your package.json
npm install --save font-awesome
Styling If using CSS
Insert into your style.css
@import '~font-awesome/css/font-awesome.css';
Styling If using SCSS
Insert into your style.scss
$fa-font-path: "../node_modules/font-awesome/fonts";
@import '~font-awesome/scss/font-awesome.scss';
Usage with plain Angular 2.4+ 4+
<i class="fa fa-area-chart"></i>
Usage with Angular Material
In your app.module.ts modify the constructor to use the MdIconRegistry
export class AppModule {
constructor(matIconRegistry: MatIconRegistry) {
matIconRegistry.registerFontClassAlias('fontawesome', 'fa');
}
}
and add MatIconModule
to your @NgModule
imports
@NgModule({
imports: [
MatIconModule,
....
],
declarations: ....
}
Now in any template file you can now do
<mat-icon fontSet="fontawesome" fontIcon="fa-area-chart"></mat-icon>
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
Run cmd
and then run node server.js
. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)
Here is one way of removing a duplicate object.
The blog class should be something like this or similar, like proper pojo
public class Blog {
private String title;
private String author;
private String url;
private String description;
private int hashCode;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean equals(Object obj) {
Blog blog = (Blog)obj;
if(title.equals(blog.title) &&
author.equals(blog.author) &&
url.equals(blog.url) &&
description.equals(blog.description))
{
hashCode = blog.hashCode;
return true;
}else{
hashCode = super.hashCode();
return false;
}
}
}
And use it like this to remove duplicates objects. The key data structure here is the Set and LinkedHashSet. It will remove duplicates and also keep order of entry
Blog blog1 = new Blog();
blog1.setTitle("Game of Thrones");
blog1.setAuthor("HBO");
blog1.setDescription("The best TV show in the US");
blog1.setUrl("www.hbonow.com/gameofthrones");
Blog blog2 = new Blog();
blog2.setTitle("Game of Thrones");
blog2.setAuthor("HBO");
blog2.setDescription("The best TV show in the US");
blog2.setUrl("www.hbonow.com/gameofthrones");
Blog blog3 = new Blog();
blog3.setTitle("Ray Donovan");
blog3.setAuthor("Showtime");
blog3.setDescription("The second best TV show in the US");
blog3.setUrl("www.showtime.com/raydonovan");
ArrayList<Blog> listOfBlogs = new ArrayList<>();
listOfBlogs.add(blog1);
listOfBlogs.add(blog2);
listOfBlogs.add(blog3);
Set<Blog> setOfBlogs = new LinkedHashSet<>(listOfBlogs);
listOfBlogs.clear();
listOfBlogs.addAll(setOfBlogs);
for(int i=0;i<listOfBlogs.size();i++)
System.out.println(listOfBlogs.get(i).getTitle());
Running this should print
Game of Thrones
Ray Donovan
The second one will be removed because it is a duplicate of the first object.
This is how I do it:
// 2056776401.50 = 2,056,776,401.50
function humanizeNumber(n) {
n = n.toString()
while (true) {
var n2 = n.replace(/(\d)(\d{3})($|,|\.)/g, '$1,$2$3')
if (n == n2) break
n = n2
}
return n
}
Or, in CoffeeScript:
# 2056776401.50 = 2,056,776,401.50
humanizeNumber = (n) ->
n = n.toString()
while true
n2 = n.replace /(\d)(\d{3})($|,|\.)/g, '$1,$2$3'
if n == n2 then break else n = n2
n
There are two ways to connect your Android device with ADB over TCP?
Follow this steps
First use below command to get your device IP Address
adb shell ifconfig
OUTPUT of above command
wlan0 Link encap:UNSPEC Driver icnss
inet addr:XXX.XXX.X.XX Bcast:XXX.XXX.X.XXX
With the help you above command you will find the IP Address of connected device
Now use below command
adb tcpip 5555
The above command will restart this TCP port: 5555
Now use below command to connect your device
adb connect XXX.XXX.X.XXX:5555
^^^ ^^^ ^ ^^^
IP Address of device
You can use Android Studio Plugin Android device with ADB
Android WiFi ADB - IntelliJ/Android Studio Plugin
IntelliJ and Android Studio plugin created to quickly connect your Android device over WiFi to install, run and debug your applications without a USB connected. Press one button and forget about your USB cable
Please check this article for more information
yes datediff is implemented; see: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF
By the way I found this by Google-searching "hive datediff", it was the first result ;)
Visual Studio 2019 Community 16.3.10
I had similar issue with Release build. Debug build was compiling without any issues.
Turns out that the problem was caused by OneDrive. Most likely one could experience similar issues with any backed-up drive or cloud service.
I cleaned everything as per Avi Turner's great answer.
In addition, I manually deleted the \obj\Release -folder from my OneDrive folder and also logged to OneDrive with a browser and deleted the folder there also to prevent OneDrive from loading the cloud version back when compiling.
After that rebuilt and everything worked as should.
The way to reinstall Homebrew is completely remove it and start over. The Homebrew FAQ has a link to a shell script to uninstall homebrew.
If the only thing you've installed in /usr/local
is homebrew itself, you can just rm -rf /usr/local/* /usr/local/.git
to clear it out. But /usr/local/
is the standard Unix directory for all extra binaries, not just Homebrew, so you may have other things installed there. In that case uninstall_homebrew.sh
is a better bet. It is careful to only remove homebrew's files and leave the rest alone.
You state in the comments that the returned JSON is this:
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
You're telling Gson that you have an array of Post
objects:
List<Post> postsList = Arrays.asList(gson.fromJson(reader,
Post[].class));
You don't. The JSON represents exactly one Post
object, and Gson is telling you that.
Change your code to be:
Post post = gson.fromJson(reader, Post.class);
I think you're looking for continue
Adding to @behzad.nouri 's answer - we can create a helper routine to handle this common scenario:
def csvDf(dat,**kwargs):
from numpy import array
data = array(dat)
if data is None or len(data)==0 or len(data[0])==0:
return None
else:
return pd.DataFrame(data[1:,1:],index=data[1:,0],columns=data[0,1:],**kwargs)
Let's try it out:
data = [['','a','b','c'],['row1','row1cola','row1colb','row1colc'],
['row2','row2cola','row2colb','row2colc'],['row3','row3cola','row3colb','row3colc']]
csvDf(data)
In [61]: csvDf(data)
Out[61]:
a b c
row1 row1cola row1colb row1colc
row2 row2cola row2colb row2colc
row3 row3cola row3colb row3colc
After verifying that the certificate is issued by a known Certificate Authority (CA), the Subject Alternative Names will be checked, or the Common Name will be checked, to verify that the hostname matches. This is in the checkServerIdentity function. If the certificate has Subject Alternative Names and the hostname is not listed, you'll see the error message described:
Hostname/IP doesn't match certificate's altnames
If you have the CA cert that is used to generate the certificate you're using (usually the case when using self-signed certificates), this can be provided with
var r = require('request');
var opts = {
method: "POST",
ca: fs.readFileSync("ca.cer")
};
r('https://api.dropbox.com', opts, function (error, response, body) {
// do something
});
This will verify that the certificate is issued by the CA provided, but hostname verification will still be performed. Just supplying the CA will be enough if the cert contains the hostname in the Subject Alternative Names. If it doesn't and you also want to skip hostname verification, you can pass a noop function for checkServerIdentity
var r = require('request');
var opts = {
method: "POST",
ca: fs.readFileSync("ca.cer"),
agentOptions: { checkServerIdentity: function() {} }
};
r('https://api.dropbox.com', opts, function (error, response, body) {
// do something
});
This answer similar to others, but using preferred stringr::str_detect
and dplyr rownames_to_column
.
library(tidyverse)
mtcars %>%
rownames_to_column("type") %>%
filter(stringr::str_detect(type, 'Toyota|Mazda') )
#> type mpg cyl disp hp drat wt qsec vs am gear carb
#> 1 Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
#> 2 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
#> 3 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
#> 4 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
Created on 2018-06-26 by the reprex package (v0.2.0).
Based on First answer here is the complete image selection options:
Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
|PNG|*.PNG;*.png
|JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
|Bitmap(.BMP,.bmp)|*.BMP;*.bmp
|GIF|*.GIF;*.gif
|TIF|*.tif;*.tiff
|ICO|*.ico;*.ICO";
In sake of readability it should be something like
<?php
$countries = $myaddress->get_countries();
foreach($countries as $value) {
$selected ='';
if($value=='United States') $selected ='selected="selected"';
echo '<option value="'.$value.'"'.$selected.'>'.$value.'</option>';
}
?>
desire to stuff EVERYTHING in a single line is a decease, man. Write distinctly.
But there is another way, a better one. There is no need to use echo at all. Learn to use templates. Prepare your data first, and display it only then ready.
Business logic part:
$countries = $myaddress->get_countries();
$selected_country = 1;
Template part:
<? foreach($countries as $row): ?>
<option value="<?=$row['id']?>"<? if ($row['id']==$current_country):> "selected"><? endif ?>
<?=$row['name']?>
</option>
<? endforeach ?>
For my point of view, First thing is to install soap into Centos
yum install php-soap
Second, see if the soap package exist or not
yum search php-soap
third, thus you must see some result of soap package you installed, now type a command in your terminal in the root folder for searching the location of soap for specific path
find -name soap.so
fourth, you will see the exact path where its installed/located, simply copy the path and find the php.ini to add the extension path,
usually the path of php.ini file in centos 6 is in
/etc/php.ini
fifth, add a line of code from below into php.ini file
extension='/usr/lib/php/modules/soap.so'
and then save the file and exit.
sixth run apache restart command in Centos. I think there is two command that can restart your apache ( whichever is easier for you )
service httpd restart
OR
apachectl restart
Lastly, check phpinfo() output in browser, you should see SOAP section where SOAP CLIENT, SOAP SERVER etc are listed and shown Enabled.
I was getting this error when using a bitmap like this:
bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.myBitMap);
What fixed the problem for me was to reduce the size of the bitmap (>1000px high to 700px).
You need to use GROUP BY
instead of DISTINCT
if you want to use aggregation functions.
SELECT title, MIN(date)
FROM table
GROUP BY title
This is a general solution to loading data into a C++ program, and uses the readline function. This could be modified for CSV files, but the delimiter is a space here.
int n = 5, p = 2;
int X[n][p];
ifstream myfile;
myfile.open("data.txt");
string line;
string temp = "";
int a = 0; // row index
while (getline(myfile, line)) { //while there is a line
int b = 0; // column index
for (int i = 0; i < line.size(); i++) { // for each character in rowstring
if (!isblank(line[i])) { // if it is not blank, do this
string d(1, line[i]); // convert character to string
temp.append(d); // append the two strings
} else {
X[a][b] = stod(temp); // convert string to double
temp = ""; // reset the capture
b++; // increment b cause we have a new number
}
}
X[a][b] = stod(temp);
temp = "";
a++; // onto next row
}
The short answer here is the serial ID is computed via a hash if you don't specify it. (Static members are not inherited--they are static, there's only (1) and it belongs to the class).
http://docs.oracle.com/javase/6/docs/platform/serialization/spec/class.html
The getSerialVersionUID method returns the serialVersionUID of this class. Refer to Section 4.6, "Stream Unique Identifiers." If not specified by the class, the value returned is a hash computed from the class's name, interfaces, methods, and fields using the Secure Hash Algorithm (SHA) as defined by the National Institute of Standards.
If you alter a class or its hierarchy your hash will be different. This is a good thing. Your objects are different now that they have different members. As such, if you read it back in from its serialized form it is in fact a different object--thus the exception.
The long answer is the serialization is extremely useful, but probably shouldn't be used for persistence unless there's no other way to do it. Its a dangerous path specifically because of what you're experiencing. You should consider a database, XML, a file format and probably a JPA or other persistence structure for a pure Java project.
I had a similar problem. I ended up nuking it from orbit, and lost my SVN history in the process. But at least I made that damn error go away.
This is probably a sub-optimal sequence of commands to execute, but it should fairly closely follow the sequence of commands that I actually did to get things to work:
cp -rp target ~/other/location/target-20111108
svn rm target --force
cp -rp ~/other/location/target-20111108 target-other-name
cd target-other-name
find . -name .svn -print | xargs rm -rf
cd ..
svn add target-other-name
svn ci -m "Re-re-re-re-re-re-re-re-re-re import target"
svn mv target-other-name target
svn ci -m "Re-re-re-re-re-re-re-re-re-re import target"
Here is what worked for me to solve part 1 of this question:
location / {
rewrite ^([^.]*[^/])$ $1/ permanent;
try_files $uri $uri/ /index.php =404;
include fastcgi_params;
fastcgi_pass php5-fpm-sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors on;
}
rewrite ^([^.]*[^/])$ $1/ permanent; rewrites non-file addresses (addresses without file extensions) to have a "/" at the end. I did this because I was running into "Access denied." message when I tried to access the folder without it.
try_files $uri $uri/ /index.php =404; is borrowed from SanjuD's answer, but with an extra 404 reroute if the location still isn't found.
fastcgi_index index.php; was the final piece of the puzzle that I was missing. The folder didn't reroute to the index.php without this line.
According to the doc, scipy.misc.imread
is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread
instead.
Example:
import imageio
im = imageio.imread('my_image.png')
print(im.shape)
You can also use imageio to load from fancy sources:
im = imageio.imread('http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png')
Edit:
To load all of the *.png
files in a specific folder, you could use the glob
package:
import imageio
import glob
for im_path in glob.glob("path/to/folder/*.png"):
im = imageio.imread(im_path)
print(im.shape)
# do whatever with the image here
open the sql file on Notepad++ and ctrl + H.
Then you put "utf8mb4
" on search and "utf8
" on replace.
The issue will be fixed then.
You can use the iterator that is returned by the begin() method of the map template:
std::map<K,V> myMap;
std::pair<K,V> firstEntry = *myMap.begin()
But remember that the std::map container stores its content in an ordered way. So the first entry is not always the first entry that has been added.
Here's a generic version of a sproc I recently wrote for Oracle that allows for dynamic paging/sorting - HTH
-- p_LowerBound = first row # in the returned set; if second page of 10 rows,
-- this would be 11 (-1 for unbounded/not set)
-- p_UpperBound = last row # in the returned set; if second page of 10 rows,
-- this would be 20 (-1 for unbounded/not set)
OPEN o_Cursor FOR
SELECT * FROM (
SELECT
Column1,
Column2
rownum AS rn
FROM
(
SELECT
tbl.Column1,
tbl.column2
FROM MyTable tbl
WHERE
tbl.Column1 = p_PKParam OR
tbl.Column1 = -1
ORDER BY
DECODE(p_sortOrder, 'A', DECODE(p_sortColumn, 1, Column1, 'X'),'X'),
DECODE(p_sortOrder, 'D', DECODE(p_sortColumn, 1, Column1, 'X'),'X') DESC,
DECODE(p_sortOrder, 'A', DECODE(p_sortColumn, 2, Column2, sysdate),sysdate),
DECODE(p_sortOrder, 'D', DECODE(p_sortColumn, 2, Column2, sysdate),sysdate) DESC
))
WHERE
(rn >= p_lowerBound OR p_lowerBound = -1) AND
(rn <= p_upperBound OR p_upperBound = -1);
Quite old post, but it might help somebody new into git.
I will go with
git rebase master
You clone a repository with git clone [url]. Like so,
$ git clone https://github.com/libgit2/libgit2
Python's if
can be used as a ternary operator:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
Use the json
module to produce JSON output:
import json
with open(outputfilename, 'wb') as outfile:
json.dump(row, outfile)
This writes the JSON result directly to the file (replacing any previous content if the file already existed).
If you need the JSON result string in Python itself, use json.dumps()
(added s
, for 'string'):
json_string = json.dumps(row)
The L
is just Python syntax for a long integer value; the json
library knows how to handle those values, no L
will be written.
Demo string output:
>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'
This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.
Use kebab-case
for all package, folder and file names.
You should imagine that any folder or file might be extracted to its own package some day. Packages cannot contain uppercase letters.
New packages must not have uppercase letters in the name. https://docs.npmjs.com/files/package.json#name
Therefore, camelCase
should never be used. This leaves snake_case
and kebab-case
.
kebab-case
is by far the most common convention today. The only use of underscores is for internal node packages, and this is simply a convention from the early days.
Try this For ORDER BY DESC
SELECT * FROM testdata ORDER BY LENGHT(name) DESC, name DESC
One technique I think is a little easier and that hasn't been mentioned before here:
var asdf = new [] {
(Age: 1, Name: "cow"),
(Age: 2, Name: "bird")
}.ToList();
I think that's a little cleaner than:
var asdf = new List<Tuple<int, string>> {
(Age: 1, Name: "cow"),
(Age: 2, Name: "bird")
};
In case there are many people using your vagrant file - you might want to set name dynamically. Below is the example how to do it using username from your HOST machine as the name of the box and hostname:
require 'etc'
vagrant_name = "yourProjectName-" + Etc.getlogin
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"
config.vm.hostname = vagrant_name
config.vm.provider "virtualbox" do |v|
v.name = vagrant_name
end
end
/* comment here */
here is an example: SELECT 1 /* this is an in-line comment */ + 1;
You were just missing the second half of the column statement telling it to remove the entire column, since most normal Ranges start with a Column Letter, it was looking for a number and didn't get one. The ":" gets the whole column, or row.
I think what you were looking for in your Range was this:
Range("C:C,F:F,I:I,L:L,O:O,R:R").Delete
Just change the column letters to match your needs.
This works for me:
Before installing nvm
, run this in terminal: touch ~/.bash_profile
After, run this in terminal:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.1/install.sh | bash
Important... - DO NOT forget to Restart your terminal OR use command source ~/.nvm/nvm.sh
(this will refresh the available commands in your system path).
In the terminal, use command nvm --version
and you should see the version
No, there isn't such constant.
Besides the already stated answers about using Vector, Vector also has a bunch of methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation.
I also had the same problem, I had assumed that Laravel is installed "out of the box" but it seems it isn't. I SSH'ed to the machine and ran these commands:
cd Code
sudo composer self-update #not necessary, but I did it anyways
composer create-project laravel/laravel Laravel --prefer-dist
And everything was running as usual.
Small change like this can be done
SELECT EmplID
, EmplName
, InTime
, [TimeOut]
, [DateVisited]
, CASE WHEN minpart=0
THEN CAST(hourpart as nvarchar(200))+':00'
ELSE CAST((hourpart-1) as nvarchar(200))+':'+ CAST(minpart as nvarchar(200))END as 'total time'
FROM
(
SELECT EmplID, EmplName, InTime, [TimeOut], [DateVisited],
DATEDIFF(Hour,InTime, [TimeOut]) as hourpart,
DATEDIFF(minute,InTime, [TimeOut])%60 as minpart
from times) source
I'd like to write explicitly two methods which allow accomplishing this in pure JavaScript:
document.getElementsByClassName('realClasssName').length
Note 1: Argument of this method needs a string with the real class name, without the dot at the begin of this string.
document.querySelectorAll('.realClasssName').length
Note 2: Argument of this method needs a string with the real class name but with the dot at the begin of this string.
Note 3: This method works also with any other CSS selectors, not only with class selector. So it's more universal.
I also write one method, but using two name conventions to solve this problem using jQuery:
jQuery('.realClasssName').length
or
$('.realClasssName').length
Note 4: Here we also have to remember about the dot, before the class name, and we can also use other CSS selectors.
You go into your router configuration and forward port 80 to the LAN IP of the computer running the web server.
Then anyone outside your network (but not you inside the network) can access your site using your WAN IP address (whatismyipcom).
Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.
Typically, this is how I handle this case:
val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics
val df = spark.read.table("some_table").
.select(columnOfInterests.map(c => col(c)):_*)
.groupBy(dimensions.map(d => col(d)): _*)
.agg(metrics.map( m => m -> "sum").toMap)
.toDF(columnOfInterests:_*) // that's the interesting part
The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2)
and sum(col3)
to simply col2
and col3
.
Sets behave different than dicts, you need to use set operations like issubset():
>>> k
{'ip': '123.123.123.123', 'pw': 'test1234', 'port': 1234, 'debug': True}
>>> set('ip,port,pw'.split(',')).issubset(set(k.keys()))
True
>>> set('ip,port,pw'.split(',')) in set(k.keys())
False
Take a look here: https://github.com/ifsnop/mysqldump-php ! It is a native solution written in php.
You can install it using composer, and it is as easy as doing:
<?php
use Ifsnop\Mysqldump as IMysqldump;
try {
$dump = new IMysqldump\Mysqldump('database', 'username', 'password');
$dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
echo 'mysqldump-php error: ' . $e->getMessage();
}
?>
It supports advanced users, with lots of options copied from the original mysqldump.
All the options are explained at the github page, but more or less are auto-explicative:
$dumpSettingsDefault = array(
'include-tables' => array(),
'exclude-tables' => array(),
'compress' => 'None',
'no-data' => false,
'add-drop-database' => false,
'add-drop-table' => false,
'single-transaction' => true,
'lock-tables' => false,
'add-locks' => true,
'extended-insert' => true,
'disable-foreign-keys-check' => false,
'where' => '',
'no-create-info' => false
);
I know this is a pretty old question but this was my solution that helped with visualizing the table so you can create a class structure. This is also using the HTML Agility Pack
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
var table = doc.DocumentNode.SelectSingleNode("//table");
var tableRows = table.SelectNodes("tr");
var columns = tableRows[0].SelectNodes("th/text()");
for (int i = 1; i < tableRows.Count; i++)
{
for (int e = 0; e < columns.Count; e++)
{
var value = tableRows[i].SelectSingleNode($"td[{e + 1}]");
Console.Write(columns[e].InnerText + ":" + value.InnerText);
}
Console.WriteLine();
}
Here is one that I made that is pure javascript/css only.
https://jsfiddle.net/KirbyLWallace/x5sbe0dk/5/
It's meant to be used in full width screen, but I've modified to fit a specific width for the fiddle.
<body onResize="scaleElements()">
<div id="table-container-div">
<table id="data-table">
<thead id="th-header">
<tr id="th-header-row">
<td>Column1</td>
<td>Column2</td>
<td>Column3</td>
<td>Column4</td>
</tr>
</thead>
<tbody id="tbl-body">
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
</tbody>
</table>
javascript:
(() => {
scaleElements();
})();
function scaleElements() {
// element() is just shorthand for document.getElementById().
// scaleElements() scales a number of other things, not included here,
// that get rescaled any time the browser, or a container is resized.
// the table header row here is just one of them...
//
// this thing includes checks to see if a table with the table & thead
// is on the page. If it is, it checks to see if the span container is
// here (it's not on the first run, but it is on subsequent calls. So,
// it adds it if it needs it, or reuses it if it's there.
if (element("data-table")) {
if (element("th-span-container")) {
element("th-span-container").parentElement.removeChild(element("th-span-container"));
}
var x = document.createElement("div");
x.id = "th-span-container";
x.style.cssFloat = "left";
x.style.position = "fixed";
x.style.top = "10px";
// you will want to fiddle with your own particular positioning.
// this one is positioned to work on a table that is below a page
// logo banner.
var tds = element("th-header-row").getElementsByTagName("td");
for (i = 0; i < tds.length; i++) {
let z = tds[i];
let y = document.createElement("span");
y.style.padding = "0px";
y.style.margin = "0px";
y.style.fontFamily = "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
y.style.fontSize = "13px";
y.style.border = "0px";
y.style.position = "absolute";
y.style.color = "white";
y.style.backgroundColor = "#3D6588";
y.style.left = z.offsetLeft + "px";
y.style.height = z.offsetHeight + "px";
y.style.lineHeight = z.offsetHeight + "px";
y.style.width = z.offsetWidth + "px";
y.innerHTML = z.innerHTML;
x.appendChild(y);
}
element("table-container-div").appendChild(x);
element("th-header-row").style.visibility = "hidden";
}
}
function element(e) {
return document.getElementById(e);
}
css:
body {
background: black;
}
#table-container-div {
width: 310px;
position: absolute;
top: 10px;
bottom: 10px;
overflow-x: hidden;
overflow-y: auto;
min-width: 320px;
}
table {
font-size: 13px;
height: 120px;
width: 300px;
border: 0px solid red;
background-color: #11171F;
}
tr {
height: 22px;
color: #cff3ff;
}
tr:hover {
background-color: dimgrey;
}
td {
color:white;
border-right: 1px dotted #4F4F4F;
}
#th-header-row {
background-color: #3D6588;
color: white;
}
You'll have to make a join:
SELECT A.SalesOrderID, B.Foo
FROM A
JOIN B bo ON bo.id = (
SELECT TOP 1 id
FROM B bi
WHERE bi.SalesOrderID = a.SalesOrderID
ORDER BY bi.whatever
)
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
, assuming that b.id
is a PRIMARY KEY
on B
In MS SQL 2005
and higher you may use this syntax:
SELECT SalesOrderID, Foo
FROM (
SELECT A.SalesOrderId, B.Foo,
ROW_NUMBER() OVER (PARTITION BY B.SalesOrderId ORDER BY B.whatever) AS rn
FROM A
JOIN B ON B.SalesOrderID = A.SalesOrderID
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
) i
WHERE rn
This will select exactly one record from B
for each SalesOrderId
.
Easy, you can use a Post request and submit your file as binary (byte array).
String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
"yourfile");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
} catch (Exception e) {
// show error
}
Add this below code(<handler>
) on your web.config within <system.webServer>
:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:
vars:
myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"
You can now sync all your settings across devices with VSCode's built-in Settings Sync
. It's found under Code > Preferences > Turn on Settings Sync...
Read more about it in the official docs here
I built a jQuery plugin to do this.
(function ($) {
$.fn.wysiwygEvt = function () {
return this.each(function () {
var $this = $(this);
var htmlold = $this.html();
$this.bind('blur keyup paste copy cut mouseup', function () {
var htmlnew = $this.html();
if (htmlold !== htmlnew) {
$this.trigger('change')
}
})
})
}
})(jQuery);
You can simply call $('.wysiwyg').wysiwygEvt();
You can also remove / add events if you wish
Setting windowLightStatusBar
to true
not works with Mi phones, some Meizu phones, Blackview phones, WileyFox etc.
I've found such hack for Mi and Meizu devices. This is not a comprehensive solution of this perfomance problem, but maybe it would be useful to somebody.
And I think, it would be better to tell your customer that coloring status bar (for example) white - is not a good idea. instead of using different hacks it would be better to define appropriate colorPrimaryDark
according to the guidelines
On the very left of the Chrome Developer Tools toolbar there is a button that lets you select an item to inspect regardless of context menu handlers. It looks like a square with arrow pointing to the center.
My opinion is, Instead of storing images directly to the database, It is recommended to store the image location in the database. As we compare both options, Storing images in the database is safe for security purpose. Disadvantage are
If database is corrupted, no way to retrieve.
Retrieving image files from db is slow when compare to other option.
On the other hand, storing image file location in db will have following advantages.
It is easy to retrieve.
If more than one images are stored, we can easily retrieve image information.
In addition to kus answer.
There are some changes in Xcode 8.0
Step 1:
Change scheme destination to Generic IOS device
.
Step 2:
Click Product
> Archive
> once this is complete open up the Organiser and click the latest version.
Step 3:
Click on Export...
option from right side of organiser window.
Step 4: Select a method for export > Choose correct signing > Save to Destination.
Xcode 10.0
Step 3: From Right Side Panel Click on Distribute App.
Step 4: Select Method of distribution and click next.
Step 5: It Opens up distribution option window. Select All compatible device variants and click next.
Step 6: Choose signing certificate.
Step 7: It will open up Preparing archive for distribution window. it takes few min.
Step 8: It will open up Archives window. Click on export and save it.
In addition to Daniel Howard's answer, here is what new
does (or at least seems to do):
function New(func) {
var res = {};
if (func.prototype !== null) {
res.__proto__ = func.prototype;
}
var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
return ret;
}
return res;
}
While
var obj = New(A, 1, 2);
is equivalent to
var obj = new A(1, 2);
I figured out how to do this with InjectionTokens (see example below), and if your project was built using the Angular CLI
you can use the environment files found in /environments
for static application wide settings
like an API endpoint, but depending on your project's requirements you will most likely end up using both since environment files are just object literals, while an injectable configuration using InjectionToken
's can use the environment variables and since it's a class can have logic applied to configure it based on other factors in the application, such as initial http request data, subdomain, etc.
Injection Tokens Example
/app/app-config.module.ts
import { NgModule, InjectionToken } from '@angular/core';
import { environment } from '../environments/environment';
export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');
export class AppConfig {
apiEndpoint: string;
}
export const APP_DI_CONFIG: AppConfig = {
apiEndpoint: environment.apiEndpoint
};
@NgModule({
providers: [{
provide: APP_CONFIG,
useValue: APP_DI_CONFIG
}]
})
export class AppConfigModule { }
/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppConfigModule } from './app-config.module';
@NgModule({
declarations: [
// ...
],
imports: [
// ...
AppConfigModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
Now you can just DI it into any component, service, etc:
/app/core/auth.service.ts
import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { APP_CONFIG, AppConfig } from '../app-config.module';
import { AuthHttp } from 'angular2-jwt';
@Injectable()
export class AuthService {
constructor(
private http: Http,
private router: Router,
private authHttp: AuthHttp,
@Inject(APP_CONFIG) private config: AppConfig
) { }
/**
* Logs a user into the application.
* @param payload
*/
public login(payload: { username: string, password: string }) {
return this.http
.post(`${this.config.apiEndpoint}/login`, payload)
.map((response: Response) => {
const token = response.json().token;
sessionStorage.setItem('token', token); // TODO: can this be done else where? interceptor
return this.handleResponse(response); // TODO: unset token shouldn't return the token to login
})
.catch(this.handleError);
}
// ...
}
You can then also type check the config using the exported AppConfig.
In my opinion the best choice is to put __ init __.py in the folder and call the file with
from dirBar.Bar import *
It is not recommended to use sys.path.append() because something might gone wrong if you use the same file name as the existing python package. I haven't test that but that will be ambiguous.
A simple function to remove leading and trailing whitespace:
trim <- function( x ) {
gsub("(^[[:space:]]+|[[:space:]]+$)", "", x)
}
Usage:
> text = " foo bar baz 3 "
> trim(text)
[1] "foo bar baz 3"
Building on @Mike Gledhill's code, I've taken it a step further and added more parameters. If you have a SVG RECT and want text to wrap inside it, this may be handy:
function wraptorect(textnode, boxObject, padding, linePadding) {
var x_pos = parseInt(boxObject.getAttribute('x')),
y_pos = parseInt(boxObject.getAttribute('y')),
boxwidth = parseInt(boxObject.getAttribute('width')),
fz = parseInt(window.getComputedStyle(textnode)['font-size']); // We use this to calculate dy for each TSPAN.
var line_height = fz + linePadding;
// Clone the original text node to store and display the final wrapping text.
var wrapping = textnode.cloneNode(false); // False means any TSPANs in the textnode will be discarded
wrapping.setAttributeNS(null, 'x', x_pos + padding);
wrapping.setAttributeNS(null, 'y', y_pos + padding);
// Make a copy of this node and hide it to progressively draw, measure and calculate line breaks.
var testing = wrapping.cloneNode(false);
testing.setAttributeNS(null, 'visibility', 'hidden'); // Comment this out to debug
var testingTSPAN = document.createElementNS(null, 'tspan');
var testingTEXTNODE = document.createTextNode(textnode.textContent);
testingTSPAN.appendChild(testingTEXTNODE);
testing.appendChild(testingTSPAN);
var tester = document.getElementsByTagName('svg')[0].appendChild(testing);
var words = textnode.textContent.split(" ");
var line = line2 = "";
var linecounter = 0;
var testwidth;
for (var n = 0; n < words.length; n++) {
line2 = line + words[n] + " ";
testing.textContent = line2;
testwidth = testing.getBBox().width;
if ((testwidth + 2*padding) > boxwidth) {
testingTSPAN = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
testingTSPAN.setAttributeNS(null, 'x', x_pos + padding);
testingTSPAN.setAttributeNS(null, 'dy', line_height);
testingTEXTNODE = document.createTextNode(line);
testingTSPAN.appendChild(testingTEXTNODE);
wrapping.appendChild(testingTSPAN);
line = words[n] + " ";
linecounter++;
}
else {
line = line2;
}
}
var testingTSPAN = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
testingTSPAN.setAttributeNS(null, 'x', x_pos + padding);
testingTSPAN.setAttributeNS(null, 'dy', line_height);
var testingTEXTNODE = document.createTextNode(line);
testingTSPAN.appendChild(testingTEXTNODE);
wrapping.appendChild(testingTSPAN);
testing.parentNode.removeChild(testing);
textnode.parentNode.replaceChild(wrapping,textnode);
return linecounter;
}
document.getElementById('original').onmouseover = function () {
var container = document.getElementById('destination');
var numberoflines = wraptorect(this,container,20,1);
console.log(numberoflines); // In case you need it
};
I recommend the Java VisualVM distributed with the JDK (jvisualvm.exe). It can connect dynamically and access the threads and heap. I have found in invaluable for some problems.
If you like to keep it fixed width, for example 10 digits, do it like this
Key = i.ToString("0000000000");
Replace with as many digits as you like.
i = 123
will then result in Key = "0000000123"
.
The GIMP (GNU Image Manipulation Program). It's free, open source and runs on Windows and Linux (and maybe Mac?).
Using @Autowired
or ApplicationContext.getBean()
is really the same thing. In both ways you get the bean that is configured in your context and in both ways your code depends on spring.
The only thing you should avoid is instantiating your ApplicationContext. Do this only once! In other words, a line like
ApplicationContext context = new ClassPathXmlApplicationContext("AppContext.xml");
should only be used once in your application.
For quick queries you can allow room to execute it on UI thread.
AppDatabase db = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, DATABASE_NAME).allowMainThreadQueries().build();
In my case I had to figure out of the clicked user in list exists in database or not. If not then create the user and start another activity
@Override
public void onClick(View view) {
int position = getAdapterPosition();
User user = new User();
String name = getName(position);
user.setName(name);
AppDatabase appDatabase = DatabaseCreator.getInstance(mContext).getDatabase();
UserDao userDao = appDatabase.getUserDao();
ArrayList<User> users = new ArrayList<User>();
users.add(user);
List<Long> ids = userDao.insertAll(users);
Long id = ids.get(0);
if(id == -1)
{
user = userDao.getUser(name);
user.setId(user.getId());
}
else
{
user.setId(id);
}
Intent intent = new Intent(mContext, ChatActivity.class);
intent.putExtra(ChatActivity.EXTRAS_USER, Parcels.wrap(user));
mContext.startActivity(intent);
}
}
while IFS= read -r line; do echo ${#line}; done < abc.txt
It is POSIX, so it should work everywhere.
Edit: Added -r as suggested by William.
Edit: Beware of Unicode handling. Bash and zsh, with correctly set locale, will show number of codepoints, but dash will show bytes—so you have to check what your shell does. And then there many other possible definitions of length in Unicode anyway, so it depends on what you actually want.
Edit: Prefix with IFS=
to avoid losing leading and trailing spaces.
I am not an expert but try white-space:nowrap;
The white-space property is supported in all major browsers.
Note: The value "inherit"
is not supported in IE7 and earlier. IE8 requires a !DOCTYPE
. IE9 supports "inherit"
.
Try this:
ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = 'dodge', stat='identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)
If you are using graphLab, you can use this function. It is really powerfull
products['word_count'] = graphlab.text_analytics.count_words(your_text)
If it has a UI, it has an "API". Let's use the following example: I want to publish the pic I use in any new blog post I create. Let's assume is Wordpress.
If the script always outputs lines of 10 characters followed by 3 extra (in other words, you just want the first 10 characters), you can use
script | cut -c 1-10
If it outputs an uncertain number of non-space characters, followed by a space and then 2 other extra characters (in other words, you just want the first field), you can use
script | cut -d ' ' -f 1
... as in majhool's comment earlier. Depending on your platform, you may also have colrm, which, again, would work if the lines are a fixed length:
script | colrm 11
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
<param name="Threshold" value="INFO" />
<param name="File" value="sample.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" />
</layout>
</appender>
<root>
<priority value ="debug" />
<appender-ref ref="fileAppender" />
</root>
</log4j:configuration>
Log4j can be a bit confusing. So lets try to understand what is going on in this file: In log4j you have two basic constructs appenders and loggers.
Appenders define how and where things are appended. Will it be logged to a file, to the console, to a database, etc.? In this case you are specifying that log statements directed to fileAppender will be put in the file sample.log
using the pattern specified in the layout tags. You could just as easily create a appender for the console or the database. Where the console appender would specify things like the layout on the screen and the database appender would have connection details and table names.
Loggers respond to logging events as they bubble up. If an event catches the interest of a specific logger it will invoke its attached appenders. In the example below you have only one logger the root logger - which responds to all logging events by default. In addition to the root logger you can specify more specific loggers that respond to events from specific packages. These loggers can have their own appenders specified using the appender-ref
tags or will otherwise inherit the appenders from the root logger. Using more specific loggers allows you to fine tune the logging level on specific packages or to direct certain packages to other appenders.
So what this file is saying is:
The net out is that if you have a logger.debug("blah blah")
in your code it will get ignored. A logger.info("Blah blah");
will output to sample.log.
The snippet below could be added to the file above with the log4j tags. This logger would inherit the appenders from <root>
but would limit the all logging events from the package org.springframework
to those logged at level info
or above.
<!-- Example Package level Logger -->
<logger name="org.springframework">
<level value="info"/>
</logger>
An easier way to do this is using crop from ImageOps. You can feed the number of pixels you want to crop from each side.
from PIL import ImageOps
border = (0, 30, 0, 30) # left, up, right, bottom
ImageOps.crop(img, border)
@ViewChild('keywords-input') keywordsInput;
doesn't match id="keywords-input"
id="keywords-input"
should be instead a template variable:
#keywordsInput
Note that camel case should be used, since -
is not allowed in template reference names.
@ViewChild()
supports names of template variables as string:
@ViewChild('keywordsInput') keywordsInput;
or component or directive types:
@ViewChild(MyKeywordsInputComponent) keywordsInput;
See also https://stackoverflow.com/a/35209681/217408
Hint:
keywordsInput
is not set before ngAfterViewInit()
is called
This problem was created by a regression in a recent release. You can find the pull request that fixes this problem at https://github.com/facebook/react-native-fbsdk/pull/339
Here ya go:
viewNoteDateMonth.text = [[displayDate objectAtIndex:2] uppercaseString];
Btw:
"april"
is lowercase
? [NSString lowercaseString]
"APRIL"
is UPPERCASE
? [NSString uppercaseString]
"April May"
is Capitalized/Word Caps
? [NSString capitalizedString]
"April may"
is Sentence caps
? (method missing; see workaround below)
Hence what you want is called "uppercase", not "capitalized". ;)
As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:
@interface NSString ()
- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences
@end
@implementation NSString
- (NSString *)sentenceCapitalizedString {
if (![self length]) {
return [NSString string];
}
NSString *uppercase = [[self substringToIndex:1] uppercaseString];
NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
return [uppercase stringByAppendingString:lowercase];
}
- (NSString *)realSentenceCapitalizedString {
__block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
[self enumerateSubstringsInRange:NSMakeRange(0, [self length])
options:NSStringEnumerationBySentences
usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
[mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
}];
return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}
@end
F5 is a standard page reload.
and
Ctrl + F5 refreshes the page by clearing the cached content of the page.
Having the cursor in the address field and pressing Enter will also do the same as Ctrl + F5.
I resolved this problem by taking the full and transactional backup. Sometimes, the backup process is not completed and that's one of the reason the .ldf file is not getting shrink. Try this. It worked for me.
IP can be any LAN or WAN IP address. But you'll want to set your firewall connection allow it.
Device connection with webserver pc can be by LAN or WAN (i.e by wifi, connectify, adhoc, cable, mypublic wifi etc)
You should follow these steps:
This IP will be of that device which has the web server.
I would globally set your cultures. ModelBinder pick that up!
<system.web>
<globalization uiCulture="en-AU" culture="en-AU" />
Or you just change this for this page.
But globally in web.config I think is better
Just for the completeness, we can also avoid declaring private_class_method in a separate line. I personally don't like this usage but good to know that it exists.
private_class_method def self.method_name
....
end
I was getting the same error on a restored database when I tried to insert a new record using the EntityFramework. It turned out that the Indentity/Seed was screwing things up.
Using a reseed command fixed it.
DBCC CHECKIDENT ('[Prices]', RESEED, 4747030);GO
It sounds like you just want to reset to C; that is make the tree:
A-B-C
You can do that with reset
:
git reset --hard HEAD~3
(Note: You said three commits ago so that's what I wrote; in your example C is only two commits ago, so you might want to use HEAD~2
)
You can also use revert
if you want, although as far as I know you need to do the reverts one at a time:
git revert HEAD # Reverts E
git revert HEAD~2 # Reverts D
That will create a new commit F that's the same contents as D, and G that's the same contents as C. You can rebase
to squash those together if you want
Found this:
The google-services.json file is generally placed in the app/ directory, but as of version 2.0.0-alpha3 of the plugin support was added for build types, which would make the following directory structure valid:
app/src/ main/google-services.json dogfood/google-services.json mytype1/google-services.json ...
Exit
[construct], and intelisense will tell you which one(s) are valid in a particular place.
For macOS Mojave
just run pip install psycopg2-binary
. Works fine for me, python version -> Python 3.7.2
You can use both !=
or <>
.
However, note that !=
is preferred where <>
is deprecated.
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); //copy
In this case, list1
is of type ArrayList
.
List<Integer> list2 = Arrays.asList(ia);
Here, the list is returned as a List
view, meaning it has only the methods attached to that interface. Hence why some methods are not allowed on list2
.
ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));
Here, you ARE creating a new ArrayList
. You're simply passing it a value in the constructor. This is not an example of casting. In casting, it might look more like this:
ArrayList list1 = (ArrayList)Arrays.asList(ia);
Cron is so named "deamon" (same as service under Win).
Most likely cron is already installed on your system (if it is a Linux/Unix system).
Look here: http://www.comptechdoc.org/os/linux/startupman/linux_sucron.html
or there http://en.wikipedia.org/wiki/Cron
for more details.
To date: Seeing a lot of searches and suggestions to disable YouTube logo and branding from an embedded video; I recommend you consider the following:
Yet! You have the option of having Modest-Branding using this parameters:
https://www.youtube.com/embed/'+videourl+'?modestbranding=1
And some other parameters for customization:
&showinfo=0 //Turn off Title & Ratings
&showsearch=0 //Turn off Search
&rel=1 //Turn on Related Videos
&iv_load_policy=3 //Turn off Annotations
&cc_load_policy=1 //Force Closed Captions
&autoplay=1 //Turn on AutoPlay (not recommended)
&loop=1 //Loop Playback
&fs=0 //Remove Full Screen Option (not sure why you’d want to)
And here is the general customization window:
Disclaimer: I don't work for YouTube; simply I respect the copyrights.
Existing good jQuery plugin Purl (A JavaScript URL parser).This utility can be used in two ways - with jQuery or without...
You can do something like this:
#container {_x000D_
background-color: red;_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
.child {_x000D_
background-color: blue;_x000D_
width: 150px;_x000D_
height: 50px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="inner">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Rather than going the harder route of downloading specific packages. I prefer to go the faster route of using Conda. pip has its issues.
Conda , install conda from : https://conda.io/docs/install/quick.html#windows-miniconda-install
C:\Users\xyz>conda install -c anaconda scipy=0.18.1
Fetching package metadata .............
Solving package specifications:
Package plan for installation in environment C:\Users\xyz\Miniconda3:
The following NEW packages will be INSTALLED:
mkl: 2017.0.1-0 anaconda
numpy: 1.12.0-py36_0 anaconda
scipy: 0.18.1-np112py36_1 anaconda
The following packages will be SUPERCEDED by a higher-priority channel:
conda: 4.3.11-py36_0 --> 4.3.11-py36_0 anaconda
conda-env: 2.6.0-0 --> 2.6.0-0 anaconda
Proceed ([y]/n)? y
conda-env-2.6. 100% |###############################| Time: 0:00:00 32.92 kB/s
mkl-2017.0.1-0 100% |###############################| Time: 0:00:24 5.45 MB/s
numpy-1.12.0-p 100% |###############################| Time: 0:00:00 5.09 MB/s
scipy-0.18.1-n 100% |###############################| Time: 0:00:02 5.59 MB/s
conda-4.3.11-p 100% |###############################| Time: 0:00:00 4.70 MB/s
you can use Sqlitebrowser. In the browser mode, for the respective database and the table, under the tab -database structure,following the option Modify Table, respective column could be removed.
CocoaPods
program that is built with Ruby and it will be installable with the default Ruby available on macOS.
pod --version //1.8.0.beta.2
//or
gem which cocoapods //Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.0.beta.2/lib/cocoapods.rb
//install or update
sudo gem install cocoapods
Version of pods that is specified in Podfile
Podfile.lock
It is located in the same folder as Podfile
. Here you can find a version of a pod which is used
If you are interested in all available version of specific pod you can use
pod search <pod_name>
//or
pod trunk info <pod_name>
//specific version
pod '<framework_name>', "<semantic_versioning>"
// for example
pod 'MyFramework', "1.0"
Expanding on Adam Rackis's answer - we can make the extension method generic simply like this:
public static TResult GetPropertyValue<TResult>(this object t, string propertyName)
{
object val = t.GetType().GetProperties().Single(pi => pi.Name == propertyName).GetValue(t, null);
return (TResult)val;
}
You can throw some error handling around that too if you like.
WORKED FOR ME :)
i upgraded the java to the latest version 8 previously it was 7 and then go to OPEN MODULE SETTING right clicking on project and changed the jdk path to /usr/lib/jvm/java-8-oracle the new java 8 installed. And restart the studio
check in /usr/lib/jvm for java 8 folder name
To create a label for text:
JLabel label1 = new JLabel("Test");
To change the text in the label:
label1.setText("Label Text");
And finally to clear the label:
label1.setText("");
And all you have to do is place the label in your layout, or whatever layout system you are using, and then just add it to the JFrame...
The InterruptedException
is usually thrown when a sleep is interrupted.
Enclose it in a try catch block, then the execution will be transfered to catch.
BEGIN TRY
PRINT 'This will be printed'
RAISERROR ('Custom Exception', 16, 1);
PRINT 'This will not be printed'
END TRY
BEGIN CATCH
PRINT 'This will be printed 2nd'
END CATCH;
In my case, I was using a dependency scoped as <scope>test</scope>
. This made the class available at development time but, by at compile time, I got this message.
Turn the class scope for <scope>provided</scope>
solved the problem.
You can simply declare them as local functions in a razor block (i.e. @{}
).
@{
int Add(int x, int y)
{
return x + y;
}
}
<div class="container">
<p>
@Add(2, 5)
</p>
</div>
System.out.println
System
is a class in the java.lang
package.
out
is a static
data member of the System
class and references a variable of the PrintStream
class.
Yet another way to plot the sine wave.
import numpy as np
import matplotlib
matplotlib.use('TKAgg') #use matplotlib backend TKAgg (optional)
import matplotlib.pyplot as plt
t = np.linspace(0.0, 5.0, 50000) # time axis
sig = np.sin(t)
plt.plot(t,sig)
There is a proposal open in GitHub for the C# language about having better support for raw string literals. One valid answer, is to encourage the C# team to add a new feature to the language (such as triple quote - like Python).
see https://github.com/dotnet/csharplang/discussions/89#discussioncomment-257343
Old thread, I know, but for future reference, the --proxy option is now passed with an "="
Example:
$ sudo pip install --proxy=http://yourproxy:yourport package_name
I encountered this issue when trying to import the results of a Stored Proc into a temp table, and that Stored Proc inserted into a temp table as part of its own operation. The issue being that SQL Server does not allow the same process to write to two different temp tables at the same time.
The accepted OPENROWSET answer works fine, but I needed to avoid using any Dynamic SQL or an external OLE provider in my process, so I went a different route.
One easy workaround I found was to change the temporary table in my stored procedure to a table variable. It works exactly the same as it did with a temp table, but no longer conflicts with my other temp table insert.
Just to head off the comment I know that a few of you are about to write, warning me off Table Variables as performance killers... All I can say to you is that in 2020 it pays dividends not to be afraid of Table Variables. If this was 2008 and my Database was hosted on a server with 16GB RAM and running off 5400RPM HDDs, I might agree with you. But it's 2020 and I have an SSD array as my primary storage and hundreds of gigs of RAM. I could load my entire company's database to a table variable and still have plenty of RAM to spare.
Table Variables are back on the menu!
When setting an image in a tableViewCell
or collectionViewCell
, this worked for me:
Place the following code in your cellForRowAtIndexPath
or cellForItemAtIndexPath
// Obtain pointer to cell. Answer assumes that you've done this, but here for completeness.
CheeseCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cheeseCell" forIndexPath:indexPath];
// Grab the image from document library and set it to the cell.
UIImage *myCheese = [UIImage imageNamed:@"swissCheese.png"];
[cell.cheeseThumbnail setImage:myCheese forState:UIControlStateNormal];
NOTE: xCode seemed to get hung up on this for me. I had to restart both xCode and the Simulator, it worked properly.
This assumes that you've got cheeseThumbnail set up as an IBOutlet... and some other stuff... hopefully you're familiar enough with table/collection views and can fit this in.
Hope this helps.
Your understanding is correct. However, if we walk through:
(.*)
will swallow the whole string;(\\d+)
is satistifed (which is why 0
is captured, and not 3000
);(.*)
will then capture the rest.I am not sure what the original intent of the author was, however.
I haven't had any problems with the code below. (Relative paths must start with '/' or '\').
private bool IsValidPath(string path, bool allowRelativePaths = false)
{
bool isValid = true;
try
{
string fullPath = Path.GetFullPath(path);
if (allowRelativePaths)
{
isValid = Path.IsPathRooted(path);
}
else
{
string root = Path.GetPathRoot(path);
isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
}
}
catch(Exception ex)
{
isValid = false;
}
return isValid;
}
For example these would return false:
IsValidPath("C:/abc*d");
IsValidPath("C:/abc?d");
IsValidPath("C:/abc\"d");
IsValidPath("C:/abc<d");
IsValidPath("C:/abc>d");
IsValidPath("C:/abc|d");
IsValidPath("C:/abc:d");
IsValidPath("");
IsValidPath("./abc");
IsValidPath("./abc", true);
IsValidPath("/abc");
IsValidPath("abc");
IsValidPath("abc", true);
And these would return true:
IsValidPath(@"C:\\abc");
IsValidPath(@"F:\FILES\");
IsValidPath(@"C:\\abc.docx\\defg.docx");
IsValidPath(@"C:/abc/defg");
IsValidPath(@"C:\\\//\/\\/\\\/abc/\/\/\/\///\\\//\defg");
IsValidPath(@"C:/abc/def~`!@#$%^&()_-+={[}];',.g");
IsValidPath(@"C:\\\\\abc////////defg");
IsValidPath(@"/abc", true);
IsValidPath(@"\abc", true);
Maybe you can script/control winscp?
Update: winscp now has a .NET library available as a nuget package that supports SFTP, SCP, and FTPS
When you close the video you just need to pause it.
$("#closeSimple").click(function() {
$("div#simpleModal").removeClass("show");
$("#videoContainer")[0].pause();
return false;
});
<video id="videoContainer" width="320" height="240" src="Davis_5109iPadFig3.m4v" controls="controls"> </video>
Also, for reference, here's the Opera documentation for scripting video controls.
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
Since my other answer was obviously not well understood, here's a second attempt:
There's two approaches to answer the question.
Forget about the :after
pseudo-selector, and go for something like
.pdflink {
min-height: 20px;
padding-right: 10px;
background-position: right bottom;
background-size: 10px 20px;
background-repeat: no-repeat;
}
The question is: Can you style generated content? The answer is: No, you can't. There's been a lengthy discussion on the W3C mailing list on this issue, but no solution so far.
Generated content is rendered into a generated box, and you can style that box, but not the content as such. Different browsers show very different behaviour
#foo {content: url("bar.jpg"); width: 42px; height:42px;} #foo::before {content: url("bar.jpg"); width: 42px; height:42px;}
Chrome resizes the first one, but uses the intrinsic dimensions of the image for the second
firefox and ie don't support the first, and use intrinsic dimensions for the second
opera uses intrinsic dimensions for both cases
(from http://lists.w3.org/Archives/Public/www-style/2011Nov/0451.html )
Similarly, browsers show very different results on things like http://jsfiddle.net/Nwupm/1/ , where more than one element is generated. Keep in mind that CSS3 is still in early development stage, and this issue has yet to be solved.
I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.
It works (refreshes the graphs) if I put
plt.clf()
plt.cla()
plt.close()
after every plt.show()
Note : Just be careful if 0 is an acceptable value for a required field. As @Harold1983- mentioned, these are treated as empty in PHP. For these kind of things we should use isset instead of empty.
$requestArr = $_POST['data']// Requested data
$requiredFields = ['emailType', 'emailSubtype'];
$missigFields = $this->checkRequiredFields($requiredFields, $requestArr);
if ($missigFields) {
$errorMsg = 'Following parmeters are mandatory: ' . $missigFields;
return $errorMsg;
}
// Function to check whether the required params is exists in the array or not.
private function checkRequiredFields($requiredFields, $requestArr) {
$missigFields = [];
// Loop over the required fields and check whether the value is exist or not in the request params.
foreach ($requiredFields as $field) {`enter code here`
if (empty($requestArr[$field])) {
array_push($missigFields, $field);
}
}
$missigFields = implode(', ', $missigFields);
return $missigFields;
}
js
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#div1").on('click', function(){
console.log("click!!!");
});
});
</script>
html
<div id="div1">div!</div>
If you're on windows and using apache, maybe via WAMP or the Drupal stack installer, you can additionally download the git for windows package, which includes many useful linux command line tools, one of which is openssl.
The following command creates the self signed certificate and key needed for apache and works fine in windows:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privatekey.key -out certificate.crt
Add the following line to the beginning script1.py
#!/usr/bin/env python
and then make the script executable:
$ chmod +x script1.py
If the script resides in a directory that appears in your PATH
variable, you can simply type
$ script1.py
Otherwise, you'll need to provide the full path (either absolute or relative). This includes the current working directory, which should not be in your PATH
.
$ ./script1.py
For form login:
<form method="post" action="/login">
<input type="text" id="email" name="email" size="35" maxlength="40" placeholder="Email" />
<input type="password" id="password" name="password" size="15" maxlength="20" placeholder="Password"/>
<input type="submit" id="send" value="Send">
</form>
Javascript:
$(document).ready(function() {
$('#send').prop('disabled', true);
$('#email, #password').keyup(function(){
if ($('#password').val() != '' && $('#email').val() != '')
{
$('#send').prop('disabled', false);
}
else
{
$('#send').prop('disabled', true);
}
});
});
I had this issue and realized it was because I was calling setContentView(int id)
twice in my Activity
's onCreate
/*
It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
* put string into file jsonFileArr.json
* [{"username":"Hello","email":"[email protected]","credits"
* :"100","twitter_username":""},
* {"username":"Goodbye","email":"[email protected]"
* ,"credits":"0","twitter_username":""},
* {"username":"mlsilva","email":"[email protected]"
* ,"credits":"524","twitter_username":""},
* {"username":"fsouza","email":"[email protected]"
* ,"credits":"1052","twitter_username":""}]
*/
public class TestaGsonLista {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Temp\\jsonFileArr.json"));
JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement str = jsonArray.get(i);
Usuario obj = gson.fromJson(str, Usuario.class);
//use the add method from the list and returns it.
System.out.println(obj);
System.out.println(str);
System.out.println("-------");
}
} catch (IOException e) {
e.printStackTrace();
}
}
If it's a File, you can get the parts by creating an instanceof File and then ask for its segments.
This is good because it'll work regardless of the direction of the slashes; it's platform independent (except for the "drive letters" in windows...)
Have a look at using DATEADD
something like
SELECT DATEADD(minute, -30, GETDATE())
The error is here:
hasLetter("a",words[]);
You are passing the first item of words
, instead of the array.
Instead, pass the array to the function:
hasLetter("a",words);
Problem solved!
Here's a breakdown of what the problem was:
I'm guessing in your browser (chrome throws a different error), words[] == words[0]
, so when you call hasLetter("a",words[]);
, you are actually calling hasLetter("a",words[0]);
. So, in essence, you are passing the first item of words to your function, not the array as a whole.
Of course, because words
is just an empty array, words[0]
is undefined
. Therefore, your function call is actually:
hasLetter("a", undefined);
which means that, when you try to access d[ascii]
, you are actually trying to access undefined[0]
, hence the error.
I like PyInstaller - especially the "windowed" variant:
pyinstaller --onefile --windowed myscript.py
It will create one single *.exe file in a distination/folder.
First rollback your previous migration
php artisan migrate:rollback
After that, you can modify your existing migration file (add new , rename or delete columns) then Re-Run your migration file
php artisan migrate
CodeLens is not available in the Community editions. You need Professional or higher to switch it on.
In VS2015, one way to "get" CodeLens was to install the SQL Server Developer Tools (SSDT) but I believe this has been rectified in VS2017.
Still you can get all method reference by right clicking on the method and "Find All references"
Use display:none
to not show the items, then with JQuery you can use fadeIn()
and fadeOut()
to hide/unhide the elements.
Generally speaking, you'll hardly ever need to do type comparisons unless you're doing something with reflection or interfaces. Nonetheless:
If you know the type you want to compare it with, use the is
or as
operators:
if( unknownObject is TypeIKnow ) { // run code here
The as
operator performs a cast that returns null if it fails rather than an exception:
TypeIKnow typed = unknownObject as TypeIKnow;
If you don't know the type and just want runtime type information, use the .GetType() method:
Type typeInformation = unknownObject.GetType();
In newer versions of C#, you can use the is
operator to declare a variable without needing to use as
:
if( unknownObject is TypeIKnow knownObject ) {
knownObject.SomeMember();
}
Previously you would have to do this:
TypeIKnow knownObject;
if( (knownObject = unknownObject as TypeIKnow) != null ) {
knownObject.SomeMember();
}
There are two ways to get variable from URL in PHP:
When your URL is: http://www.example.com/index.php?id=7
you can get this id
via $_GET['id']
or $_REQUEST['id']
command and store in $id
variable.
Lest's take a look:
// url is www.example.com?id=7
//get id from url via $_GET['id'] command:
$id = $_GET['id']
same will be:
//get id from url via $_REQUEST['id'] command:
$id = $_REQUEST['id']
the difference is that variables can be passed to file via URL or via POST method.
if variable is passed through url, then you can get it with $_GET['variable_name']
or $_REQUEST['variable_name']
but if variable is posted, then you need to you $_POST['variable_name']
or $_REQUEST['variable_name']
So as you see $_REQUEST['variable_name']
can be used in both ways.
P.S: Also remember - never do like this: $results = mysql_query("SELECT * FROM next WHERE id=$id");
it may cause MySQL Injection and your database can be hacked.
Try to use:
$results = mysql_query("SELECT * FROM next WHERE id='".mysql_real_escape_string($id)."'");
Erik's answer doesn't work on Windows Phone as is. The following does:
class WebClientEx : WebClient
{
private WebResponse m_Resp = null;
protected override WebResponse GetWebResponse(WebRequest Req, IAsyncResult ar)
{
try
{
this.m_Resp = base.GetWebResponse(request);
}
catch (WebException ex)
{
if (this.m_Resp == null)
this.m_Resp = ex.Response;
}
return this.m_Resp;
}
public HttpStatusCode StatusCode
{
get
{
if (m_Resp != null && m_Resp is HttpWebResponse)
return (m_Resp as HttpWebResponse).StatusCode;
else
return HttpStatusCode.OK;
}
}
}
At least it does when using OpenReadAsync
; for other xxxAsync
methods, careful testing would be highly recommended. The framework calls GetWebResponse somewhere along the code path; all one needs to do is capture and cache the response object.
The fallback code is 200 in this snippet because genuine HTTP errors - 500, 404, etc - are reported as exceptions anyway. The purpose of this trick is to capture non-error codes, in my specific case 304 (Not modified). So the fallback assumes that if the status code is somehow unavailable, at least it's a non-erroneous one.
The Android build tools provide a debug signing mode that makes it easier for you to develop and debug your application, while still meeting the Android system requirement for signing your APK. When using debug mode to build your app, the SDK tools invoke Keytool to automatically create a debug keystore and key. This debug key is then used to automatically sign the APK, so you do not need to sign the package with your own key.
The SDK tools create the debug keystore/key with predetermined names/passwords:
Keystore name: "debug.keystore"
Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"
CN: "CN=Android Debug,O=Android,C=US"
If necessary, you can change the location/name of the debug keystore/key or supply a custom debug keystore/key to use. However, any custom debug keystore/key must use the same keystore/key names and passwords as the default debug key (as described above). (To do so in Eclipse/ADT, go to Windows > Preferences > Android > Build.)
Caution: You cannot release your application to the public when signed with the debug certificate.
Source: Developer.Android
You can copy the HTML svg tag from the website, then paste the code on a new html file and rename the extension to svg. It worked for me. Hope it helps you.
Here there are two issues we have to concentrate on:
HAX device failed to open,
For this problem, you have to run the HAX device setup file from the HAX addon folder. Follow Speed Up Android Emulator to know clearly how.
If you created the AVD through AVD manager then you can change the RAM size in AVD Manager and device edit option.
If you created the AVD through command line, then you should start the AVD from command line will work,
emulator -memory 512 -avd gtv_avd
We can also define it using global
in setupTests
// setupTests.js
global.open = jest.fn()
And call it using global
in the actual test:
// yourtest.test.js
it('correct url is called', () => {
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
Declare them outside the subroutines, like this:
Public wbA as Workbook
Public wbB as Workbook
Sub MySubRoutine()
Set wbA = Workbooks.Open("C:\file.xlsx")
Set wbB = Workbooks.Open("C:\file2.xlsx")
OtherSubRoutine
End Sub
Sub OtherSubRoutine()
MsgBox wbA.Name, vbInformation
End Sub
Alternately, you can pass variables between subroutines:
Sub MySubRoutine()
Dim wbA as Workbook
Dim wbB as Workbook
Set wbA = Workbooks.Open("C:\file.xlsx")
Set wbB = Workbooks.Open("C:\file2.xlsx")
OtherSubRoutine wbA, wbB
End Sub
Sub OtherSubRoutine(wb1 as Workbook, wb2 as Workbook)
MsgBox wb1.Name, vbInformation
MsgBox wb2.Name, vbInformation
End Sub
Or use Functions
to return values:
Sub MySubroutine()
Dim i as Long
i = MyFunction()
MsgBox i
End Sub
Function MyFunction()
'Lots of code that does something
Dim x As Integer, y as Double
For x = 1 to 1000
'Lots of code that does something
Next
MyFunction = y
End Function
In the second method, within the scope of OtherSubRoutine
you refer to them by their parameter names wb1
and wb2
. Passed variables do not need to use the same names, just the same variable types. This allows you some freedom, for example you have a loop over several workbooks, and you can send each workbook to a subroutine to perform some action on that Workbook, without making all (or any) of the variables public in scope.
A Note About User Forms
Personally I would recommend keeping Option Explicit
in all of your modules and forms (this prevents you from instantiating variables with typos in their names, like lCoutn
when you meant lCount
etc., among other reasons).
If you're using Option Explicit
(which you should), then you should qualify module-scoped variables for style and to avoid ambiguity, and you must qualify user-form Public
scoped variables, as these are not "public" in the same sense. For instance, i
is undefined, though it's Public
in the scope of UserForm1
:
You can refer to it as UserForm1.i
to avoid the compile error, or since forms are New
-able, you can create a variable object to contain reference to your form, and refer to it that way:
NB: In the above screenshots x
is declared Public x as Long
in another standard code module, and will not raise the compilation error. It may be preferable to refer to this as Module2.x
to avoid ambiguity and possible shadowing in case you re-use variable names...
You don't need quotes around the variable, so simply change this:
Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"}
into this:
Get-ADComputer -Filter {name -like $nameregex -and Enabled -eq "true"}
Note, however, that the scriptblock notation for filter statements is misleading, because the statement is actually a string, so it's better to write it as such:
Get-ADComputer -Filter "name -like '$nameregex' -and Enabled -eq 'true'"
And FTR: you're using wildcard matching here (operator -like
), not regular expressions (operator -match
).
As far as I know you can only join this way:
var query = from obj_i in set1
join obj_j in set2 on
new {
JoinProperty1 = obj_i.SomeField1,
JoinProperty2 = obj_i.SomeField2,
JoinProperty3 = obj_i.SomeField3,
JoinProperty4 = obj_i.SomeField4
}
equals
new {
JoinProperty1 = obj_j.SomeOtherField1,
JoinProperty2 = obj_j.SomeOtherField2,
JoinProperty3 = obj_j.SomeOtherField3,
JoinProperty4 = obj_j.SomeOtherField4
}
The main requirements are: Property names, types and order in the anonymous objects you're joining on must match.
You CAN'T use ANDs, ORs, etc. in joins. Just object1 equals object2.
More advanced stuff in this LinqPad example:
class c1
{
public int someIntField;
public string someStringField;
}
class c2
{
public Int64 someInt64Property {get;set;}
private object someField;
public string someStringFunction(){return someField.ToString();}
}
void Main()
{
var set1 = new List<c1>();
var set2 = new List<c2>();
var query = from obj_i in set1
join obj_j in set2 on
new {
JoinProperty1 = (Int64) obj_i.someIntField,
JoinProperty2 = obj_i.someStringField
}
equals
new {
JoinProperty1 = obj_j.someInt64Property,
JoinProperty2 = obj_j.someStringFunction()
}
select new {obj1 = obj_i, obj2 = obj_j};
}
Addressing names and property order is straightforward, addressing types can be achieved via casting/converting/parsing/calling methods etc. This might not always work with LINQ to EF or SQL or NHibernate, most method calls definitely won't work and will fail at run-time, so YMMV (Your Mileage May Vary). This is because they are copied to public read-only properties in the anonymous objects, so as long as your expression produces values of correct type the join property - you should be fine.
var x = confirm("Are you sure you want to send sms?");
if (x)
return true;
else
return false;
The previous answers did not work for me, so I decided to improve this.
You should work with url('')
, and not with value.
<li *ngFor="let item of items">
<div
class="img-wrapper"
[ngStyle]="{'background-image': !item.featured ? 'url(\'images/img1.png\')' : 'url(\'images/img2.png\')'}">
</div>
</li>
setTheArray([...theArray, newElement]);
is the simplest answer but be careful for the mutation of items in theArray. Use deep cloning of array items.
hmm I thought that mkdir -p does that?
mkdir -p this/is/a/full/path/of/stuff
You can try this one it is short
SystemClock.sleep(7000);
WARNING: Never, ever, do this on a UI thread.
Use this to sleep eg. background thread.
Full solution for your problem will be: This is available API 1
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View button) {
button.setBackgroundResource(R.drawable.avatar_dead);
final long changeTime = 1000L;
button.postDelayed(new Runnable() {
@Override
public void run() {
button.setBackgroundResource(R.drawable.avatar_small);
}
}, changeTime);
}
});
Without creating tmp Handler. Also this solution is better than @tronman because we do not retain view by Handler. Also we don't have problem with Handler created at bad thread ;)
public static void sleep (long ms)
Added in API level 1
Waits a given number of milliseconds (of uptimeMillis) before returning. Similar to sleep(long), but does not throw InterruptedException; interrupt() events are deferred until the next interruptible operation. Does not return until at least the specified number of milliseconds has elapsed.
Parameters
ms to sleep before returning, in milliseconds of uptime.
Code for postDelayed from View class:
/**
* <p>Causes the Runnable to be added to the message queue, to be run
* after the specified amount of time elapses.
* The runnable will be run on the user interface thread.</p>
*
* @param action The Runnable that will be executed.
* @param delayMillis The delay (in milliseconds) until the Runnable
* will be executed.
*
* @return true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the Runnable will be processed --
* if the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*
* @see #post
* @see #removeCallbacks
*/
public boolean postDelayed(Runnable action, long delayMillis) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.postDelayed(action, delayMillis);
}
// Assume that post will succeed later
ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
return true;
}
My problem was I'm using RVM and had the wrong Ruby version activated...
Hope this helps at least one person
HTTPS is so powerful because it uses asymmetric cryptography. This type of cryptography not only allows you to create an encrypted tunnel but you can verify that you are talking to the right person, and not a hacker.
Here is Java source code which uses the asymmetric cipher RSA (used by PGP) to communicate: http://www.hushmail.com/services/downloads/