What is the difference between them?
Image: the generic Linux kernel binary image file.
zImage: a compressed version of the Linux kernel image that is self-extracting.
uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.
Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:
Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.
(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)
Which type of kernel image do I have to use?
You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.
ADDENDUM
I know that u-boot needs a kernel in uImage format.
That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.
#include<iostream>
int main()
{//initialize variables
int limit;
int num;
int sum=0;
int counter=0;
cout<<"Enter limit of numbers you wish to see"<<" ";
cin>>limit;
cout<<endl;
while(counter<limit)
{
cout<<"Enter number "<<endl;
cin>>num;
sum=sum+num;
counter++;
}
cout<<"The sum of numbers is "<<" "<<endl
return 0;
}
Have a look at json_encode
(http://php.net/manual/en/function.json-encode.php). It is available as of PHP 5.2. Use the parameter dataType: 'json'
to have it parsed for you. You'll have the Object as the first argument in success then. For further information have a look at the jQuery-documentation: http://api.jquery.com/jQuery.ajax/
var scrollBottom = $(window).scrollTop() + $(window).height();
hash.store(key, value) - Stores a key-value pair in hash.
Example:
hash #=> {"a"=>9, "b"=>200, "c"=>4}
hash.store("d", 42) #=> 42
hash #=> {"a"=>9, "b"=>200, "c"=>4, "d"=>42}
1) Add On Error Resume Next
at top of the page
2) Add following code at bottom of the page
If Err.Number <> 0 Then
Response.Write (Err.Description)
Response.End
End If
On Error GoTo 0
I've had to do this before using Paramiko in a case where I wanted to run a dynamic, local PyQt4 script on a host running an ssh server that has connected my OpenVPN server and ask for their routing preference (split tunneling).
So long as the ssh server you are connecting to has all of the required dependencies of your script (PyQt4 in my case), you can easily encapsulate the data by encoding it in base64 and use the exec()
built-in function on the decoded message. If I remember correctly my one-liner for this was:
stdout = client.exec_command('python -c "exec(\\"' + open('hello.py','r').read().encode('base64').strip('\n') + '\\".decode(\\"base64\\"))"' )[1]
It is hard to read and you have to escape the escape sequences because they are interpreted twice (once by the sender and then again by the receiver). It also may need some debugging, I've packed up my server to PCS or I'd just reference my OpenVPN routing script.
The difference in doing it this way as opposed to sending a file is that it never touches the disk on the server and is run straight from memory (unless of course they log the command). You'll find that encapsulating information this way (although inefficient) can help you package data into a single file.
For instance, you can use this method to include raw data from external dependencies (i.e. an image) in your main script.
Add the schema name to the entity and it will find it. Worked for me!
When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).
Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle
message because you asked for some nonexistent data.
When you perform a cd
operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.
I resolved it by selecting https as the protocol and then adding my github username and password
There are a couple of reasons for this:
Set to null. Then there are no references anymore and the object will become eligible for Garbage Collection. GC will automatically remove the object from the heap.
For linux/unix OS, you can use the shell syntax
const shell = require('child_process').execSync ;
const currentPath= `/path/to/name.png`;
const newPath= `/path/to/another_name.png`;
shell(`mv ${currentPath} ${newPath}`);
That's it!
The easiest way to debug python - especially for programmers that are used to Visual Studio - is using PTVS (Python Tools for Visual Studio). The steps are simple:
If you want to debug Django using PTVS, you need to do the following:
You can try to change the default .py
program via policy management. Go to windows, search for regedit, right click it. And then run as administrator. Then, you can search the key word "python.exe" And change your Python27 path to you Anaconda path.
I'll assume that the data to transmit is a string.
As other commenters have stated, AJAX is one possible solution, but the cons outweigh the pros: it has a latency and it is harder to program (it needs the code to retrieve the value both server- and client-side), when a simpler escaping function should suffice.
So, we're back to escaping. json_encode($string)
works if you encode the source string as UTF-8 first in case it is not already, because json_encode
requires UTF-8 data. If the string is in ISO-8859-1 then you can simply use json_encode(utf8_encode($string))
; otherwise you can always use iconv
to do the conversion first.
But there's a big gotcha. If you're using it in events, you need to run htmlspecialchars()
on the result in order to make it correct code. And then you have to either be careful to use double quotes to enclose the event, or always add ENT_QUOTES
to htmlspecialchars. For example:
<?php
$myvar = "I'm in \"UTF-8\" encoding and I have <script>script tags</script> & ampersand!";
// Fails:
//echo '<body onload="alert(', json_encode($myvar), ');">';
// Fails:
//echo "<body onload='alert(", json_encode($myvar), ");'>";
// Fails:
//echo "<body onload='alert(", htmlspecialchars(json_encode($myvar)), ");'>";
// Works:
//echo "<body onload='alert(", htmlspecialchars(json_encode($myvar), ENT_QUOTES), ");'>";
// Works:
echo '<body onload="alert(', htmlspecialchars(json_encode($myvar)), ');">';
echo "</body>";
However, you can't use htmlspecialchars
on regular JavaScript code (code enclosed in <script>
...</script>
tags). That makes use of this function prone to mistakes, by forgetting to htmlspecialchars
the result when writing event code.
It's possible to write a function that does not have that problem, and can be used both in events and in regular JavaScript code, as long as you enclose your events always in single quotes, or always in double quotes. Here is my proposal, requiring them to be in double quotes (which I prefer):
<?php
// Optionally pass the encoding of the source string, if not UTF-8
function escapeJSString($string, $encoding = 'UTF-8')
{
if ($encoding != 'UTF-8')
$string = iconv($encoding, 'UTF-8', $string);
$flags = JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_SLASHES;
$string = substr(json_encode($string, $flags), 1, -1);
return "'$string'";
}
The function requires PHP 5.4+. Example usage:
<?php
$myvar = "I'm in \"UTF-8\" encoding and I have <script>script tags</script> & ampersand!";
// Note use of double quotes to enclose the event definition!
echo '<body onload="alert(', escapeJSString($myvar), ');">';
// Example with regular code:
echo '<script>alert(', escapeJSString($myvar), ');</script>';
echo '</body>';
If your are using MySQL Latest version following may help to reach your requirement.
select * from products where attribs_json->"$.feature.value[*]" in (1,3)
Without jQuery:
textContent:
var text = document.querySelector('.someClassname').textContent;
Markup:
var text = document.querySelector('.someClassname').innerHTML;
Markup including the matched element:
var text = document.querySelector('.someClassname').outerHTML;
though outerHTML may not be supported by all browsers of interest and document.querySelector requires IE 8 or higher.
I found the solution.
dim bExists
ssig="Unable to open registry key"
set wshShell= Wscript.CreateObject("WScript.Shell")
strKey = "HKEY_USERS\.Default\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Digest\"
on error resume next
present = WshShell.RegRead(strKey)
if err.number<>0 then
if right(strKey,1)="\" then 'strKey is a registry key
if instr(1,err.description,ssig,1)<>0 then
bExists=true
else
bExists=false
end if
else 'strKey is a registry valuename
bExists=false
end if
err.clear
else
bExists=true
end if
on error goto 0
if bExists=vbFalse then
wscript.echo strKey & " does not exist."
else
wscript.echo strKey & " exists."
end if
There are two major performance issues with your code:
Using Add method
The Add method becomes only slower and slower at each entity you add.
See: http://entityframework.net/improve-ef-add-performance
For example, adding 10,000 entities via:
Note: Entities has not been saved yet in the database!
The problem is that the Add method tries to DetectChanges at every entity added while AddRange does it once after all entities have been added to the context.
Common solutions are:
Using SaveChanges
Entity Framework has not been created for Bulk Operations. For every entity you save, a database round-trip is performed.
So, if you want to insert 20,000 records, you will perform 20,000 database round-trip which is INSANE!
There are some third-party libraries supporting Bulk Insert available:
See: Entity Framework Bulk Insert library
Be careful, when choosing a bulk insert library. Only Entity Framework Extensions support all kind of associations and inheritance, and it's the only one still supported.
Disclaimer: I'm the owner of Entity Framework Extensions
This library allows you to perform all bulk operations you need for your scenarios:
Example
// Easy to use
context.BulkSaveChanges();
// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);
// Perform Bulk Operations
context.BulkDelete(customers);
context.BulkInsert(customers);
context.BulkUpdate(customers);
// Customize Primary Key
context.BulkMerge(customers, operation => {
operation.ColumnPrimaryKeyExpression =
customer => customer.Code;
});
EDIT: Answer Question in Comment
Is there a recommend max size for each bulk insert for the library you created
Not too high, not too low. There isn't a particular value that fit in all scenarios since it depends on multiple factors such as row size, index, trigger, etc.
It's normally recommended to be around 4000.
Also is there a way to tie it all in one transaction and not worry about it timing out
You can use Entity Framework transaction. Our library uses the transaction if one is started. But be careful, a transaction that takes too much time come also with problems such as some row/index/table lock.
Try this
UPDATE `table` SET `uid` = CASE
WHEN id = 1 THEN 2952
WHEN id = 2 THEN 4925
WHEN id = 3 THEN 1592
ELSE `uid`
END
WHERE id in (1,2,3)
Since jQuery 1.7, you can use jQuery.isNumeric()
:
$.isNumeric('-1'); // true
$.isNumeric('-1.5'); // true
$.isNumeric('0'); // true
$.isNumeric('0.42'); // true
$.isNumeric('.42'); // true
$.isNumeric('0x89f'); // true (valid hexa number)
$.isNumeric('99,999'); // false
$.isNumeric('#abcdef'); // false
$.isNumeric('1.2.3'); // false
$.isNumeric(''); // false
$.isNumeric('blah'); // false
Just note that unlike what you said, 0x89f
is a valid number (hexa)
This should cover most basic use cases.
const capitalize = (str) => {
if (typeof str !== 'string') {
throw Error('Feed me string')
} else if (!str) {
return ''
} else {
return str
.split(' ')
.map(s => {
if (s.length == 1 ) {
return s.toUpperCase()
} else {
const firstLetter = s.split('')[0].toUpperCase()
const restOfStr = s.substr(1, s.length).toLowerCase()
return firstLetter + restOfStr
}
})
.join(' ')
}
}
capitalize('THIS IS A BOOK') // => This Is A Book
capitalize('this is a book') // => This Is A Book
capitalize('a 2nd 5 hour boOk thIs weEk') // => A 2nd 5 Hour Book This Week
Edit: Improved readability of mapping.
When entered as the reference of a Named range
, it refers to range on the sheet the named range is used on.
For example, create a named range MyName
refering to =SUM(!B1:!K1)
Place a formula on Sheet1
=MyName
. This will sum Sheet1!B1:K1
Now place the same formula (=MyName
) on Sheet2
. That formula will sum Sheet2!B1:K1
Note: (as pnuts commented) this and the regular SheetName!B1:K1
format are relative, so reference different cells as the =MyName
formula is entered into different cells.
Hibernate support reattach detached entity by serval ways, see Hibernate user guide.
The hasClass method will accept an array of class names as an argument, you can do something like this:
$(document).ready(function() {
function filterFilesList() {
var rows = $('.file-row');
var checked = $("#filterControls :checkbox:checked");
if (checked.length) {
var criteriaCollection = [];
checked.each(function() {
criteriaCollection.push($(this).val());
});
rows.each(function() {
var row = $(this);
var rowMatch = row.hasClass(criteriaCollection);
if (rowMatch) {
row.show();
} else {
row.hide(200);
}
});
} else {
rows.each(function() {
$(this).show();
});
}
}
$("#filterControls :checkbox").click(filterFilesList);
filterFilesList();
});
On Ubuntu 14 and Mysql 5.5.53 this setting seems to be enabled by default. To disable it you need to add secure-file-priv = ""
to your my.cnf file under the mysqld config group. eg:-
[mysqld]
secure-file-priv = ""
You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html
SELECT column1, CONVERT(column2 USING utf8)
FROM my_table
WHERE my_condition;
I don't know you specific situation. Back when I was writing C programs, we have always used #2.
#define FALSE = 0
#define TRUE = !FALSE
This might be otherwise under alien platform to DOS or Intel-based processors. But I used to use both C and ASM together writing graphic libraries and graphical IDE. I was a true fan of Micheal Abrash and was intending to learn about texture mapping and so. Anyway! That's not the subject of the question here!
This was the most commonly used form to define boolean values in C, as this headerfile stdbool.h did not exist then.
Today I just wrote a post about "Why do we use the letters like “e” in e.preventDefault()?" and I think my answer will make some sense...
At first,let us see the syntax of addEventListener
Normally it will be: target.addEventListener(type, listener[, useCapture]);
And the definition of the parameters of addEventlistener are:
type :A string representing the event type to listen out for.
listener :The object which receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be an object implementing the EventListener interface, or a JavaScript function.
(From MDN)
But I think there is one thing should be remarked: When you use Javascript function as the listener, the object that implements the Event interface(object event) will be automatically assigned to the "first parameter" of the function.So,if you use function(e) ,the object will be assigned to "e" because "e" is the only parameter of the function(definitly the first one !),then you can use e.preventDefault to prevent something....
let us try the example as below:
<p>Please click on the checkbox control.</p>
<form>
<label for="id-checkbox">Checkbox</label>
<input type="checkbox" id="id-checkbox"/>
</div>
</form>
<script>
document.querySelector("#id-checkbox").addEventListener("click", function(e,v){
//var e=3;
var v=5;
var t=e+v;
console.log(t);
e.preventDefault();
}, false);
</script>
the result will be : [object MouseEvent]5 and you will prevent the click event.
but if you remove the comment sign like :
<script>
document.querySelector("#id-checkbox").addEventListener("click", function(e,v){
var e=3;
var v=5;
var t=e+v;
console.log(t);
e.preventDefault();
}, false);
</script>
you will get : 8 and an error:"Uncaught TypeError: e.preventDefault is not a function at HTMLInputElement. (VM409:69)".
Certainly,the click event will not be prevented this time.Because the "e" was defined again in the function.
However,if you change the code to:
<script>
document.querySelector("#id-checkbox").addEventListener("click", function(e,v){
var e=3;
var v=5;
var t=e+v;
console.log(t);
event.preventDefault();
}, false);
</script>
every thing will work propertly again...you will get 8 and the click event be prevented...
Therefore, "e" is just a parameter of your function and you need an "e" in you function() to receive the "event object" then perform e.preventDefault(). This is also the reason why you can change the "e" to any words that is not reserved by js.
df.iloc[i]
returns the ith
row of df
. i
does not refer to the index label, i
is a 0-based index.
In contrast, the attribute index
returns actual index labels, not numeric row-indices:
df.index[df['BoolCol'] == True].tolist()
or equivalently,
df.index[df['BoolCol']].tolist()
You can see the difference quite clearly by playing with a DataFrame with a non-default index that does not equal to the row's numerical position:
df = pd.DataFrame({'BoolCol': [True, False, False, True, True]},
index=[10,20,30,40,50])
In [53]: df
Out[53]:
BoolCol
10 True
20 False
30 False
40 True
50 True
[5 rows x 1 columns]
In [54]: df.index[df['BoolCol']].tolist()
Out[54]: [10, 40, 50]
If you want to use the index,
In [56]: idx = df.index[df['BoolCol']]
In [57]: idx
Out[57]: Int64Index([10, 40, 50], dtype='int64')
then you can select the rows using loc
instead of iloc
:
In [58]: df.loc[idx]
Out[58]:
BoolCol
10 True
40 True
50 True
[3 rows x 1 columns]
Note that loc
can also accept boolean arrays:
In [55]: df.loc[df['BoolCol']]
Out[55]:
BoolCol
10 True
40 True
50 True
[3 rows x 1 columns]
If you have a boolean array, mask
, and need ordinal index values, you can compute them using np.flatnonzero
:
In [110]: np.flatnonzero(df['BoolCol'])
Out[112]: array([0, 3, 4])
Use df.iloc
to select rows by ordinal index:
In [113]: df.iloc[np.flatnonzero(df['BoolCol'])]
Out[113]:
BoolCol
10 True
40 True
50 True
There's a plugin for jQuery called 'rich array' discussed in Rich Array jQuery plugin .
I have to dedupe a very big table with many columns and speed is important. Thus I use this method which works for any table:
delete T from
(select Row_Number() Over(Partition By BINARY_CHECKSUM(*) order by %%physloc%% ) As RowNumber, * From MyTable) T
Where T.RowNumber > 1
Windows Subsystem for Linux did not exist when this question was asked. It gave these results in my test:
uname -s -> Linux
uname -o -> GNU/Linux
uname -r -> 4.4.0-17763-Microsoft
This means that you need uname -r to distinguish it from native Linux.
build.gradle
multiDexEnabled true
implementation 'androidx.multidex:multidex:2.0.1'
AndroidManifest.xml
<application
android:name="androidx.multidex.MultiDexApplication"
i think the simple solution is:
sh /dir/* > ./result.txt
I would say the biggest difference between orElse
and orElseGet
comes when we want to evaluate something to get the new value in the else
condition.
Consider this simple example -
// oldValue is String type field that can be NULL
String value;
if (oldValue != null) {
value = oldValue;
} else {
value = apicall().value;
}
Now let's transform the above example to using Optional
along with orElse
,
// oldValue is Optional type field
String value = oldValue.orElse(apicall().value);
Now let's transform the above example to using Optional
along with orElseGet
,
// oldValue is Optional type field
String value = oldValue.orElseGet(() -> apicall().value);
When orElse
is invoked, the apicall().value
is evaluated and passed to the method. Whereas, in the case of orElseGet
the evaluation only happens if the oldValue
is empty. orElseGet
allows lazy evaluation.
The alt
attribute is defined in a set of tags (namely, img
, area
and optionally for input
and applet
) to allow you to provide a text equivalent for the object.
A text equivalent brings the following benefits to your web site and its visitors in the following common situations:
The objective of this technique is to provide context sensitive help for users as they enter data in forms by providing the help information in a title
attribute. The help may include format information or examples of input.
Example 1: A pulldown menu that limits the scope of a search
A search form uses a pulldown menu to limit the scope of the search. The pulldown menu is immediately adjacent to the text field used to enter the search term. The relationship between the search field and the pulldown menu is clear to users who can see the visual design, which does not have room for a visible label. The title
attribute is used to identify the select
menu. The title
attribute can be spoken by screen readers or displayed as a tool tip for people using screen magnifiers.
<label for="searchTerm">Search for:</label>
<input id="searchTerm" type="text" size="30" value="" name="searchTerm">
<select title="Search in" id="scope">
...
</select>
Example 2: Input fields for a phone number
A Web page contains controls for entering a phone number in the United States, with three fields for area code, exchange, and last four digits.
<fieldset>
<legend>Phone number</legend>
<input id="areaCode" name="areaCode" title="Area Code" type="text" size="3" value="" >
<input id="exchange" name="exchange" title="First three digits of phone number" type="text" size="3" value="" >
<input id="lastDigits" name="lastDigits" title="Last four digits of phone number" type="text" size="4" value="" >
</fieldset>
Example 3: A Search Function
A Web page contains a text field where the user can enter search terms and a button labeled "Search" for performing the search. The title
attribute is used to identify the form control and the button is positioned right after the text field so that it is clear to the user that the text field is where the search term should be entered.
<input type="text" title="Type search term here"/> <input type="submit" value="Search"/>
Example 4: A data table of form controls
A data table of form controls needs to associate each control with the column and row headers for that cell. Without a title (or off-screen LABEL) it is difficult for non-visual users to pause and interrogate for corresponding row/column header values using their assistive technology while tabbing through the form.
For example, a survey form has four column headers in first row: Question, Agree, Undecided, Disagree. Each following row contains a question and a radio button in each cell corresponding to answer choice in the three columns. The title attribute for every radio button is a concatenation of the answer choice (column header) and the text of the question (row header) with a hyphen or colon as a separator.
Allowed attributes mentioned at MDN.
alt
crossorigin
decoding
height
importance
(experimental api)intrinsicsize
(experimental api)ismap
referrerpolicy
(experimental api)src
srcset
width
usemap
As you can see title
attribute is not allowed inside img
element. I would use alt
attribute and if requires I would use CSS (Example: pseudo class :hover
) instead of title
attribute.
var1
is a regular string, whereas var2
is an array, this is how you should compare (in this case):
puts var1 == var2[0]
ES5 Version:
var counts = [4, 9, 15, 6, 2],_x000D_
goal = 5;_x000D_
_x000D_
var closest = counts.reduce(function(prev, curr) {_x000D_
return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);_x000D_
});_x000D_
_x000D_
console.log(closest);
_x000D_
You could use the printf(1) command, e.g. like
printf "Hello times %d\nHere\n" $[2+3]
The printf
command may accept arguments and needs a format control string similar (but not exactly the same) to the one for the standard C printf(3) function...
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
Why grep ps
, when the pid has been written to the $CATALINA_PID
file?
I have a cron
'd checker script which sends out an email when tomcat is down:
kill -0 `cat $CATALINA_PID` > /dev/null 2>&1
if [ $? -gt 0 ]
then
echo "Check tomcat" | mailx -s "Tomcat not running" [email protected]
fi
I guess you could also use wget
to check the health of your tomcat. If you have a diagnostics page with user load etc, you could fetch it periodically and parse it to determine if anything is going wrong.
This worked for me:
ng-include src="'views/templates/drivingskills.html'"
complete div:
<div id="drivivgskills" ng-controller="DrivingSkillsCtrl" ng-view ng-include src="'views/templates/drivingskills.html'" ></div>
See if this is what you want to do:
@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set stamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%
copy "F:\Folder\File 1.xlsx" "F:\Folder\Archive\File 1 - %stamp%.xlsx"
I did it one time with a workaround, hope it helps.
string fullName = typeof(MyObj).FullName;
switch (fullName)
{
case "fullName1":
case "fullName2":
case "fullName3":
}
Go to the Team Explorer tab then click Branches. In the branches select your branch from remotes/origin. For example, you want to reset your master branch. Right-click at the master branch in remotes/origin then select Reset then click Delete changes. This will reset your local branch and removes all locally committed changes.
Well, the straightforward method is to create an appropriate class/structure which holds all your parameter values and pass that to the thread.
Another solution in VB10 is to use the fact that lambdas create a closure, which basically means the compiler doing the above automatically for you:
Dim evaluator As New Thread(Sub()
testthread(goodList, 1)
End Sub)
To install plugin "git" with all its dependencies:
curl -XPOST http://localhost:8080/pluginManager/installNecessaryPlugins -d '<install plugin="git@current" />'
Here, the plugin installed is git
; the version, specified as @current
is ignored by Jenkins. Jenkins is running on localhost
port 8080
, change this as needed. As far as I know, this is the simplest way to install a plugin with all its dependencies 'by hand'. Tested on Jenkins v1.644
Solution(s) for this, found in the official wampserver.com forums:
This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )
To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80"
. Note thatPID
on the right side. This is the process id of the software which currently usesport 80
. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID
you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).
left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80"
to 8080
. Restart. Done !
Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here
By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.
IMPORTANT: you have to use localhost
or 127.0.0.1
now with port 8080
, this means 127.0.0.1:8080
or localhost:8080
.
Try with this JSFiddle
DEMO : http://jsfiddle.net/2yEtK/3/
Jquery Code:
$("a.removeRecord").live("click",function(event){
event.stopPropagation();
if(confirm("Do you want to delete?")) {
this.click;
alert("Ok");
}
else
{
alert("Cancel");
}
event.preventDefault();
});
You can also define the pointcut as
public pointcut publicMethodInsideAClassMarkedWithAtMonitor() : execution(public * (@Monitor *).*(..));
Try this:
^[1-9]\d*$
...and some padding to exceed 30 character SO answer limit :-).
A typical way would be to use stringstream
:
#include <iomanip>
#include <sstream>
double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();
See fixed
Use fixed floating-point notation
Sets the
floatfield
format flag for the str stream tofixed
.When
floatfield
is set tofixed
, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision
) and with no exponent part.
and setprecision.
For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.
Assuming a compliant compiler (which we lack at the time of writing), something like this can be considered:
#include <array>
#include <charconv>
double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
std::chars_format::fixed, 2);
if (ec == std::errc{}) {
std::string s(buffer.data(), ptr);
// ....
}
else {
// error handling
}
ActionResult is an abstract class that can have several subtypes.
ViewResult - Renders a specifed view to the response stream
PartialViewResult - Renders a specifed partial view to the response stream
EmptyResult - An empty response is returned
RedirectResult - Performs an HTTP redirection to a specifed URL
RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
JsonResult - Serializes a given ViewData object to JSON format
JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
ContentResult - Writes content to the response stream without requiring a view
FileContentResult - Returns a file to the client
FileStreamResult - Returns a file to the client, which is provided by a Stream
FilePathResult - Returns a file to the client
I have a problem with these javascript functions:
function ClickConnect(){
console.log("Clicked on connect button");
document.querySelector("colab-connect-button").click()
}
setInterval(ClickConnect,60000)
They print the "Clicked on connect button" on the console before the button is actually clicked. As you can see from different answers in this thread, the id of the connect button has changed a couple of times since Google Colab was launched. And it could be changed in the future as well. So if you're going to copy an old answer from this thread it may say "Clicked on connect button" but it may actually not do that. Of course if the clicking won't work it will print an error on the console but what if you may not accidentally see it? So you better do this:
function ClickConnect(){
document.querySelector("colab-connect-button").click()
console.log("Clicked on connect button");
}
setInterval(ClickConnect,60000)
And you'll definitely see if it truly works or not.
If you are testing asynchronous code, you need to make sure to place done()
in the callback of that asynchronous code. I had that issue when testing http requests to a REST API.
You can remove it from the repo and commit the change.
git rm .idea/ -r --cached
git add -u .idea/
git commit -m "Removed the .idea folder"
After that, you can push it to the remote and every checkout/clone after that will be ok.
I use this guard gem to auto-run my test. It execute test after create or update operations on test file.
https://github.com/guard/guard-test
or usually you can run using following command
rspec spec/controllers/groups_controller_spec.rb
UPDATE
The other Questions are outmoded. The terrible legacy classes such as SimpleDateFormat
were supplanted years ago by the modern java.time classes.
For defining your own custom formatting patterns, the codes in DateTimeFormatter
are similar to but not exactly the same as the codes in SimpleDateFormat
. Be sure to study the documentation. And search Stack Overflow for many examples.
DateTimeFormatter f =
DateTimeFormatter.ofPattern(
"dd MMM uuuu" ,
Locale.ITALY
)
;
The ISO 8601 standard defines formats for many types of date-time values. These formats are designed for data-exchange, being easily parsed by machine as well as easily read by humans across cultures.
The java.time classes use ISO 8601 formats by default when generating/parsing strings. Simply call the toString
& parse
methods. No need to specify a formatting pattern.
Instant.now().toString()
2018-11-05T18:19:33.017554Z
For a value in UTC, the Z
on the end means UTC, and is pronounced “Zulu”.
Rather than specify a formatting pattern, you can let java.time automatically localize for you. Use the DateTimeFormatter.ofLocalized…
methods.
Get current moment with the wall-clock time used by the people of a particular region (a time zone).
ZoneId z = ZoneId.of( "Africa/Tunis" );
ZonedDateTime zdt = ZonedDateTime.now( z );
Generate text in standard ISO 8601 format wisely extended to append the name of the time zone in square brackets.
zdt.toString(): 2018-11-05T19:20:23.765293+01:00[Africa/Tunis]
Generate auto-localized text.
Locale locale = Locale.CANADA_FRENCH;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale );
String output = zdt.format( f );
output: lundi 5 novembre 2018 à 19:20:23 heure normale d’Europe centrale
Generally a better practice to auto-localize rather than fret with hard-coded formatting patterns.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
The switch method (as mentioned by Guffa) works very nicely indeed. However, the default warning settings in most linters will alert you about the use of fall-through. It's one of the main reasons I use switches at all, so I pretty much ignore this warning, but you should be aware that the using the fall-through feature of the switch statement can be tricky. In cases like this, though - I'd go for it.
this should be on here: it works anyway. And it looks good compared to the above ones.
hlsl code
float3 Hue(float H)
{
half R = abs(H * 6 - 3) - 1;
half G = 2 - abs(H * 6 - 2);
half B = 2 - abs(H * 6 - 4);
return saturate(half3(R,G,B));
}
half4 HSVtoRGB(in half3 HSV)
{
return half4(((Hue(HSV.x) - 1) * HSV.y + 1) * HSV.z,1);
}
float3 is 16 bit precision vector3 data type, i.e. float3 hue() is returns a data type (x,y,z) e.g. (r,g,b), half is same with half precision, 8bit, a float4 is (r,g,b,a) 4 values.
If the target directory is empty, use find, filter with only directories, filter by name, execute rmdir:
find . -type d -name a -exec rmdir {} \;
If you want to recursively delete its contents, replace -exec rmdir {} \;
with -delete
or -prune -exec rm -rf {} \;
. Other answers include details about these versions, credit them too.
All the 3 first ways are identical. You have make sure that if t
is a matrix you add .
before using multiplication or the power.
for matrix:
t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));
gives the results:
x =
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
y =
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
z=
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
And using a scalar:
p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);
gives the results:
x =
1.2341e-004
y =
1.2341e-004
z =
1.2341e-004
Some of the other answers did not work for me: It was not possible to create the checkpoint while the db was online, because the transaction log was full (how ironic). However, after setting the database to emergency mode, I was able to shrink the log file:
alter database <database_name> set emergency;
use <database_name>;
checkpoint;
checkpoint;
alter database <database_name> set online;
dbcc shrinkfile(<database_name>_log, 200);
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
If you want to search for the last instance of a string in a text, you can run rfind.
Example:
s="Hello"
print s.rfind('l')
output: 3
*no import needed
Complete syntax:
stringEx.rfind(substr, beg=0, end=len(stringEx))
[System.IO.Directory]::CreateDirectory('full path to directory')
This internally checks for directory existence, and creates one, if there is no directory. Just one line and native .NET method working perfectly.
At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.
It could look like this:
LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();
Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();
Simply choose whatever Integer value you want for the ID:
rowLayout.setId(12345);
If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.
UPDATE:
Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".
MainActivity.java:
public class MainActivity extends Activity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setId(12345);
getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();
fragContainer.addView(ll);
}
}
TestFragment.java:
public class TestFragment extends Fragment {
public static TestFragment newInstance(String text) {
TestFragment f = new TestFragment();
Bundle b = new Bundle();
b.putString("text", text);
f.setArguments(b);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, container, false);
((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));
return v;
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rlMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<LinearLayout
android:id="@+id/llFragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="19dp"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="200dp" >
<TextView
android:id="@+id/tvFragText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="" />
</RelativeLayout>
And this is the result of the above code: (the two Fragments are aligned next to each other)
I didn't want to introduce an asset catalog.
Per the answer from seahorseseaeo here, adding the following to info.plist worked for me. (I edited it as a "source code".) I then named the images [email protected] and [email protected]
<key>UILaunchImages</key>
<array>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>8.0</string>
<key>UILaunchImageName</key>
<string>Default-667h</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{375, 667}</string>
</dict>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>8.0</string>
<key>UILaunchImageName</key>
<string>Default-736h</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{414, 736}</string>
</dict>
</array>
You can't do a XMLHttpRequest crossdomain, the only "option" would be a technique called JSONP, which comes down to this:
To start request: Add a new <script>
tag with the remote url, and then make sure that remote url returns a valid javascript file that calls your callback function. Some services support this (and let you name your callback in a GET parameters).
The other easy way out, would be to create a "proxy" on your local server, which gets the remote request and then just "forwards" it back to your javascript.
edit/addition:
I see jQuery has built-in support for JSONP, by checking if the URL contains "callback=?" (where jQuery will replace ? with the actual callback method). But you'd still need to process that on the remote server to generate a valid response.
You can hide a JPanel by calling setVisible(false)
. For example:
public static void main(String args[]){
JFrame f = new JFrame();
f.setLayout(new BorderLayout());
final JPanel p = new JPanel();
p.add(new JLabel("A Panel"));
f.add(p, BorderLayout.CENTER);
//create a button which will hide the panel when clicked.
JButton b = new JButton("HIDE");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
p.setVisible(false);
}
});
f.add(b,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
I had a similar problem and used
ng-change="handler(objectInScope)"
in my handler I call a method of the objectInScope to modify itself correctly (coarse input). In the controller I have initiated somewhere that
$scope.objectInScope = myObject;
I know this doesn't use any fancy filters or watchers... but it's simple and works great. The only down-side to this is that the objectInScope is sent in the call to the handler...
<a href="javascript:void(0);"></a>
javascript:
tells the browser going to write javascript code
My simple, simple, simple approach! =D
Code
string_to_test = "The criminals stole $1,000,000 in jewels."
chars_to_check = ["$", ",", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for char in chars_to_check:
if char in string_to_test:
print("Char \"" + char + "\" detected!")
Output
Char "$" detected!
Char "," detected!
Char "0" detected!
Char "1" detected!
Thanks!
All these answers doesn't work from M - to - Android"O" - 8, Due to Dozer mode that restrict the service - whatever service or any background operation that requires discrete things in background would be no longer able to run.
So the approach would be listening to the system FusedLocationApiClient through BroadCastReciever that always listening the location and work even in Doze mode.
Posting the link would be pointless, please search FusedLocation with Broadcast receiver.
Thanks
You can use String arrays to add jComboBox items
String [] items = { "First item", "Second item", "Third item", "Fourth item" };
JComboBox comboOne = new JComboBox (items);
Here is the other way:
using Newtonsoft.Json.Linq;
internal class DymanicTest
{
public static string Json = @"{
""AED"": 3.672825,
""AFN"": 56.982875,
""ALL"": 110.252599,
""AMD"": 408.222002,
""ANG"": 1.78704,
""AOA"": 98.192249,
""ARS"": 8.44469
}";
public static void Run()
{
dynamic dynamicObject = JObject.Parse(Json);
foreach (JProperty variable in dynamicObject)
{
if (variable.Name == "AMD")
{
var value = variable.Value;
}
}
}
}
Another approach may be writing special function to extract all elements values from one string by regular-expression:
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main (String[] args){
HashMap<String,Integer> hashMapStringInteger = createHashMapStringIntegerInOneStat("'one' => '1', 'two' => '2' , 'three'=>'3' ");
System.out.println(hashMapStringInteger); // {one=1, two=2, three=3}
}
private static HashMap<String, Integer> createHashMapStringIntegerInOneStat(String str) {
HashMap<String, Integer> returnVar = new HashMap<String, Integer>();
String currentStr = str;
Pattern pattern1 = Pattern.compile("^\\s*'([^']*)'\\s*=\\s*>\\s*'([^']*)'\\s*,?\\s*(.*)$");
// Parse all elements in the given string.
boolean thereIsMore = true;
while (thereIsMore){
Matcher matcher = pattern1.matcher(currentStr);
if (matcher.find()) {
returnVar.put(matcher.group(1),Integer.valueOf(matcher.group(2)));
currentStr = matcher.group(3);
}
else{
thereIsMore = false;
}
}
// Validate that all elements in the given string were parsed properly
if (currentStr.length() > 0){
System.out.println("WARNING: Problematic string format. given String: " + str);
}
return returnVar;
}
}
in your view, instead of:
@Html.EditorFor(model => model.Comments[0].Comment)
just use:
@Html.TextAreaFor(model => model.Comments[0].Comment, 5, 1, null)
Use head
:
dnow <- data.frame(x=rnorm(100), y=runif(100))
head(dnow,4) ## default is 6
Follow my steps :
Answer is to escape the dash!
Not an answer to OP's question but it's worth mentioning that there is the viridis
package which has good color palettes for sequential data. They are perceptually uniform, colorblind safe and printer-friendly.
To get the palette, simply install the package and use the function viridis_pal()
. There are four options "A", "B", "C" and "D" to choose
install.packages("viridis")
library(viridis)
viridis_pal(option = "D")(n) # n = number of colors seeked
There is also an excellent talk explaining the complexity of good colormaps on YouTube:
A Better Default Colormap for Matplotlib | SciPy 2015 | Nathaniel Smith and Stéfan van der Walt
My solution is simplier and checked on Ruby 2.0. It also enable download Json. (run CMD.exe as administrator)
C:\RubyDev>devkitvars.bat
Adding the DevKit to PATH...
And then write again gem command.
Using file extension and getimagesize
function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.
for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one.
Also its possible to get uploaded file content and search it for special character like <?php
to find the file is image or not.
The menu location seems to have changed to:
Query Designer --> Pane --> SQL
Just to include the latest update (UPDATE 4) in @Arhimed 's immaculate answer in the very good summary of @sulai:
void doTheTask(AsyncTask task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // Android 4.4 (API 19) and above
// Parallel AsyncTasks are possible, with the thread-pool size dependent on device
// hardware
task.execute(params);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Android 3.0 to
// Android 4.3
// Parallel AsyncTasks are not possible unless using executeOnExecutor
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else { // Below Android 3.0
// Parallel AsyncTasks are possible, with fixed thread-pool size
task.execute(params);
}
}
I am still a beginner at git, and it was just a stupid mistake I made, long story in one sentence. I was not in a subfolder as @gaoagong reported, but the other way round, in a parent folder. Strange enough, I did not get the idea from that answer, instead, the idea came up when I tested git add --all
, see the long story below.
Example in details. Actual repo:
The Parent folder that I had opened mistakenly on parent level (vscode_git in my case):
I had cloned a repo, but I had a parent folder above this repo which I had opened instead, and then I tried adding a file of the subfolder's repo with git add 'd:\Stack Overflow\vscode_git\vscode-java\.github\ISSUE_TEMPLATE.md'
, which simply did nothing, no warning message, and the git status
afterwards said:
nothing added to commit but untracked files present (use "git add" to track)
Running git add --all
gave me the yellow notes:
warning: adding embedded git repository: vscode-java the embedded repository and will not know how to obtain it.
hint: If you meant to add a submodule, use: git submodule add vscode-java
hint: If you added this path by mistake, you can remove it from the index with git rm --cached vscode-java
See "git help submodule" for more information.git
To fix this, I reverted the git add --all
with git rm --cached -r -f -- "d:\Stack Overflow\vscode_git\vscode-java" rm 'vscode-java'
:
Then, by simply opening the actual repo folder instead,
the git worked as expected again. Of course the ".git" folder of the parent folder could be deleted then:
In my case, I added my libraries to Modulepath instead on Classpath.
It only works if JUnit is correctly added to Classpath.
You can Kill a specific instance of MS Word.
foreach (var process in Process.GetProcessesByName("WINWORD"))
{
// Temp is a document which you need to kill.
if (process.MainWindowTitle.Contains("Temp"))
process.Kill();
}
You can only return one value, but it can be an object that has multiple fields - ie a "value object". Eg
public class MyResult {
int returnCode;
String errorMessage;
// etc
}
public MyResult someMethod() {
// impl here
}
that value is contained in the variable $#
Nor Kelsey, nor Brendan solutions does not works for me in Visual Studio 2015 Community.
Here is my brief steps how to create service with installer:
->
New->
ProjectDouble click serviceInstaller1. Visual Studio creates serviceInstaller1_AfterInstall
event. Write code:
private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
using (System.ServiceProcess.ServiceController sc = new
System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
{
sc.Start();
}
}
Build solution. Right click on project and select 'Open Folder in File Explorer'. Go to bin\Debug.
Create install.bat with below script:
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
@echo off
CLS
ECHO.
ECHO =============================
ECHO Running Admin shell
ECHO =============================
:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )
:getPrivileges
if '%1'=='ELEV' (shift & goto gotPrivileges)
ECHO.
ECHO **************************************
ECHO Invoking UAC for Privilege Escalation
ECHO **************************************
setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion
ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs"
ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs"
"%temp%\OEgetPrivileges.vbs"
exit /B
:gotPrivileges
::::::::::::::::::::::::::::
:START
::::::::::::::::::::::::::::
setlocal & pushd .
cd /d %~dp0
%windir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i "WindowsService1.exe"
pause
/i
to /u
)A mask defines which bits you want to keep, and which bits you want to clear.
Masking is the act of applying a mask to a value. This is accomplished by doing:
Below is an example of extracting a subset of the bits in the value:
Mask: 00001111b
Value: 01010101b
Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:
Mask: 00001111b
Value: 01010101b
Result: 00000101b
Masking is implemented using AND, so in C we get:
uint8_t stuff(...) {
uint8_t mask = 0x0f; // 00001111b
uint8_t value = 0x55; // 01010101b
return mask & value;
}
Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &
, and >>
(shift right). This is how we can extract the four bytes from a 32-bit integer:
void more_stuff(uint32_t value) { // Example value: 0x01020304
uint32_t byte1 = (value >> 24); // 0x01020304 >> 24 is 0x01 so
// no masking is necessary
uint32_t byte2 = (value >> 16) & 0xff; // 0x01020304 >> 16 is 0x0102 so
// we must mask to get 0x02
uint32_t byte3 = (value >> 8) & 0xff; // 0x01020304 >> 8 is 0x010203 so
// we must mask to get 0x03
uint32_t byte4 = value & 0xff; // here we only mask, no shifting
// is necessary
...
}
Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:
uint32_t byte3 = (value & 0xff00) >> 8;
http://www.quirksmode.org/js/cookies.html
update would just be resetting it using createCookie
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
var expires = "; expires=" + date.toGMTString();
} else {
var expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
I came across this error while making a segue from a table view controller to a view controller because I had forgotten to specify the custom class name for the view controller in the main storyboard.
Something simple that is worth checking if all else looks ok
I would like to offer a minor improvement on the last loop answer given in the previous post (that post is correct and should still be accepted). The implicit assumption made when labeling the last example is that plt.label(LIST)
puts label number X in LIST
with the line corresponding to the Xth time plot
was called. I have run into problems with this approach before. The recommended way to build legends and customize their labels per matplotlibs documentation ( http://matplotlib.org/users/legend_guide.html#adjusting-the-order-of-legend-item) is to have a warm feeling that the labels go along with the exact plots you think they do:
...
# Plot several different functions...
labels = []
plotHandles = []
for i in range(1, num_plots + 1):
x, = plt.plot(some x vector, some y vector) #need the ',' per ** below
plotHandles.append(x)
labels.append(some label)
plt.legend(plotHandles, labels, 'upper left',ncol=1)
In bash:
while read -r line ; do
[[ $line == all:* ]] && line+=" anotherthing"
echo "$line"
done < filename
Below is reference from https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java
/**
* Gets the base name, without extension, of given file name.
* <p/>
* e.g. getBaseName("file.txt") will return "file"
*
* @param fileName
* @return the base name
*/
public static String getBaseName(String fileName) {
int index = fileName.lastIndexOf('.');
if (index == -1) {
return fileName;
} else {
return fileName.substring(0, index);
}
}
While Ryan is correct, the solution can be much simpler based on what is known about the source of the randomness. To re-state the problem:
[0, MAX)
with uniform distribution. [rmin, rmax]
where 0 <= rmin < rmax < MAX
.In my experience, if the number of bins (or "boxes") is significantly smaller than the range of the original numbers, and the original source is cryptographically strong - there is no need to go through all that rigamarole, and simple modulo division would suffice (like output = rnd.next() % (rmax+1)
, if rmin == 0
), and produce random numbers that are distributed uniformly "enough", and without any loss of speed. The key factor is the randomness source (i.e., kids, don't try this at home with rand()
).
Here's an example/proof of how it works in practice. I wanted to generate random numbers from 1 to 22, having a cryptographically strong source that produced random bytes (based on Intel RDRAND). The results are:
Rnd distribution test (22 boxes, numbers of entries in each box): 1: 409443 4.55% 2: 408736 4.54% 3: 408557 4.54% 4: 409125 4.55% 5: 408812 4.54% 6: 409418 4.55% 7: 408365 4.54% 8: 407992 4.53% 9: 409262 4.55% 10: 408112 4.53% 11: 409995 4.56% 12: 409810 4.55% 13: 409638 4.55% 14: 408905 4.54% 15: 408484 4.54% 16: 408211 4.54% 17: 409773 4.55% 18: 409597 4.55% 19: 409727 4.55% 20: 409062 4.55% 21: 409634 4.55% 22: 409342 4.55% total: 100.00%
This is as close to uniform as I need for my purpose (fair dice throw, generating cryptographically strong codebooks for WWII cipher machines such as http://users.telenet.be/d.rijmenants/en/kl-7sim.htm, etc). The output does not show any appreciable bias.
Here's the source of cryptographically strong (true) random number generator: Intel Digital Random Number Generator and a sample code that produces 64-bit (unsigned) random numbers.
int rdrand64_step(unsigned long long int *therand)
{
unsigned long long int foo;
int cf_error_status;
asm("rdrand %%rax; \
mov $1,%%edx; \
cmovae %%rax,%%rdx; \
mov %%edx,%1; \
mov %%rax, %0;":"=r"(foo),"=r"(cf_error_status)::"%rax","%rdx");
*therand = foo;
return cf_error_status;
}
I compiled it on Mac OS X with clang-6.0.1 (straight), and with gcc-4.8.3 using "-Wa,q" flag (because GAS does not support these new instructions).
I've modified your plunker to get it working via angular-xeditable:
http://plnkr.co/edit/xUDrOS?p=preview
It is common solution for inline editing - you creale hyperlinks with editable-text
directive
that toggles into <input type="text">
tag:
<a href="#" editable-text="bday.name" ng-click="myform.$show()" e-placeholder="Name">
{{bday.name || 'empty'}}
</a>
For date I used editable-date
directive that toggles into html5 <input type="date">
.
There are some guys at Mozilla working on implementing a PDF reader using HTML5 and JavaScript. It is called pdf.js and one of the developers just made an interesting blog post about the project.
I also tried to make an executable jar file that I could run with the following command:
java -jar <jarfile>
After some searching I found the following link:
Packaging and Deploying Desktop Java Applications
I set the project's main class:
Then in the fodler dist the newly created jar should be executable with the command I mentioned above.
I had good experience with SUDS https://fedorahosted.org/suds
Used their TestSuite as documentation.
None of the video settings posted above worked in modern browsers I tested (like Firefox) using the embed
or object
elements in HTML5. For video
or audio
elements they did stop autoplay. For embed
and object
they did not.
I tested this using the embed
and object
elements using several different media types as well as HTML attributes (like autostart and autoplay). These videos always played regardless of any combination of settings in several browsers. Again, this was not an issue using the newer HTML5 video
or audio
elements, just when using embed
and object
.
It turns out the new browser settings for video "autoplay" have changed. Firefox will now ignore the autoplay
attributes on these tags and play videos anyway unless you explicitly set to "block audio and video" autoplay in your browser settings.
To do this in Firefox I have posted the settings below:
Your videos will NOT autoplay now when displaying videos in web pages using object
or embed
elements.
And with HTML5 we have native DOM Mutation Observers.
Command CHCP shows the current codepage. It has three digits: 8xx and is different from Windows 12xx. So typing a English-only text you wouldn't see any difference, but an extended codepage (like Cyrillic) will be printed wrongly.
Very easy to use extension for UIView, editable directly from storyboard. Swift 4+
@IBDesignable extension UIView {
@IBInspectable var shadowColor: UIColor?{
set {
guard let uiColor = newValue else { return }
layer.shadowColor = uiColor.cgColor
}
get{
guard let color = layer.shadowColor else { return nil }
return UIColor(cgColor: color)
}
}
@IBInspectable var shadowOpacity: Float{
set {
layer.shadowOpacity = newValue
}
get{
return layer.shadowOpacity
}
}
@IBInspectable var shadowOffset: CGSize{
set {
layer.shadowOffset = newValue
}
get{
return layer.shadowOffset
}
}
@IBInspectable var shadowRadius: CGFloat{
set {
layer.shadowRadius = newValue
}
get{
return layer.shadowRadius
}
}
}
Here is an option that's easier to extend than yours, but no, there is none built into the library itself.
private static List<string> suffixes = new List<string> { " B", " KB", " MB", " GB", " TB", " PB" };
public static string Foo(int number)
{
for (int i = 0; i < suffixes.Count; i++)
{
int temp = number / (int)Math.Pow(1024, i + 1);
if (temp == 0)
return (number / (int)Math.Pow(1024, i)) + suffixes[i];
}
return number.ToString();
}
It works for me thank you. I had this issue when I installed .Net Framework 4.7.1, somehow DbProviderFactories
settings under System.Data
in machine config got wiped-out. It started working after adding the necessary configuration settings as shown below DataProviderFactories
<system.data>
<DbProviderFactories>
<add name="Oracle Data Provider for .NET" invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET" type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=4.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
</DbProviderFactories>
</system.data>
If by chance you have deleted JRE SYSTEM LIBRARY, then go to your JRE installation and add jars from there.
Eg:- C:\Program Files (x86)\Java\jre7\lib ---add jars from here
C:\Program Files (x86)\Java\jre7\lib\ext ---add jars from here
If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
If you have a seeder in your database, run php artisan migrate:fresh --seed
svn update /path/to/working/copy
If subversion is not in your PATH, then of course
/path/to/subversion/svn update /path/to/working/copy
or if you are in the current root directory of your svn repo (it contains a .svn subfolder), it's as simple as
svn update
Still using indirect. Say your A1 cell is your variable that will contain the name of the referenced sheet (Jan). If you go by:
=INDIRECT(CONCATENATE("'",A1," Item'", "!J3"))
Then you will have the 'Jan Item'!J3 value.
This wont necessarily fix the problem...but it will tell you what the real problem is.
Its currently trying to use a custom error page that doesn't exist.
If you add this line to Web.config (under system.web tag) it should give you the real error.
<system.web>
<!-- added line -->
<customErrors mode="Off"/>
<!-- added line -->
</system.web>
Straight out from the documentation:
Suppose the website example.com would like to send notifications to its users via a Telegram bot. Here's what they could do to enable notifications for a user with the ID 123.
memcache_key = "vCH1vGWJxfSeofSAs0K5PA"
/start
. If the key exists, record the chat_id passed to the webhook as telegram_chat_id for the user 123. Remove the key from Memcache.telegram_chat_id
. If yes, use the sendMessage
method in the Bot API to send them a message in Telegram.Perhaps you can try to BeginInvoke a delegate pointing to your method like so:
delegate string SynchOperation(string value);
class Program
{
static void Main(string[] args)
{
BeginTheSynchronousOperation(CallbackOperation, "my value");
Console.ReadLine();
}
static void BeginTheSynchronousOperation(AsyncCallback callback, string value)
{
SynchOperation op = new SynchOperation(SynchronousOperation);
op.BeginInvoke(value, callback, op);
}
static string SynchronousOperation(string value)
{
Thread.Sleep(10000);
return value;
}
static void CallbackOperation(IAsyncResult result)
{
// get your delegate
var ar = result.AsyncState as SynchOperation;
// end invoke and get value
var returned = ar.EndInvoke(result);
Console.WriteLine(returned);
}
}
Then use the value in the method you sent as AsyncCallback to continue..
You are very close; currently you compare the row[2]
with integer 0
, make the comparison with the string "0"
. When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:
row[2]!="0":
Also, you can use the with
keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close
statements:
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != "0":
writer.writerow(row)
Note that input
is a Python builtin, so I've used another variable name instead.
Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0"
would work, so you can either use strip(row[2]) != 0
, or check against " 0"
.
The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:
$ cat test.py
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != " 0":
writer.writerow(row)
$ cat first.csv
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py
$ cat first_edit.csv
6.5, 5.4, 1, 320
Use window.open()
:
var win = window.open('http://stackoverflow.com/', '_blank');
if (win) {
//Browser has allowed it to be opened
win.focus();
} else {
//Browser has blocked it
alert('Please allow popups for this website');
}
Depending on the browsers implementation this will work
There is nothing you can do to make it open in a window rather than a tab.
You can use the contentDocument or contentWindow property for that purpose. Here is the sample code.
function gethtml() {
const x = document.getElementById("myframe")
const y = x.contentWindow || x.contentDocument
const z = y.document ? y.document : y
alert(z.body.innerHTML)
}
here, myframe
is the id of your iframe.
Note: You can't extract the content out of an iframe from a src outside you domain.
Usually the progress bar is either themed or honors the user's color preferences. So for changing the color you either need to turn off visual styles and set ForeColor
or draw the control yourself.
As for the continuous style instead of blocks you can set the Style
property:
pBar.Style = ProgressBarStyle.Continuous;
<Directory /uploads>
Options +Indexes
</Directory>
Here's what worked for me:
<pre class="prettyprint linenums">
<code class="language-xml"><?php echo htmlspecialchars(file_get_contents("example.xml"), ENT_QUOTES); ?></code>
</pre>
Using htmlspecialchars will prevent tags from being displayed as html and won't break anything. Note that I'm using Prettyprint to highlight the code ;)
There is not a drawTriangle method neither in Graphics nor Graphics2D. You need to do it by yourself. You can draw three lines using the drawLine
method or use one these methods:
These methods work with polygons. You may change the prefix draw
to fill
when you want to fill the polygon defined by the point set. I inserted the documentation links. Take a look to learn how to use them.
There is the GeneralPath class too. It can be used with Graphics2D, which is capable to draw Shapes. Take a look:
@JoeSchr has an answer. Here is another way to do if you don't want deep: true
mounted() {
this.yourMethod();
// re-render any time a prop changes
Object.keys(this.$options.props).forEach(key => {
this.$watch(key, this.yourMethod);
});
},
A thread is something like some branch. Multi-branched means when there are at least two branches. If the branches are reduced, then the minimum remains one. This one is although like the branches removed, but in general we do not consider it branch.
Similarly when there are at least two threads we call it multi-threaded program. If the threads are reduced, the minimum remains one. Hello program is a single threaded program, but no one needs to know multi-threading to write or run it.
In simple words when a program is not said to be having threads, it means that the program is not a multi-threaded program, more over in true sense it is a single threaded program, in which YOU CAN put your code as if it is multi-threaded.
Below a useless code is given, but it will suffice to do away with your some confusions about Runnable
. It will print "Hello World".
class NamedRunnable implements Runnable {
public void run() { // The run method prints a message to standard output.
System.out.println("Hello World");
}
public static void main(String[]arg){
NamedRunnable namedRunnable = new NamedRunnable( );
namedRunnable.run();
}
}
From SDK:
Cancelling a task
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true.
After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.
To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)
So your code is right for dialog listener:
uploadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
myTask.cancel(true);
//finish();
}
});
Now, as I have mentioned earlier from SDK, you have to check whether the task is cancelled or not, for that you have to check isCancelled() inside the onPreExecute() method.
For example:
if (isCancelled())
break;
else
{
// do your work here
}
You can try this:
td p {word-break:break-all;}
This, however, makes it appear like this when there's enough space, unless you add a <br>
tag:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
So, I would then suggest adding <br>
tags where there are newlines, if possible.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Also, if this doesn't solve your problem, there's a similar thread here.
The built in FTP command doesn't have a facility for security. Use cUrl instead. It's scriptable, far more robust and has FTP security.
If the size of strings is relatively big (hundreds of bytes or more) and c++17 is available, you might want to use Boyer-Moore-Horspool searcher (example from cppreference.com):
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
int main()
{
std::string in = "Lorem ipsum dolor sit amet, consectetur adipiscing elit,"
" sed do eiusmod tempor incididunt ut labore et dolore magna aliqua";
std::string needle = "pisci";
auto it = std::search(in.begin(), in.end(),
std::boyer_moore_searcher(
needle.begin(), needle.end()));
if(it != in.end())
std::cout << "The string " << needle << " found at offset "
<< it - in.begin() << '\n';
else
std::cout << "The string " << needle << " not found\n";
}
As the OP said, TLS v1.1 and v1.2 protocols are supported in API level 16+, but are not enabled by default, we just need to enable it.
Example here uses HttpsUrlConnection
, not HttpUrlConnection
. Follow https://blog.dev-area.net/2015/08/13/android-4-1-enable-tls-1-1-and-tls-1-2/, we can create a factory
class MyFactory extends SSLSocketFactory {
private javax.net.ssl.SSLSocketFactory internalSSLSocketFactory;
public MyFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
internalSSLSocketFactory = context.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return internalSSLSocketFactory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return internalSSLSocketFactory.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket());
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
}
return socket;
}
}
No matter which Networking library you use, make sure ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
gets called so the Socket has enabled TLS protocols.
Now, you can use that in HttpsUrlConnection
class MyHttpRequestTask extends AsyncTask<String,Integer,String> {
@Override
protected String doInBackground(String... params) {
String my_url = params[0];
try {
URL url = new URL(my_url);
HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
httpURLConnection.setSSLSocketFactory(new MyFactory());
// setting the Request Method Type
httpURLConnection.setRequestMethod("GET");
// adding the headers for request
httpURLConnection.setRequestProperty("Content-Type", "application/json");
String result = readStream(httpURLConnection.getInputStream());
Log.e("My Networking", "We have data" + result.toString());
}catch (Exception e){
e.printStackTrace();
Log.e("My Networking", "Oh no, error occurred " + e.toString());
}
return null;
}
private static String readStream(InputStream is) throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("US-ASCII")));
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
if (reader != null) {
reader.close();
}
return total.toString();
}
}
For example
new MyHttpRequestTask().execute(myUrl);
Also, remember to bump minSdkVersion
in build.gradle to 16
minSdkVersion 16
If you need a full svg not only a path and you want it to be modifiable on client side (e.g. change text, hide details, ...) you can use an alternative data 'URL' with included svg:
var svg = '<svg width="400" height="110"><rect width="300" height="100" /></svg>';
icon.url = 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg);
JavaScript (Firefox) btoa() is used to get the base64 encoding from the SVG text. Your may also use http://dopiaza.org/tools/datauri/index.php to generate base data URLs.
Here is a full example jsfiddle:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var template = [
'<?xml version="1.0"?>',
'<svg width="26px" height="26px" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg">',
'<circle stroke="#222" fill="{{ color }}" cx="50" cy="50" r="35"/>',
'</svg>'
].join('\n');
var svg = template.replace('{{ color }}', '#800');
var docMarker = new google.maps.Marker({
position: new google.maps.LatLng(-33.92, 151.25),
map: map,
title: 'Dynamic SVG Marker',
icon: { url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg), scaledSize: new google.maps.Size(20, 20) },
optimized: false
});
var docMarker = new google.maps.Marker({
position: new google.maps.LatLng(-33.95, 151.25),
map: map,
title: 'Dynamic SVG Marker',
icon: { url: 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg), scaledSize: new google.maps.Size(20, 20) },
optimized: false
});
</script>
</body>
</html>
Additional Information can be found here.
Avoid base64 encoding:
In order to avoid base64 encoding you can replace 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg)
with 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg)
This should work with modern browsers down to IE9.
The advantage is that encodeURIComponent
is a default js function and available in all modern browsers. You might also get smaller links but you need to test this and consider to use '
instead of "
in your svg.
Also see Optimizing SVGs in data URIs for additional info.
IE support: In order to support SVG Markers in IE one needs two small adaptions as described here: SVG Markers in IE. I updated the example code to support IE.
I happened to be in a particular situation where my usecase resembled the one of Mureinik but I ended-up using the solution of Tomasz Nurkiewicz.
Here is how:
class TestedClass extends AARRGGHH {
public LoginContext login(String user, String password) {
LoginContext lc = new LoginContext("login", callbackHandler);
lc.doThis();
lc.doThat();
return lc;
}
}
Now, PowerMockRunner
failed to initialize TestedClass
because it extends AARRGGHH
, which in turn does more contextual initialization... You see where this path was leading me: I would have needed to mock on several layers. Clearly a HUGE smell.
I found a nice hack with minimal refactoring of TestedClass
: I created a small method
LoginContext initLoginContext(String login, CallbackHandler callbackHandler) {
new lc = new LoginContext(login, callbackHandler);
}
The scope of this method is necessarily package
.
Then your test stub will look like:
LoginContext lcMock = mock(LoginContext.class)
TestedClass testClass = spy(new TestedClass(withAllNeededArgs))
doReturn(lcMock)
.when(testClass)
.initLoginContext("login", callbackHandler)
and the trick is done...
you can
float Lasttime;
public float Sec = 3f;
public int Num;
void Start(){
ExampleStart();
}
public void ExampleStart(){
Lasttime = Time.time;
}
void Update{
if(Time.time - Lasttime > sec){
// if(Num == step){
// Yourcode
//You Can Change Sec with => sec = YOURTIME(Float)
// Num++;
// ExampleStart();
}
if(Num == 0){
TextUI.text = "Welcome to Number Wizard!";
Num++;
ExampleStart();
}
if(Num == 1){
TextUI.text = ("The highest number you can pick is " + max);
Num++;
ExampleStart();
}
if(Num == 2){
TextUI.text = ("The lowest number you can pick is " + min);
Num++;
ExampleStart();
}
}
}
Khaled Developer
Easy For Gaming
I'm making @Laurence Gonsalves' comment into an answer because it's the only one that works semantically and doesn't look like a hack.
Try adding this to your stylesheet:
optgroup + optgroup { border-top: 1px solid black }
Much less cheesy looking than a bunch of dashes.
Sometimes you want to change the capitalization of a lot of file names on a case insensitive filesystem (e.g. on OS X or Windows). Doing git mv
commands will tire quickly. To make things a bit easier this is what I do:
git add . -A
to remove all files.git add .
. Git should see that the files are renamed.Now you can make a commit saying you have changed the file name capitalization.
This should work.
$(".formData").val("valuesgoeshere")
For empty
$(".formData").val("")
If this does not work, you should post a jsFiddle.
Demo:
$(function() {_x000D_
$(".resetInput").on("click", function() {_x000D_
$(".formData").val("");_x000D_
});_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="text" class="formData" value="yoyoyo">_x000D_
_x000D_
_x000D_
<button class="resetInput">Click Here to reset</button>
_x000D_
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue"
to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
When your class implements Comparable, the compareTo
method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals()
comparisons return true.
A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.
For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b")
would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.
In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.
Try something like this:
#include <signal.h>
pid_t child_pid = -1 ; //Global
void kill_child(int sig)
{
kill(child_pid,SIGKILL);
}
int main(int argc, char *argv[])
{
signal(SIGALRM,(void (*)(int))kill_child);
child_pid = fork();
if (child_pid > 0) {
/*PARENT*/
alarm(30);
/*
* Do parent's tasks here.
*/
wait(NULL);
}
else if (child_pid == 0){
/*CHILD*/
/*
* Do child's tasks here.
*/
}
}
The error message is pretty self-explanatory: your application needs the Oracle Client installed on the machine it's running on. Your development PC already has it. Make sure your target PC has it, too.
Edit: The System.Data.OracleClient namespace is deprecated. Make sure you use the driver native to your database system, that would be ODP.NET from Oracle.
Just use resize: none
textarea {
resize: none;
}
You can also decide to resize your textareas only horizontal or vertical, this way:
textarea { resize: vertical; }
textarea { resize: horizontal; }
Finally,
resize: both
enables the resize grabber.
Right click on the project in which you want to put jar file. A window will open like this
Click on the AddExternal Jars there you can give the path to that jar file
The answer from @Emiliano is excellent. You can also pass named parameters like so:
powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"
Note the parameters are outside the command call, and you'll use:
[parameter(Mandatory=$false)]
[string]$NamedParam1,
[parameter(Mandatory=$false)]
[string]$NamedParam2
See LINQ: How to get the latest/last record with a group by clause
var firstItemsInGroup = from b in mainButtons
group b by b.category into g
select g.First();
I assume that mainButtons are already sorted correctly.
If you need to specify custom sort order, use OrderBy override with Comparer.
var firstsByCompareInGroups = from p in rows
group p by p.ID into grp
select grp.OrderBy(a => a, new CompareRows()).First();
See an example in my post "Select First Row In Group using Custom Comparer"
There is now an open-source extension in the Marketplace that seems to do what the OP was asking for:
If it doesn't do exactly what you want, the code is available, so you can modify it to suit your scenario.
HTH
The answer is "no, you probably can't".
While there is stuff in there that might say who created a given object, there are a lot of "ifs" behind them. A quick (and not necessarily complete) review:
sys.objects (and thus sys.tables, sys.procedures, sys.views, etc.) has column principal_id. This value is a foreign key that relates to the list of database users, which in turn can be joined with the list of SQL (instance) logins. (All of this info can be found in further system views.)
But.
A quick check on our setup here and a cursory review of BOL indicates that this value is only set (i.e. not null) if it is "different from the schema owner". In our development system, and we've got dbo + two other schemas, everything comes up as NULL. This is probably because everyone has dbo rights within these databases.
This is using NT authentication. SQL authentication probably works much the same. Also, does everyone have and use a unique login, or are they shared? If you have employee turnover and domain (or SQL) logins get dropped, once again the data may not be there or may be incomplete.
You can look this data over (select * from sys.objects), but if principal_id is null, you are probably out of luck.
What is the difference between Git and GitHub?
Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.
Is git saving every repository locally (in the user's machine) and in GitHub?
If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.
How does Git compare to a backup system such as Time Machine?
Git is specifically designed and optimized for source code.
Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?
Exactly.
If are not collaborating and you are already using a backup system why would you use Git?
See #4.
Something fairly ODBC compliant if needed might be the following:
select ifnull(repeat('0', 5 - (floor(log10(FIELD_NAME)) + 1)), '')
+ cast (FIELD as varchar(10))
from TABLE_NAME
This bases on the fact that the amount of digits for a base-10 number can be found by the integral component of its log. From this we can subtract it from the desired padding width. Repeat will return null
for values under 1 so we need ifnull
.
Found this interesting approach when I wanted to implement enums in SQL Server.
The approach mentioned below in the link is quite compelling, considering all your database enum needs could be satisfied with 2 central tables.
I would use spans or float the div left. The only problem with floating is that you have to clear the float afterwards or the containing div must have the overflow style set to auto
EDIT:
This answer will not work for Python3 and will give a RuntimeError
.
RuntimeError: dictionary changed size during iteration.
This happens because mydict.keys()
returns an iterator not a list.
As pointed out in comments simply convert mydict.keys()
to a list by list(mydict.keys())
and it should work.
A simple test in the console shows you cannot modify a dictionary while iterating over it:
>>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> for k, v in mydict.iteritems():
... if k == 'two':
... del mydict[k]
...
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
As stated in delnan's answer, deleting entries causes problems when the iterator tries to move onto the next entry. Instead, use the keys()
method to get a list of the keys and work with that:
>>> for k in mydict.keys():
... if k == 'two':
... del mydict[k]
...
>>> mydict
{'four': 4, 'three': 3, 'one': 1}
If you need to delete based on the items value, use the items()
method instead:
>>> for k, v in mydict.items():
... if v == 3:
... del mydict[k]
...
>>> mydict
{'four': 4, 'one': 1}
(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :
Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.
This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).
Go to the search bar on your Windows and search for Services. Launch Services and look for MySQLxx (xx depends on your MySQL version) in the long list of services. Right-click on MySQLxx and hit Start. MySQL should work fine now.
as @DLeh says Use rather
var controller = DependencyResolver.Current.GetService<ControllerB>();
But, giving the controller, a controlller context is important especially when you need to access the User
object, Server
object, or the HttpContext
inside the 'child' controller.
I have added a line of code:
controller.ControllerContext = new ControllerContext(Request.RequestContext, controller);
or else you could have used System.Web to acces the current context too, to access Server
or the early metioned objects
NB: i am targetting the framework version 4.6 (Mvc5)
Try like below... it will help you...
Some time in Window Form Focus()
doesn't work correctly. So better you can use Select()
to focus the textbox.
txtbox.Select(); // to Set Focus
txtbox.Select(txtbox.Text.Length, 0); //to set cursor at the end of textbox
you can use CASE
WHEN
as follow as achieve the as IF
ELSE
.
SELECT FROM A a
LEFT JOIN B b
ON a.col1 = b.col1
AND (CASE
WHEN a.col2 like '0%' then TRIM(LEADING '0' FROM a.col2)
ELSE substring(a.col2,1,2)
END
)=b.col2;
p.s:just in case somebody needs this way.
Add
<form target="_blank" ...></form>
or
form.setAttribute("target", "_blank");
to your form's definition.
Did you try using t.Text
?
One way is to create a Spliterator
from the Iterator
and use that as a basis for your stream:
Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();
Stream<String> targetStream = StreamSupport.stream(
Spliterators.spliteratorUnknownSize(sourceIterator, Spliterator.ORDERED),
false);
An alternative which is maybe more readable is to use an Iterable
- and creating an Iterable
from an Iterator
is very easy with lambdas because Iterable
is a functional interface:
Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();
Iterable<String> iterable = () -> sourceIterator;
Stream<String> targetStream = StreamSupport.stream(iterable.spliterator(), false);
I'm writing this answer w.r.t. to python 3, as I've initially got the same problem.
I was supposed to get data from arduino using PySerial
, and write them in a .csv file. Each reading in my case ended with '\r\n'
, so newline was always separating each line.
In my case, newline=''
option didn't work. Because it showed some error like :
with open('op.csv', 'a',newline=' ') as csv_file:
ValueError: illegal newline value: ''
So it seemed that they don't accept omission of newline here.
Seeing one of the answers here only, I mentioned line terminator in the writer object, like,
writer = csv.writer(csv_file, delimiter=' ',lineterminator='\r')
and that worked for me for skipping the extra newlines.
You could split things up, it would require more code but would work just the way you like it:
DateTime year = DateTime.Now.Year;
DateTime month = DateTime.Now.Month;
DateTime day = DateTime.Now.Day;
ect.
finally:
Console.WriteLine(year+month+day+etc.);
This is a very bold way of handling it though...
It took me a while, but here's how I made it dynamic. It doesn't depend on a sorted table.
First I started with a column of state names (Column A) and a column of aircraft in each state (Column B). (Row 1 is a header row).
Finding the cell that contains the number of aircraft was:
=MATCH(MAX($B$2:$B$54),$B$2:$B$54,0)+MIN(ROW($B$2:$B$54))-1
I put that into a cell and then gave that cell a name, "StateRow" Then using the tips from above, I wound up with this:
=INDIRECT(ADDRESS(StateRow,1))
This returns the name of the state from the dynamic value in row "StateRow", column 1
Now, as the values in the count column change over time as more data is entered, I always know which state has the most aircraft.
My simple answer.
def get_files_tree(src="src_path"):
req_files = []
for r, d, files in os.walk(src):
for file in files:
src_file = os.path.join(r, file)
src_file = src_file.replace('\\', '/')
if src_file.endswith('.db'):
continue
req_files.append(src_file)
return req_files
def copy_tree_force(src_path="",dest_path=""):
"""
make sure that all the paths has correct slash characters.
"""
for cf in get_files_tree(src=src_path):
df= cf.replace(src_path, dest_path)
if not os.path.exists(os.path.dirname(df)):
os.makedirs(os.path.dirname(df))
shutil.copy2(cf, df)
he does an integer divide, which means 3 / 4 = 0. cast one of the brackets to float
(float)(a.y - b.y) / (a.x - b.x);
You could define controller at the <html>
level.
<html ng-app="app" ng-controller="titleCtrl">
<head>
<title>{{ Page.title() }}</title>
...
You create service: Page
and modify from controllers.
myModule.factory('Page', function() {
var title = 'default';
return {
title: function() { return title; },
setTitle: function(newTitle) { title = newTitle }
};
});
Inject Page
and Call 'Page.setTitle()' from controllers.
Here is the concrete example: http://plnkr.co/edit/0e7T6l
Assuming you can get a Stream, FileStream or MemoryStream for instance, you can do this:
Stream file = [Some Code that Gets you a stream];
var filename = [The name of the file you want to user to download/see];
if (file != null && file.CanRead)
{
context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
context.Response.ContentType = "application/octet-stream";
context.Response.ClearContent();
file.CopyTo(context.Response.OutputStream);
}
Thats a copy and paste from some of my working code, so the content type might not be what youre looking for, but writing the stream to the response is the trick on the last line.
Not with a regular statement, no.
What you can do is wrap the functionality in a PL/pgsql function (or another language, but PL/pgsql seems to be the most appropriate for this), and then just call that function. That means it'll still be a single statement to your app.
Please change small "mm" month to capital "MM" it will work.for reference below is the sample code.
Date myDate = new Date();
SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);
Date dt = sm.parse(strDate);
System.out.println(strDate);
If you want to get rid of all leading and trailing extraneous whitespace then you want to do something like this:
// \\A = Start of input boundary
// \\z = End of input boundary
string = string.replaceAll("\\A\\s+(.*?)\\s+\\z", "$1");
Then you can remove the duplicates using the other strategies listed here:
string = string.replaceAll("\\s+"," ");
ps -ef |grep node find app.js , kill pid of app.js
Refered to the answers given above (I do not have enough reputation to refer separately to individual solutions, hence I do this collectively in this place), I want to supplement them with some important suggestions:
docker-compose you can install from the repository (if you have this package in the repository, if not you can adding to system a repository with this package) or download binary with use curl - totourial on the official website of the project - src: https://docs.docker.com/compose/install /
docker-compose from the repository is in version 1.8.0 (at least at me). This docker-compose version does not support configuration files in version 3. It only has version = <2 support. Inthe official site of the project is a recommendation to use container configuration in version 3 - src: https://docs.docker.com/compose/compose-file / compose-versioning /. From my own experience with work in the docker I recommend using container configurations in version 3 - there are more configuration options to use than in versions <3. If you want to use the configurations configurations in version 3 you have to do update / install docker-compose to the version of at least 1.17 - preferably the latest stable. The official site of the project is toturial how to do this process - src: https://docs.docker.com/compose/install/
when you try to manually remove the old docker-compose binaries, you can have information about the missing file in the default path /usr/local/bin/docker-compose
. At my case, docker-compose was in the default path /usr/bin/docker-compose. In this case, I suggest you use the find tool in your system to find binary file docker-compose - example syntax: sudo find / -name 'docker-compose'
. It helped me. Thanks to this, I removed the old docker-compose version and added the stable to the system - I use the curl tool to download binary file docker-compose, putting it in the right path and giving it the right permissions - all this process has been described in the posts above.
Regards, Adam
Before you can commit and push, you need to init a working repository tree for a submodule. I am using tortoise and do following things:
First check if there exist .git file (not a directory)
If there was .git file, there surly was .git directory which tracks local tree. You still need to a branch (you can create one) or switch to master (which sometimes does not work). Best to do is - git fetch - git pull. Do not omit fetch.
Now your commits and pulls will be synchronized with your origin/master
To avoid this sort of trouble, you can use replace
(which takes a plain string) instead of replaceAll
(which takes a regular expression). You will still need to escape backslashes, but not in the wild ways required with regular expressions.
Try: "\r\n"
Java 7 example:
// append = true
try(PrintWriter output = new PrintWriter(new FileWriter("log.txt",true)))
{
output.printf("%s\r\n", "NEWLINE");
}
catch (Exception e) {}
My requirement was slightly different than the question, still this is also a useful way of stopping the thread to be executing its tasks. All I wanted to do is to stop the thread on exiting the screen and resumes while returning to the screen.
As per the Android docs, this would be the proposed replacement for stop method which has been deprecated from API 15
Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running.
My Thread class
class ThreadClass implements Runnable {
...
@Override
public void run() {
while (count < name.length()) {
if (!exited) // checks boolean
{
// perform your task
}
...
OnStop and OnResume would look like this
@Override
protected void onStop() {
super.onStop();
exited = true;
}
@Override
protected void onResume() {
super.onResume();
exited = false;
}
If you're on Windows and it's not possible to use caching_sha2_password
at all, you can do the following:
The Installer will make all the configuration changes needed for you.
Here's the simplest way that I know of to do this:
final Runnable stuffToDo = new Thread() {
@Override
public void run() {
/* Do stuff here. */
}
};
final ExecutorService executor = Executors.newSingleThreadExecutor();
final Future future = executor.submit(stuffToDo);
executor.shutdown(); // This does not cancel the already-scheduled task.
try {
future.get(5, TimeUnit.MINUTES);
}
catch (InterruptedException ie) {
/* Handle the interruption. Or ignore it. */
}
catch (ExecutionException ee) {
/* Handle the error. Or ignore it. */
}
catch (TimeoutException te) {
/* Handle the timeout. Or ignore it. */
}
if (!executor.isTerminated())
executor.shutdownNow(); // If you want to stop the code that hasn't finished.
Alternatively, you can create a TimeLimitedCodeBlock class to wrap this functionality, and then you can use it wherever you need it as follows:
new TimeLimitedCodeBlock(5, TimeUnit.MINUTES) { @Override public void codeBlock() {
// Do stuff here.
}}.run();
Another possibility would be to use pidof
it usually comes with most distributions. It will return you the PID of a given process by using it's name.
pidof process_name
This way you could store that information in a variable and execute kill -9
on it.
#!/bin/bash
pid=`pidof process_name`
kill -9 $pid
It works for me. Simple variant
public void makeSound(){
File lol = new File("somesound.wav");
try{
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(lol));
clip.start();
} catch (Exception e){
e.printStackTrace();
}
}
I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.
//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
"ln": {c.ln},
"ip": {c.ip},
"ua": {c.ua}})
//okay, moving on...
if err != nil {
//handle postform error
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
//handle read response error
}
fmt.Printf("%s\n", string(body))
The jQuery answer was pretty useful to me. With a little refactory it fitted my needs well. I hope it helps anybody else.
function onReady ( callback ){
var addListener = document.addEventListener || document.attachEvent,
removeListener = document.removeEventListener || document.detachEvent
eventName = document.addEventListener ? "DOMContentLoaded" : "onreadystatechange"
addListener.call(document, eventName, function(){
removeListener( eventName, arguments.callee, false )
callback()
}, false )
}
I developed a noSQL database for storing DOM trees in Web Browsers where references to all DOM elements on page are stored in a short index. Thus function "getElementById()" is not needed to get/modify an element. When elements in DOM tree are instantiated on page the database assigns surrogate primary keys to each element. It is a free tool http://js2dx.com
You cannot type it directly on the browser URL bar.
You can see how POST data is sent on the Internet with Live HTTP Headers for example. Result will be something like that
http://127.0.0.1/pass.php
POST /pass.php HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://127.0.0.1/pass.php
Cookie: passx=87e8af376bc9d9bfec2c7c0193e6af70; PHPSESSID=l9hk7mfh0ppqecg8gialak6gt5
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 30
username=zurfyx&pass=password
Where it says
Content-Length: 30
username=zurfyx&pass=password
will be the post values.
Java documentation is helpful to know the root cause of a particular IOException.
Just have a look at the direct known sub-interfaces of IOException
from the documentation page:
ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException
Most of these exceptions are self-explanatory.
A few IOExceptions
with root causes:
EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.
SocketException: Thrown to indicate that there is an error creating or accessing a Socket.
RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.
UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).
MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
You said you didn't want to do this in AJAX. While AJAX is great for this, there is a way to show one DIV while waiting for the entire <body>
to load. It goes something like this:
<html>
<head>
<style media="screen" type="text/css">
.layer1_class { position: absolute; z-index: 1; top: 100px; left: 0px; visibility: visible; }
.layer2_class { position: absolute; z-index: 2; top: 10px; left: 10px; visibility: hidden }
</style>
<script>
function downLoad(){
if (document.all){
document.all["layer1"].style.visibility="hidden";
document.all["layer2"].style.visibility="visible";
} else if (document.getElementById){
node = document.getElementById("layer1").style.visibility='hidden';
node = document.getElementById("layer2").style.visibility='visible';
}
}
</script>
</head>
<body onload="downLoad()">
<div id="layer1" class="layer1_class">
<table width="100%">
<tr>
<td align="center"><strong><em>Please wait while this page is loading...</em></strong></p></td>
</tr>
</table>
</div>
<div id="layer2" class="layer2_class">
<script type="text/javascript">
alert('Just holding things up here. While you are reading this, the body of the page is not loading and the onload event is being delayed');
</script>
Final content.
</div>
</body>
</html>
The onload event won't fire until all of the page has loaded. So the layer2 <DIV>
won't be displayed until the page has finished loading, after which onload will fire.
You could use RcppRoll
for very quick moving averages written in C++. Just call the roll_mean
function. Docs can be found here.
Otherwise, this (slower) for loop should do the trick:
ma <- function(arr, n=15){
res = arr
for(i in n:length(arr)){
res[i] = mean(arr[(i-n):i])
}
res
}
The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g"
, containing way too many slashes.
Since sed
can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:
replacement="/my/path"
sed --expression "s@pattern@$replacement@"
Note that this is not bullet proof: if the replacement string later contains @
it will break for the same reason, and any backslash sequences like \1
will still be interpreted according to sed
rules. Using |
as a delimiter is also a nice option as it is similar in readability to /
.
If you are using Java 6 or higher you can use wildcards of this form:
java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp
If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:
java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp
There is nothing like lib\*\*
or lib\**
wildcard for the kind of job you want to be done.
If you haven't installed matplotlib yet just try the command.
> pip install matplotlib
import matplotlib.pyplot as plot
plot.hist(weightList,density=1, bins=20)
plot.axis([50, 110, 0, 0.06])
#axis([xmin,xmax,ymin,ymax])
plot.xlabel('Weight')
plot.ylabel('Probability')
plot.show()
When you type x = 0
that is creating a new int
variable (name) and assigning a zero to it.
When you type x[age1]
that is trying to access the age1
'th entry, as if x
were an array.
The yield keyword is used together with the return keyword to provide a value to the enumerator object. yield return specifies the value, or values, returned. When the yield return statement is reached, the current location is stored. Execution is restarted from this location the next time the iterator is called.
To explain the meaning using an example:
public IEnumerable<int> SampleNumbers() { int counter = 0; yield return counter; counter = counter + 2; yield return counter; counter = counter + 3; yield return counter ; }
Values returned when this is iterated are: 0, 2, 5.
It’s important to note that counter variable in this example is a local variable. After the second iteration which returns the value of 2, third iteration starts from where it left before, while preserving the previous value of local variable named counter which was 2.
By executing the following command, it will save a jenkins-ci.org.key file in the current working directory:
curl -O http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key
Then use the following command to add the key file:
apt-key add jenkins-ci.org.key
If the system returns OK, then the key file has been successfully added.
am assuming that you want to know how to format numbers in SSRS
Just right click
the TextBox
on which you want to apply formatting, go to its expression
.
suppose its expression is something like below
=Fields!myField.Value
then do this
=Format(Fields!myField.Value,"##.##")
or
=Format(Fields!myFields.Value,"00.00")
difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00
this should give you an idea.
also: you might have to convert your field into a numerical one. i.e.
=Format(CDbl(Fields!myFields.Value),"00.00")
so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:
UPDATE :
if you want to apply variable formatting on the same column based on row values i.e.
you want myField
to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)
Go to the appropriate textbox and go to its expression and do this:
=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0,
Format(Fields!myField.Value, "##.##"),Fields!myField.Value)
so basically you are using IIF(condition, true,false)
operator of SSRS,
ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.
this should give you an idea, how to handle variable formatting.
In Laravel Version - 4, HTML and Form existed, but not now.
Why:
The only reason is they have collected some user requirements and they want it more lightweight and so they removed it as in the sense that a user can add it manually.
What to do to add HTML & Forms in Laravel 5.2 or 5.3:
For 5.2:
Go to the Laravel Collective site and installation processes have demonstrated their.
Like for 5.2: on the command line, run the command
composer require "laravelcollective/html":"^5.2.0"
Then, in the provider array which is in config/app.php. Add this line at last using a comma(,):
Collective\Html\HtmlServiceProvider::class,
For using HTML and FORM text we need to alias them in the aliases array of config/app.php. Add the two lines at the last
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
And for 5.3:
Just run the command
composer require "laravelcollective/html":"^5.3.0"
And the rest of the procedure is like 5.2.
Then you can use Laravel Form and other HTML links in your projects. For this, follow this documentation:
5.2: https://laravelcollective.com/docs/5.2/html
5.3: https://laravelcollective.com/docs/5.3/html
Demo Code:
To open a form, open and close a tag:
{!! Form::open(['url' => 'foo/bar']) !!}
{!! Form::close() !!}
And for creating label and input text with a Bootstrap form-control class and other use:
{!! Form::label('title', 'Post Title') !!}
{!! Form::text('title', null, array('class' => 'form-control')) !!}
And for more, use the documentation, https://laravelcollective.com/.