ESLint 2.x experimentally supports ObjectRestSpread syntax, you can enable it by adding the following to your .eslintrc
: docs
"parserOptions": {
"ecmaVersion": 6,
"ecmaFeatures": {
"experimentalObjectRestSpread": true
}
},
ESLint 1.x doesn't natively support the spread operator, one way to get around this is using the babel-eslint parser. The latest installation and usage instructions are on the project readme.
hbn's answer won't work out of the box if the file to load is in a subdirectory or is named with dashes.
In such a case you may consider this alternative :
exec open(myconfig.py).read()
Or the simpler but deprecated in python3 :
execfile(myconfig.py)
I guess Stephan202's warning applies to both options, though, and maybe the loop on lines is safer.
Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.
In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:
CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
one int;
two int;
BEGIN
one := 1;
two := 2;
RETURN one + two;
END
$$;
SELECT somefuncname();
The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.
Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/
Add a Button or link to your page like this
<p><a href="#inline">click to open</a></p>
“#inline” here should be the “id” of the that will contain the form.
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method
<script type="text/javascript">
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
//This will post it to the php page
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
You can add anything you want to do in your PHP file.
IMPORTANT NOTE: You should not concatenate SQL queries unless you trust the user completely. Query concatenation involves risk of SQL Injection being used to take over the world, ...khem, your database.
If you don't want to go into details how to execute query using SqlCommand
then you could call the same command line like this:
string userInput = "Brian";
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = string.Format(@"sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS
-s ; -W -w 100 -Q "" SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName,
tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = '{0}' """, userInput);
process.StartInfo = startInfo;
process.Start();
Just ensure that you escape each double quote "
with ""
I had a similar issue today. For some reason, my GET request was fine, but PUT request was failing for my WCF WebHttp Service
Adding the following to the Web.config solved the issue
<system.web>
<authentication mode="Forms" />
</system.web>
If we need only one column to be numeric
yyz$b <- as.numeric(as.character(yyz$b))
But, if all the columns needs to changed to numeric
, use lapply
to loop over the columns and convert to numeric
by first converting it to character
class as the columns were factor
.
yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
Both the columns in the OP's post are factor
because of the string "n/a"
. This could be easily avoided while reading the file using na.strings = "n/a"
in the read.table/read.csv
or if we are using data.frame
, we can have character
columns with stringsAsFactors=FALSE
(the default is stringsAsFactors=TRUE
)
Regarding the usage of apply
, it converts the dataset to matrix
and matrix
can hold only a single class. To check the class
, we need
lapply(yyz, class)
Or
sapply(yyz, class)
Or check
str(yyz)
You could use JavaScript. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for PDF you will have to change the mime type and the magic number):
<form id="form-id">
<input type="file" id="input-id" accept="image/jpeg"/>
</form>
<script type="text/javascript">
$(function(){
$("#input-id").on('change', function(event) {
var file = event.target.files[0];
if(file.size>=2*1024*1024) {
alert("JPG images of maximum 2MB");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
if(!file.type.match('image/jp.*')) {
alert("only JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
var fileReader = new FileReader();
fileReader.onload = function(e) {
var int32View = new Uint8Array(e.target.result);
//verify the magic number
// for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
alert("ok!");
} else {
alert("only valid JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
};
fileReader.readAsArrayBuffer(file);
});
});
</script>
Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.
If you mean the first and last entry of the array when talking about a.first and a.last, it goes like this:
foreach ($arr_nav as $inner_array) {
echo reset($inner_array); //apple, orange, pear
echo end($inner_array); //My Apple, View All Oranges, A Pear
}
arrays in PHP have an internal pointer which you can manipulate with reset, next, end. Retrieving keys/values works with key and current, but using each might be better in many cases..
I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here's a comparison of splice
and delete
for removing every 'c'
from the items
Array.
var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
items.splice(items.indexOf('c'), 1);
}
console.log(items); // ["a", "b", "d", "a", "b", "d"]
items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
delete items[items.indexOf('c')];
}
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
?
If you use sufficiently big list not in b
clause will do a linear search for each of the item in a
. Why not use set? Set takes iterable as parameter to create a new set object.
>>> a = ["a", "b", "c", "d", "e"]
>>> b = ["c", "d", "f", "g"]
>>> set(a).intersection(set(b))
{'c', 'd'}
Another approach that works is to create a unique window id and store this value along with the session id in a database table. The window id I often use is integer(now). This value is created when a window is opened and re-assigned to the same window if the window is refreshed, reloaded or submitted to itself. Window values (inputs) are saved in the local table using the link. When a value is required, it is obtained from the database table based on the window id / session id link. While this approach requires a local database, it is virtually foolproof. The use of a database table was easy for me, but I see no reason why local arrays would not work just as well.
You can display the ActiveRecord generated SQL:
Before the query runs:
$this->db->_compile_select();
And after it has run:
$this->db->last_query();
The perfect solution for this would be to work with Proguard. as aleb mentioned in the comment. It will decrease the size of the dex file by half.
You can do by xlwings as well
import xlwings as xw
for book in xlwings.books:
print(book)
I checked many solutions and anyone wasn't working good.
So I tried a small trick and it works:
tfoot with style:position: fixed; bottom: 0px;
is placed at the bottom of last page, but if footer is too high it is overlapped by content of table.
tfoot with only: display: table-footer-group;
isn't overlapped, but is not on the bottom of last page...
Let's put two tfoot:
TFOOT.placer {_x000D_
display: table-footer-group;_x000D_
height: 130px;_x000D_
}_x000D_
_x000D_
TFOOT.contenter {_x000D_
display: table-footer-group;_x000D_
position: fixed;_x000D_
bottom: 0px; _x000D_
height: 130px;_x000D_
}
_x000D_
<TFOOT class='placer'> _x000D_
<TR>_x000D_
<TD>_x000D_
<!-- empty here_x000D_
-->_x000D_
</TD>_x000D_
</TR>_x000D_
</TFOOT> _x000D_
<TFOOT class='contenter'> _x000D_
<TR>_x000D_
<TD>_x000D_
your long text or high image here_x000D_
</TD>_x000D_
</TR>_x000D_
</TFOOT>
_x000D_
One reserves place on non-last pages, second puts in your accual footer.
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
I faced the problem with my Jenkins. When I have renewed the certificate I started facing this error.
stderr fatal: unable to access server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt
So I have added my new certificate in the following file:
/etc/ssl/certs/ca-certificates.crt
The content of that file looks like this:
-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----
Just append your certificate in the bottom:
-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----
Check Collections#sort
method. This automatically sorts your list according to natural ordering. You can apply this method on each sublist you obtain using List#subList
method.
private List<String> teamsName = new ArrayList<String>();
List<String> subList = teamsName.subList(1, teamsName.size());
Collections.sort(subList);
(5/9)
will by default be computed as an integer division and will be zero. Try (5.0/9)
You can assign a const
object to a non-const
object just fine. Because you're copying and thus creating a new object, const
ness is not violated.
int main() {
const int a = 3;
int b = a;
}
It's different if you want to obtain a pointer or reference to the original, const
object:
int main() {
const int a = 3;
int& b = a; // or int* b = &a;
}
// error: invalid initialization of reference of type 'int&' from
// expression of type 'const int'
You can use const_cast
to hack around the type safety if you really must, but recall that you're doing exactly that: getting rid of the type safety. It's still undefined to modify a
through b
in the below example:
int main() {
const int a = 3;
int& b = const_cast<int&>(a);
b = 3;
}
Although it compiles without errors, anything can happen including opening a black hole or transferring all your hard-earned savings into my bank account.
If you have arrived at what you think is a requirement to do this, I'd urgently revisit your design because something is very wrong with it.
Here is another method using .loc
to replace inf with nan on a Series:
s.loc[(~np.isfinite(s)) & s.notnull()] = np.nan
So, in response to the original question:
df = pd.DataFrame(np.ones((3, 3)), columns=list('ABC'))
for i in range(3):
df.iat[i, i] = np.inf
df
A B C
0 inf 1.000000 1.000000
1 1.000000 inf 1.000000
2 1.000000 1.000000 inf
df.sum()
A inf
B inf
C inf
dtype: float64
df.apply(lambda s: s[np.isfinite(s)].dropna()).sum()
A 2
B 2
C 2
dtype: float64
Check this in the web.config and change overrideModeDefault
from Deny
to Allow
.
<configSections>
<sectionGroup name="system.webServer">
<section name="handlers" overrideModeDefault="Deny" />
<section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Deny" />
You can also manage sections on web server level in your IIS management console from "Feature Delegation".
There are 2 ways to output your number with leading zeroes:
Using the 0
flag and the width specifier:
int zipcode = 123;
printf("%05d\n", zipcode); // outputs 00123
Using the precision specifier:
int zipcode = 123;
printf("%.5d\n", zipcode); // outputs 00123
The difference between these is the handling of negative numbers:
printf("%05d\n", -123); // outputs -0123 (pad to 5 characters)
printf("%.5d\n", -123); // outputs -00123 (pad to 5 digits)
Zip codes are unlikely to be negative, so it should not matter.
Note however that zip codes may actually contain letters and dashes, so they should be stored as strings. Including the leading zeroes in the string is straightforward so it solves your problem in a much simpler way.
Note that in both examples above, the 5
width or precision values can be specified as an int
argument:
int width = 5;
printf("%0*d\n", width, 123); // outputs 00123
printf("%.*d\n", width, 123); // outputs 00123
There is one more trick to know: a precision of 0
causes no output for the value 0
:
printf("|%0d|%0d|\n", 0, 1); // outputs |0|1|
printf("|%.0d|%.0d|\n", 0, 1); // outputs ||1|
Other have hit this one on the head:
main(int argc, char **argv)
give you direct access to the command line (after it has been mangled and tokenized by the shell)getopt()
and getopt_long()
but as you've seen the code to use them is a bit wordy, and quite idomatic. I generally push it out of view with something like:
typedef
struct options_struct {
int some_flag;
int other_flage;
char *use_file;
} opt_t;
/* Parses the command line and fills the options structure,
* returns non-zero on error */
int parse_options(opt_t *opts, int argc, char **argv);
Then first thing in main:
int main(int argc, char **argv){
opt_t opts;
if (parse_options(&opts,argc,argv)){
...
}
...
}
Or you could use one of the solutions suggested in Argument-parsing helpers for C/UNIX.
There is a nice form plugin that allows you to send an HTML form asynchroniously.
$(document).ready(function() {
$('#myForm1').ajaxForm();
});
or
$("select").change(function(){
$('#myForm1').ajaxSubmit();
});
to submit the form immediately
// This code was tested by me (Helio Barbosa)
// this directory (../backup) is for try only.
// it is necessary create it and put files into him.
$hDir = '../backup';
if ($handle = opendir( $hDir )) {
echo "Manipulador de diretório: $handle\n";
echo "Arquivos:\n";
/* Esta é a forma correta de varrer o diretório */
/* Here is the correct form to do find files into the directory */
while (false !== ($file = readdir($handle))) {
// echo($file . "</br>");
$filepath = $hDir . "/" . $file ;
// echo( $filepath . "</br>" );
if(is_file($filepath))
{
echo("Deleting:" . $file . "</br>");
unlink($filepath);
}
}
closedir($handle);
}
The paint()
method supports painting via a Graphics object.
The repaint()
method is used to cause paint()
to be invoked by the AWT painting thread.
CSV files have no limit of rows you can add to them. Excel won't hold more that the 1 million lines of data if you import a CSV file having more lines.
Excel will actually ask you whether you want to proceed when importing more than 1 million data rows. It suggests to import the remaining data by using the text import wizard again - you will need to set the appropriate line offset.
Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines
there are mainly three options are possible for mapping purpose
While using the pojo classes,it is easy for a developer to map with the database. POJO classes are created for database and at the same time value-objects classes are created with getter and setter methods that will easily hold the content.
So,for the purpose of mapping in between java with database, value-objects and POJO classes are implemented.
This should work for multiplication:
.data
.text
.globl main
main:
# $4 * $5 = $2
addi $4, $0, 0x9
addi $5, $0, 0x6
add $2, $0, $0 # initialize product to zero
Loop:
beq $5, $0, Exit # if multiplier is 0,terminate loop
andi $3, $5, 1 # mask out the 0th bit in multiplier
beq $3, $0, Shift # if the bit is 0, skip add
addu $2, $2, $4 # add (shifted) multiplicand to product
Shift:
sll $4, $4, 1 # shift up the multiplicand 1 bit
srl $5, $5, 1 # shift down the multiplier 1 bit
j Loop # go for next
Exit: #
EXIT:
li $v0,10
syscall
Using spring boot you will no need to build configuration. This will have done automatically when you create project.
If you use spring MVC you need to build configuration yourself. It is more complicated, but it is crucial.
I recommend to create a directive
<input type="file" custom-on-change handler="functionToBeCalled(params)">
app.directive('customOnChange', [function() {
'use strict';
return {
restrict: "A",
scope: {
handler: '&'
},
link: function(scope, element){
element.change(function(event){
scope.$apply(function(){
var params = {event: event, el: element};
scope.handler({params: params});
});
});
}
};
}]);
this directive can be used many times, it uses its own scope and doesn't depend on parent scope. You can also give some params to handler function. Handler function will be called with scope object, that was active when you changed the input. $apply updates your model each time the change event is called
I recently came up against a very similar problem, and believe my solution would work for you too. I had a text file which contained a list of items in the form:
["first item", 'the "Second" item', "thi'rd", 'some \\"hellish\\" \'quoted" item']
I wanted to parse the above into a python list but was not keen on eval() as I couldn't trust the input. I tried first using JSON but it only accepts double quoted items, so I wrote my own very simple lexer for this specific case (just plug in your own "stringtoparse" and you will get as output list: 'items')
#This lexer takes a JSON-like 'array' string and converts single-quoted array items into escaped double-quoted items,
#then puts the 'array' into a python list
#Issues such as ["item 1", '","item 2 including those double quotes":"', "item 3"] are resolved with this lexer
items = [] #List of lexed items
item = "" #Current item container
dq = True #Double-quotes active (False->single quotes active)
bs = 0 #backslash counter
in_item = False #True if currently lexing an item within the quotes (False if outside the quotes; ie comma and whitespace)
for c in stringtoparse[1:-1]: #Assuming encasement by brackets
if c=="\\": #if there are backslashes, count them! Odd numbers escape the quotes...
bs = bs + 1
continue
if (dq and c=='"') or (not dq and c=="'"): #quote matched at start/end of an item
if bs & 1==1: #if escaped quote, ignore as it must be part of the item
continue
else: #not escaped quote - toggle in_item
in_item = not in_item
if item!="": #if item not empty, we must be at the end
items += [item] #so add it to the list of items
item = "" #and reset for the next item
continue
if not in_item: #toggle of single/double quotes to enclose items
if dq and c=="'":
dq = False
in_item = True
elif not dq and c=='"':
dq = True
in_item = True
continue
if in_item: #character is part of an item, append it to the item
if not dq and c=='"': #if we are using single quotes
item += bs * "\\" + "\"" #escape double quotes for JSON
else:
item += bs * "\\" + c
bs = 0
continue
Hopefully it is useful to somebody. Enjoy!
Try this,
IFS=''
while read line
do
echo $line
done < file.txt
EDIT:
From man bash
IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with the read builtin command. The default value is
``<space><tab><newline>''
I read through this question, and feel the best way to implement useEffect is not mentioned in the answers. Let's say you have a network call, and would like to do something once you have the response. For the sake of simplicity, let's store the network response in a state variable. One might want to use action/reducer to update the store with the network response.
const [data, setData] = useState(null);
/* This would be called on initial page load */
useEffect(()=>{
fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(data => {
setData(data);
})
.catch(err => {
/* perform error handling if desired */
});
}, [])
/* This would be called when store/state data is updated */
useEffect(()=>{
if (data) {
setPosts(data.children.map(it => {
/* do what you want */
}));
}
}, [data]);
Reference => https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
Add a GitHub repository as remote origin (replace [] with your URL):
git remote add origin [[email protected]:...]
Switch to your master branch and copy it to develop branch:
git checkout master
git checkout -b develop
Push your develop branch to the GitHub develop branch (-f
means force):
git push -f origin develop:develop
I'll start off with this: consistency is king, the decision is less important than the consistency in your code base.
NULL is defined as 0
or 0L
in C++.
If you've read The C++ Programming Language Bjarne Stroustrup suggests using 0
explicitly to avoid the NULL
macro when doing assignment, I'm not sure if he did the same with comparisons, it's been a while since I read the book, I think he just did if(some_ptr)
without an explicit comparison but I am fuzzy on that.
The reason for this is that the NULL
macro is deceptive (as nearly all macros are) it is actually 0
literal, not a unique type as the name suggests it might be. Avoiding macros is one of the general guidelines in C++. On the other hand, 0
looks like an integer and it is not when compared to or assigned to pointers. Personally I could go either way, but typically I skip the explicit comparison (though some people dislike this which is probably why you have a contributor suggesting a change anyway).
Regardless of personal feelings this is largely a choice of least evil as there isn't one right method.
This is clear and a common idiom and I prefer it, there is no chance of accidentally assigning a value during the comparison and it reads clearly:
if (some_ptr) {}
This is clear if you know that some_ptr
is a pointer type, but it may also look like an integer comparison:
if (some_ptr != 0) {}
This is clear-ish, in common cases it makes sense... But it's a leaky abstraction, NULL
is actually 0
literal and could end up being misused easily:
if (some_ptr != NULL) {}
C++11 has nullptr
which is now the preferred method as it is explicit and accurate, just be careful about accidental assignment:
if (some_ptr != nullptr) {}
Until you are able to migrate to C++0x I would argue it's a waste of time worrying about which of these methods you use, they are all insufficient which is why nullptr was invented (along with generic programming issues which came up with perfect forwarding.) The most important thing is to maintain consistency.
C is a different beast.
In C NULL
can be defined as 0
or as ((void *)0)
, C99 allows for implementation defined null pointer constants. So it actually comes down to the implementation's definition of NULL
and you will have to inspect it in your standard library.
Macros are very common and in general they are used a lot to make up for deficiencies in generic programming support in the language and other things as well. The language is much simpler and reliance on the preprocessor more common.
From this perspective I'd probably recommend using the NULL
macro definition in C.
You can call a function after the state value has updated:
this.setState({foo: 'bar'}, () => {
// Do something here.
});
Also, if you have lots of states to update at once, group them all within the same setState
:
Instead of:
this.setState({foo: "one"}, () => {
this.setState({bar: "two"});
});
Just do this:
this.setState({
foo: "one",
bar: "two"
});
I have started Activity A->B->C->D. When the back button is pressed on Activity D I want to go to Activity A. Since A is my starting point and therefore already on the stack all the activities in top of A is cleared and you can't go back to any other Activity from A.
This actually works in my code:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent a = new Intent(this,A.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
return true;
}
return super.onKeyDown(keyCode, event);
}
I realise I'm a little late , but this works with PURE javascript, and it even gives you the coordinates of the pointer within the element if the element is bigger than the viewport and the user has scrolled.
var element_offset_x ; // The distance from the left side of the element to the left of the content area
....// some code here (function declaration or element lookup )
element_offset_x = element.getBoundingClientRect().left - document.getElementsByTagName("html")[0].getBoundingClientRect().left ;
....// code here
function mouseMoveEvent(event)
{
var pointer_location = (event.clientX + window.pageXOffset) - element_offset_x ;
}
How it works.
The first thing we do is get the location of the HTML element (the content area) relative to the current viewport. If the page has scrollbars and is scrolled, then the number returned by getBoundingClientRect().left
for the html tag will be negative. We then use this number to compute the distance between the element and the left of the content area. With element_offset_x = element.getBoundingClientRect().left......;
Knowing the distance of the element from the content area. event.clientX
gives us the distance of the pointer from the viewport. It is important to understand that the viewport and the content area are two different entities, the viewport can move if the page is scrolled. Hence, clientX will return the SAME number even if the page is scrolled.
To compensate for this , we need to add the x position of the pointer (relative to the viewport) , to the x position of the viewport (relative to the content area ). The X position of the viewport is found with window.pageXOffset.
string path=@"E:\AppServ\Example.txt";
if(!File.Exists(path))
{
File.Create(path).Dispose();
using( TextWriter tw = new StreamWriter(path))
{
tw.WriteLine("The very first line!");
}
}
else if (File.Exists(path))
{
using(TextWriter tw = new StreamWriter(path))
{
tw.WriteLine("The next line!");
}
}
The real answer to this is to put a @ At symbol before the variable which will suppress the error
@$_GET["field"]
@$_POST["field"]
It will work some slower, but will keep the code clean.
When something saves time for the programmer, and costs time for the website users (or requires more hardware), it depends on how much people will use it.
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.
I looked at the sprite text example and it looks awfully complicated for such a task, I considered rendering to a texture too, but I'm worried about the performance hit that might cause. I might just have to go with a view instead and worry about porting when it's time to cross that bridge :)
Quick and dirty way:
<View
android:id="@+id/colored_bar"
android:layout_width="48dp"
android:layout_height="3dp"
android:background="@color/bar_red" />
Apparently the only reliable and accepted solution would be to do feature detection like this:
browser_treats_urls_like_safari_does = false;
var last_location_hash = location.hash;
location.hash = '"blah"';
if (location.hash == '#%22blah%22')
browser_treats_urls_like_safari_does = true;
location.hash = last_location_hash;
For people just stumbling upon this now, I resolved an error of this type that was thrown with all the references and using statements placed properly. There's evidently some confusion with substituting in a function that returns DataTable instead of calling it on a declared DataTable. For example:
This worked for me:
DataTable dt = SomeObject.ReturnsDataTable();
List<string> ls = dt.AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();
But this didn't:
List<string> ls = SomeObject.ReturnsDataTable().AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();
I'm still not 100% sure why, but if anyone is frustrated by an error of this type, give this a try.
You actually don't need to use the attach at all. I had the same problem and it was resolved by removing the attach statement.
Here's a workaround.
Make a template subclass B of A. Do the template-argument-independent part of the construction in A's constructor. Do the template-argument-dependent part in B's constructor.
Your question is a bit confusing, but I am assuming - you are first doing 'ssh' to find out which files or rather specifically directories are there and then again on your local computer, you are trying to scp 'all' files in that directory to local path. you should simply do scp -r
.
So here in your case it'd be something like
local> scp -r [email protected]:/path/to/dir local/path
If youare using some other executable that provides 'scp like functionality', refer to it's manual for recursively copying files.
Another way of doing so is:
while i<len(your_list):
if #condition :
del your_list[i]
else:
i+=1
So, you delete the elements side by side while checking
I came across a similar issue. However this issue was caused because of the way i designed the pages to bring the requests in. I placed all of my .js files as the last thing to be applied to the page, therefore they are at the end of my document. The .js files have all my functions include. The script manager seems that to be able to call this function it needs the js file already present with the function being called at the time of load. Hope this helps anyone else.
It is a Generic Type Parameter.
A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.
For example:
public T[] Reverse<T>(T[] array)
{
var result = new T[array.Length];
int j=0;
for(int i=array.Length - 1; i>= 0; i--)
{
result[j] = array[i];
j++;
}
return result;
}
reverses the elements in an array. The key point here is that the array elements can be of any type, and the function will still work. You specify the type in the method call; type safety is still guaranteed.
So, to reverse an array of strings:
string[] array = new string[] { "1", "2", "3", "4", "5" };
var result = reverse(array);
Will produce a string array in result
of { "5", "4", "3", "2", "1" }
This has the same effect as if you had called an ordinary (non-generic) method that looks like this:
public string[] Reverse(string[] array)
{
var result = new string[array.Length];
int j=0;
for(int i=array.Length - 1; i >= 0; i--)
{
result[j] = array[i];
j++;
}
return result;
}
The compiler sees that array
contains strings, so it returns an array of strings. Type string
is substituted for the T
type parameter.
Generic type parameters can also be used to create generic classes. In the example you gave of a SampleCollection<T>
, the T
is a placeholder for an arbitrary type; it means that SampleCollection
can represent a collection of objects, the type of which you specify when you create the collection.
So:
var collection = new SampleCollection<string>();
creates a collection that can hold strings. The Reverse
method illustrated above, in a somewhat different form, can be used to reverse the collection's members.
For Windows 8 and Windows Server 2012 use dism /online /enable-feature /featurename:IIS-ASPNET45
As administrative command prompt.
if you are trying to use jquery in your electron app before adding jquery you should add it to your modules:
<script>
if (typeof module === 'object') {
window.module = module;
module = undefined;
}
</script>
<script src="js/jquery-3.5.1.min.js"></script>
EDIT: A more generic way of doing this that doesn't rely on the layout type (other than that it is a layout type which supports margins):
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
You should check the docs for TextView. Basically, you'll want to get the TextView's LayoutParams object, and modify the margins, then set it back to the TextView. Assuming it's in a LinearLayout, try something like this:
TextView tv = (TextView)findViewById(R.id.my_text_view);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
tv.setLayoutParams(params);
I can't test it right now, so my casting may be off by a bit, but the LayoutParams are what need to be modified to change the margin.
Don't forget that if your TextView is inside, for example, a RelativeLayout, one should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams
It is simple actually, like C programming you just need to pass the array indices on the right hand side while declaration. But yeah the syntax will be like [0:3] for 4 elements.
reg a[0:3];
This will create a 1D of array of single bit. Similarly 2D array can be created like this:
reg [0:3][0:2];
Now in C suppose you create a 2D array of int, then it will internally create a 2D array of 32 bits. But unfortunately Verilog is an HDL, so it thinks in bits rather then bunch of bits (though int datatype is there in Verilog), it can allow you to create any number of bits to be stored inside an element of array (which is not the case with C, you can't store 5-bits in every element of 2D array in C). So to create a 2D array, in which every individual element can hold 5 bit value, you should write this:
reg [0:4] a [0:3][0:2];
When I'd like to view incoming connections from our application servers to the database I use the following command:
SELECT username FROM v$session
WHERE username IS NOT NULL
ORDER BY username ASC;
Simple, but effective.
final
can be used to mark a variable "unchangeable"
private final String name = "foo"; //the reference name can never change
final
can also make a method not "overrideable"
public final String toString() { return "NULL"; }
final
can also make a class not "inheritable". i.e. the class can not be subclassed.
public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed
finally
is used in a try/catch statement to execute code "always"
lock.lock();
try {
//do stuff
} catch (SomeException se) {
//handle se
} finally {
lock.unlock(); //always executed, even if Exception or Error or se
}
Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable
finalize
is called when an object is garbage collected. You rarely need to override it. An example:
protected void finalize() {
//free resources (e.g. unallocate memory)
super.finalize();
}
Since office 2013 use this inbuilt function here.
If before office 2013
Function encodeURL(str As String)
Dim ScriptEngine As ScriptControl
Set ScriptEngine = New ScriptControl
ScriptEngine.Language = "JScript"
ScriptEngine.AddCode "function encode(str) {return encodeURIComponent(str);}"
Dim encoded As String
encoded = ScriptEngine.Run("encode", str)
encodeURL = encoded
End Function
Add Microsoft Script Control as reference and you are done.
Same as last post just complete function ..works!
For me it worked after stopping Web Deployment Agent Service.
If you are on linux and have inotify-tools installed, you can do this:
file=/tmp/list.txt
while [ ! -f "$file" ]
do
inotifywait -qqt 2 -e create -e moved_to "$(dirname $file)"
done
This reduces the delay introduced by sleep while still polling every "x" seconds. You can add more events if you anticipate that they are needed.
Preferences
> Accounts
> Add Apple ID
:You can now run your project on a device!
Using return false;
or e.stopPropogation();
will not allow further code to execute. It will stop flow at this point itself.
You can use
var modal_template_html = $.trim($('#modal_template').html());
var template = $(modal_template_html);
dataGridView1.DataSource=null;
How much a stack can grow?
You can use a VM option named ss
to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M
to set the maximum of stack size to 1M.
Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss
set the size of the Java Stack in most cases.
For many JVMs, they put different default values for stack size on different platforms.
Can we limit this growth?
When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).
Does stack has some default minimum value or default maximum value?
As I said before, different VMs are different, and may change over versions. See here.
how does garbage collection work on stack?
Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.
This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.
git grep
Here is the syntax using git grep
with multiple patterns:
git grep --all-match --no-index -l -e string1 -e string2 -e string3 file
You may also combine patterns with Boolean expressions such as --and
, --or
and --not
.
Check man git-grep
for help.
--all-match
When giving multiple pattern expressions, this flag is specified to limit the match to files that have lines to match all of them.
--no-index
Search files in the current directory that is not managed by Git.
-l
/--files-with-matches
/--name-only
Show only the names of files.
-e
The next parameter is the pattern. Default is to use basic regexp.
Other params to consider:
--threads
Number of grep worker threads to use.
-q
/--quiet
/--silent
Do not output matched lines; exit with status 0 when there is a match.
To change the pattern type, you may also use -G
/--basic-regexp
(default), -F
/--fixed-strings
, -E
/--extended-regexp
, -P
/--perl-regexp
, -f file
, and other.
Related:
For OR operation, see:
It's really simple using the forEach method since ES5+. You can directly change each property of each object in your array.
myArray.forEach(function (arrayElem){
arrayElem = newPropertyValue;
});
If you want to access a specific property on each object:
myArray.forEach(function (arrayElem){
arrayElem.nameOfYourProperty = newPropertyValue;
});
Yes, you can use numpy
for that.
import numpy as np
a = arange(3,dtype=float)
a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf
a # is now [nan,inf,-inf]
np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True
A simple solution is to assign color for each class. This way, we can control how each color is for each class. For example:
arr1 = [1, 2, 3, 4, 5]
arr2 = [2, 3, 3, 4, 4]
labl = [0, 1, 1, 0, 0]
color= ['red' if l == 0 else 'green' for l in labl]
plt.scatter(arr1, arr2, color=color)
This is what I tried for a right outer join [as per my requirement]:
m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink,
by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"),
by.y=c("company_permalink"), all.y=TRUE)
This worked.
If your mongoDB server(remote server)'s version is greater then 4.0.3, then you will face this issue. Hence you should replace your current mongo-client shell with below mongo :
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
Then you mongo client will be able to connect your remove mongodb
I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.
You can use an object as a map:
var hasName = ({
"true" : "Y",
"false" : "N"
})[name];
This also scales nicely for many options
var hasName = ({
"true" : "Y",
"false" : "N",
"fileNotFound" : "O"
})[name];
(Bonus point for people getting the reference)
Note: you should use actual booleans instead of the string value "true" for your variables indicating truth values.
I would use this syntax
Delete a
from TableA a
Inner Join TableB b
on a.BId = b.BId
WHERE [filter condition]
More recent answer with an example, which uses React.useState
Keeping the state in the parent component is the recommended way. The parent needs to have an access to it as it manages it across two children components. Moving it to the global state, like the one managed by Redux, is not recommended for same same reason why global variable is worse than local in general in software engineering.
When the state is in the parent component, the child can mutate it if the parent gives the child value
and onChange
handler in props (sometimes it is called value link or state link pattern). Here is how you would do it with hooks:
function Parent() {
var [state, setState] = React.useState('initial input value');
return <>
<Child1 value={state} onChange={(v) => setState(v)} />
<Child2 value={state}>
</>
}
function Child1(props) {
return <input
value={props.value}
onChange={e => props.onChange(e.target.value)}
/>
}
function Child2(props) {
return <p>Content of the state {props.value}</p>
}
The whole parent component will re-render on input change in the child, which might be not an issue if the parent component is small / fast to re-render. The re-render performance of the parent component still can be an issue in the general case (for example large forms). This is solved problem in your case (see below).
State link pattern and no parent re-render are easier to implement using the 3rd party library, like Hookstate - supercharged React.useState
to cover variety of use cases, including your's one. (Disclaimer: I am an author of the project).
Here is how it would look like with Hookstate. Child1
will change the input, Child2
will react to it. Parent
will hold the state but will not re-render on state change, only Child1
and Child2
will.
import { useStateLink } from '@hookstate/core';
function Parent() {
var state = useStateLink('initial input value');
return <>
<Child1 state={state} />
<Child2 state={state}>
</>
}
function Child1(props) {
// to avoid parent re-render use local state,
// could use `props.state` instead of `state` below instead
var state = useStateLink(props.state)
return <input
value={state.get()}
onChange={e => state.set(e.target.value)}
/>
}
function Child2(props) {
// to avoid parent re-render use local state,
// could use `props.state` instead of `state` below instead
var state = useStateLink(props.state)
return <p>Content of the state {state.get()}</p>
}
PS: there are many more examples here covering similar and more complicated scenarios, including deeply nested data, state validation, global state with setState
hook, etc. There is also complete sample application online, which uses the Hookstate and the technique explained above.
Here is a sample project, based on antew's detailed and helpful answer, that implements a ListView
with multiple headers that incorporates view holders to improve scrolling performance.
In this project, the objects represented in the ListView
are instances of either the class HeaderItem
or the class RowItem
, both of which are subclasses of the abstract class Item
. Each subclass of Item
corresponds to a different view type in the custom adapter, ItemAdapter
. The method getView()
on ItemAdapter
delegates the creation of the view for each list item to an individualized getView()
method on either HeaderItem
or RowItem
, depending on the Item
subclass used at the position passed to the getView()
method on the adapter. Each Item
subclass provides its own view holder.
The view holders are implemented as follows. The getView()
methods on the Item
subclasses check whether the View
object that was passed to the getView()
method on ItemAdapter
is null. If so, the appropriate layout is inflated, and a view holder object is instantiated and associated with the inflated view via View.setTag()
. If the View
object is not null, then a view holder object was already associated with the view, and the view holder is retrieved via View.getTag()
. The way in which the view holders are used can be seen in the following code snippet from HeaderItem
:
@Override
View getView(LayoutInflater i, View v) {
ViewHolder h;
if (v == null) {
v = i.inflate(R.layout.header, null);
h = new ViewHolder(v);
v.setTag(h);
} else {
h = (ViewHolder) v.getTag();
}
h.category.setText(text());
return v;
}
private class ViewHolder {
final TextView category;
ViewHolder(View v) {
category = v.findViewById(R.id.category);
}
}
The complete implementation of the ListView follows. Here is the Java code:
import android.app.ListActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ItemAdapter(getItems()));
}
class ItemAdapter extends ArrayAdapter<Item> {
final private List<Class<?>> viewTypes;
ItemAdapter(List<Item> items) {
super(MainActivity.this, 0, items);
if (items.contains(null))
throw new IllegalArgumentException("null item");
viewTypes = getViewTypes(items);
}
private List<Class<?>> getViewTypes(List<Item> items) {
Set<Class<?>> set = new HashSet<>();
for (Item i : items)
set.add(i.getClass());
List<Class<?>> list = new ArrayList<>(set);
return Collections.unmodifiableList(list);
}
@Override
public int getViewTypeCount() {
return viewTypes.size();
}
@Override
public int getItemViewType(int position) {
Item t = getItem(position);
return viewTypes.indexOf(t.getClass());
}
@Override
public View getView(int position, View v, ViewGroup unused) {
return getItem(position).getView(getLayoutInflater(), v);
}
}
abstract private class Item {
final private String text;
Item(String text) {
this.text = text;
}
String text() { return text; }
abstract View getView(LayoutInflater i, View v);
}
private class HeaderItem extends Item {
HeaderItem(String text) {
super(text);
}
@Override
View getView(LayoutInflater i, View v) {
ViewHolder h;
if (v == null) {
v = i.inflate(R.layout.header, null);
h = new ViewHolder(v);
v.setTag(h);
} else {
h = (ViewHolder) v.getTag();
}
h.category.setText(text());
return v;
}
private class ViewHolder {
final TextView category;
ViewHolder(View v) {
category = v.findViewById(R.id.category);
}
}
}
private class RowItem extends Item {
RowItem(String text) {
super(text);
}
@Override
View getView(LayoutInflater i, View v) {
ViewHolder h;
if (v == null) {
v = i.inflate(R.layout.row, null);
h = new ViewHolder(v);
v.setTag(h);
} else {
h = (ViewHolder) v.getTag();
}
h.option.setText(text());
return v;
}
private class ViewHolder {
final TextView option;
ViewHolder(View v) {
option = v.findViewById(R.id.option);
}
}
}
private List<Item> getItems() {
List<Item> t = new ArrayList<>();
t.add(new HeaderItem("Header 1"));
t.add(new RowItem("Row 2"));
t.add(new HeaderItem("Header 3"));
t.add(new RowItem("Row 4"));
t.add(new HeaderItem("Header 5"));
t.add(new RowItem("Row 6"));
t.add(new HeaderItem("Header 7"));
t.add(new RowItem("Row 8"));
t.add(new HeaderItem("Header 9"));
t.add(new RowItem("Row 10"));
t.add(new HeaderItem("Header 11"));
t.add(new RowItem("Row 12"));
t.add(new HeaderItem("Header 13"));
t.add(new RowItem("Row 14"));
t.add(new HeaderItem("Header 15"));
t.add(new RowItem("Row 16"));
t.add(new HeaderItem("Header 17"));
t.add(new RowItem("Row 18"));
t.add(new HeaderItem("Header 19"));
t.add(new RowItem("Row 20"));
t.add(new HeaderItem("Header 21"));
t.add(new RowItem("Row 22"));
t.add(new HeaderItem("Header 23"));
t.add(new RowItem("Row 24"));
t.add(new HeaderItem("Header 25"));
t.add(new RowItem("Row 26"));
t.add(new HeaderItem("Header 27"));
t.add(new RowItem("Row 28"));
t.add(new RowItem("Row 29"));
t.add(new RowItem("Row 30"));
t.add(new HeaderItem("Header 31"));
t.add(new RowItem("Row 32"));
t.add(new HeaderItem("Header 33"));
t.add(new RowItem("Row 34"));
t.add(new RowItem("Row 35"));
t.add(new RowItem("Row 36"));
return t;
}
}
There are also two list item layouts, one for each Item subclass. Here is the layout header
, used by HeaderItem:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFAAAAAA"
>
<TextView
android:id="@+id/category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:textColor="#FF000000"
android:textSize="20sp"
android:textStyle="bold"
/>
</LinearLayout>
And here is the layout row
, used by RowItem:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
>
<TextView
android:id="@+id/option"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
/>
</LinearLayout>
Here is an image of a portion of the resulting ListView:
There are two approaches which are not mentioned above, but both of which solve the problem in a way which complies with PEP 8 and allow you to make better use of your space. They are:
msg = (
'This message is so long, that it requires '
'more than {x} lines.{sep}'
'and you may want to add more.').format(
x=x, sep=2*'\n')
print(msg)
Notice how the parentheses are used to allow us not to add plus signs between pure strings, and spread the result over multiple lines without the need for explicit line continuation '\' (ugly and cluttered).
The advantages are same with what is described below, the difference is that you can do it anywhere.
Compared to the previous alternative, it is visually better when inspecting code, because it outlines the start and end of msg
clearly (compare with msg +=
one every line, which needs one additional thinking step to deduce that those lines add to the same string - and what if you make a typo, forgetting a +
on one random line ?).
Regarding this approach, many times we have to build a string using iterations and checks within the iteration body, so adding its pieces within the function call, as shown later, is not an option.
A close alternative is:
msg = 'This message is so long, that it requires '
msg += 'many lines to write, one reason for that\n'
msg += 'is that it contains numbers, like this '
msg += 'one: ' + str(x) +', which take up more space\n'
msg += 'to insert. Note how newlines are also included '
msg += 'and can be better presented in the code itself.'
print(msg)
Though the first is preferable.
The other approach is like the previous ones, though it starts the message on the line below the print
.
The reason for this is to gain space on the left, otherwise the print(
itself "pushes" you to the right. This consumption of indentation is the inherited by the rest of the lines comprising the message, because according to PEP 8 they must align with the opening parenthesis of print
above them. So if your message was already long, this way it's forced to be spread over even more lines.
Contrast:
raise TypeError('aaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaa')
with this (suggested here):
raise TypeError(
'aaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaa')
The line spread was reduced. Of course this last approach does no apply so much to print
, because it is a short call. But it does apply to exceptions.
A variation you can have is:
raise TypeError((
'aaaaaaaaaaaaaaaaaaaaaaaa'
'aaaaaaaaaaaaaaaaaaaaaaaa'
'aaaaa {x} aaaaa').format(x=x))
Notice how you don't need to have plus signs between pure strings. Also, the indentation guides the reader's eyes, no stray parentheses hanging below to the left. The replacements are very readable. In particular, such an approach makes writing code that generates code or mathematical formulas a very pleasant task.
Having a map doesn't look good at all with a large amount of components. I'm actually surprised that no one has suggested something like this:
var componentName = "StringThatContainsComponentName";
const importedComponentModule = require("path/to/component/" + componentName).default;
return React.createElement(importedComponentModule);
This one has really helped me when I needed to render a pretty large amount of components loaded in a form of json array.
This is kind of mucky, and when I say kind of mucky I may mean revolting, but supposing you can furnish your parameterised type with an empty constructor, then:
public static T GetTInstance<T>() where T: new()
{
var constructorTypeSignature = new Type[] {typeof (object)};
var constructorParameters = new object[] {"Create a T"};
return (T) new T().GetType().GetConstructor(constructorTypeSignature).Invoke(constructorParameters);
}
Will effectively allow you to construct an object from a parameterised type with an argument. In this case I am assuming the constructor I want has a single argument of type object
. We create a dummy instance of T using the constraint permitted empty constructor and then use reflection to get one of its other constructors.
From the id Selector jQuery page:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
Naughty Google. But they don't even close their <html>
and <body>
tags I hear. The question is though, why Misha's 2nd and 3rd queries return 2 and not 1 as well.
Beware the leading 00 that can appear in the modulus when using:
openssl rsa -pubin -inform PEM -text -noout < public.key
The example modulus contains 257 bytes rather than 256 bytes because of that 00, which is included because the 9 in 98 looks like a negative signed number.
This is another great change from Google ... The suggested modification: replace onAttach(Activity activity)
with onAttach(Context context)
crashed my apps on older APIs since onAttach(Context context)
will not be called on native fragments.
I am using the native fragments (android.app.Fragment) so I had to do the following to make it work again on older APIs (< 23).
Here is what I did:
@Override
public void onAttach(Context context) {
super.onAttach(context);
// Code here
}
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// Code here
}
}
Many problem for this, with my problem is missing '/' example: jquery-1.10.2.js:8720 XMLHttpRequest cannot load http://localhost:xxxProduct/getList_tagLabels/ It's must be: http://localhost:xxx/Product/getList_tagLabels/
I hope this help for who meet this problem.
Summary of difference -
when list is created without using new operator Arrays.asList() method it return Wrapper which means
1. you can perform add/update Operation.
2. the changes done in original array will be reflected to List as well and vice versa.
The rest of the sentence is:
where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.
This basically means that the following XML element
<foo>hello
wor
ld</foo>
could be represented like this in a denormalized node:
Element foo
Text node: ""
Text node: "Hello "
Text node: "wor"
Text node: "ld"
When normalized, the node will look like this
Element foo
Text node: "Hello world"
And the same goes for attributes: <foo bar="Hello world"/>
, comments, etc.
An easy solution to solve this problem is by just adding more seconds to the animation in a:hover
and taking advantage of the transitions in @keyframes
a:hover {
animation: hover 200s infinite alternate ease-in-out;
}
Just make the progression of @keyframes
go faster by using percentages.
@keyframes hover {
0% {
transform: scale(1, 1);
}
1% {
transform: scale(1.1, 1.1);
}
100% {
transform: scale(1.1, 1.1);
}
}
200 seconds or 300 seconds in the animation is more than enough to make sure the animation doesn't restart. A normal person won't last more than a few seconds hovering an image.
To DELETE, without changing the references, you should first delete or otherwise alter (in a manner suitable for your purposes) all relevant rows in other tables.
To TRUNCATE you must remove the references. TRUNCATE is a DDL statement (comparable to CREATE and DROP) not a DML statement (like INSERT and DELETE) and doesn't cause triggers, whether explicit or those associated with references and other constraints, to be fired. Because of this, the database could be put into an inconsistent state if TRUNCATE was allowed on tables with references. This was a rule when TRUNCATE was an extension to the standard used by some systems, and is mandated by the the standard, now that it has been added.
The following tables are store WooCommerce products database :
wp_posts -
The core of the WordPress data is the posts. It is stored a post_type
like product or variable_product
.
wp_postmeta-
Each post features information called the meta data and it is stored in the wp_postmeta. Some plugins may add their own information to this table like WooCommerce plugin store product_id
of product in wp_postmeta table.
Product categories, subcategories stored in this table :
following Query Return a list of product categories
SELECT wp_terms.*
FROM wp_terms
LEFT JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
WHERE wp_term_taxonomy.taxonomy = 'product_cat';
for more reference -
The statement should be of the order
Without 'GO' in between, the whole thing will be considered as one single script and when the select statement looks for the column,it won't be found.
With 'GO' , it will consider the part of the script up to 'GO' as one single batch and will execute before getting into the query after 'GO'.
On some earlier iOS versions(like iOS 9, 10), scrollViewDidEndDecelerating
won't be triggered if the scrollView is suddenly stopped by touching.
But in the current version (iOS 13), scrollViewDidEndDecelerating
will be triggered for sure (As far as I know).
So, if your App targeted earlier versions as well, you might need a workaround like the one mentioned by Ashley Smart, or you can the following one.
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if !scrollView.isTracking, !scrollView.isDragging, !scrollView.isDecelerating { // 1
scrollViewDidEndScrolling(scrollView)
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate, scrollView.isTracking, !scrollView.isDragging, !scrollView.isDecelerating { // 2
scrollViewDidEndScrolling(scrollView)
}
}
func scrollViewDidEndScrolling(_ scrollView: UIScrollView) {
// Do something here
}
UIScrollView will be stoped in three ways:
- quickly scrolled and stopped by itself
- quickly scrolled and stopped by finger touch (like Emergency brake)
- slowly scrolled and stopped
The first one can be detected by scrollViewDidEndDecelerating
and other similar methods while the other two can't.
Luckily, UIScrollView
has three statuses we can use to identify them, which is used in the two lines commented by "//1" and "//2".
find source/ -type f | rsync -a --exclude-from - source/ target/
Copy dir only with associated permission and ownership
The reliable solution is catching the ObjectDisposedException.
The solution to write your overridden implementation of the Dispose method doesn't work, since there is a race condition between the thread calling Dispose method and the one accessing to the object: after having checked the hypothetic IsDisposed property , the object could be really disposed, throwing the exception all the same.
Another approach could be exposing a hypothetic event Disposed (like this), which is used to notify about the disposing object to every object interested, but this could be difficoult to plan depending on the software design.
The solution for me was to add :
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
</system.webServer>
To my web.config
This error is exactly what it means: Something bad happened, that would not normally happen.
In my most recent case, the REAL error was:
Msg 9002, Level 17, State 2, Procedure MyProcedure, Line 2 [Batch Start Line 3]
The transaction log for database 'MyDb' is full due to 'LOG_BACKUP'.
Here is my checklist of things to try, perhaps in this exact order:
The question is really about scope, as the other guy put it.
In short, consider this "module":
Public Var1 As variant 'Var1 can be used in all
'modules, class modules and userforms of
'thisworkbook and will preserve any values
'assigned to it until either the workbook
'is closed or the project is reset.
Dim Var2 As Variant 'Var2 and Var3 can be used anywhere on the
Private Var3 As Variant ''current module and will preserve any values
''they're assigned until either the workbook
''is closed or the project is reset.
Sub MySub() 'Var4 can only be used within the procedure MySub
Dim Var4 as Variant ''and will only store values until the procedure
End Sub ''ends.
Sub MyOtherSub() 'You can even declare another Var4 within a
Dim Var4 as Variant ''different procedure without generating an
End Sub ''error (only possible confusion).
You can check out this MSDN reference for more on variable declaration and this other Stack Overflow Question for more on how variables go out of scope.
Two other quick things:
You might be interested in itertools.product
, which returns an iterable yielding tuples of values from all the iterables you pass it. That is, itertools.product(A, B)
yields all values of the form (a, b)
, where the a
values come from A
and the b
values come from B
. For example:
import itertools
A = [50, 60, 70]
B = [0.1, 0.2, 0.3, 0.4]
print [a + b for a, b in itertools.product(A, B)]
This prints:
[50.1, 50.2, 50.3, 50.4, 60.1, 60.2, 60.3, 60.4, 70.1, 70.2, 70.3, 70.4]
Notice how the final argument passed to itertools.product
is the "inner" one. Generally, itertools.product(a0, a1, ... an)
is equal to [(i0, i1, ... in) for in in an for in-1 in an-1 ... for i0 in a0]
use ROUND () (See examples ) function in sql server
select round(11.6,0)
result:
12.0
ex2:
select round(11.4,0)
result:
11.0
if you don't want the decimal part, you could do
select cast(round(11.6,0) as int)
if ($number % 6 != 0) {
$number += 6 - ($number % 6);
}
The modulus operator gives the remainder of the division, so $number % 6 is the amount left over when dividing by 6. This will be faster than doing a loop and continually rechecking.
If decreasing is acceptable then this is even faster:
$number -= $number % 6;
Similar to R's seq
function, this one returns a sequence in any order given the correct step value. The last value is equal to the stop value.
def seq(start, stop, step=1):
n = int(round((stop - start)/float(step)))
if n > 1:
return([start + step*i for i in range(n+1)])
elif n == 1:
return([start])
else:
return([])
seq(1, 5, 0.5)
[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]
seq(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
seq(10, 0, -2)
[10, 8, 6, 4, 2, 0]
seq(1, 1)
[ 1 ]
work with you apply runat="server" in your div section...
<div runat="server" id="hideid">
On your button click event:
protected void btnSubmit_Click(object sender, EventArgs e)
{
hideid.Visible = false;
}
Check with your firewall expert. They open the firewall for PROD servers so there is no need to use the Proxy.
Thanks your tip helped me solve my problem:
Had to to set the Credentials in two locations to get past the 407 error:
HttpWebRequest webRequest = WebRequest.Create(uirTradeStream) as HttpWebRequest;
webRequest.Proxy = WebRequest.DefaultWebProxy;
webRequest.Credentials = new NetworkCredential("user", "password", "domain");
webRequest.Proxy.Credentials = new NetworkCredential("user", "password", "domain");
and voila!
In addition to BoshWash's answer, here is the picture generated by his code:
Like you, I cannot get MS Office Web Components to work. I would not consider Google Docs since Google seems to think they own anything that passes through their hands. I have tried MS Publish Objects but the quality of the generated html/css is truely awful.
The secret of converting an Excel worksheet to html that will display correctly on a smartphone is to create clean, lean html/css.
The structure of the HTML is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
HEAD
</head>
<body>
BODY
</body>
</html>
There are useful html elements that can replace "HEAD" but it is not clear to me how you would generate them from an Excel worksheet. They would need to be added separately.
The obvious output for a worksheet or a range is an html table so the following assumes BODY will be replaced by an html table.
The structure of an html table is:
<table TABLE-ATTRIBUTES>
<tr TABLE-ROW-ATTRIBUTES>
<td TABLE-CELL-ATTRIBUTES>CELL-VALUE</td>
More <td>...</td> elements as necessary
</tr>
More <tr>...</tr> as necessary
</table>
Include as few TABLE-ATTRIBUTES, TABLE-ROW-ATTRIBUTES and TABLE-CELL-ATTRIBUTES as possible. Do not set column widths in pixels. Use css attributes rather than html attributes.
A table attribute worth considering is style = "border-collapse: collapse;"
. The default is separate
with a gap around each cell. With collapse
the cells touch as they do with Excel.
Three table attribute worth considering are style="background-color:aliceblue;"
, style="color:#0000FF;"
and style="text-align:right;"
. With the first, you can specify the background colour to be any of the fifty or so named html colours. With the second, you can specify the font colour to be any of 256*256*256 colours. With the third you can right-align numeric values.
The above covers only a fraction of the formatting information that could be converted from Excel to html/css. I am developing an add-in that will convert as much Excel formatting as possible but I hope the above helps anyone with simple requirements.
You can also use the new Java 8 API
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class StackoverflowTest{
public static void main(String args[]){
String strDate = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454
}
}
The DateTimeFormatter
class replaces the old SimpleDateFormat
. You can then create a ZonedDateTime
from which you can extract the desired epoch time.
The main advantage is that you are now thread safe.
Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "USER_ID")
Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> receiver;
}
public class Notification implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "NOTIFICATION_ID")
Long notificationId;
@Column(name = "TEXT")
String text;
@Column(name = "ALERT_STATUS")
@Enumerated(EnumType.STRING)
AlertStatus alertStatus = AlertStatus.NEW;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SENDER_ID")
@JsonIgnore
User sender;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "RECEIVER_ID")
@JsonIgnore
User receiver;
}
What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..
User model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
List<Notification> receiver;
Notification model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> **sender**;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> **receiver**;
I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.
You can use tee
to write the result of your query to a file:
tee somepath\filename.txt
ExpandoObject
is what are you looking for.
dynamic MyDynamic = new ExpandoObject(); // note, the type MUST be dynamic to use dynamic invoking.
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;
Since I'm in a different timezone, my JavaScript and C# end up having 2 hours difference between the same date (even when I tried to send the date to a webservice as a date [not converted to string/another object]).
I tried to use the getTime() in JavaScript and add the milliseconds to a C# date (starting on 1970-01-01) but I've always ended up with two hours in advance on my C# date.
To grant that I would get the same Date and Hour in both sides I ended up doing this:
In JavaScript I've used the UTC function:
var jsDate = Date.UTC(year,month,day,hours,minutes,seconds,millisec);
And in C# to get the correct DateTime I did this:
var date = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(jsDate);
Hope it helps someone.
Because the second element is null after you clear the list.
Use:
String s = myList.get(0);
And remember, index 0 is the first element.
If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:
You can also click the 'n commits' link below their name on the repo's "contributors" page:
Alternatively, you can directly append ?author=<theusername>
or ?author=<emailaddress>
to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:
For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress>
to the URL - the author's name will not be clickable from the commits list.
You can also get the list of commits by a particular author from the command line using
git log --author=[your git name]
Example:
git log --author=Prem
Nothing really new here, but I discovered today that ThreadLocal
is very useful when using Bean Validation in a web application. Validation messages are localized, but by default use Locale.getDefault()
. You can configure the Validator
with a different MessageInterpolator
, but there's no way to specify the Locale
when you call validate
. So you could create a static ThreadLocal<Locale>
(or better yet, a general container with other things you might need to be ThreadLocal
and then have your custom MessageInterpolator
pick the Locale
from that. Next step is to write a ServletFilter
which uses a session value or request.getLocale()
to pick the locale and store it in your ThreadLocal
reference.
From the official documentation regarding the Formatter class:
The constructor takes two optional arguments: a message format string and a date format string.
So change
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")
to
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
"%Y-%m-%d %H:%M:%S")
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox): http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
streetno = { 1 : "Sachin Tendulkar",
2 : "Dravid",
3 : "Sehwag",
4 : "Laxman",
5 : "Kohli" }
And to retrieve values:
name = streetno.get(3, "default value")
Or
name = streetno[3]
That's using number as keys, put quotes around the numbers to use strings as keys.
This fixes UTF-8 printing in python:
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
The way docker look for file is from the current directory i.e. if your command is
COPY target/xyz.jar app.jar
ADD target/xyz.jar app.jar
The xyz jar should be in the current/target directory - here current is the place where you have your docker file. So if you have docker in a different dir. its better bring to main project directory and have a straight path to the jar being added or copied to the image.
Short answer:
const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];
e = ''
while e == '':
try:
response = ur.urlopen('https://https://raw.githubusercontent.com/MrMe42/Joe-Bot-Home-Assistant/mac/Joe.py')
e = ' '
except:
print('Connection refused. Retrying...')
time.sleep(1)
This should work. It sets e to '' and the while loop checks to see if it is still ''. If there is an error caught be the try statement, it prints that the connection was refused, waits 1 second and then starts over. It will keep going until there is no error in try, which then sets e to ' ', which kills the while loop.
You could use the n-th child selector.
to target the nth element you could then use:
td:nth-child(n) {
/* your stuff here */
}
(where n
starts at 1)
I haven't used it yet but I would take a look at http://www.zoneminder.com/ The documentation explains you can install it on a modest machine with linux and use IP cameras for remote recording.
Andrew
You can simply prevent the default behavior of the click event directly in your template.
<a href="#" ng-click="$event.preventDefault();logout()" />
Per the angular documentation,
Directives like ngClick and ngFocus expose a $event object within the scope of that expression.
try
double myPrice = 123.0;
String.Format(((Math.Round(myPrice) == myPrice) ? "{0:0}" : "{0:0.00}"), myPrice);
select template; iframe controller, ng model update
index.html
angularapp.controller('FieldCtrl', function ($scope, $sce) {
var iframeclass = '';
$scope.loadTemplate = function() {
if ($scope.template.length > 0) {
// add iframe classs
iframeclass = $scope.template.split('.')[0];
iframe.classList.add(iframeclass);
$scope.activeTemplate = $sce.trustAsResourceUrl($scope.template);
} else {
iframe.classList.remove(iframeclass);
};
};
});
// custom directive
angularapp.directive('myChange', function() {
return function(scope, element) {
element.bind('input', function() {
// the iframe function
iframe.contentWindow.update({
name: element[0].name,
value: element[0].value
});
});
};
});
iframe.html
window.update = function(data) {
$scope.$apply(function() {
$scope[data.name] = (data.value.length > 0) ? data.value: defaults[data.name];
});
};
Check this link: http://plnkr.co/edit/TGRj2o?p=preview
Thanks Attack. I wanted to use jQuery.
You pointed me in the right direction, and this is what I ended up with:
Here is a link to the plugin: https://plugins.jquery.com/textfill/
And a link to the source: http://jquery-textfill.github.io/
;(function($) {
$.fn.textfill = function(options) {
var fontSize = options.maxFontPixels;
var ourText = $('span:visible:first', this);
var maxHeight = $(this).height();
var maxWidth = $(this).width();
var textHeight;
var textWidth;
do {
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
fontSize = fontSize - 1;
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
return this;
}
})(jQuery);
$(document).ready(function() {
$('.jtextfill').textfill({ maxFontPixels: 36 });
});
and my html is like this
<div class='jtextfill' style='width:100px;height:50px;'>
<span>My Text Here</span>
</div>
This is my first jquery plugin, so it's probably not as good as it should be. Pointers are certainly welcome.
you should put your icon on the project folder, before build it
Consider a skewed binary tree with 3 nodes as 7, 3, 2. For any operation like for searching 2, we have to traverse 3 nodes, for deleting 2 also, we have to traverse 3 nodes and for for inserting 1 also, we have to traverse 3 nodes. So, binary tree has worst case complexity of O(n).
Think of the phrase in the square brackets as a WHERE clause in SQL.
So this query says, "select the "href" attribute (@) of an "a" tag that appears anywhere (//), but only where (the bracketed phrase) the textual contents of the "a" tag is equal to 'programming questions site'".
You can also change Window's environment variables with:
$env:NODE_OPTIONS="--max-old-space-size=8192"
The accepted answer does not work here, I am on MacOS. The following code works:
if [ $(echo "$number" | grep -c '^[0-9]\+$') = 0 ]; then
echo "it is a number"
else
echo "not a number"
fi
These guys have an API that will give the results. It's also free to use.
Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.
Here's a a couple of useful link that I found when I started with JNI
http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html
concerning your problem you can use this
JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)
{
const char *nativeString = env->GetStringUTFChars(javaString, 0);
// use your string
env->ReleaseStringUTFChars(javaString, nativeString);
}
This worked for me:
class JSONHeaderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain) : Response {
val request = chain.request().newBuilder()
.header("Content-Type", "application/json")
.build()
return chain.proceed(request)
}
}
fun provideHttpClient(): OkHttpClient {
val okHttpClientBuilder = OkHttpClient.Builder()
okHttpClientBuilder.addInterceptor(JSONHeaderInterceptor())
return okHttpClientBuilder.build()
}
Try to look at the following link: Python | change text color in shell
Or read here: http://bytes.com/topic/python/answers/21877-coloring-print-lines
In general solution is to use ANSI codes while printing your string.
There is a solution that performs exactly what you need.
Note: You can do it for as many earlier versions you want, i.e. IE9, IE8 and so on.
Step 1: Create HTML Page where to place the HTML Code.
Step 2: In the HTML Code Page Bottom(footer)Create Javascript: and put Jquery Code in Script tag.
Step 3: Create PHP File and php code copy past. after Jquery Code in $.ajax
Code url apply which one on your php file name.
JS
//$(document).on("change", "#avatar", function() { // If you want to upload without a submit button
$(document).on("click", "#upload", function() {
var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
form_data.append("user_id", 123) // Adding extra parameters to form_data
$.ajax({
url: "/upload_avatar", // Upload Script
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
// Do something after Ajax completes
}
});
});
HTML
<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />
Php
print_r($_FILES);
print_r($_POST);
There are many ways to update the rows.
When it comes to UPDATE
the rows using subqueries, you can use any of these approaches.
UPDATE
<table1>
SET
customer=<table2>.customer,
address=<table2>.address,
partn=<table2>.partn
FROM
<table2>
WHERE
<table1>.address_id=<table2>.address_i;
Explanation:
table1
is the table which we want to update,table2
is the table, from which we'll get the value to be replaced/updated. We are usingFROM
clause, to fetch thetable2
's data.WHERE
clause will help to set the proper data mapping.
UPDATE
<table1>
SET
customer=subquery.customer,
address=subquery.address,
partn=subquery.partn
FROM
(
SELECT
address_id, customer, address, partn
FROM /* big hairy SQL */ ...
) AS subquery
WHERE
dummy.address_id=subquery.address_id;
Explanation: Here we are using subquerie inside the
FROM
clause, and giving an alias to it. So that it will act like the table.
UPDATE
<table1>
SET
customer=<table2>.customer,
address=<table2>.address,
partn=<table2>.partn
FROM
<table2> as t2
JOIN <table3> as t3
ON
t2.id = t3.id
WHERE
<table1>.address_id=<table2>.address_i;
Explanation: Sometimes we face the situation in that table join is so important to get proper data for the update. To do so, Postgres allows us to Join multiple tables inside the
FROM
clause.
Approach-4 [Using WITH statement]
WITH subquery AS (
SELECT
address_id,
customer,
address,
partn
FROM
<table1>;
)
UPDATE <table-X>
SET customer = subquery.customer,
address = subquery.address,
partn = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;
WITH subquery AS (
SELECT address_id, customer, address, partn
FROM
<table1> as t1
JOIN
<table2> as t2
ON
t1.id = t2.id;
-- You can build as COMPLEX as this query as per your need.
)
UPDATE <table-X>
SET customer = subquery.customer,
address = subquery.address,
partn = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;
Explanation: From Postgres 9.1, this(
WITH
) concept has been introduces. Using that We can make any complex queries and generate desire result. Here we are using this approach to update the table.
I hope, this would be helpful.
This is pretty must just a copy of that projects demo page and shows uploading a single file on form submit with upload progress.
(function (angular) {
'use strict';
angular.module('uploadModule', [])
.controller('uploadCtrl', [
'$scope',
'$upload',
function ($scope, $upload) {
$scope.model = {};
$scope.selectedFile = [];
$scope.uploadProgress = 0;
$scope.uploadFile = function () {
var file = $scope.selectedFile[0];
$scope.upload = $upload.upload({
url: 'api/upload',
method: 'POST',
data: angular.toJson($scope.model),
file: file
}).progress(function (evt) {
$scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
}).success(function (data) {
//do something
});
};
$scope.onFileSelect = function ($files) {
$scope.uploadProgress = 0;
$scope.selectedFile = $files;
};
}
])
.directive('progressBar', [
function () {
return {
link: function ($scope, el, attrs) {
$scope.$watch(attrs.progressBar, function (newValue) {
el.css('width', newValue.toString() + '%');
});
}
};
}
]);
}(angular));
HTML
<form ng-submit="uploadFile()">
<div class="row">
<div class="col-md-12">
<input type="text" ng-model="model.fileDescription" />
<input type="number" ng-model="model.rating" />
<input type="checkbox" ng-model="model.isAGoodFile" />
<input type="file" ng-file-select="onFileSelect($files)">
<div class="progress" style="margin-top: 20px;">
<div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
<span ng-bind="uploadProgress"></span>
<span>%</span>
</div>
</div>
<button button type="submit" class="btn btn-default btn-lg">
<i class="fa fa-cloud-upload"></i>
<span>Upload File</span>
</button>
</div>
</div>
</form>
EDIT: Added passing a model up to the server in the file post.
The form data in the input elements would be sent in the data property of the post and be available as normal form values.
Add your own flavour of the font awesome style
[class^="icon-"], [class*=" icon-"] {
display: inline-block;
width: 100%;
}
which along with your
td i {
text-align:center;
}
should center just the icons.
I suposse this is the output you need:
title,intro,tagline
2.9,Gardena,CA
It can be done with this changes to your code:
import csv
import itertools
with open('log.txt', 'r') as in_file:
lines = in_file.read().splitlines()
stripped = [line.replace(","," ").split() for line in lines]
grouped = itertools.izip(*[stripped]*1)
with open('log.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('title', 'intro', 'tagline'))
for group in grouped:
writer.writerows(group)
Non of the above worked for me using the IUS repo for CentOS 7 with PHP 7.2:
php -v
> PHP 7.2.30 (cli) (built: Apr 19 2020 00:32:29) ( NTS )
php -r 'echo session_save_path(), "\n";
>
php -r 'echo sys_get_temp_dir(), "\n";'
> /tmp
However, sessions weren't saved in the /tmp
folder, but in the /var/lib/php/mod_php/session/
folder:
ls /var/lib/php/mod_php/session/
> sess_3cebqoq314pcnc2jgqiu840h0k sess_ck5dtaerol28fpctj6nutbn6fn sess_i24lgt2v2l58op5kfmj1k6qb3h sess_nek5q1alop8fkt84gliie91703
> sess_9ff74f4q5ihccnv6com2a8409t sess_dvrt9fmfuolr8bqt9efdpcbj0d sess_igdaksn26hm1s5nfvtjfb53pl7 sess_tgf5b7gkgno8kuvl966l9ce7nn
Even though you are using ASMM, you can set a minimum size for the large pool (MMAN will not shrink it below that value). You can also try pinning some objects and increasing SGA_TARGET.
You can configure log4j.properties like above answers, or use org.apache.log4j.BasicConfigurator
public class FooImpl implements Foo {
private static final Logger LOGGER = Logger.getLogger(FooBar.class);
public Object createObject() {
BasicConfigurator.configure();
LOGGER.info("something");
return new Object();
}
}
So under the table, configure do:
configure() {
Logger root = Logger.getRootLogger();
root.addAppender(new ConsoleAppender(
new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
}
I think the problem in your Adapter
.
Make sure you have returned ViewHolder
in onCreateViewHolder()
.
Like below:
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_leaderboard, parent, false);
ViewHolder view_holder = new ViewHolder(v);
return view_holder;
}
This isn't significantly different from other answers, but I wanted the array of integers in the end:
Integer[] indices = new Integer[n];
Arrays.setAll(indices, i -> i);
Collections.shuffle(Arrays.asList(indices));
return Arrays.stream(indices).mapToInt(Integer::intValue).toArray();
The %pdb
magic command is good to use as well. Just say %pdb on
and subsequently the pdb
debugger will run on all exceptions, no matter how deep in the call stack. Very handy.
If you have a particular line that you want to debug, just raise an exception there (often you already are!) or use the %debug
magic command that other folks have been suggesting.
This is the command that you need to execute on the mirror:
git remote update
In addition to the answer from @StephanBijzitter I would use the following PATH
variables instead:
%appdata%\npm
%ProgramFiles%\nodejs
So your new PATH
would look like:
[existing stuff];%appdata%\npm;%ProgramFiles%\nodejs
This has the advantage of neiter being user dependent nor 32/64bit dependent.
Try out this step: https://www.eclipse.org/forums/index.php/t/636348/
Go to
Project -> Properties -> C/C++ General -> Preprocessor Include Paths, Macros, etc. -> Providers
To shorten Narendra's logic, you can use this:
boolean var = lis1.stream().anyMatch(element -> list2.contains(element));
File.GetLastWriteTime
to Get last modified
File.CreationTime
to get Created time
Simply add this
$id = '';
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
Quoting the spec
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.
And here's a table for typeof
To add some background, there are two data types in JavaScript:
An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.
An array can be considered to be an object with the following properties/keys:
Hope this helped shed more light on why typeof Array returns an object. Cheers!
$color = sprintf("#%06x",rand(0,16777215));
There are many ways to do it, the other answers are good, here's an alternative:
Console.WriteLine(string.Join("\n", myArrayOfObjects));
You can use instanceof
.
instanceof
RelationalExpression: RelationalExpression instanceof ReferenceType
At run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result isfalse
.
That means you can do something like this:
Object o = new int[] { 1,2 };
System.out.println(o instanceof int[]); // prints "true"
You'd have to check if the object is an instanceof boolean[]
, byte[]
, short[]
, char[]
, int[]
, long[]
, float[]
, double[]
, or Object[]
, if you want to detect all array types.
Also, an int[][]
is an instanceof Object[]
, so depending on how you want to handle nested arrays, it can get complicated.
For the toString
, java.util.Arrays
has a toString(int[])
and other overloads you can use. It also has deepToString(Object[])
for nested arrays.
public String toString(Object arr) {
if (arr instanceof int[]) {
return Arrays.toString((int[]) arr);
} else //...
}
It's going to be very repetitive (but even java.util.Arrays
is very repetitive), but that's the way it is in Java with arrays.
Try like this:
if($user_sam -ne $NULL -and $user_case -ne $NULL)
Empty variables are $null
and then different from "" ([string]::empty
).
Warning: Never ever refer to w3schools for learning purposes. They have so many mistakes in their tutorials.
According to the mysqli_query documentation, the first parameter must be a connection string:
$link = mysqli_connect("localhost","root","","web_table");
mysqli_query($link,"INSERT INTO web_formitem (`ID`, `formID`, `caption`, `key`, `sortorder`, `type`, `enabled`, `mandatory`, `data`)
VALUES (105, 7, 'Tip izdelka (6)', 'producttype_6', 42, 5, 1, 0, 0)")
or die(mysqli_error($link));
Note: Add backticks ` for column names in your insert query as some of your column names are reserved words.
self and $self aren't the same. The former is the object pointed to by "this" and the latter a jQuery object whose "scope" is the object pointed to by "this". Similarly, $body isn't the body DOM element but the jQuery object whose scope is the body element.
Add the sheet name infront of the cell, e.g.:
=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")
Assumes the sheet name is "stock"
You could do something like this also:
ol {
font-weight: bold;
}
ol > li > * {
font-weight: normal;
}
So you have no "style" attributes in your HTML
I had the same problem. For me, it was caused by the default settings in the local IIS server on my machine. So the easy way to fix it, was to use the built in Visual Studio development server instead :)
Newer IIS versions on x64 machines have a setting that doesn't allow 32 bit applications to run by default. To enable 32 bit applications in the local IIS, select the relevant application pool in IIS manager, click "Advanced settings", and change "Enable 32-Bit Applications" from False to True
From CSS
video {
position: fixed; right: 0; bottom: 0;
min-width: 100%; min-height: 100%;
width: auto; height: auto; z-index: -100;
background: url(polina.jpg) no-repeat;
background-size: cover;
}
Use this:
return this.RedirectToAction<AccountController>(m => m.LogIn());
Apply the following in your Theme for the Activity in AndroidManifest.xml
:
<activity android:name=".Activity"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
That should do the trick.
Python has a strong set of introspection features.
Take a look at the following built-in functions:
type()
and dir()
are particularly useful for inspecting the type of an object and its set of attributes, respectively.
Unsorted vector:
if (std::find(v.begin(), v.end(),value)!=v.end())
...
Sorted vector:
if (std::binary_search(v.begin(), v.end(), value)
...
P.S. may need to include <algorithm>
header
It's just the incorrect lines of code you were trying to execute..
hope it help..
This has to do with contiguous memory.
Here's some info I found online for somebody asking that before, supposedly from a "VM god":
The reason we need a contiguous memory region for the heap is that we have a bunch of side data structures that are indexed by (scaled) offsets from the start of the heap. For example, we track object reference updates with a "card mark array" that has one byte for each 512 bytes of heap. When we store a reference in the heap we have to mark the corresponding byte in the card mark array. We right shift the destination address of the store and use that to index the card mark array. Fun addressing arithmetic games you can't do in Java that you get to (have to :-) play in C++.
Usually we don't have trouble getting modest contiguous regions (up to about 1.5GB on Windohs, up to about 3.8GB on Solaris. YMMV.). On Windohs, the problem is mostly that there are some libraries that get loaded before the JVM starts up that break up the address space. Using the /3GB switch won't rebase those libraries, so they are still a problem for us.
We know how to make chunked heaps, but there would be some overhead to using them. We have more requests for faster storage management than we do for larger heaps in the 32-bit JVM. If you really want large heaps, switch to the 64-bit JVM. We still need contiguous memory, but it's much easier to get in a 64-bit address space.
In case we have a list of words that we need to find all common substrings I check some of the codes above and the best was https://stackoverflow.com/a/42882629/8520109 but it has some bugs for example 'histhome' and 'homehist'. In this case, we should have 'hist' and 'home' as a result. Furthermore, it differs if the order of arguments is changed. So I change the code to find every block of substring and it results a set of common substrings:
main = input().split(" ") #a string of words separated by space
def longestSubstringFinder(string1, string2):
'''Find the longest matching word'''
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
for j in range(len2):
lcs_temp=0
match=''
while ((i+lcs_temp < len1) and (j+lcs_temp<len2) and string1[i+lcs_temp] == string2[j+lcs_temp]):
match += string2[j+lcs_temp]
lcs_temp+=1
if (len(match) > len(answer)):
answer = match
return answer
def listCheck(main):
'''control the input for finding substring in a list of words'''
string1 = main[0]
result = []
for i in range(1, len(main)):
string2 = main[i]
res1 = longestSubstringFinder(string1, string2)
res2 = longestSubstringFinder(string2, string1)
result.append(res1)
result.append(res2)
result.sort()
return result
first_answer = listCheck(main)
final_answer = []
for item1 in first_answer: #to remove some incorrect match
string1 = item1
double_check = True
for item2 in main:
string2 = item2
if longestSubstringFinder(string1, string2) != string1:
double_check = False
if double_check:
final_answer.append(string1)
print(set(final_answer))
main = 'ABACDAQ BACDAQA ACDAQAW XYZCDAQ' #>>> {'CDAQ'}
main = 'homehist histhome' #>>> {'hist', 'home'}
I'm not gonna claim that this is more elegant than the highest-voted solution...but this is cool (well, at least in my mind LOL) in its own way:
$server = "ftp.lolcats.com"
$filelist = "file1.txt file2.txt"
"open $server
user $user $password
binary
cd $dir
" +
($filelist.split(' ') | %{ "put ""$_""`n" }) | ftp -i -in
As you can see, it uses that dinky built-in windows FTP client. Much shorter and straightforward, too. Yes, I've actually used this and it works!
I think the easiest way to match the characters like
\^$.?*|+()[
are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:
> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")
This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\
to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp
to see more info about this.
https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf
REST is not necessarily tied to HTTP. RESTful web services are just web services that follow a RESTful architecture.
What is Rest -
1- Client-server
2- Stateless
3- Cacheable
4- Layered system
5- Code on demand
6- Uniform interface
Your query ($myQuery) is failing and therefore not producing a query resource, but instead producing FALSE.
To reveal what your dynamically generated query looks like and reveal the errors, try this:
$result2 = mysql_query($myQuery) or die($myQuery."<br/><br/>".mysql_error());
The error message will guide you to the solution, which from your comment below is related to using ORDER BY on a field that doesn't exist in the table you're SELECTing from.
I think you can try
<a href="JavaScript:void(0)">link</a>
The only catch I see over here is high level browser security may prompt on executing javascript.
Though this is one of the easier way than
<a href="#" onclick="return false;">Link</a>
this should be used sparingly
Read this article for some pointers https://web.archive.org/web/20090301044015/http://blog.reindel.com/2006/08/11/a-hrefjavascriptvoid0-avoid-the-void
SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.
Let's suppose you have two databases on the same server - Db1
and Db2
. Db1
has a table called Clients
with a column ClientId
and Db2
has a table called Messages
with a column ClientId
(let's leave asside why those tables are in different databases).
Now, to perform a join on the above-mentioned tables you will be using this query:
select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId
This should work:
Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + "/myFolder/");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");
if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
{
startActivity(intent);
}
else
{
// if you reach this place, it means there is no any file
// explorer app installed on your device
}
Please, be sure that you have any file explorer app installed on your device.
EDIT: added a shantanu's recommendation from the comment.
LIBRARIES: You can also have a look at the following libraries https://android-arsenal.com/tag/35 if the current solution doesn't help you.
Just try -webkit-flexbox
. it's working for safari.
webkit-flex
safari will not taking.
Instead of show
, try to use CSS to hide and show the content.
function switch_tabs(obj) {
$('.tab-content').css('display', 'none'); // you could still use `.hide()` here
$('.tabs a').removeClass("selected");
var id = obj.attr("rel");
$('#' + id).css('display', 'inline-block');
obj.addClass("selected");
}
I had the same problem, after loads of research and Googling, I found the following solution worked best for me! plenty of trial and error went into this one.
--- SOLVED / SOLUTION ---
JS
$(document).ready(function() {
$("header").delay(5000).queue(function(){
$(this).css({"background-image":"url(<?php bloginfo('template_url') ?>/img/header-boy-hover.jpg)"});
});
});
CSS
header {
-webkit-transition:all 1s ease-in;
-moz-transition:all 1s ease-in;
-o-transition:all 1s ease-in;
-ms-transition:all 1s ease-in;
transition:all 1s ease-in;
}
DLL Export Viewer by NirSoft can be used to display exported functions in a DLL.
This utility displays the list of all exported functions and their virtual memory addresses for the specified DLL files. You can easily copy the memory address of the desired function, paste it into your debugger, and set a breakpoint for this memory address. When this function is called, the debugger will stop in the beginning of this function.
There are quite number of tools available for viewing large files. http://download.cnet.com/Large-Text-File-Viewer/3000-2379_4-90541.html This for instance. However, I was successful with larger files viewing in Visual studio. Thought it took some time to load, it worked.
The one liner "no imports" version
a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [1,5,7]
[ a[i] for i in ind_pos ]
Building of off an earlier example, I think there is a cleaner way of doing this. Create an index.html
file in your project and using Stephen's code from above, just convert it into an HTML doc.
<!DOCTYPE html>
<html>
<base target="_top">
<script>
function onSuccess(url) {
var a = document.createElement("a");
a.href = url;
a.target = "_blank";
window.close = function () {
window.setTimeout(function() {
google.script.host.close();
}, 9);
};
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
window.document.body.append(a);
}
event.initEvent("click", true, true);
a.dispatchEvent(event);
} else {
a.click();
}
close();
}
function onFailure(url) {
var div = document.getElementById('failureContent');
var link = '<a href="' + url + '" target="_blank">Process</a>';
div.innerHtml = "Failure to open automatically: " + link;
}
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).getUrl();
</script>
<body>
<div id="failureContent"></div>
</body>
<script>
google.script.host.setHeight(40);
google.script.host.setWidth(410);
</script>
</html>
Then, in your Code.gs
script, you can have something like the following,
function getUrl() {
return 'http://whatever.com';
}
function openUrl() {
var html = HtmlService.createHtmlOutputFromFile("index");
html.setWidth(90).setHeight(1);
var ui = SpreadsheetApp.getUi().showModalDialog(html, "Opening ..." );
}
For those who are on windows and were struggling to find an working answer here's mine: pynput
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
The function above will print whichever key you are pressing plus start an action as you release the 'esc' key. The keyboard documentation is here for a more variated usage.
Markus von Broady highlighted a potential issue that is: This answer doesn't require you being in the current window to this script be activated, a solution to windows would be:
from win32gui import GetWindowText, GetForegroundWindow
current_window = (GetWindowText(GetForegroundWindow()))
desired_window_name = "Stopwatch" #Whatever the name of your window should be
#Infinite loops are dangerous.
while True: #Don't rely on this line of code too much and make sure to adapt this to your project.
if current_window == desired_window_name:
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
Is there anything wrong with Nahuel Greco's solution aside from the compilation error?
If I change one line
// Compilation error
setsockopt(fd, SO_SNDTIMEO, &timeout, sizeof(timeout));
to
// Fixed?
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
then it seems to work as advertised - socket()
returns a timeout error.
Resulting code:
struct timeval timeout;
timeout.tv_sec = 7; // after 7 seconds connect() will timeout
timeout.tv_usec = 0;
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
connect(...)
I'm not versed enough to know the tradeoffs are between a send timeout and a non-blocking socket, but I'm curious to learn.
In case you have an async helperFunction()
called from your test... (one explicilty with the ES7 async
keyword, I mean)
? make sure, you call that as await helperFunction(whateverParams)
(well, yeah, naturally, once you know...)
And for that to work (to avoid ‘await is a reserved word’), your test-function must have an outer async marker:
it('my test', async () => { ...
If accuracy is an issue here you can create random numbers with a finer graduation by randomizing the significant bits. Let's assume we want to have a double between 0.0 and 1000.0.
On MSVC (12 / Win32) RAND_MAX is 32767 for example.
If you use the common rand()/RAND_MAX
scheme your gaps will be as large as
1.0 / 32767.0 * ( 1000.0 - 0.0) = 0.0305 ...
In case of IEE 754 double variables (53 significant bits) and 53 bit randomization the smallest possible randomization gap for the 0 to 1000 problem will be
2^-53 * (1000.0 - 0.0) = 1.110e-13
and therefore significantly lower.
The downside is that 4 rand() calls will be needed to obtain the randomized integral number (assuming a 15 bit RNG).
double random_range (double const range_min, double const range_max)
{
static unsigned long long const mant_mask53(9007199254740991);
static double const i_to_d53(1.0/9007199254740992.0);
unsigned long long const r( (unsigned long long(rand()) | (unsigned long long(rand()) << 15) | (unsigned long long(rand()) << 30) | (unsigned long long(rand()) << 45)) & mant_mask53 );
return range_min + i_to_d53*double(r)*(range_max-range_min);
}
If the number of bits for the mantissa or the RNG is unknown the respective values need to be obtained within the function.
#include <limits>
using namespace std;
double random_range_p (double const range_min, double const range_max)
{
static unsigned long long const num_mant_bits(numeric_limits<double>::digits), ll_one(1),
mant_limit(ll_one << num_mant_bits);
static double const i_to_d(1.0/double(mant_limit));
static size_t num_rand_calls, rng_bits;
if (num_rand_calls == 0 || rng_bits == 0)
{
size_t const rand_max(RAND_MAX), one(1);
while (rand_max > (one << rng_bits))
{
++rng_bits;
}
num_rand_calls = size_t(ceil(double(num_mant_bits)/double(rng_bits)));
}
unsigned long long r(0);
for (size_t i=0; i<num_rand_calls; ++i)
{
r |= (unsigned long long(rand()) << (i*rng_bits));
}
r = r & (mant_limit-ll_one);
return range_min + i_to_d*double(r)*(range_max-range_min);
}
Note: I don't know whether the number of bits for unsigned long long (64 bit) is greater than the number of double mantissa bits (53 bit for IEE 754) on all platforms or not.
It would probably be "smart" to include a check like if (sizeof(unsigned long long)*8 > num_mant_bits) ...
if this is not the case.
You can also use the java.time package in Java 8 and convert your java.util.Date
object to a java.time.LocalDate
object and then just use the getMonthValue()
method.
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue();
Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH)
in adarshr's answer which gives values from 0 to 11.
But as Basil Bourque said in the comments, the preferred way is to get a Month
enum object with the LocalDate::getMonth
method.
You can do it for arbitrary refs. This is how to move a branch pointer:
git update-ref -m "reset: Reset <branch> to <new commit>" refs/heads/<branch> <commit>
where -m
adds a message to the reflog for the branch.
The general form is
git update-ref -m "reset: Reset <branch> to <new commit>" <ref> <commit>
You can pick nits about the reflog message if you like - I believe the branch -f
one is different from the reset --hard
one, and this isn't exactly either of them.
You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream ifs( "c:/demo.txt" ); // note no mode needed
if ( ! ifs.is_open() ) {
cout <<" Failed to open" << endl;
}
else {
cout <<"Opened OK" << endl;
}
}
What does this code produce on your system?
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
My workarounds:
git fetch --depth=1
git checkout <branch_name>
if you don't have a local clone:
git clone --depth 1 -b <branch_name> <repo_url>