Function firstBlankRow() As Long
Dim emptyCells As Boolean
For Each rowinC In Sheet7.Range("A" & currentEmptyRow & ":A5000") ' (row,col)
If rowinC.Value = "" Then
currentEmptyRow = rowinC.row
'firstBlankRow = rowinC.row 'define class variable to simplify computing complexity for other functions i.e. no need to call function again
Exit Function
End If
Next
End Function
I had a similar issue in MVC (which lead me to this problem).
I am receiving a FORM as a string response from a WebClient.UploadValues() request, which I then have to submit - so I can't use a second WebClient or HttpWebRequest. This request returned the string.
using (WebClient client = new WebClient())
{
byte[] response = client.UploadValues(urlToCall, "POST", new NameValueCollection()
{
{ "test", "value123" }
});
result = System.Text.Encoding.UTF8.GetString(response);
}
My solution, which could be used to solve the OP, is to append a Javascript auto submit to the end of the code, and then using @Html.Raw() to render it on a Razor page.
result += "<script>self.document.forms[0].submit()</script>";
someModel.rawHTML = result;
return View(someModel);
Razor Code:
@model SomeModel
@{
Layout = null;
}
@Html.Raw(@Model.rawHTML)
I hope this can help anyone who finds themselves in the same situation.
Short answer for the code in question is:
UPDATE `table` SET test=number
Here table
is the table name and it's surrounded by grave accent (aka back-ticks `) as this is MySQL convention to escape keywords (and TABLE
is a keyword in that case).
BEWARE, that this is pretty dangerous query which will wipe everything in column test
in every row of your table replacing it by the number
(regardless of it's value)
It is more common to use WHERE
clause to limit your query to only specific set of rows:
UPDATE `products` SET `in_stock` = true WHERE `supplier_id` = 10
a = ["A", "B", "C", "B", "A"]
a.detect{ |e| a.count(e) > 1 }
I know this isn't very elegant answer, but I love it. It's beautiful one liner code. And works perfectly fine unless you need to process huge data set.
Looking for faster solution? Here you go!
def find_one_using_hash_map(array)
map = {}
dup = nil
array.each do |v|
map[v] = (map[v] || 0 ) + 1
if map[v] > 1
dup = v
break
end
end
return dup
end
It's linear, O(n), but now needs to manage multiple lines-of-code, needs test cases, etc.
If you need an even faster solution, maybe try C instead.
And here is the gist comparing different solutions: https://gist.github.com/naveed-ahmad/8f0b926ffccf5fbd206a1cc58ce9743e
I recently ran into this problem again. It's been a while since I last worked with submodules and having learned more about git I realized that simply checking out the branch you want to commit on is sufficient. Git will keep the working tree even if you don't stash it.
git checkout existing_branch_name
If you want to work on a new branch this should work for you:
git checkout -b new_branch_name
The checkout will fail if you have conflicts in the working tree, but that should be quite unusual and if it happens you can just stash it, pop it and resolve the conflict.
Compared to the accepted answer, this answer will save you the execution of two commands, that don't really take that long to execute anyway. Therefore I will not accept this answer, unless it miraculously gets more upvotes (or at least close) than the currently accepted answer.
If somebody still gets this page in search results:
fig, ax = plt.subplots()
plt.plot(...)
every_nth = 4
for n, label in enumerate(ax.xaxis.get_ticklabels()):
if n % every_nth != 0:
label.set_visible(False)
As you are aware, everything passed as email message has to be textualized.
<img />
tag is sufficient (the url of the image must be linked to a Source ID).A Typical email example will look like this:
From: foo1atbar.net
To: foo2atbar.net
Subject: A simple example
Mime-Version: 1.0
Content-Type: multipart/related; boundary="boundary-example"; type="text/html"
--boundary-example
Content-Type: text/html; charset="US-ASCII"
... text of the HTML document, which might contain a URI
referencing a resource in another body part, for example
through a statement such as:
<IMG SRC="cid:foo4atfoo1atbar.net" ALT="IETF logo">
--boundary-example
Content-Location: CID:somethingatelse ; this header is disregarded
Content-ID: <foo4atfoo1atbar.net>
Content-Type: IMAGE/GIF
Content-Transfer-Encoding: BASE64
R0lGODlhGAGgAPEAAP/////ZRaCgoAAAACH+PUNv
cHlyaWdodCAoQykgMTk5LiBVbmF1dGhvcml6ZWQgZHV
wbGljYXRpb24gcHJvaGliaXRlZC4A etc...
--boundary-example--
As you can see, the Content-ID: <foo4atfoo1atbar.net>
ID is matched to the <IMG>
at SRC="cid:foo4atfoo1atbar.net"
. That way, the client browser will render your image as a content and not as an attachement.
Hope this helps.
I had the same problem using Phantomjs as browser, so I solved in the following way:
driver.find_element_by_css_selector('div.button.c_button.s_button').click()
Essentially I have added the name of the DIV tag into the quote.
This is my solution, it's not that tricky and allow you to use it for several markup throught a simple ng-class directive. Like so you can choose the class and the scrollPos for each case.
Your App.js :
angular.module('myApp',[])
.controller('mainCtrl',function($window, $scope){
$scope.scrollPos = 0;
$window.onscroll = function(){
$scope.scrollPos = document.body.scrollTop || document.documentElement.scrollTop || 0;
$scope.$apply(); //or simply $scope.$digest();
};
});
Your index.html :
<html ng-app="myApp">
<head></head>
<body>
<section ng-controller="mainCtrl">
<p class="red" ng-class="{fix:scrollPos >= 100}">fix me when scroll is equals to 100</p>
<p class="blue" ng-class="{fix:scrollPos >= 150}">fix me when scroll is equals to 150</p>
</section>
</body>
</html>
working JSFiddle here
EDIT :
As
$apply()
is actually calling$rootScope.$digest()
you can directly use$scope.$digest()
instead of$scope.$apply()
for better performance depending on context.
Long story short :$apply()
will always work but force the$digest
on all scopes that may cause perfomance issue.
There is no way to retrieve localStorage, sessionStorage or cookie values via javascript in the browser after they've been deleted via javascript.
If what you're really asking is if there is some other way (from outside the browser) to recover that data, that's a different question and the answer will entirely depend upon the specific browser and how it implements the storage of each of those types of data.
For example, Firefox stores cookies as individual files. When a cookie is deleted, its file is deleted. That means that the cookie can no longer be accessed via the browser. But, we know that from outside the browser, using system tools, the contents of deleted files can sometimes be retrieved.
If you wanted to look into this further, you'd have to discover how each browser stores each data type on each platform of interest and then explore if that type of storage has any recovery strategy.
For me the easiest way to get it to work, is to put the component.requestFocus();
line, after the setVisible(true);
line, at the bottom of your frame or panel constructor.
This probably has something to do with asking for the focus, after all components have been created, because creating a new component, after asking for the focus request, will make your component loose te focus, and make the focus go to your newly created component. At least, that's what I assume.
Strangely setting a transparent border solved this for me:
@media print {
div {
border: 1px solid rgba(0,0,0,0)
}
}
Maybe it will suffice to set the border on the container element. <- Untestet.
You should read Learn Prolog Now! Chapter 10.2 Using Cut. This provides an example:
max(X,Y,Z) :- X =< Y,!, Y = Z.
to be said,
Z
is equal to Y
IF !
is true (which it always is) AND X
is <= Y
.
The code below will convert any XMLObject or string to a native JavaScript object. Then you can walk on the object to extract any value you want.
/**
* Tries to convert a given XML data to a native JavaScript object by traversing the DOM tree.
* If a string is given, it first tries to create an XMLDomElement from the given string.
*
* @param {XMLDomElement|String} source The XML string or the XMLDomElement prefreably which containts the necessary data for the object.
* @param {Boolean} [includeRoot] Whether the "required" main container node should be a part of the resultant object or not.
* @return {Object} The native JavaScript object which is contructed from the given XML data or false if any error occured.
*/
Object.fromXML = function( source, includeRoot ) {
if( typeof source == 'string' )
{
try
{
if ( window.DOMParser )
source = ( new DOMParser() ).parseFromString( source, "application/xml" );
else if( window.ActiveXObject )
{
var xmlObject = new ActiveXObject( "Microsoft.XMLDOM" );
xmlObject.async = false;
xmlObject.loadXML( source );
source = xmlObject;
xmlObject = undefined;
}
else
throw new Error( "Cannot find an XML parser!" );
}
catch( error )
{
return false;
}
}
var result = {};
if( source.nodeType == 9 )
source = source.firstChild;
if( !includeRoot )
source = source.firstChild;
while( source ) {
if( source.childNodes.length ) {
if( source.tagName in result ) {
if( result[source.tagName].constructor != Array )
result[source.tagName] = [result[source.tagName]];
result[source.tagName].push( Object.fromXML( source ) );
}
else
result[source.tagName] = Object.fromXML( source );
} else if( source.tagName )
result[source.tagName] = source.nodeValue;
else if( !source.nextSibling ) {
if( source.nodeValue.clean() != "" ) {
result = source.nodeValue.clean();
}
}
source = source.nextSibling;
}
return result;
};
String.prototype.clean = function() {
var self = this;
return this.replace(/(\r\n|\n|\r)/gm, "").replace(/^\s+|\s+$/g, "");
}
A rather nice (I think) header file containing macros for most 2x2, 3x3 and 4x4 matrix operations has been available with most OpenGL toolkits. Not as standard but I've seen it at various places.
You can check it out here. At the end of it you will find both inverse of 2x2, 3x3 and 4x4.
Blending mode used to apply the background tint.
Tint to apply to the background. Must be a color value, in the form of
#rgb
,#argb
,#rrggbb
, or#aarrggbb
.This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
Similar to what @nosaiba-darwish said here: here
This is what we usually do in our company:
git clone -b <name_of_branch> --single-branch <git_url> folder_to_clone_locally
Get all radios:
var radios = $("input[type='radio']");
Filter to get the one that's checked
radios.filter(":checked");
OR
Another way you can find radio button value
var RadeoButtonStatusCheck = $('form input[type=radio]:checked').val();
I looked at most the solutions posted, but came across a different one that I prefer. It's simple, doesn't use threads, and works for what I want it to.
http://weblogs.asp.net/kennykerr/archive/2004/11/26/where-is-form-s-loaded-event.aspx
I added to the solution in the article and moved the code into a base class that all my forms inherit from. Now I just call one function: ShowWaitForm() during the frm_load() event of any form that needs a wait dialogue box while the form is loading. Here's the code:
public class MyFormBase : System.Windows.Forms.Form
{
private MyWaitForm _waitForm;
protected void ShowWaitForm(string message)
{
// don't display more than one wait form at a time
if (_waitForm != null && !_waitForm.IsDisposed)
{
return;
}
_waitForm = new MyWaitForm();
_waitForm.SetMessage(message); // "Loading data. Please wait..."
_waitForm.TopMost = true;
_waitForm.StartPosition = FormStartPosition.CenterScreen;
_waitForm.Show();
_waitForm.Refresh();
// force the wait window to display for at least 700ms so it doesn't just flash on the screen
System.Threading.Thread.Sleep(700);
Application.Idle += OnLoaded;
}
private void OnLoaded(object sender, EventArgs e)
{
Application.Idle -= OnLoaded;
_waitForm.Close();
}
}
MyWaitForm is the name of a form you create to look like a wait dialogue. I added a SetMessage() function to customize the text on the wait form.
If your text is:
Joe said, "Fred was here with his "Wife"".
This is saved in a CSV as:
"Joe said, ""Fred was here with his ""Wife""""."
(Rule is double quotes go around the whole field, and double quotes are converted to two double quotes). So a simple Optionally Enclosed By clause is needed but not sufficient. CSVs are tough due to this rule. You can sometimes use a Replace clause in the loader for that field but depending on your data this may not be enough. Often pre-processing of a CSV is needed to load in Oracle. Or save it as an XLS and use Oracle SQL Developer app to import to the table - great for one-time work, not so good for scripting.
Use the raw_input()
function to get input from users (2.x):
print "Enter a file name:",
filename = raw_input()
or just:
filename = raw_input('Enter a file name: ')
or if in Python 3.x:
filename = input('Enter a file name: ')
In user crontab (crontab -e
) do not put the user field.
Correct cron is:
0-59 * * * * echo "Hello World"
Syntax with user field is for /etc/crontab
only:
0-59 * * * * mollerhoj3 echo "Hello World"
all(getattr(someTime,x)==getattr(today(),x) for x in ['year','month','day'])
One should compare using .date()
, but I leave this method as an example in case one wanted to, for example, compare things by month or by minute, etc.
Here's a jquery plugin to do the same: http://s.technabled.com/jquery-foggle
Here's a simple lock mechanism, implemented via closure
const createLock = () => {
let lockStatus = false
const release = () => {
lockStatus = false
}
const acuire = () => {
if (lockStatus == true)
return false
lockStatus = true
return true
}
return {
lockStatus: lockStatus,
acuire: acuire,
release: release,
}
}
lock = createLock() // create a lock
lock.acuire() // acuired a lock
if (lock.acuire()){
console.log("Was able to acuire");
} else {
console.log("Was not to acuire"); // This will execute
}
lock.release() // now the lock is released
if(lock.acuire()){
console.log("Was able to acuire"); // This will execute
} else {
console.log("Was not to acuire");
}
lock.release() // Hey don't forget to release
_x000D_
select left('TEST STRING', len('TEST STRING')-1)
Actually you are using the getLastInsertId or getInsertId in a wrong manner. getLastInsertId() is meant to work only after save() method. It will even not work after a manual insert, as cake engine is storing the mysql_insert_id under $this->_insertID inside the save method which can be retrieved via the getLastInsertId or getInsertId. Now in your case
$this->Model->id
OR
$this->Model->find('first',array('order'=>'id DESC'))
Will do.
If you can edit the class containing that object, I usually just add the annotation
import com.fasterxml.jackson.annotation.JsonIgnore;
@JsonIgnore
NonSerializeableClass obj;
You could use
Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column) Duplicates and blank lines have been removed and the data has been sorted alphabetically.
as indicated above. However, the way I did it because I need to replace the duplicates by blank lines and not just remove the lines, once sorted alphabetically:
REPLACE:
((^.*$)(\n))(?=\k<1>)
by
$3
This will convert:
Shorts
Shorts
Shorts
Shorts
Shorts
Shorts Two Pack
Shorts Two Pack
Signature Braces
Signature Braces
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
to:
Shorts
Shorts Two Pack
Signature Braces
Signature Cotton Trousers
That's how I did it because I specifically needed those lines.
While the accepted answer is very true, just want to point out that AllowTransparency has some downfalls. It does not allow child window controls to show up, ie WebBrowser, and it usually forces software rendering which can have negative performance effects.
There is a better work around though.
When you want to create a window with no border that is resizeable and is able to host a WebBrowser control or a Frame control pointed to a URL you simply couldn't, the contents of said control would show empty.
I found a workaround though; in the Window, if you set the WindowStyle to None, ResizeMode to NoResize (bear with me, you will still be able to resize once done) then make sure you have UNCHECKED AllowsTransparency you will have a static sized window with no border and will show the browser control.
Now, you probably still want to be able to resize right? Well we can to that with a interop call:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
//Attach this to the MouseDown event of your drag control to move the window in place of the title bar
private void WindowDrag(object sender, MouseButtonEventArgs e) // MouseDown
{
ReleaseCapture();
SendMessage(new WindowInteropHelper(this).Handle,
0xA1, (IntPtr)0x2, (IntPtr)0);
}
//Attach this to the PreviewMousLeftButtonDown event of the grip control in the lower right corner of the form to resize the window
private void WindowResize(object sender, MouseButtonEventArgs e) //PreviewMousLeftButtonDown
{
HwndSource hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
SendMessage(hwndSource.Handle, 0x112, (IntPtr)61448, IntPtr.Zero);
}
And voila, A WPF window with no border and still movable and resizable without losing compatibility with with controls like WebBrowser
I like JSON mainly because it's so terse. For web content that can be gzipped, this isn't necessarily a big deal (hence why xhtml is so popular). But there are occasions where this can be beneficial.
For example, for one project I was transmitting information that needed to be serialized and transmitted via XMPP. Since most servers will limit the amount of data you can transmit in a single message, I found it helpful to use JSON over the obvious alternative, XML.
As an added bonus, if you're familiar with Python or Javascript, you already pretty much know JSON and can interpret it without much training at all.
You can also get BLOB object directly from XMLHttpRequest. Setting responseType to blob makes the trick. Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/image.jpg");
xhr.responseType = "blob";
xhr.onload = response;
xhr.send();
And the response function looks like this:
function response(e) {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
document.querySelector("#image").src = imageUrl;
}
We just have to make an empty image element in HTML:
<img id="image"/>
You can use font-size
property for option if you need.
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
https://perldoc.perl.org/perlre.html#Quoting-metacharacters and https://perldoc.perl.org/functions/quotemeta.html
In the official documentation, such characters are called metacharacters. Example of quoting:
my $regex = quotemeta($string)
s/$regex/something/
First we generate a cdf[x] which is
The probability that a point is less than distance x from the centre of the circle. Assume the circle has a radius of R.
obviously if x is zero then cdf[0] = 0
obviously if x is R then the cdf[R] = 1
obviously if x = r then the cdf[r] = (Pi r^2)/(Pi R^2)
This is because each "small area" on the circle has the same probability of being picked, So the probability is proportionally to the area in question. And the area given a distance x from the centre of the circle is Pi r^2
so cdf[x] = x^2/R^2 because the Pi cancel each other out
we have cdf[x]=x^2/R^2 where x goes from 0 to R
So we solve for x
R^2 cdf[x] = x^2
x = R Sqrt[ cdf[x] ]
We can now replace cdf with a random number from 0 to 1
x = R Sqrt[ RandomReal[{0,1}] ]
Finally
r = R Sqrt[ RandomReal[{0,1}] ];
theta = 360 deg * RandomReal[{0,1}];
{r,theta}
we get the polar coordinates {0.601168 R, 311.915 deg}
You can use replace
instead of gsub
.
"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a relative import rather than an absolute import. The '..' means, go to the directory above me:
from ..Common import Common
As a caveat, this will only work if you run your python as a module, from outside of the package. For example:
python -m Proj
This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users.
You can add Common/ to your sys.path (the list of paths python looks at to import things):
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))
import Common
os.path.dirname(__file__)
just gives you the directory that your current python file is in, and then we navigate to 'Common/' the directory and import 'Common' the module.
Prefixing with 'r'
works very well, but it needs to be in the correct syntax. For example:
passwordFile = open(r'''C:\Users\Bob\SecretPasswordFile.txt''')
No need for \\
here - maintains readability and works well.
The iPython shell makes this easy: function?
will give you the documentation. function??
shows also the code. BUT this only works for pure python functions.
Then you can always download the source code for the (c)Python.
If you're interested in pythonic implementations of core functionality have a look at PyPy source.
There are rules that determine whether a browser will accept the Set-header response header (server-side cookie writing), a slightly different rules/interpretations for cookie set using Javascript (I haven't tested VBScript).
Then there are rules that determine whether the browser will send a cookie along with the page request.
There are differences between the major browser engines how domain matches are handled, and how parameters in path values are interpreted. You can find some empirical evidence in the article How Different Browsers Handle Cookies Differently
In Swift3:
let fileUrl = Foundation.URL(string: filePath)
(In the diagrams and text below, PC
is the address of the branch instruction itself. PC+4
is the end of the branch instruction itself, and the start of the branch delay slot. Except in the absolute jump diagram.)
In MIPS branch instruction has only 16 bits offset to determine next instruction. We need a register added to this 16 bit value to determine next instruction and this register is actually implied by architecture. It is PC register since PC gets updated (PC+4) during the fetch cycle so that it holds the address of the next instruction.
We also limit the branch distance to -2^15 to +2^15 - 1
instruction from the (instruction after the) branch instruction. However, this is not real issue since most branches are local anyway.
So step by step :
For Jump instruction MIPS has only 26 bits to determine Jump location. Jumps are relative to PC in MIPS. Like branch, immediate jump value needs to be word-aligned; therefore, we need to multiply 26 bit address with four.
Again step by step:
In other words, replace the lower 28 bits of the PC + 4 with the lower 26 bits of the fetched instruction shifted left by 2 bits.
Jumps are region-relative to the branch-delay slot, not necessarily the branch itself. In the diagram above, PC has already advanced to the branch delay slot before the jump calculation. (In a classic-RISC 5 stage pipeline, the BD was fetched in the same cycle the jump is decoded, so that PC+4 next instruction address is already available for jumps as well as branches, and calculating relative to the jump's own address would have required extra work to save that address.)
Source: Bilkent University CS 224 Course Slides
Manually switching system-default version without 3rd party tools:
As detailed in this older answer, on macOS /usr/bin/java
is a wrapper tool that will use Java version pointed by JAVA_HOME
or if that variable is not set will look for Java installations under /Library/Java/JavaVirtualMachines/
and will use the one with highest version. It determines versions by looking at Contents/Info.plist
under each package.
Armed with this knowledge you can:
Info.plist
in versions you don't want to use as default (that file is not used by the actual Java runtime itself).$JAVA_HOME
I've just verified this is still true with OpenJDK & Mojave.
On a brand new system, there is no Java version installed:
$ java -version
No Java runtime present, requesting install.
Cancel this, download OpenJDK 11 & 12ea on https://jdk.java.net ; install OpenJDK11:
$ cd /Library/Java/JavaVirtualMachines/
$ sudo tar xzf ~/Downloads/openjdk-11.0.1_osx-x64_bin.tar.gz
System java is now 11:
$ java -version
openjdk version "11.0.1" 2018-10-16
[...]
Install OpenJDK12 (early access at the moment):
$ sudo tar xzf ~/Downloads/openjdk-12-ea+17_osx-x64_bin.tar.gz
System java is now 12:
$ java -version
openjdk version "12-ea" 2019-03-19
[...]
Now let's "hide" OpenJDK 12 from system java wrapper:
$ cd jdk-12.jdk/Contents/
$ sudo mv Info.plist Info.plist.disabled
System java is back to 11:
$ java -version
openjdk version "11.0.1" 2018-10-16
[...]
And you can still use version 12 punctually by manually setting JAVA_HOME
:
$ export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
$ java -version
openjdk version "12-ea" 2019-03-19
[...]
DECLARE @ADate Date, @ATime Time, @ADateTime Datetime
SELECT @ADate = '2010-02-20', @ATime = '18:53:00.0000000'
SET @ADateTime = CAST (
CONVERT(Varchar(10), @ADate, 112) + ' ' +
CONVERT(Varchar(8), @ATime) AS DateTime)
SELECT @ADateTime [A nice datetime :)]
This will render you a valid result.
Although I would suggest the Apache approach is better, SVN Serve works fine and is pretty straightforward.
Assuming your repository is called "my_repo", and it is stored in C:\svn_repos:
Create a file called "passwd" in "C:\svn_repos\my_repo\conf". This file should look like:
[Users]
username = password
john = johns_password
steve = steves_password
In C:\svn_repos\my_repo\conf\svnserve.conf set:
[general]
password-db = passwd
auth-access=read
auth-access=write
This will force users to log in to read or write to this repository.
Follow these steps for each repository, only including the appropriate users in the passwd
file for each repository.
Update using NuGet Package Manager
Console in your Visual Studio
Update-Package -reinstall Microsoft.AspNet.Mvc
By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers:
old 1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new 1: insert into customers (customer_name) values ('Marks Ltd')
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks Ltd
If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off
to switch off the behaviour while running the script:
SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd
You might want to add set define on
at the end of the script to restore the default behaviour.
A bit late, but you can easily find a string with this query
DECLARE
@search_string VARCHAR(100),
@table_name SYSNAME,
@table_id INT,
@column_name SYSNAME,
@sql_string VARCHAR(2000)
SET @search_string = 'StringtoSearch'
DECLARE tables_cur CURSOR FOR SELECT ss.name +'.'+ so.name [name], object_id FROM sys.objects so INNER JOIN sys.schemas ss ON so.schema_id = ss.schema_id WHERE type = 'U'
OPEN tables_cur
FETCH NEXT FROM tables_cur INTO @table_name, @table_id
WHILE (@@FETCH_STATUS = 0)
BEGIN
DECLARE columns_cur CURSOR FOR SELECT name FROM sys.columns WHERE object_id = @table_id
AND system_type_id IN (167, 175, 231, 239)
OPEN columns_cur
FETCH NEXT FROM columns_cur INTO @column_name
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @sql_string = 'IF EXISTS (SELECT * FROM ' + @table_name + ' WHERE [' + @column_name + ']
LIKE ''%' + @search_string + '%'') PRINT ''' + @table_name + ', ' + @column_name + ''''
EXECUTE(@sql_string)
FETCH NEXT FROM columns_cur INTO @column_name
END
CLOSE columns_cur
DEALLOCATE columns_cur
FETCH NEXT FROM tables_cur INTO @table_name, @table_id
END
CLOSE tables_cur
DEALLOCATE tables_cur
Yes, but don't - escaping forward slashes is a good thing. When using JSON inside <script>
tags it's necessary as a </script>
anywhere - even inside a string - will end the script tag.
Depending on where the JSON is used it's not necessary, but it can be safely ignored.
If you are editing HTML in Notepad you should use "Save As" and alter the default "Encoding:" selection at the botom of the dialog to UTF-8. you should also include-
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
_x000D_
This un-ambiguously sets the correct character set and informs the browser.
Currently (June 2016) typing in the link as http://www.example.com will only produce plain text.
You can now however put in an html anchor :
<a href="http://www.example.com">My Example Site</a>
In command line it's better to use REG tool rather than REGEDIT:
REG IMPORT yourfile.reg
REG is designed for console mode, while REGEDIT is for graphical mode. This is why running regedit.exe /S yourfile.reg is a bad idea, since you will not be notified if the there's an error, whereas REG Tool will prompt:
> REG IMPORT missing_file.reg
ERROR: Error opening the file. There may be a disk or file system error.
> %windir%\System32\reg.exe /?
REG Operation [Parameter List]
Operation [ QUERY | ADD | DELETE | COPY |
SAVE | LOAD | UNLOAD | RESTORE |
COMPARE | EXPORT | IMPORT | FLAGS ]
Return Code: (Except for REG COMPARE)
0 - Successful
1 - Failed
For help on a specific operation type:
REG Operation /?
Examples:
REG QUERY /?
REG ADD /?
REG DELETE /?
REG COPY /?
REG SAVE /?
REG RESTORE /?
REG LOAD /?
REG UNLOAD /?
REG COMPARE /?
REG EXPORT /?
REG IMPORT /?
REG FLAGS /?
Use the operator sizeof
, it will give you the size of a type expressed in byte. One byte is eight bits. See the following program:
#include <iostream>
int main(int,char**)
{
std::cout << "unsigned long long " << sizeof(unsigned long long) << "\n";
std::cout << "unsigned long long int " << sizeof(unsigned long long int) << "\n";
return 0;
}
I would apply this rule to all input fields of type text, so it doesn't need to be duplicated later:
input[type=text]::-ms-clear { display: none; }
One can even get less specific by using just:
::-ms-clear { display: none; }
I have used the later even before adding this answer, but thought that most people would prefer to be more specific than that. Both solutions work fine.
Another thing to check is if you have LogicalName or ManifestResourceName defined on the EmbeddedResource. Make sure those are defined appropriately if your project file is using them as they can cause the resources to live under a name you are not expecting.
can you try something like this. You have to put each json in the data not json[i], because in the way you are doing it you are getting and putting only the properties of each json. Put the whole json instead in the data
var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
console.log("\n The details of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);
my_json = feed;
console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
data.push(my_json);
});
JOIN t2 ON t1.id=t2.id AND t1.date=t2.date
Try to use:
unlink('.'.Storage::url($news->photo));
Look the dot and concatenation before the call of facade Storage.
change your
return @str1+'present in the string' ;
to
set @r = @str1+'present in the string'
Hash tables deal with collisions in one of two ways.
Option 1: By having each bucket contain a linked list of elements that are hashed to that bucket. This is why a bad hash function can make lookups in hash tables very slow.
Option 2: If the hash table entries are all full then the hash table can increase the number of buckets that it has and then redistribute all the elements in the table. The hash function returns an integer and the hash table has to take the result of the hash function and mod it against the size of the table that way it can be sure it will get to bucket. So by increasing the size, it will rehash and run the modulo calculations which if you are lucky might send the objects to different buckets.
Java uses both option 1 and 2 in its hash table implementations.
def randchar(a, b):
return chr(random.randint(ord(a), ord(b)))
I think you just need to set the db to single user mode before attempting to restore, like below, just make sure you're using master
USE master
GO
ALTER DATABASE AdventureWorksDW
SET SINGLE_USER
I needed a way to do this in an AJAX return, so I wrote this piece:
<p id="num_results">Number of results: <span></span></p>
<div id="results"></div>
<script type="text/javascript">
$(function(){
ajax();
})
//Function that makes Ajax call out to receive search results
var ajax = function() {
//Setup Ajax
$.ajax({
url: '/path/to/url', //URL to load
type: 'GET', //Type of Ajax call
dataType: 'html', //Type of data to be expected on return
success: function(data) { //Function that manipulates the returned AJAX'ed data
$('#results').html(data); //Load the data into a HTML holder
var $el = $('#results'); //jQuery Object that is holding the results
setTimeout(function(){ //Custom callback function to count the number of results
callBack($el);
});
}
});
}
//Custom Callback function to return the number of results
var callBack = function(el) {
var length = $('tr', $(el)).not('tr:first').length; //Count all TR DOM elements, except the first row (which contains the header information)
$('#num_results span').text(length); //Write the counted results to the DOM
}
</script>
Obviously this is a quick example, but it may be helpful.
Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:
Option Explicit
Dim StdIn: Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript
Main()
Sub Main()
Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false
Do until objInputFile.AtEndOfStream
tmpStr = objInputFile.ReadLine
If foundStrMatch(tmpStr)=true Then
If foundFirstMatch = false Then
index = getIndex(tmpStr)
foundFirstMatch = true
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
If index = getIndex(tmpStr) Then
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
ElseIf index < getIndex(tmpStr) Then
index = getIndex(tmpStr)
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
Else
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub
Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function
Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
getIndex = CInt(char1 & char2)
Else
getIndex = CInt(char1)
End If
End Function
Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
foundStrMatch = true
Else
foundStrMatch = false
End If
End Function
This is the original txt file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
And this is the result I'm expecting
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
Hadley has been developing a package called forcats
. This package makes the task so much easier. You can exploit fct_infreq()
when you want to change the order of x-axis by the frequency of a factor. In the case of the mtcars
example in this post, you want to reorder levels of cyl
by the frequency of each level. The level which appears most frequently stays on the left side. All you need is the fct_infreq()
.
library(ggplot2)
library(forcats)
ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
geom_bar() +
labs(x = "cyl")
If you wanna go the other way around, you can use fct_rev()
along with fct_infreq()
.
ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
geom_bar() +
labs(x = "cyl")
Create a linked server to the source server. The easiest way is to right click "Linked Servers" in Management Studio; it's under Management -> Server Objects.
Then you can copy the table using a 4-part name, server.database.schema.table
:
select *
into DbName.dbo.NewTable
from LinkedServer.DbName.dbo.OldTable
This will both create the new table with the same structure as the original one and copy the data over.
I find that the OS Utils from Swingx does the job.
If you are not so keen on having to decorate code with Attributes as I am, esp when you cant tell at compile time what will happen here is my solution.
Using the Javascript Serializer
public static class JsonSerializerExtensions
{
public static string ToJsonString(this object target,bool ignoreNulls = true)
{
var javaScriptSerializer = new JavaScriptSerializer();
if(ignoreNulls)
{
javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(target.GetType(), true) });
}
return javaScriptSerializer.Serialize(target);
}
public static string ToJsonString(this object target, Dictionary<Type, List<string>> ignore, bool ignoreNulls = true)
{
var javaScriptSerializer = new JavaScriptSerializer();
foreach (var key in ignore.Keys)
{
javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(key, ignore[key], ignoreNulls) });
}
return javaScriptSerializer.Serialize(target);
}
}
public class PropertyExclusionConverter : JavaScriptConverter
{
private readonly List<string> propertiesToIgnore;
private readonly Type type;
private readonly bool ignoreNulls;
public PropertyExclusionConverter(Type type, List<string> propertiesToIgnore, bool ignoreNulls)
{
this.ignoreNulls = ignoreNulls;
this.type = type;
this.propertiesToIgnore = propertiesToIgnore ?? new List<string>();
}
public PropertyExclusionConverter(Type type, bool ignoreNulls)
: this(type, null, ignoreNulls){}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { this.type })); }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var result = new Dictionary<string, object>();
if (obj == null)
{
return result;
}
var properties = obj.GetType().GetProperties();
foreach (var propertyInfo in properties)
{
if (!this.propertiesToIgnore.Contains(propertyInfo.Name))
{
if(this.ignoreNulls && propertyInfo.GetValue(obj, null) == null)
{
continue;
}
result.Add(propertyInfo.Name, propertyInfo.GetValue(obj, null));
}
}
return result;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException(); //Converter is currently only used for ignoring properties on serialization
}
}
You can do it like this:
$str = "abc-123-xyz-789";
$arr = explode('-', $str);
$last = array_pop( $arr );
echo $last; //echoes 789
itertools.combinations is in general the fastest way to get combinations from a Python container (if you do in fact want combinations, i.e., arrangements WITHOUT repetitions and independent of order; that's not what your code appears to be doing, but I can't tell whether that's because your code is buggy or because you're using the wrong terminology).
If you want something different than combinations perhaps other iterators in itertools, product
or permutations
, might serve you better. For example, it looks like your code is roughly the same as:
for val in itertools.product(np.arange(0, 1, 0.1), repeat=6):
print F(val)
All of these iterators yield tuples, not lists or numpy arrays, so if your F is picky about getting specifically a numpy array you'll have to accept the extra overhead of constructing or clearing and re-filling one at each step.
A rewrite of the answer by Sarfraz would be something like this, I think:
<script>
document.getElementById('change').onclick = changeColor;
function changeColor() {
document.body.style.color = "purple";
return false;
}
</script>
You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );
Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc();
the function would actually execute when the handler is being set.
And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)
I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).
A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.
Do like this:
create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;
I am a fan of Cmder, a package including clink, conemu, msysgit, and some cosmetic enhancements.
https://github.com/cmderdev/cmder
var matches = [];
$(".className:checked").each(function() {
matches.push(this.value);
});
For Next button you can use xpath or cssSelector as below:
xpath for Next button: //input[@value='Next']
cssPath for Next button: input[value=Next]
You can write your query like so:
SELECT * FROM MyTable WHERE (A LIKE '%text1%' OR A LIKE '%text2%')
The %
is a wildcard, meaning that it searches for all rows where column A contains either text1 or text2
Since version 3.2 :
def toSigned(n, byte_count):
return int.from_bytes(n.to_bytes(byte_count, 'little'), 'little', signed=True)
output :
In [8]: toSigned(5, 1)
Out[8]: 5
In [9]: toSigned(0xff, 1)
Out[9]: -1
N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):
N[i]/2
will be a float64
but range()
expects an integer. Just cast the call to
for j in range(int(N[i]/2)):
Extract the package to C:\ from here and install it
Copy the path C:\MinGW\bin
which contains gcc.exe.
go to Control Panel->System->Advanced>Environment variables
, and add or modify PATH. (just concatenate with ';')
Then, open a cmd.exe command prompt
(Windows + R and type cmd, if already opened, please close and open a new one, to get the path change)
change the folder to your file path by cd D:\c code Path
type gcc main.c -o helloworld.o
. It will compile the code. for C++ use g++
7 type ./helloworld
to run the program.
If zlib1.dll is missing, download from here
There are various Inline
elements that can help you, for the simplest formatting options you can use Bold
, Italic
and Underline
:
<TextBlock>
Sample text with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> words.
</TextBlock>
I think it is worth noting, that those elements are in fact just shorthands for Span
elements with various properties set (i.e.: for Bold
, the FontWeight
property is set to FontWeights.Bold
).
This brings us to our next option: the aforementioned Span
element.
You can achieve the same effects with this element as above, but you are granted even more possibilities; you can set (among others) the Foreground
or the Background
properties:
<TextBlock>
Sample text with <Span FontWeight="Bold">bold</Span>, <Span FontStyle="Italic">italic</Span> and <Span TextDecorations="Underline">underlined</Span> words. <Span Foreground="Blue">Coloring</Span> <Span Foreground="Red">is</Span> <Span Background="Cyan">also</Span> <Span Foreground="Silver">possible</Span>.
</TextBlock>
The Span
element may also contain other elements like this:
<TextBlock>
<Span FontStyle="Italic">Italic <Span Background="Yellow">text</Span> with some <Span Foreground="Blue">coloring</Span>.</Span>
</TextBlock>
There is another element, which is quite similar to Span
, it is called Run
. The Run
cannot contain other inline elements while the Span
can, but you can easily bind a variable to the Run
's Text
property:
<TextBlock>
Username: <Run FontWeight="Bold" Text="{Binding UserName}"/>
</TextBlock>
Also, you can do the whole formatting from code-behind if you prefer:
TextBlock tb = new TextBlock();
tb.Inlines.Add("Sample text with ");
tb.Inlines.Add(new Run("bold") { FontWeight = FontWeights.Bold });
tb.Inlines.Add(", ");
tb.Inlines.Add(new Run("italic ") { FontStyle = FontStyles.Italic });
tb.Inlines.Add("and ");
tb.Inlines.Add(new Run("underlined") { TextDecorations = TextDecorations.Underline });
tb.Inlines.Add("words.");
If you want this environment variable available to all users and on system start then you can add the following to /etc/profile.d/java.sh (create it if necessary):
export JDK_HOME=/usr/lib/jvm/java-7-oracle
export JAVA_HOME=/usr/lib/jvm/java-7-oracle
Then in a terminal run:
sudo chmod +x /etc/profile.d/java.sh
source /etc/profile.d/java.sh
My second question is - should it point to java-6-sun or java-6-sun-1.6.0.24 ?
It should always point to java-7-oracle
as that symlinks to the latest installed one (assuming you installed Java from the Ubuntu repositories and now from the download available at oracle.com).
Decoding is redundant
You only had this "error" in the first place, because of a misunderstanding of what's happening.
You get the b
because you encoded to utf-8
and now it's a bytes object.
>> type("text".encode("utf-8"))
>> <class 'bytes'>
Fixes:
If you just want to apply a function to each element and put the results in an output array, you can use arrayfun
.
As others have pointed out, for most operations, it's best to avoid loops in MATLAB and vectorise your code instead.
An example usage:
>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world
The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.
This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray
:
>>> s = bytearray(1000000) # a million zeroed bytes
>>> t = buffer(s, 1) # slice cuts off the first byte
>>> s[1] = 5 # set the second element in s
>>> t[0] # which is now also the first element in t!
'\x05'
This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.
Note that buffer
has been replaced by the better named memoryview
in Python 3, though you can use either in Python 2.7.
Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.
If you're using Selenium with Firefox you should be able to use EXSLT extensions, and regexp:test()
Does this work for you?
String expr = "//*[regexp:test(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));
In answer the question heading (found by a google search) and not the re-question To stop the line breaking when you have different heading tags e.g.
<h5 style="display:inline;"> What the... </h5><h1 style="display:inline;"> heck is going on? </h1>
Will give you:
What the...heck is going on?
and not
What the...
heck is going on?
It's also possible to specify the ForeignKey()
attribute on the navigation property:
[ForeignKey("HomeTeamID")]
public virtual Team HomeTeam { get; set; }
[ForeignKey("GuestTeamID")]
public virtual Team GuestTeam { get; set; }
That way you don't need to add any code to the OnModelCreate
method
This is why I recently wrote to accomplish this. I know this has already been answered but I'm leaving this for later uses.
This method only allows 0-9 both keyboard and numpad, backspaces, tab, left and right arrows (normal form operations)
$(".numbersonly-format").keydown(function (event) {
// Prevent shift key since its not needed
if (event.shiftKey == true) {
event.preventDefault();
}
// Allow Only: keyboard 0-9, numpad 0-9, backspace, tab, left arrow, right arrow, delete
if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46) {
// Allow normal operation
} else {
// Prevent the rest
event.preventDefault();
}
});
U can try routines in c time library (time.h). Plus take a look at the clock() in the same lib. It gives the clock ticks since the prog has started. But you can save its value before the operation you want to concentrate on, and then after that operation capture the cliock ticks again and find the difference between then to get the time difference.
I had the same problem when my plugin was depending on another project, which exported some packages in its manifest file. Instead of changing access rules, I have managed to solve the problem by adding the required packages into its Export-Package section. This makes the packages legally visible. Eclipse actually provides this fix on the "Access restriction" error marker.
I've always assumed this was necessary as the output from the mapper is the input for the reducer, so it was sorted based on the keyspace and then split into buckets for each reducer input. You want to ensure all the same values of a Key end up in the same bucket going to the reducer so they are reduced together. There is no point sending K1,V2 and K1,V4 to different reducers as they need to be together in order to be reduced.
Tried explaining it as simply as possible
Possible alternatives
js-floating-table-headers
js-floating-table-headers (Google Code)
In Drupal
I have a Drupal 6 site. I was on the admin "modules" page, and noticed the tables had this exact feature!
Looking at the code, it seems to be implemented by a file called tableheader.js
. It applies the feature on all tables with the class sticky-enabled
.
For a Drupal site, I'd like to be able to make use of that tableheader.js
module as-is for user content. tableheader.js
doesn't seem to be present on user content pages in Drupal. I posted a forum message to ask how to modify the Drupal theme so it's available. According to a response, tableheader.js
can be added to a Drupal theme using drupal_add_js()
in the theme's template.php
as follows:
drupal_add_js('misc/tableheader.js', 'core');
If you used [STAThread]
to the main entry of your application and still get the error you may need to make a Thread-Safe call to the control... something like below. In my case with the same problem the following solution worked!
Private void YourFunc(..)
{
if (this.InvokeRequired)
{
Invoke(new MethodInvoker(delegate()
{
// Call your method YourFunc(..);
}));
}
else
{
///
}
You should only need to unbind the service in onDestroy()
. Then, The warning will go.
See here.
As the Activity doc tries to explain, there are three main bind/unbind groupings you will use: onCreate() and onDestroy(), onStart() and onStop(), and onResume() and onPause().
I suspect the problem is the slashes in the format string versus the ones in the data. That's a culture-sensitive date separator character in the format string, and the final argument being null
means "use the current culture". If you either escape the slashes ("M'/'d'/'yyyy") or you specify CultureInfo.InvariantCulture
, it will be okay.
If anyone's interested in reproducing this:
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M'/'d'/'yyyy",
new CultureInfo("de-DE"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("en-US"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
CultureInfo.InvariantCulture);
// Fails
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("de-DE"));
another approach:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
var a = addCommas(10000.00);
alert(a);
Another amazing plugin: http://www.teamdf.com/web/jquery-number-format/178/
I was getting this error after deploying on IIS Server PC.
https://www.microsoft.com/en-us/download/details.aspx?id=42295enter link description here
https://www.microsoft.com/en-us/download/details.aspx?id=45496
It may require restart your computer.
I simply declared as below in web.xml file and Its working for me :
<welcome-file-list>
<welcome-file>/WEB-INF/jsps/index.jsp</welcome-file>
</welcome-file-list>
And NO html/jsp pages present in public directory except static resources(css, js, images). Now I can access my index page with URL like : http://localhost:8080/app/ Its calling /WEB-INF/jsps/index.jsp page. When hosted live in production the final URL looks like https://eisdigital.com/
First a disclaimer beforehand: the posted code snippets are all basic examples. You'll need to handle trivial IOException
s and RuntimeException
s like NullPointerException
, ArrayIndexOutOfBoundsException
and consorts yourself.
We first need to know at least the URL and the charset. The parameters are optional and depend on the functional requirements.
String url = "http://example.com";
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String param1 = "value1";
String param2 = "value2";
// ...
String query = String.format("param1=%s¶m2=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
The query parameters must be in name=value
format and be concatenated by &
. You would normally also URL-encode the query parameters with the specified charset using URLEncoder#encode()
.
The String#format()
is just for convenience. I prefer it when I would need the String concatenation operator +
more than twice.
It's a trivial task. It's the default request method.
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...
Any query string should be concatenated to the URL using ?
. The Accept-Charset
header may hint the server what encoding the parameters are in. If you don't send any query string, then you can leave the Accept-Charset
header away. If you don't need to set any headers, then you can even use the URL#openStream()
shortcut method.
InputStream response = new URL(url).openStream();
// ...
Either way, if the other side is an HttpServlet
, then its doGet()
method will be called and the parameters will be available by HttpServletRequest#getParameter()
.
For testing purposes, you can print the response body to stdout as below:
try (Scanner scanner = new Scanner(response)) {
String responseBody = scanner.useDelimiter("\\A").next();
System.out.println(responseBody);
}
Setting the URLConnection#setDoOutput()
to true
implicitly sets the request method to POST. The standard HTTP POST as web forms do is of type application/x-www-form-urlencoded
wherein the query string is written to the request body.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
InputStream response = connection.getInputStream();
// ...
Note: whenever you'd like to submit a HTML form programmatically, don't forget to take the name=value
pairs of any <input type="hidden">
elements into the query string and of course also the name=value
pair of the <input type="submit">
element which you'd like to "press" programmatically (because that's usually been used in the server side to distinguish if a button was pressed and if so, which one).
You can also cast the obtained URLConnection
to HttpURLConnection
and use its HttpURLConnection#setRequestMethod()
instead. But if you're trying to use the connection for output you still need to set URLConnection#setDoOutput()
to true
.
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("POST");
// ...
Either way, if the other side is an HttpServlet
, then its doPost()
method will be called and the parameters will be available by HttpServletRequest#getParameter()
.
You can fire the HTTP request explicitly with URLConnection#connect()
, but the request will automatically be fired on demand when you want to get any information about the HTTP response, such as the response body using URLConnection#getInputStream()
and so on. The above examples does exactly that, so the connect()
call is in fact superfluous.
You need an HttpURLConnection
here. Cast it first if necessary.
int status = httpConnection.getResponseCode();
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
When the Content-Type
contains a charset
parameter, then the response body is likely text based and we'd like to process the response body with the server-side specified character encoding then.
String contentType = connection.getHeaderField("Content-Type");
String charset = null;
for (String param : contentType.replace(" ", "").split(";")) {
if (param.startsWith("charset=")) {
charset = param.split("=", 2)[1];
break;
}
}
if (charset != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
for (String line; (line = reader.readLine()) != null;) {
// ... System.out.println(line) ?
}
}
} else {
// It's likely binary content, use InputStream/OutputStream.
}
The server side session is usually backed by a cookie. Some web forms require that you're logged in and/or are tracked by a session. You can use the CookieHandler
API to maintain cookies. You need to prepare a CookieManager
with a CookiePolicy
of ACCEPT_ALL
before sending all HTTP requests.
// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
Note that this is known to not always work properly in all circumstances. If it fails for you, then best is to manually gather and set the cookie headers. You basically need to grab all Set-Cookie
headers from the response of the login or the first GET
request and then pass this through the subsequent requests.
// Gather all cookies on the first request.
URLConnection connection = new URL(url).openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
// ...
// Then use the same cookies on all subsequent requests.
connection = new URL(url).openConnection();
for (String cookie : cookies) {
connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
// ...
The split(";", 2)[0]
is there to get rid of cookie attributes which are irrelevant for the server side like expires
, path
, etc. Alternatively, you could also use cookie.substring(0, cookie.indexOf(';'))
instead of split()
.
The HttpURLConnection
will by default buffer the entire request body before actually sending it, regardless of whether you've set a fixed content length yourself using connection.setRequestProperty("Content-Length", contentLength);
. This may cause OutOfMemoryException
s whenever you concurrently send large POST requests (e.g. uploading files). To avoid this, you would like to set the HttpURLConnection#setFixedLengthStreamingMode()
.
httpConnection.setFixedLengthStreamingMode(contentLength);
But if the content length is really not known beforehand, then you can make use of chunked streaming mode by setting the HttpURLConnection#setChunkedStreamingMode()
accordingly. This will set the HTTP Transfer-Encoding
header to chunked
which will force the request body being sent in chunks. The below example will send the body in chunks of 1KB.
httpConnection.setChunkedStreamingMode(1024);
It can happen that a request returns an unexpected response, while it works fine with a real web browser. The server side is probably blocking requests based on the User-Agent
request header. The URLConnection
will by default set it to Java/1.6.0_19
where the last part is obviously the JRE version. You can override this as follows:
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7.
Use the User-Agent string from a recent browser.
If the HTTP response code is 4nn
(Client Error) or 5nn
(Server Error), then you may want to read the HttpURLConnection#getErrorStream()
to see if the server has sent any useful error information.
InputStream error = ((HttpURLConnection) connection).getErrorStream();
If the HTTP response code is -1, then something went wrong with connection and response handling. The HttpURLConnection
implementation is in older JREs somewhat buggy with keeping connections alive. You may want to turn it off by setting the http.keepAlive
system property to false
. You can do this programmatically in the beginning of your application by:
System.setProperty("http.keepAlive", "false");
You'd normally use multipart/form-data
encoding for mixed POST content (binary and character data). The encoding is in more detail described in RFC2388.
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send normal param.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
// Send text file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
writer.append(CRLF).flush();
Files.copy(textFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// Send binary file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
}
If the other side is an HttpServlet
, then its doPost()
method will be called and the parts will be available by HttpServletRequest#getPart()
(note, thus not getParameter()
and so on!). The getPart()
method is however relatively new, it's introduced in Servlet 3.0 (Glassfish 3, Tomcat 7, etc). Prior to Servlet 3.0, your best choice is using Apache Commons FileUpload to parse a multipart/form-data
request. Also see this answer for examples of both the FileUpload and the Servelt 3.0 approaches.
Sometimes you need to connect an HTTPS URL, perhaps because you're writing a web scraper. In that case, you may likely face a javax.net.ssl.SSLException: Not trusted server certificate
on some HTTPS sites who doesn't keep their SSL certificates up to date, or a java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found
or javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name
on some misconfigured HTTPS sites.
The following one-time-run static
initializer in your web scraper class should make HttpsURLConnection
more lenient as to those HTTPS sites and thus not throw those exceptions anymore.
static {
TrustManager[] trustAllCertificates = new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null; // Not relevant.
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// Do nothing. Just allow them all.
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// Do nothing. Just allow them all.
}
}
};
HostnameVerifier trustAllHostnames = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true; // Just allow them all.
}
};
try {
System.setProperty("jsse.enableSNIExtension", "false");
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCertificates, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
}
catch (GeneralSecurityException e) {
throw new ExceptionInInitializerError(e);
}
}
The Apache HttpComponents HttpClient is much more convenient in this all :)
If all you want is parsing and extracting data from HTML, then better use a HTML parser like Jsoup
Here is how to see the visual diff between whole commits, as opposed to single files, in Visual Studio (tested in VS 2017). Unfortunately, it works only for commits within one branch: In the "Team Explorer", choose the "Branches" view, right-click on the repo, and choose "View history" as in the following image.
Then the history of the current branch appears in the main area. (Where branches that ended as earlier commits on the current branch are marked by labels.) Now select a couple of commits with Ctrl-Left, then right click and select "Compare Commits..." from the pop-up menu.
For more on comparing branches in the Microsoft world, see this stackoverflow question: Differences between git branches using Visual Studio.
Try this one:
$('body').tooltip({
selector: '[rel=tooltip]'
});
Register your element.
var vr = document.registerElement('v-r'); // vertical rule please, yes!
*The -
is mandatory in all custom elements.
v-r {
height: 100%;
width: 1px;
border-left: 1px solid gray;
/*display: inline-block;*/
/*margin: 0 auto;*/
}
*You might need to fiddle a bit with display:inline-block|inline
because inline
won't expand to containing element's height. Use the margin to center the line within a container.
js: document.body.appendChild(new vr());
or
HTML: <v-r></v-r>
*Unfortunately you can't create custom self-closing tags.
<h1>THIS<v-r></v-r>WORKS</h1>
example: http://html5.qry.me/vertical-rule
Simply apply this CSS class to your designated element.
.vr {
height: 100%;
width: 1px;
border-left: 1px solid gray;
/*display: inline-block;*/
/*margin: 0 auto;*/
}
*See notes above.
Use "$@"
(works for all POSIX compatibles).
[...] , bash features the "$@" variable, which expands to all command-line parameters separated by spaces.
From Bash by example.
In IntelliJ IDEA this is an open bug: https://youtrack.jetbrains.com/issue/IDEA-252823
As a workaround, you can change the build tools version as other people advise.
My project was failing with this dependency:
com.android.tools.build:gradle:7.0.0-alpha03
Now it's working with this:
com.android.tools.build:gradle:4.0.2
As a side note, you should change that dependency in build.gradle
in some projects or in dependencies.kt
in newer projects.
That was the most updated version that worked.
Here is what worked for me:
render() {
const { styleValue } = this.props;
const dynamicStyleUpdatedFromProps = {
height: styleValue,
width: styleValue,
borderRadius: styleValue,
}
return (
<View style={{ ...styles.staticStyleCreatedFromStyleSheet, ...dynamicStyleUpdatedFromProps }} />
);
}
For some reason, this was the only way that mine would update properly.
Simply single line of code:
self.tblViewMessages.scrollToRow(at: IndexPath.init(row: arrayChat.count-1, section: 0), at: .bottom, animated: isAnimeted)
You can do it calling setRowSelectionInterval :
table.setRowSelectionInterval(0, 0);
to select the first row.
If you want to benchmark, you can use os.clock as shown by the doc:
local x = os.clock()
local s = 0
for i=1,100000 do s = s + i end
print(string.format("elapsed time: %.2f\n", os.clock() - x))
When you run the code
listoflists.append((list, list[0]))
You are not (as I think you expect) adding a copy of list
to the end of listoflists
. What you are doing is adding a reference to list
to the end of listoflists
. Thus, every time you update list
, it updates every reference to list
, which in this case, is every item in listoflists
What you could do instead is something like this:
listoflists = []
for i in range(1, 10):
listoflists.append((range(i), 0))
You can make the entire DIV function as a link by adding an onclick="window.location='TARGET URL'" and by setting its style to "cursor:pointer". But it's often a bad idea to do this because search engines won't be able to follow the resulting link, readers won't be able to open in tabs or copy the link location, etc. Instead, you can create a regular anchor tag and then set its style to display:block , and then style this as you would a DIV.
Have you tried mode 'a+'?
with open(filename, 'a+') as f:
f.write(...)
Note however that f.tell()
will return 0 in Python 2.x. See https://bugs.python.org/issue22651 for details.
The initial width of a block level element like div or p is auto.
Use width:auto to undo explicitly specified widths.
if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border.
So, next time you find yourself setting the width of a block level element to 100% to make it occupy all available width, consider if what you really want is setting it to auto.
I had the same problem. In my case, even though I have not understood why, the problem was due to &
in one of the elements like the following where a
and b
are two tokens/words:
<s> . . . a & b . . . </s>
and to resolve the issue I turned my element's text to the following:
<s> . . . a and b . . . </s>
I thought it might be the case for some of you. Generally, to make your life easier, just go and read the character at the index mentioned in the error message (line:..., col:...)
and see what the character is.
Install it using NuGet:
Install-Package Newtonsoft.Json
Posting this as an answer.
Actually, it is possible to create a branch in your fork from any commit of the upstream in the browser:
https://github.com/<repo>/commits/<hash>
, where repo is your fork, and hash is full hash of commit which you can find in the upstream web interface. For example, I can open https://github.com/max630/linux/commits/0aa0313f9d576affd7747cc3f179feb097d28990, which points to linux
master
as time of writing.You can then fetch that branch to your local clone, and you won't have to push all that data back to GitHub when you push edits on top of that commit. Or use the web interface to change something in that branch.
How it works (it is a guess, I don't know how exactly GitHub does it): forks share object storage and use namespaces to separate users' references. So you can access all commits through your fork, even if they did not exist by the time of forking.
The java.lang.SecurityException
you are seeing is because you may enter two entries pointing to the same activity. Remove the second one and you should be good to go.
You may be declared the activity 2 times in the manifest with different properties, like :
<activity android:name=".myclass"> </activity>
and
<activity android:name=".myclass" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You should remove the unwanted one from the manifest
There are other differences. For instance, {'time': datetime.now()}
cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
The -m
option is probably what you're looking for:
grep -m 10 PATTERN [FILE]
From man grep
:
-m NUM, --max-count=NUM
Stop reading a file after NUM matching lines. If the input is
standard input from a regular file, and NUM matching lines are
output, grep ensures that the standard input is positioned to
just after the last matching line before exiting, regardless of
the presence of trailing context lines. This enables a calling
process to resume a search.
Note: grep stops reading the file once the specified number of matches have been found!
Just give full path to exclusion file: eg..
-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt
In this example the file would be located " C:\list-of-excluded-files.txt "
or...
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt
In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "
Full path fixes syntax error.
As specified in oracle official tutorial , it states that:
If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
If I have an Application interacting with database using JDBC
, And I have a method that takes the argument as the int item
and double price
. The price
for corresponding item is read from database table. I simply multiply the total number of item
purchased with the price
value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG
in your database. So , and IllegalArguementException()
should be thrown in this case which would state that the price can't be negative
.
I hope that I have expressed my point clearly..
Following on from the answer by @karask, you could wrap the function as a helper like so:
public static bool HasProperty(ExpandoObject expandoObj,
string name)
{
return ((IDictionary<string, object>)expandoObj).ContainsKey(name);
}
I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:
Properties configProps = new Properties();
InputStream iStream = new ClassPathResource("myapp-test.properties").getInputStream();
InputStream iStream = getConfigFile();
configProps.load(iStream);
To check if browser is Google Chrome, try this:
// please note,
// that IE11 now returns undefined again for window.chrome
// and new Opera 30 outputs true for window.chrome
// but needs to check if window.opr is not undefined
// and new IE Edge outputs to true now for window.chrome
// and if not iOS Chrome check
// so use the below updated condition
var isChromium = window.chrome;
var winNav = window.navigator;
var vendorName = winNav.vendor;
var isOpera = typeof window.opr !== "undefined";
var isIEedge = winNav.userAgent.indexOf("Edge") > -1;
var isIOSChrome = winNav.userAgent.match("CriOS");
if (isIOSChrome) {
// is Google Chrome on IOS
} else if(
isChromium !== null &&
typeof isChromium !== "undefined" &&
vendorName === "Google Inc." &&
isOpera === false &&
isIEedge === false
) {
// is Google Chrome
} else {
// not Google Chrome
}
Example of use: http://codepen.io/jonathan/pen/WpQELR
The reason this works is because if you use the Google Chrome inspector and go to the console tab. Type 'window' and press enter. Then you be able to view the DOM properties for the 'window object'. When you collapse the object you can view all the properties, including the 'chrome' property.
You can't use strictly equals true anymore to check in IE for window.chrome
. IE used to return undefined
, now it returns true
. But guess what, IE11 now returns undefined again. IE11 also returns a empty string ""
for window.navigator.vendor
.
I hope this helps!
UPDATE:
Thank you to Halcyon991 for pointing out below, that the new Opera 18+ also outputs to true for window.chrome
. Looks like Opera 18 is based on Chromium 31. So I added a check to make sure the window.navigator.vendor
is: "Google Inc"
and not is "Opera Software ASA"
. Also thanks to Ring and Adrien Be for the heads up about Chrome 33 not returning true anymore... window.chrome
now checks if not null. But play close attention to IE11, I added the check back for undefined
since IE11 now outputs undefined
, like it did when first released.. then after some update builds it outputted to true
.. now recent update build is outputting undefined
again. Microsoft can't make up it's mind!
UPDATE 7/24/2015 - addition for Opera check
Opera 30 was just released. It no longer outputs window.opera
. And also window.chrome
outputs to true in the new Opera 30. So you must check if OPR is in the userAgent. I updated my condition above to account for this new change in Opera 30, since it uses same render engine as Google Chrome.
UPDATE 10/13/2015 - addition for IE check
Added check for IE Edge due to it outputting true
for window.chrome
.. even though IE11 outputs undefined
for window.chrome
. Thanks to artfulhacker for letting us know about this!
UPDATE 2/5/2016 - addition for iOS Chrome check
Added check for iOS Chrome check CriOS
due to it outputting true
for Chrome on iOS. Thanks to xinthose for letting us know about this!
UPDATE 4/18/2018 - change for Opera check
Edited check for Opera, checking window.opr
is not undefined
since now Chrome 66 has OPR
in window.navigator.vendor
. Thanks to Frosty Z and Daniel Wallman for reporting this!
Also make sure you have all @Before
-, @After
- and whatever-JUnit-annotated methods declared as public
. I had mine declared as private
which caused the issue.
A sub class is a small file of a program that extends from some other class. For example you make a class about cars in general and have basic information that holds true for all cars with your constructors and stuff then you have a class that extends from that on a more specific car or line of cars that would have new variables/methods. I see you already have plenty of examples of code from above by the time I get to post this but I hope this description helps.
Using Visual Studio
This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).
Using Process Explorer
If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)
Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.
Programmatically
Check this SO question that explains how to do it.
Yes, many changes at Heroku. If you're using a Heroku dyno for your webserver, you have to find way to alias from one DNS
name to another DNS
name (since each Heroku DNS endpoint may resolve to many IP addrs to dynamically adjust to request loads).
A CNAME
record is for aliasing www.example.com
-> www.example.com.herokudns.com.
You can't use CNAME
for a naked domain (@
), i.e. example.com
(unless you find a name server that can do CNAME Flattening
- which is what I did).
But really the easiest solution, that can pretty much be taken care of all in your GoDaddy account, is to create a CNAME record
that does this: www.example.com -> www.example.com.herokudns.com
.
And then create a permanent 301 redirect from example.com
to www.example.com
.
This requires only one heroku custom domain name configured in your heroku app settings: www.example.com.herokudns.com
. @Jonathan Roy talks about this (above) but provides a bad link.
your programs syntax, or for that matter many other things such as natural languages can be parsed using binary tree (though not necessarily).
In the "Window" menu, open "Open Perspective" -> "Debug".
click On the plus image icon(you see the below image at status bar), and then select "Logcat"....
Allocate maximum memory to your docker machine from (docker preference -> advance )
Screenshot of advance settings:
This will set the maximum limit docker consume while running containers. Now run your image in new container with -m=4g flag for 4 gigs ram or more. e.g.
docker run -m=4g {imageID}
Remember to apply the ram limit increase changes. Restart the docker and double check that ram limit did increased. This can be one of the factor you not see the ram limit increase in docker containers.
When a JSON start's with {} it is a ObjectJSON object and when it start's with [] it is an Array JOSN Array
An JSON array can consist of a/many objects and that is called an array of objects
Adapted from this answer:
function scroll(y, duration) {
var initialY = document.documentElement.scrollTop || document.body.scrollTop;
var baseY = (initialY + y) * 0.5;
var difference = initialY - baseY;
var startTime = performance.now();
function step() {
var normalizedTime = (performance.now() - startTime) / duration;
if (normalizedTime > 1) normalizedTime = 1;
window.scrollTo(0, baseY + difference * Math.cos(normalizedTime * Math.PI));
if (normalizedTime < 1) window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
This should allow you to smoothly scroll (cosine function) from anywhere to the specified "y".
The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.
See Python Idioms and Anti-Idioms (for Python 2 or Python 3) for more.
Open a Terminal window and navigate to your project directory. Run these sets of commands, depending on which compiler you have installed:
To compile multiple C++ files using clang++:
$ clang++ *.cpp
$ ./a.out
To compile multiple C++ files using g++:
$ g++ -c *.cpp
$ g++ -o temp.exe *.o
$ ./temp.exe
You may use two options:
Create Element is the fastest way (check here.):
$(document.createElement('table'));
InnerHTML is another popular approach:
$("#foo").append("<div>hello world</div>"); // Check similar for table too.
Check a real example on How to create a new table with rows using jQuery and wrap it inside div.
There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.
Check Dynamic creation of table with DOM
IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:
function createProviderFormFields(id, labelText, tooltip, regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
if you have class with id and you want to filter by id
line1 : you mape all the id
line2: filter what is not exist in the map
Set<String> mapId = entityResponse.getEntities().stream().map(Entity::getId).collect(Collectors.toSet());
List<String> entityNotExist = entityValues.stream().filter(n -> !mapId.contains(n.getId())).map(DTOEntity::getId).collect(Collectors.toList());
pip install keyboard
import keyboard
while True:
# do something
if keyboard.is_pressed("q"):
print("q pressed, ending loop")
break
$(document).ready(function() {
$(".tab").click(function () {
if(!$(this).hasClass('active'))
{
$(".tab.active").removeClass("active");
$(this).addClass("active");
}
});
});
It`s work for me! I hope it will be useful to you!
public static RichTextBox RichTextBoxChangeWordColor(ref RichTextBox rtb, string startWord, string endWord, Color color)
{
rtb.SuspendLayout();
Point scroll = rtb.AutoScrollOffset;
int slct = rtb.SelectionIndent;
int ss = rtb.SelectionStart;
List<Point> ls = GetAllWordsIndecesBetween(rtb.Text, startWord, endWord, true);
foreach (var item in ls)
{
rtb.SelectionStart = item.X;
rtb.SelectionLength = item.Y - item.X;
rtb.SelectionColor = color;
}
rtb.SelectionStart = ss;
rtb.SelectionIndent = slct;
rtb.AutoScrollOffset = scroll;
rtb.ResumeLayout(true);
return rtb;
}
public static List<Point> GetAllWordsIndecesBetween(string intoText, string fromThis, string toThis,bool withSigns = true)
{
List<Point> result = new List<Point>();
Stack<int> stack = new Stack<int>();
bool start = false;
for (int i = 0; i < intoText.Length; i++)
{
string ssubstr = intoText.Substring(i);
if (ssubstr.StartsWith(fromThis) && ((fromThis == toThis && !start) || !ssubstr.StartsWith(toThis)))
{
if (!withSigns) i += fromThis.Length;
start = true;
stack.Push(i);
}
else if (ssubstr.StartsWith(toThis) )
{
if (withSigns) i += toThis.Length;
start = false;
if (stack.Count > 0)
{
int startindex = stack.Pop();
result.Add(new Point(startindex,i));
}
}
}
return result;
}
Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.
the code of @Umair Afzal working fine in swift 5 after some changes
extension UIView {
func fadeIn(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in }) {
self.alpha = 0.0
UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.isHidden = false
self.alpha = 1.0
}, completion: completion)
}
func fadeOut(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping (Bool) -> Void = {(finished: Bool) -> Void in }) {
self.alpha = 1.0
UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.alpha = 0.0
}) { (completed) in
self.isHidden = true
completion(true)
}
}
}
for use
yourView.fadeOut()
yourView.fadeIn()
Below worked for me. Please do a slight change to make this fast
function isEmpty(obj) {
if (!obj) return true;
if (typeof obj == 'number') return false;
else if (typeof obj == 'string') return obj.length == 0;
else if (Array.isArray(obj)) return obj.length == 0;
else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
else if (typeof obj == 'boolean') return false;
}
Put your .netbeans Homefolder into a Ramdisk and Netbeans its going to be incredible fast.
I detected on my Ubuntu 16.04 that every Key-Press causes a HDD read or write action. Reason enougth for me to use a Ramdisk. As a little positive side-effect my HDD is quite now (no tickclickrrickrrrticktick any more) and has a longer live.
From version 0.8.0, dplyr
offers a handy function called group_split()
:
# On sample data from @Aus_10
df %>%
group_split(g)
[[1]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 2.04 0.627 A
2 0.530 -0.703 A
3 -0.475 0.541 A
4 1.20 -0.565 A
5 -0.380 -0.126 A
6 1.25 -1.69 A
7 -0.153 -1.02 A
8 1.52 -0.520 A
9 0.905 -0.976 A
10 0.517 -0.535 A
# … with 15 more rows
[[2]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 1.61 0.858 B
2 1.05 -1.25 B
3 -0.440 -0.506 B
4 -1.17 1.81 B
5 1.47 -1.60 B
6 -0.682 -0.726 B
7 -2.21 0.282 B
8 -0.499 0.591 B
9 0.711 -1.21 B
10 0.705 0.960 B
# … with 15 more rows
To not include the grouping column:
df %>%
group_split(g, keep = FALSE)
As mentioned by @pinouchon you can pass it with the help of array index
my_array[0] value
my_array[1] value
In addition to this, to pass list of hashes, you can follow something like:
my_array[0][key1] value1
my_array[0][key2] value2
Example:
To pass param1=[{name:test_name, value:test_value}, {...}]
param1[0][name] test_name
param1[0][value] test_value
Preventing a crash caused by the caller sending in an invalid pointer is a good way to make silent bugs that are hard to find.
Isn't it better for the programmer using your API to get a clear message that his code is bogus by crashing it rather than hiding it?
If you are using hadoop 2.* API there are more elegant solutions:
Configuration conf = getConf();
Job job = Job.getInstance(conf);
FileSystem fs = FileSystem.get(conf);
//the second boolean parameter here sets the recursion to true
RemoteIterator<LocatedFileStatus> fileStatusListIterator = fs.listFiles(
new Path("path/to/lib"), true);
while(fileStatusListIterator.hasNext()){
LocatedFileStatus fileStatus = fileStatusListIterator.next();
//do stuff with the file like ...
job.addFileToClassPath(fileStatus.getPath());
}
You can use code like this
The filter is empty string. The filename is AnyName but not blank
openFileDialog.FileName = "AnyFile";
openFileDialog.Filter = string.Empty;
openFileDialog.CheckFileExists = false;
openFileDialog.CheckPathExists = false;
Even once you fixed the mis-cased if
and improper indentation in your code, it wouldn't work as you probably expected. To check a string against a set of strings, use in
. Here's how you'd do it (and note that if
is all lowercase and that the code within the if
block is indented one level).
One approach:
if answer in ['y', 'Y', 'yes', 'Yes', 'YES']:
print("this will do the calculation")
Another:
if answer.lower() in ['y', 'yes']:
print("this will do the calculation")
Compatible with common modern browers (IE 8+): http://jsfiddle.net/m5Xz2/3/
.lineContainer {_x000D_
display:table;_x000D_
border-collapse:collapse;_x000D_
width:100%;_x000D_
}_x000D_
.lineContainer div {_x000D_
display:table-cell;_x000D_
border:1px solid black;_x000D_
height:10px;_x000D_
}_x000D_
.left {_x000D_
width:100px;_x000D_
}
_x000D_
<div class="lineContainer">_x000D_
<div class="left">left</div>_x000D_
<div class="right">right</div>_x000D_
</div>
_x000D_
As already mentioned in comments to the first answer, the return std::move(...);
construct can make a difference in cases other than returning of local variables. Here's a runnable example that documents what happens when you return a member object with and without std::move()
:
#include <iostream>
#include <utility>
struct A {
A() = default;
A(const A&) { std::cout << "A copied\n"; }
A(A&&) { std::cout << "A moved\n"; }
};
class B {
A a;
public:
operator A() const & { std::cout << "B C-value: "; return a; }
operator A() & { std::cout << "B L-value: "; return a; }
operator A() && { std::cout << "B R-value: "; return a; }
};
class C {
A a;
public:
operator A() const & { std::cout << "C C-value: "; return std::move(a); }
operator A() & { std::cout << "C L-value: "; return std::move(a); }
operator A() && { std::cout << "C R-value: "; return std::move(a); }
};
int main() {
// Non-constant L-values
B b;
C c;
A{b}; // B L-value: A copied
A{c}; // C L-value: A moved
// R-values
A{B{}}; // B R-value: A copied
A{C{}}; // C R-value: A moved
// Constant L-values
const B bc;
const C cc;
A{bc}; // B C-value: A copied
A{cc}; // C C-value: A copied
return 0;
}
Presumably, return std::move(some_member);
only makes sense if you actually want to move the particular class member, e.g. in a case where class C
represents short-lived adapter objects with the sole purpose of creating instances of struct A
.
Notice how struct A
always gets copied out of class B
, even when the class B
object is an R-value. This is because the compiler has no way to tell that class B
's instance of struct A
won't be used any more. In class C
, the compiler does have this information from std::move()
, which is why struct A
gets moved, unless the instance of class C
is constant.
Let me recommend you using Selenide library. It allows writing much more concise and readable tests. It can wait for presence of elements with much shorter syntax:
$("#elementId").shouldBe(visible);
Here is a sample project for testing Google search: https://github.com/selenide-examples/google
Buffer contains metadata which helps improve write performance
Cache contains the file content itself (sometimes yet to write to disk) which improves read performance
It is possible of course, use -l:
instead of -l
. For example -l:libXYZ.a
to link with libXYZ.a
. Notice the lib
written out, as opposed to -lXYZ
which would auto expand to libXYZ
.
Try this:
<video src="{{ asset('path/to/your_video.mp4' )}}" muted autoplay loop playsinline></video>
And put this js
after that:
window.addEventListener('load', async () => {
let video = document.querySelector('video[muted][autoplay]');
try {
await video.play();
} catch (err) {
video.controls = true;
}
});
You need to provide a body for the get;
portion as well as the set;
portion of the property.
I suspect you want this to be:
private int _hour; // backing field
private int Hour
{
get { return _hour; }
set
{
//make sure hour is positive
if (value < MIN_HOUR)
{
_hour = 0;
MessageBox.Show("Hour value " + value.ToString() + " cannot be negative. Reset to " + MIN_HOUR.ToString(),
"Invalid Hour", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
//take the modulus to ensure always less than 24 hours
//works even if the value is already within range, or value equal to 24
_hour = value % MAX_HOUR;
}
}
}
That being said, I'd also consider making this code simpler. It's probably is better to use exceptions rather than a MessageBox inside of your property setter for invalid input, as it won't tie you to a specific UI framework.
If that is inappropriate, I would recommend converting this to a method instead of using a property setter. This is especially true since properties have an implicit expectation of being "lightweight"- and displaying a MessageBox to the user really violates that expectation.
Fetch both the key and the value from the dictionary in the loop:
{% for key, value in mydict.items %}
{{ value }}
{% endfor %}
I find this easier to read and it avoids the need for special coding. I usually need the key and the value inside the loop anyway.
You can use eval(jsonString) if you trust the data in the string, otherwise you'll need to parse it properly - check json.org for some code samples.
You can regroup your steps functions calls in a facade function :
sub facade()
call step1()
call step2()
call step3()
call step4()
call step5()
end sub
Then, let your error handling be in an upper function that calls the facade :
sub main()
On error resume next
call facade()
If Err.Number <> 0 Then
' MsgBox or whatever. You may want to display or log your error there
msgbox Err.Description
Err.Clear
End If
On Error Goto 0
end sub
Now, let's suppose step3()
raises an error. Since facade()
doesn't handle errors (there is no On error resume next
in facade()
), the error will be returned to main()
and step4()
and step5()
won't be executed.
Your error handling is now refactored in 1 code block
List<WebElement>itemNames = wd.findElements(By.cssSelector("a strong"));
System.out.println("No items in Catalog page: " + itemNames.size());
for (WebElement itemName:itemNames)
{
System.out.println(itemName.getText());
}
I translated the sample from Michael Borgwardt. This is the result:
public static bool NearlyEqual(float a, float b, float epsilon){
float absA = Math.Abs (a);
float absB = Math.Abs (b);
float diff = Math.Abs (a - b);
if (a == b) {
return true;
} else if (a == 0 || b == 0 || diff < float.Epsilon) {
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < epsilon;
} else { // use relative error
return diff / (absA + absB) < epsilon;
}
}
Feel free to improve this answer.
I have this method for deserializing an XML and converting the type:
public <T> Object deserialize(String xml, Class objClass ,TypeReference<T> typeReference ) throws IOException {
XmlMapper xmlMapper = new XmlMapper();
Object obj = xmlMapper.readValue(xml,objClass);
return xmlMapper.convertValue(obj,typeReference );
}
and this is the call:
List<POJO> pojos = (List<POJO>) MyUtilClass.deserialize(xml, ArrayList.class,new TypeReference< List< POJO >>(){ });
I have been able to use a method like this with some success:
WebElement getStaleElemById(String id) {
try {
return driver.findElement(By.id(id));
} catch (StaleElementReferenceException e) {
System.out.println("Attempting to recover from StaleElementReferenceException ...");
return getStaleElemById(id);
}
}
Yes, it just keeps polling the element until it's no longer considered stale (fresh?). Doesn't really get to the root of the problem, but I've found that the WebDriver can be rather picky about throwing this exception -- sometimes I get it, and sometimes I don't. Or it could be that the DOM really is changing.
So I don't quite agree with the answer above that this necessarily indicates a poorly-written test. I've got it on fresh pages which I have not interacted with in any way. I think there is some flakiness in either how the DOM is represented, or in what WebDriver considers to be stale.
This is the most common issue faced by Windows users for running Docker Containers. IMO this is the "million dollar question on Docker"; @"Rocco Smit" has rightly pointed out "inbound traffic for it was disabled by default on my host machine's firewall"; in my case, my McAfee Anti Virus software. I added additional ports to be allowed for inbound traffic from other computers on the same Wifi LAN in the Firewall Settings of McAfee; then it was magic. I had struggled for more than a week browsing all over internet, SO, Docker documentations, Tutorials after Tutorials related to the Networking of Docker, and the many illustrations of "not supported on Windows" for "macvlan", "ipvlan", "user defined bridge" and even this same SO thread couple of times. I even started browsing google with "anybody using Docker in Production?", (yes I know Linux is more popular for Prod workloads compared to Windows servers) as I was not able to access (from my mobile in the same Home wifi) an nginx app deployed in Docker Container on Windows. After all, what good it is, if you cannot access the application (deployed on a Docker Container) from other computers / devices in the same LAN at-least; Ultimately in my case, the issue was just with a firewall blocking inbound traffic;
I found that using the XFBML version of the Facebook like button instead of the HTML5 version fixed this problem. Add the below code where you want the button to appear:
<div id="fb-root"></div>
<script>(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<fb:like send="true" layout="button_count" width="50" show_faces="false" font="arial"></fb:like>
Then add this to your HTML tag:
xmlns:fb="http://ogp.me/ns/fb#"
Solution given by Shashi's link is the best... no needs to contact dba or someone else
make a backup
create table xxxx_backup as select * from xxxx;
delete all rows
delete from xxxx;
commit;
insert your backup.
insert into xxxx (select * from xxxx_backup);
commit;
You cannot truncate a datetime object because it is immutable.
However, here is one way to construct a new datetime with 0 hour, minute, second, and microsecond fields, without throwing away the original date or tzinfo:
newdatetime = now.replace(hour=0, minute=0, second=0, microsecond=0)
My team use Gradle and Nexus OSS 3.5.2,
I have found a solution: upload artyfacts from locakhost (I checked Nexus documentation and did not found anything about uploading artifacts from folders) => I have shared directory (use Apache httpd) and connected one to created new Nexus proxy repository. Now when I want to add my own artifacts I can upload ones into shared directory in my remote server.
Maybe someone find my solution useful:
My question is here: Is it possible to deploy artifacts from local folder in Sonatype Nexus Repository Manager 3.x
Please try this:
CREATE TABLE article (
article_id bigint(20) NOT NULL serial,
article_name varchar(20) NOT NULL,
article_desc text NOT NULL,
date_added datetime default NULL,
PRIMARY KEY (article_id)
);
Here is a function that I have in my PowerShell profile for loading SQL snapins:
function Load-SQL-Server-Snap-Ins
{
try
{
$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"
if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
{
throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
}
$item = Get-ItemProperty $sqlpsreg
$sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
$assemblyList = @(
"Microsoft.SqlServer.Smo",
"Microsoft.SqlServer.SmoExtended",
"Microsoft.SqlServer.Dmf",
"Microsoft.SqlServer.WmiEnum",
"Microsoft.SqlServer.SqlWmiManagement",
"Microsoft.SqlServer.ConnectionInfo ",
"Microsoft.SqlServer.Management.RegisteredServers",
"Microsoft.SqlServer.Management.Sdk.Sfc",
"Microsoft.SqlServer.SqlEnum",
"Microsoft.SqlServer.RegSvrEnum",
"Microsoft.SqlServer.ServiceBrokerEnum",
"Microsoft.SqlServer.ConnectionInfoExtended",
"Microsoft.SqlServer.Management.Collector",
"Microsoft.SqlServer.Management.CollectorEnum"
)
foreach ($assembly in $assemblyList)
{
$assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly)
if ($assembly -eq $null)
{ Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
}
Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000
Push-Location
if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null)
{
cd $sqlpsPath
Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
Update-TypeData -PrependPath SQLProvider.Types.ps1xml
Update-FormatData -PrependPath SQLProvider.Format.ps1xml
}
}
catch
{
Write-Host "`t`t$($MyInvocation.InvocationName): $_"
}
finally
{
Pop-Location
}
}
You can do this to only monitor own properties of the object:
var arr = [];
for (var key in p) {
if (p.hasOwnProperty(key)) {
arr.push(p[key]);
}
}
In Ruby IO module documentation, I suppose.
Mode | Meaning
-----+--------------------------------------------------------
"r" | Read-only, starts at beginning of file (default mode).
-----+--------------------------------------------------------
"r+" | Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w" | Write-only, truncates existing file
| to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" | Read-write, truncates existing file to zero length
| or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a" | Write-only, starts at end of file if file exists,
| otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" | Read-write, starts at end of file if file exists,
| otherwise creates a new file for reading and
| writing.
-----+--------------------------------------------------------
"b" | Binary file mode (may appear with
| any of the key letters listed above).
| Suppresses EOL <-> CRLF conversion on Windows. And
| sets external encoding to ASCII-8BIT unless explicitly
| specified.
-----+--------------------------------------------------------
"t" | Text file mode (may appear with
| any of the key letters listed above except "b").
Open your project in Android Studio
Click on res
Right click on drawable
Click on Show in Explorer
Double click on drawable
folder.
Copy your image file in it and rename as your wish.
Now write your image file name after @drawable/
.
It will show the image you've selected.
Here's another one-liner
( echo 0 ; sed 's/$/ +/' foo ; echo p ) | dc
This assumes the numbers are integers. If you need decimals, try
( echo 0 2k ; sed 's/$/ +/' foo ; echo p ) | dc
Adjust 2 to the number of decimals needed.
// pages/about.js
import Link from 'next/link'
export default ({ url: { query: { name } } }) => (
<p>Welcome to About! { name }</p>
)
_x000D_
Summarized: Oracle under Windows has problems with usernames containing non-English letters or special characters:
If your machine is fresh installed, first look here. All the network related or 32 vs. 64 related issues may be not significant for you:
As others already pointed out partly, this error is highly related to the name of the TEMP dir. It occurred to me when installing Oracle 11g first time on a totally fresh Windows (e.g. Server 2008 R2 or Win 7, not important).
As I found out, on my machine the problem was, that the username contained a German special character ("ö"). Moreover Oracle cannot handle any special character, I assume, the TEMP path is limited to letters. Other colleagues here have reported problems with underscore and chinese characters.
Explanation: In Windows the TEMP dir (environment variable %TEMP%) is by default in the user directory, for example:
C:\Users\ThisUser\AppData\Local\Temp
If "ThisUser" contains special or non-ASCII characters, then in this case this affects the TEMP path, and that is where Oracle is gettings problems.
Setting the TEMP dir to different directory is of course another possibility instead of installing with another username.
Moreover, Oracle is not a fully native Windows citizen which everybody will recognize, if he opens the Oracle install logfile with notepad ;-) Obviously, this is not programmed cleanly and portable, e.g. with using "std::endl" instead of "\n" . (Yes, Notepad++ and other editors do the job.)
Overall, my impression is, if the database were of the same quality as it's installer, Oracle would not be so successful ..
Last remark: Yes, after failed install because of the special characters you see only one Oracle service named OracleRemExecService, but there is no reason to stop this manually as recommended in other solutions, if you are able to install again a fresh OS..
The only three literal characters which are treated specially in the replace clause are /
(to close the clause), \
(to escape characters, backreference, &c.), and &
(to include the match in the replacement). Therefore, all you need to do is escape those three characters:
sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"
Example:
$ export REPLACE="'\"|\\/><&!"
$ echo fooKEYWORDbar | sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"
foo'"|\/><&!bar
This code is working fine to download a file automatically from spring controller on clicking a link on jsp.
@RequestMapping(value="/downloadLogFile")
public void getLogFile(HttpSession session,HttpServletResponse response) throws Exception {
try {
String filePathToBeServed = //complete file name with path;
File fileToDownload = new File(filePathToBeServed);
InputStream inputStream = new FileInputStream(fileToDownload);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment; filename="+fileName+".txt");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
} catch (Exception e){
LOGGER.debug("Request could not be completed at this moment. Please try again.");
e.printStackTrace();
}
}
add this to your package.json file
scripts {
"dev": "nodemon --watch '**/*.ts' --exec 'ts-node' index.ts"
}
and to make this work you also need to install ts-node as dev-dependency
yarn add ts-node -D
run yarn dev
to start the dev server
google the javascript same origin policy
in a nutshell, the url you are trying to use must have the same root and protocol. so http://yoursite.com cannot access https://yoursite.com or http://anothersite.com
is you absolutely MUST bypass this protection (which is at the browser level, as galimy pointed out), consider the ProxyPass module for your favorite web server.
I had this problem yesterday. @Quentin's answer is ok:
No, you cannot reference one rule-set from another.
but I made a javascript function to simulate inheritance in css (like .Net):
var inherit_array;_x000D_
var inherit;_x000D_
inherit_array = [];_x000D_
Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {_x000D_
Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {_x000D_
if (cssRule_i.style != null) {_x000D_
inherit = cssRule_i.style.getPropertyValue("--inherits").trim();_x000D_
} else {_x000D_
inherit = "";_x000D_
}_x000D_
if (inherit != "") {_x000D_
inherit_array.push({ selector: cssRule_i.selectorText, inherit: inherit });_x000D_
}_x000D_
});_x000D_
});_x000D_
Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {_x000D_
Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {_x000D_
if (cssRule_i.selectorText != null) {_x000D_
inherit_array.forEach(function (inherit_i, index) {_x000D_
if (cssRule_i.selectorText.split(", ").includesMember(inherit_i.inherit.split(", ")) == true) {_x000D_
cssRule_i.selectorText = cssRule_i.selectorText + ", " + inherit_i.selector;_x000D_
}_x000D_
});_x000D_
}_x000D_
});_x000D_
});
_x000D_
Array.prototype.includesMember = function (arr2) {_x000D_
var arr1;_x000D_
var includes;_x000D_
arr1 = this;_x000D_
includes = false;_x000D_
arr1.forEach(function (arr1_i, index) {_x000D_
if (arr2.includes(arr1_i) == true) {_x000D_
includes = true;_x000D_
}_x000D_
});_x000D_
return includes;_x000D_
}
_x000D_
and equivalent css:
.test {_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
.productBox, .imageBox {_x000D_
--inherits: .test;_x000D_
display: inline-block;_x000D_
}
_x000D_
and equivalent HTML :
<div class="imageBox"></div>
_x000D_
I tested it and worked for me, even if rules are in different css files.
Update: I found a bug in hierarchichal inheritance in this solution, and am solving the bug very soon .
You have to loop through every cell in the range "D3:D6"
and construct your To
string. Simply assigning it to a variant will not solve the purpose. EmailTo
becomes an array if you assign the range directly to it. You can do this as well but then you will have to loop through the array to create your To
string
Is this what you are trying? (TRIED AND TESTED)
Option Explicit
Sub Mail_workbook_Outlook_1()
'Working in 2000-2010
'This example send the last saved version of the Activeworkbook
Dim OutApp As Object
Dim OutMail As Object
Dim emailRng As Range, cl As Range
Dim sTo As String
Set emailRng = Worksheets("Selections").Range("D3:D6")
For Each cl In emailRng
sTo = sTo & ";" & cl.Value
Next
sTo = Mid(sTo, 2)
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = sTo
.CC = "[email protected];[email protected]"
.BCC = ""
.Subject = "RMA #" & Worksheets("RMA").Range("E1")
.Body = "Attached to this email is RMA #" & _
Worksheets("RMA").Range("E1") & _
". Please follow the instructions for your department included in this form."
.Attachments.Add ActiveWorkbook.FullName
'You can add other files also like this
'.Attachments.Add ("C:\test.txt")
.Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
This one will give you date no time:
=FormatDateTime(DateAdd("m", -1, DateSerial(Year(Today()), Month(Today()), 1)),
DateFormat.ShortDate)
This one will give you datetime:
=dateadd("m",-1,dateserial(year(Today),month(Today),1))
Here are my observation, firstly you need to include the header math.h
as sqrt()
function declared in math.h
header file. For e.g
#include <math.h>
secondly, if you read manual page of sqrt you will notice this line Link with -lm.
#include <math.h> /* header file you need to include */
double sqrt(double x); /* prototype of sqrt() function */
Link with -lm. /* Library linking instruction */
But application still says undefined reference to sqrt. Do you see any problem here?
Compiler error is correct as you haven't linked your program with library lm
& linker is unable to find reference of sqrt()
, you need to link it explicitly. For e.g
gcc -Wall -Wextra -Werror -pedantic test.c -lm
You can use the data attribute:
<div class="datepicker" data-date-start-date="+1d"></div>
This should do what you want:
print tempfile.gettempdir()
For me on my Windows box, I get:
c:\temp
and on my Linux box I get:
/tmp
len(list_name)
function takes list as a parameter and it calls list's __len__()
function.
you can use the UNION ALL
keyword for this.
Here is the MSDN doc to do it in T-SQL http://msdn.microsoft.com/en-us/library/ms180026.aspx
UNION ALL - combines the result set
UNION- Does something like a Set Union and doesnt output duplicate values
For the difference with an example: http://sql-plsql.blogspot.in/2010/05/difference-between-union-union-all.html
Yes, git rm <filename>
will stage the deleted state of a file, where <filename>
could be a glob pattern:
$ git rm modules/welcome/language/*/kaimonokago_lang.php
rm modules/welcome/language/english/kaimonokago_lang.php
rm modules/welcome/language/french/kaimonokago_lang.php
rm modules/welcome/language/german/kaimonokago_lang.php
rm modules/welcome/language/norwegian/kaimonokago_lang.php
$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# deleted: modules/welcome/language/english/kaimonokago_lang.php
# ...
Then, you can commit.
git commit -a
will do this in one go, if you want.
You can also use git add -u
to stage all the changes, including all the deleted files, then commit.
If you plot a logarithmic function on a graphical calculator or something similar, you'll see that it rises really slowly -- even more slowly than a linear function.
This is why algorithms with a logarithmic time complexity are highly sought after: even for really big n (let's say n = 10^8, for example), they perform more than acceptably.
Exception code c0000005
is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:
N
and you access elements with index >=N
.To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.
You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.
You can use the following CSS to style the input element.
input[type="date"] {_x000D_
background-color: red;_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-clear-button {_x000D_
font-size: 18px;_x000D_
height: 30px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-inner-spin-button {_x000D_
height: 28px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
font-size: 15px;_x000D_
}
_x000D_
<input type="date" value="From" name="from" placeholder="From" required="" />
_x000D_
first check with instanceof keyword . if true then cast it.
Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.
Use this way instead of your way.
addslashes(trim($_POST['username']));