Its simpler than you think.
According to Microsoft:
The lock
keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
The lock
keyword calls Enter
at the start of the block and Exit
at the end of the block. lock
keyword actually handles Monitor
class at back end.
For example:
private static readonly Object obj = new Object();
lock (obj)
{
// critical section
}
In the above code, first the thread enters a critical section, and then it will lock obj
. When another thread tries to enter, it will also try to lock obj
, which is already locked by the first thread. Second thread will have to wait for the first thread to release obj
. When the first thread leaves, then another thread will lock obj
and will enter the critical section.
A multiple select is really just a select with a multiple
attribute. With that in mind, it should be as easy as...
Form::select('sports[]', $sports, null, array('multiple'))
The first parameter is just the name, but post-fixing it with the []
will return it as an array when you use Input::get('sports')
.
The second parameter is an array of selectable options.
The third parameter is an array of options you want pre-selected.
The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple
property to the actual select element..
The other answers address the main thrust of the question, but just to comment on this part...
PS C:\> [array]$foo = @("bar") PS C:\> $foo -eq $null PS C:\>
How can "-eq $null" give no results? It's either $null or it's not.
It's confusing at first, but that is giving you the result of $foo -eq $null
, it's just that the result has no displayable representation.
Since $foo
holds an array, $foo -eq $null
means "return an array containing the elements of $foo
that are equal to $null
". Are there any elements of $foo
that are equal to $null
? No, so $foo -eq $null
should return an empty array. That's exactly what it does, the problem is that when an empty array is displayed at the console you see...nothing...
PS> @()
PS>
The array is still there, even if you can't see its elements...
PS> @().GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> @().Length
0
We can use similar commands to confirm that $foo -eq $null
is returning an array that we're not able to "see"...
PS> $foo -eq $null
PS> ($foo -eq $null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> ($foo -eq $null).Length
0
PS> ($foo -eq $null).GetValue(0)
Exception calling "GetValue" with "1" argument(s): "Index was outside the bounds of the array."
At line:1 char:1
+ ($foo -eq $null).GetValue(0)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IndexOutOfRangeException
Note that I am calling the Array.GetValue
method instead of using the indexer (i.e. ($foo -eq $null)[0]
) because the latter returns $null
for invalid indices and there's no way to distinguish them from a valid index that happens to contain $null
.
We see similar behavior if we test for $null
in/against an array that contains $null
elements...
PS> $bar = @($null)
PS> $bar -eq $null
PS> ($bar -eq $null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> ($bar -eq $null).Length
1
PS> ($bar -eq $null).GetValue(0)
PS> $null -eq ($bar -eq $null).GetValue(0)
True
PS> ($bar -eq $null).GetValue(0) -eq $null
True
PS> ($bar -eq $null).GetValue(1)
Exception calling "GetValue" with "1" argument(s): "Index was outside the bounds of the array."
At line:1 char:1
+ ($bar -eq $null).GetValue(1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IndexOutOfRangeException
In this case, $bar -eq $null
returns an array containing one element, $null
, which has no visual representation at the console...
PS> @($null)
PS> @($null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> @($null).Length
1
Syntax:
LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL]
INFILE 'file_name' INTO TABLE `tbl_name`
CHARACTER SET [CHARACTER SET charset_name]
FIELDS [{FIELDS | COLUMNS}[TERMINATED BY 'string']]
[LINES[TERMINATED BY 'string']]
[IGNORE number {LINES | ROWS}]
See this Example:
LOAD DATA LOCAL INFILE
'E:\\wamp\\tmp\\customer.csv' INTO TABLE `customer`
CHARACTER SET 'utf8'
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;
Please check the below its working on my side in below code your handler will run after every 1 Second when you are on same activity
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
runnable = new Runnable()
{
@Override
public void run()
{
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
import os
rows, columns = os.popen('stty size', 'r').read().split()
uses the 'stty size' command which according to a thread on the python mailing list is reasonably universal on linux. It opens the 'stty size' command as a file, 'reads' from it, and uses a simple string split to separate the coordinates.
Unlike the os.environ["COLUMNS"] value (which I can't access in spite of using bash as my standard shell) the data will also be up-to-date whereas I believe the os.environ["COLUMNS"] value would only be valid for the time of the launch of the python interpreter (suppose the user resized the window since then).
(See answer by @GringoSuave on how to do this on python 3.3+)
You can't name a variable with capital letters or Ruby will asume its a constant and will want it to keep it's value constant, in which case changing it's value would be an error an "dynamic constant assignment error". With lower case should be fine
class MyClass
def mymethod
myconstant = "blah"
end
end
I would just use
string data= "/temp string";
data = data.substring(1)
Output:
temp string
That always works for me.
You cannot use WHILE
like that; see: mysql DECLARE WHILE outside stored procedure how?
You have to put your code in a stored procedure. Example:
CREATE PROCEDURE myproc()
BEGIN
DECLARE i int DEFAULT 237692001;
WHILE i <= 237692004 DO
INSERT INTO mytable (code, active, total) VALUES (i, 1, 1);
SET i = i + 1;
END WHILE;
END
Fiddle: http://sqlfiddle.com/#!2/a4f92/1
Alternatively, generate a list of INSERT
statements using any programming language you like; for a one-time creation, it should be fine. As an example, here's a Bash one-liner:
for i in {2376921001..2376921099}; do echo "INSERT INTO mytable (code, active, total) VALUES ($i, 1, 1);"; done
By the way, you made a typo in your numbers; 2376921001 has 10 digits, 237692200 only 9.
To find any number of special characters use the following regex pattern: ([^(A-Za-z0-9 )]{1,})
[^(A-Za-z0-9 )] this means any character except the alphabets, numbers, and space. {1,0} this means one or more characters of the previous block.
You want font-weight, not text-decoration (along with suitable additional markup, such as <em>
or <span>
, so you can apply different styling to different parts of the heading)
The hashcode determines which bucket for the hashmap to check. If there is more than one object in the bucket then a linear search is done to find which item in the bucket equals the desired item (using the equals()
) method.
In other words, if you have a perfect hashcode then hashmap access is constant, you will never have to iterate through a bucket (technically you would also have to have MAX_INT buckets, the Java implementation may share a few hash codes in the same bucket to cut down on space requirements). If you have the worst hashcode (always returns the same number) then your hashmap access becomes linear since you have to search through every item in the map (they're all in the same bucket) to get what you want.
Most of the time a well written hashcode isn't perfect but is unique enough to give you more or less constant access.
The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.
I've solved this by uninstalling XAMPP, and installing WAMP. Thanks for the help.
You can also use strdup:
char* p = strdup("abc");
This was happening for me in my Apache/2.4.18 (Ubuntu) setup. In my case, the error I was seeing was:
... AH01144: No protocol handler was valid for the URL /~socket.io/. If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule.
The configuration related to this was:
ProxyPass /~socket.io/ ws://127.0.0.1:8090/~socket.io/
ProxyPassReverse /~socket.io/ ws://127.0.0.1:8090/~socket.io/
"No protocol handler was valid for the URL /~socket.io/
" meant that Apache could not handle the request being sent to "ws://127.0.0.1:8090/~socket.io/
"
I had proxy_http
loaded, but also needed proxy_wstunnel
. Once that was enabled all was good.
Just to clarify things, you don't/can't "execute it within the HTML body".
You can modify the contents of the HTML using javascript.
You decide at what point you want the javascript to be executed.
For example, here is the contents of a html file, including javascript, that does what you want.
<html>
<head>
<script>
// The next line document.addEventListener....
// tells the browser to execute the javascript in the function after
// the DOMContentLoaded event is complete, i.e. the browser has
// finished loading the full webpage
document.addEventListener("DOMContentLoaded", function(event) {
var col1 = ["Full time student checking (Age 22 and under) ", "Customers over age 65", "Below $500.00" ];
var col2 = ["None", "None", "$8.00"];
var TheInnerHTML ="";
for (var j = 0; j < col1.length; j++) {
TheInnerHTML += "<tr><td>"+col1[j]+"</td><td>"+col2[j]+"</td></tr>";
}
document.getElementById("TheBody").innerHTML = TheInnerHTML;});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Balance</th>
<th>Fee</th>
</tr>
</thead>
<tbody id="TheBody">
</tbody>
</table>
</body>
Enjoy !
First,
sudo apt-get install libusb-1.0-0-dev
updatedb && locate libusb.h.
Second, replace <libusb.h>
with <libusb-1.0/libusb.h>
.
update:
don't need to change any file.just add this to your Makefile.
`pkg-config libusb-1.0 --libs --cflags`
its result is that -I/usr/include/libusb-1.0 -lusb-1.0
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
editText = (EditText) row.findViewById(R.id.id_number_custom);
loadButton = (ImageButton) row.findViewById(R.id.load_data_button);
row.setTag(holder);
} else {
holder = (ImageHolder) row.getTag();
}
holder.editText.setText("Your Value");
holder.loadButton.setImageBitmap("Your Bitmap Value");
return row;
}
Now, there are plenty of example of me answering questions with essays on why following validation rules are important. I've also said that sometimes you just have to be a rebel and break the rules, and document the reasons.
You can see in this example that framesets do work in HTML5 still. I had to download the code and add an HTML5 doctype at the top, however. But the frameset element was still recognized, and the desired result was achieved.
Therefore, knowing that using framesets is completely absurd, and knowing that you have to use this as dictated by your professor/teacher, you could just deal with the single validation error in the W3C validator and use both the HTML5 video element as well as the deprecated frameset element.
<!DOCTYPE html>
<html>
<head>
</head>
<!-- frameset is deprecated in html5, but it still works. -->
<frameset framespacing="0" rows="150,*" frameborder="0" noresize>
<frame name="top" src="http://www.npscripts.com/framer/demo-top.html" target="top">
<frame name="main" src="http://www.google.com" target="main">
</frameset>
</html>
Keep in mind that if it's a project for school, it's most likely not going to be something that will be around in a year or two once the browser vendors remove frameset support for HTML5 completely. Just know that you are right and just do what your teacher/professor asks just to get the grade :)
UPDATE:
The toplevel parent doc uses XHTML and the frame uses HTML5. The validator did not complain about the frameset being illegal, and it didn't complain about the video element.
index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
</head>
<frameset framespacing="0" rows="150,*" frameborder="0" noresize>
<frame name="top" src="http://www.npscripts.com/framer/demo-top.html" target="top">
<frame name="main" src="video.html" target="main">
</frameset>
</html>
video.html:
<!doctype html>
<html>
<head>
</head>
<body>
<div id="player-container">
<div class="arrow"></div>
<div class="player">
<video id="vid1" width="480" height="267"
poster="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb480.jpg"
durationHint="33" controls>
<source src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb_trailer_iphone.m4v" />
<source src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb400p.ogv" />
</video>
</div>
</body>
</html>
To modify DSM's answer a bit, get_loc
has some weird properties depending on the type of index in the current version of Pandas (1.1.5) so depending on your Index type you might get back an index, a mask, or a slice. This is somewhat frustrating for me because I don't want to modify the entire columns just to extract one variable's index. Much simpler is to avoid the function altogether:
list(df.columns).index('pear')
Very straightforward and probably fairly quick.
This Perl one-liner shows how closely Perl is related to awk:
perl -lane 'print $F[3]' text.txt
However, the @F
autosplit array starts at index $F[0]
while awk fields start with $1
There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.
String.prototype.replaceSome = function() {
var replaceWith = Array.prototype.pop.apply(arguments),
i = 0,
r = this,
l = arguments.length;
for (;i<l;i++) {
r = r.replace(arguments[i],replaceWith);
}
return r;
}
/* replaceSome method for strings it takes as ,much arguments as we want and replaces all of them with the last argument we specified 2013 CopyRights saved for: Max Ahmed this is an example:
var string = "[hello i want to 'replace x' with eat]";
var replaced = string.replaceSome("]","[","'replace x' with","");
document.write(string + "<br>" + replaced); // returns hello i want to eat (without brackets)
*/
jsFiddle: http://jsfiddle.net/CPj89/
The magic method __getitem__
is basically used for accessing list items, dictionary entries, array elements etc. It is very useful for a quick lookup of instance attributes.
Here I am showing this with an example class Person that can be instantiated by 'name', 'age', and 'dob' (date of birth). The __getitem__
method is written in a way that one can access the indexed instance attributes, such as first or last name, day, month or year of the dob, etc.
import copy
# Constants that can be used to index date of birth's Date-Month-Year
D = 0; M = 1; Y = -1
class Person(object):
def __init__(self, name, age, dob):
self.name = name
self.age = age
self.dob = dob
def __getitem__(self, indx):
print ("Calling __getitem__")
p = copy.copy(self)
p.name = p.name.split(" ")[indx]
p.dob = p.dob[indx] # or, p.dob = p.dob.__getitem__(indx)
return p
Suppose one user input is as follows:
p = Person(name = 'Jonab Gutu', age = 20, dob=(1, 1, 1999))
With the help of __getitem__
method, the user can access the indexed attributes. e.g.,
print p[0].name # print first (or last) name
print p[Y].dob # print (Date or Month or ) Year of the 'date of birth'
I would not change the constraints, instead, you can insert a new record in the table_1 with the primary key (id_no = 7008255601088). This is nothing but a duplicate row of the id_no = 8008255601088. so now patient_address with the foreign key constraint (id_no = 8008255601088) can be updated to point to the record with the new ID(ID which needed to be updated), which is updating the id_no to id_no =7008255601088.
Then you can remove the initial primary key row with id_no =7008255601088.
Three steps include:
I had same problem. i fixed it. i was using Codeblocks and i save my .cpp file on desktop instead of saving it in Codeblocks file where MinGW is located. So i copied all dll files from MinGW>>bin folder to where my .cpp file was saved.
I bet for sure, that this is because you didn't close the running instance of the program before trying to re-compile it.
Generally, ld.exe
returns 1 when it can't access required files. This usually includes
Access denied
)The program looks completely fine, so the second point should not hit. In usual cases, it's impossible for ld
to fail to open the object file (unless you have a faulty drive and a dirty filesystem), so the first point is also nearly impossible.
Now we get to the third point. Note that Windows not allow writing to a file when it's in use, so the running instance of your program prevents ld.exe
from writing the new linked program to it.
So next time be sure to close running programs before compiling.
Use Python method datetime.strftime(format)
, where format = '%Y-%m-%d %H:%M:%S'
.
import datetime
now = datetime.datetime.utcnow()
cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, %s)",
("name", 4, now.strftime('%Y-%m-%d %H:%M:%S')))
If timezones are a concern, the MySQL timezone can be set for UTC as follows:
cursor.execute("SET time_zone = '+00:00'")
And the timezone can be set in Python:
now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
MySQL recognizes DATETIME and TIMESTAMP values in these formats:
As a string in either 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' format. A “relaxed” syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012@12@31 11^30^45' are equivalent.
The only delimiter recognized between a date and time part and a fractional seconds part is the decimal point.
The date and time parts can be separated by T rather than a space. For example, '2012-12-31 11:30:45' '2012-12-31T11:30:45' are equivalent.
As a string with no delimiters in either 'YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS' format, provided that the string makes sense as a date. For example, '20070523091528' and '070523091528' are interpreted as '2007-05-23 09:15:28', but '071122129015' is illegal (it has a nonsensical minute part) and becomes '0000-00-00 00:00:00'.
As a number in either YYYYMMDDHHMMSS or YYMMDDHHMMSS format, provided that the number makes sense as a date. For example, 19830905132800 and 830905132800 are interpreted as '1983-09-05 13:28:00'.
Install python version 3.6+
and open you text editor
or ide
write sample code like this:
from tkinter import *
root = Tk()
root.title("Answer")
root.mainloop()
The best way is to use the INFORMATION_SCHEMA metadata virtual database. Specifically the INFORMATION_SCHEMA.COLUMNS table...
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename';
It's VERY powerful, and can give you TONS of information without need to parse text (Such as column type, whether the column is nullable, max column size, character set, etc)...
Oh, and it's standard SQL (Whereas SHOW ...
is a MySQL specific extension)...
For more information about the difference between SHOW...
and using the INFORMATION_SCHEMA
tables, check out the MySQL Documentation on INFORMATION_SCHEMA
in general...
Loop through elements in the list and update the total like this:
def sum(a):
total = 0
index = 0
while index < len(a):
total = total + a[index]
index = index + 1
return total
Try -webkit-font-smoothing: subpixel-antialiased;
THIS works
<div style="display:inline-block;margin:10px auto;">
<ul style="list-style-type:none;">
<li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>root keyword text box</em>.</li>
<li style="text-align:left;"><span class="red">?</span> YouTube.com website <em>video search text box</em>.</li>
<li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>scraped keywords listbox</em>.</li>
<li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>right click context menu</em>.</li>
</ul>
</div>
In order to check the maximum allowed connections, you can run the following query:
SHOW VARIABLES LIKE "max_connections";
To check the number of active connections, you can run the following query:
SHOW VARIABLES LIKE "max_used_connections";
Hope it helps.
pass in this
in the inline click handler
<a href="123.com" onclick="click123(this);">link</a>
or use event.target
in the function (according to the W3C DOM Level 2 Event model)
function click123(event)
{
var a = event.target;
}
But of course, IE is different, so the vanilla JavaScript way of handling this is
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
}
or less verbose
function doSomething(e) {
e = e || window.event;
var targ = e.target || e.srcElement || e;
if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
}
where e
is the event object
that is passed to the function in browsers other than IE.
If you're using jQuery though, I would strongly encourage unobtrusive JavaScript and use jQuery to bind event handlers to elements.
Pandas supports NumPy syntax which allows:
df[len(df) -1:].index[0]
<em>
element - from W3C (HTML5 reference)YES! There is a clear difference.
The <em>
element represents stress emphasis of its contents. The level of emphasis that a particular piece of content has is given by its number of ancestor <em>
elements.
<strong> = important content
<em> = stress emphasis of its contents
The placement of emphasis changes the meaning of the sentence. The element thus forms an integral part of the content. The precise way in which emphasis is used in this way depends on the language.
The <em>
element also isnt intended to convey importance; for that
purpose, the <strong>
element is more appropriate.
The <em>
element isn't a generic "italics" element. Sometimes, text
is intended to stand out from the rest of the paragraph, as if it was
in a different mood or voice. For this, the i
element is more
appropriate.
Reference (examples): See W3C Reference
You need the javax.mail.jar
library.
Download it from the Java EE JavaMail GitHub page and add it to your IntelliJ project:
javax.mail.jar
File > Project Structure...
+
button (Add New Project Library)javax.mail.jar
fileUbuntu, which is a Debian derivative, follows a very precise structure when installing packages. In other words, all software installed through the packaging tools, such as apt-get or synaptic, will put the stuff in the same locations. If you become familiar with these locations, you'll always know where to find your stuff.
As a short cut, you can always open a tool like synaptic, find the installed package, and inspect the "properties". Under properties, you'll see a list of all installed files. Again, you can expect these to always follow the Debian/Ubuntu conventions; these are highly ordered Linux distributions. IN short, binaries will be in /usr/bin, or some other location on your path ( try 'echo $PATH' on the command line to see the possible locations ). Configuration is always in a subdirectory of /etc. And the "home" is typically in /usr/lib or /usr/share.
For instance, according to http://www.mkyong.com/maven/how-to-install-maven-in-ubuntu/, maven is installed like:
The Apt-get installation will install all the required files in the following folder structure
/usr/bin/mvn
/usr/share/maven2/
/etc/maven2
P.S The Maven configuration is store in /etc/maven2
Note, it's not just apt-get that will do this, it's any .deb package installer.
You can use Apache Commons Configuration library. The best part of this is, it won't even mess up the properties file and keeps it intact (even comments).
PropertiesConfiguration conf = new PropertiesConfiguration("propFile.properties");
conf.setProperty("key", "value");
conf.save();
WhatsApp Inc. does not provide an open API but a reverse-engineered library is made available on GitHub by the team Venomous on the GitHub. This however according to my knowledge is made possible in PHP. You can check the link here: https://github.com/venomous0x/WhatsAPI
Hope this helps
To refresh page you don't need react-router, simple js:
window.location.reload();
To re-render view in React component, you can just fire update with props/state.
Typically you model the enum itself as a class with the enum
stereotype
An extra pair of rabbits' ears should do the trick.
start "" "C:\Program...
START
regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START
switches.
it will take much time then normal start and it will fresh up all resources.
Just a slight addition to the above solution if you are having problem with downloaded file's name...
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
This will return the exact file name even if it contains spaces or other characters.
NoClassDefFoundError in Java:
Definition:
NoClassDefFoundError will come if a class was present during compile time but not available in java classpath during runtime. Normally you will see below line in log when you get NoClassDefFoundError: Exception in thread "main" java.lang.NoClassDefFoundError
Possible Causes:
The class is not available in Java Classpath.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Any start-up script is overriding Classpath environment variable.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Possible Resolutions:
Verify that all required Java classes are included in the application’s classpath. The most common mistake is not to include all the necessary classes, before starting to execute a Java application that has dependencies on some external libraries.
The classpath of the application is correct, but the Classpath environment variable is overridden before the application’s execution.
Verify that the aforementioned ExceptionInInitializerError does not appear in the stack trace of your application.
Resources:
3 ways to solve java.lang.NoClassDefFoundError in Java J2EE
java.lang.NoClassDefFoundError – How to solve No Class Def Found Error
In practice, it is O(1), but this actually is a terrible and mathematically non-sense simplification. The O() notation says how the algorithm behaves when the size of the problem tends to infinity. Hashmap get/put works like an O(1) algorithm for a limited size. The limit is fairly large from the computer memory and from the addressing point of view, but far from infinity.
When one says that hashmap get/put is O(1) it should really say that the time needed for the get/put is more or less constant and does not depend on the number of elements in the hashmap so far as the hashmap can be presented on the actual computing system. If the problem goes beyond that size and we need larger hashmaps then, after a while, certainly the number of the bits describing one element will also increase as we run out of the possible describable different elements. For example, if we used a hashmap to store 32bit numbers and later we increase the problem size so that we will have more than 2^32 bit elements in the hashmap, then the individual elements will be described with more than 32bits.
The number of the bits needed to describe the individual elements is log(N), where N is the maximum number of elements, therefore get and put are really O(log N).
If you compare it with a tree set, which is O(log n) then hash set is O(long(max(n)) and we simply feel that this is O(1), because on a certain implementation max(n) is fixed, does not change (the size of the objects we store measured in bits) and the algorithm calculating the hash code is fast.
Finally, if finding an element in any data structure were O(1) we would create information out of thin air. Having a data structure of n element I can select one element in n different way. With that, I can encode log(n) bit information. If I can encode that in zero bit (that is what O(1) means) then I created an infinitely compressing ZIP algorithm.
Close Code 1006
is a special code that means the connection was closed abnormally (locally) by the browser implementation.
If your browser client reports close code 1006
, then you should be looking at the websocket.onerror(evt)
event for details.
However, Chrome will rarely report any close code 1006
reasons to the Javascript side. This is likely due to client security rules in the WebSocket spec to prevent abusing WebSocket. (such as using it to scan for open ports on a destination server, or for generating lots of connections for a denial-of-service attack).
Note that Chrome will often report a close code 1006
if there is an error during the HTTP Upgrade to Websocket (this is the step before a WebSocket is technically "connected"). For reasons such as bad authentication or authorization, or bad protocol use (such as requesting a subprotocol, but the server itself doesn't support that same subprotocol), or even an attempt at talking to a server location that isn't a WebSocket (such as attempting to connect to ws://images.google.com/
)
Fundamentally, if you see a close code 1006
, you have a very low level error with WebSocket itself (similar to "Unable to Open File" or "Socket Error"), not really meant for the user, as it points to a low level issue with your code and implementation. Fix your low level issues, and then when you are connected, you can then include more reasonable error codes. You can accomplish this in terms of scope or severity in your project. Example: info and warning level are part of your project's specific protocol, and don't cause the connection to terminate. With severe or fatal messages reporting also using your project's protocol to convey as much detail as you want, and then closing the connection using the limited abilities of the WebSocket close flow.
Be aware that WebSocket close codes are very strictly defined, and the close reason phrase/message cannot exceed 123 characters in length (this is an intentional WebSocket limitation).
But not all is lost, if you are just wanting this information for debugging reasons, the detail of the closure, and its underlying reason is often reported with a fair amount of detail in Chrome's Javascript console.
Is this what you're looking for?
#include <chrono>
#include <iostream>
int main()
{
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::milliseconds ms;
typedef std::chrono::duration<float> fsec;
auto t0 = Time::now();
auto t1 = Time::now();
fsec fs = t1 - t0;
ms d = std::chrono::duration_cast<ms>(fs);
std::cout << fs.count() << "s\n";
std::cout << d.count() << "ms\n";
}
which for me prints out:
6.5e-08s
0ms
Courtesy of this page, I found this worked when the suggestions above didn't:
import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
a = np.uint8(a)
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
IPython.display.display(IPython.display.Image(data=f.getvalue()))
Similar to what Mark E has proposed, you have to come up with your own. Just to help you a bit, there is a neat article http://gleichmann.wordpress.com/2008/01/15/building-your-own-literals-in-java-tuples-and-maps/ which gives you a really neat way of creating tuples and maps that might be something you might want to consider.
Use Simple HTML
<frameset cols="25%,*">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>
The basic difference between all these annotations is as follows -
All these annotations along with the usage is defined on Codingeek - Junit5 Test Lifecycle
ObjC
NSDate *date = [NSDate date];
NSInteger era, year, month, day;
[[NSCalendar currentCalendar] getEra:&era year:&year month:&month day:&day fromDate:date];
Swift
let date = NSDate.init()
var era = 0, year = 0, month = 0, day = 0
NSCalendar.currentCalendar().getEra(&era, year:&year, month:&month, day:&day, fromDate: date)
Error happens in your function declarations,look the following sentence!You need a semicolon!
AST_NODE* Statement(AST_NODE* node)
Generally, bash works better than python only in those environments where python is not available. :)
Seriously, I have to deal with both languages daily, and will take python instantly over bash if given the choice. Alas, I am forced to use bash on certain "small" platforms because someone has (mistakenly, IMHO) decided that python is "too large" to fit.
While it is true that bash might be faster than python for some select tasks, it can never be as quick to develop with, or as easy to maintain (at least after you get past 10 lines of code or so). Bash's sole strong point wrt python or ruby or lua, etc., is its ubiquity.
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script>_x000D_
var currFFZoom = 1;_x000D_
var currIEZoom = 100;_x000D_
_x000D_
function plus(){_x000D_
//alert('sad');_x000D_
var step = 0.02;_x000D_
currFFZoom += step;_x000D_
$('body').css('MozTransform','scale(' + currFFZoom + ')');_x000D_
var stepie = 2;_x000D_
currIEZoom += stepie;_x000D_
$('body').css('zoom', ' ' + currIEZoom + '%');_x000D_
_x000D_
};_x000D_
function minus(){_x000D_
//alert('sad');_x000D_
var step = 0.02;_x000D_
currFFZoom -= step;_x000D_
$('body').css('MozTransform','scale(' + currFFZoom + ')');_x000D_
var stepie = 2;_x000D_
currIEZoom -= stepie;_x000D_
$('body').css('zoom', ' ' + currIEZoom + '%');_x000D_
};_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<!--zoom controls-->_x000D_
<a id="minusBtn" onclick="minus()">------</a>_x000D_
<a id="plusBtn" onclick="plus()">++++++</a>_x000D_
</body>_x000D_
</html>
_x000D_
in Firefox will not change the zoom only change scale!!!
If you do not need a particular order of concatenated values, and the separator can be a comma, you can do:
select col1, stragg(distinct col2)
from table
group by col1
What is the package name of your class? If there is no package name, then most likely the solution is:
java -cp FileManagement Main
You just need to do:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
$(perl test.pl test2 $count)
However, if you want to call your Perl command later, and that's why you want to assign it to a variable, then:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var="perl test.pl test2 $count" # You need double quotes to get your $count value substituted.
...stuff...
eval $var
As per Bash's help:
~$ help eval
eval: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.
Use of static keyword for that purpose is deprecated by the C++98 standard. The problem with static is that it doesn't apply to type definition. It's also an overloaded keyword used in different ways in different contexts, so unnamed namespaces simplify things a bit.
Though the previou answer are almost similar to what I am going to do, but using the index method does not require using another indexing method .loc(). It can be done in a similar but precise manner as
df.drop(df.index[df['line_race'] == 0], inplace = True)
The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH
clause. See this article for one example of translating a CONNECT BY
into a WITH
(technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.
Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:
CREATE TABLE emp(empid INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(10),
salary DECIMAL(9, 2),
mgrid INTEGER);
where mgrid
references an employee's manager's empid
, the task is, get the names of everybody who reports directly or indirectly to Joan
. In Oracle, that's a simple CONNECT
:
SELECT name
FROM emp
START WITH name = 'Joan'
CONNECT BY PRIOR empid = mgrid
In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):
WITH n(empid, name) AS
(SELECT empid, name
FROM emp
WHERE name = 'Joan'
UNION ALL
SELECT nplus1.empid, nplus1.name
FROM emp as nplus1, n
WHERE n.empid = nplus1.mgrid)
SELECT name FROM n
Oracle's START WITH
clause becomes the first nested SELECT
, the base case of the recursion, to be UNION
ed with the recursive part which is just another SELECT
.
SQL Server's specific flavor of WITH
is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.
Give the below
@ContextConfiguration(locations = {"classpath*:/spring/test-context.xml"})
And in pom.xml
give the following plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<configuration>
<additionalClasspathElements>
<additionalClasspathElement>${basedir}/src/test/resources</additionalClasspathElement>
</additionalClasspathElements>
</configuration>
If you use String concatenation in a loop, something like this,
String s = "";
for (int i = 0; i < 100; i++) {
s += ", " + i;
}
then you should use a StringBuilder
(not StringBuffer
) instead of a String
, because it is much faster and consumes less memory.
If you have a single statement,
String s = "1, " + "2, " + "3, " + "4, " ...;
then you can use String
s, because the compiler will use StringBuilder
automatically.
This isn’t a solution in the sense that it doesn’t resolve the conditions which cause the message to appear in the logs, but the message can be suppressed by appending the following to conf/logging.properties
:
org.apache.catalina.webresources.Cache.level = SEVERE
This filters out the “Unable to add the resource” logs, which are at level WARNING.
In my view a WARNING
is not necessarily an error that needs to be addressed, but rather can be ignored if desired.
Within your <jre location>\lib\security\java.policy
try adding:
grant {
permission java.security.AllPermission;
};
And see if it allows you. If so, you will have to add more granular permissions.
See:
Java 8 Documentation for java.policy files
and
http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html
Got the same issue outside of Android Studio, when trying to build for Cordova using the sdk from command line (cordova build android).
The solution provided by Rudy works in this case too. You just don't downgrade the version of Build Tools from Android Studio but you do it using the android sdk manager ui.
This technique is working for me:
$('#myInputFieldId').bind('input',function(){
alert("Hello");
});
Note that according to this JQuery doc, "on" is recommended rather than bind in newer versions.
In addition to @csgillespie's answer, segments
is also vectorised to help with this sort of thing:
plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)
You can use sessions to save $_POST
data, then retrieve that data and set it to $_POST
on the subsequent request.
User submits request to /dirty-submission-url.php
Do:
if (session_status()!==PHP_SESSION_ACTIVE)session_start();
$_SESSION['POST'] = $_POST;
}
header("Location: /clean-url");
exit;
Then the browser redirects to and requests /clean-submission-url
from your server. You will have some internal routing to figure out what to do with this.
At the beginning of the request, you will do:
if (session_status()!==PHP_SESSION_ACTIVE)session_start();
if (isset($_SESSION['POST'])){
$_POST = $_SESSION['POST'];
unset($_SESSION['POST']);
}
Now, through the rest of your request, you can access $_POST
as you could upon the first request.
There are several ways to do an email from HTML. Typically you see people doing a mailto like so:
<a href="mailto:[email protected]">Click to email</a>
But if you are doing it from a button you may want to look into a javascript solution.
Use breakpoint mixins like this:
.something {
padding: 5px;
@include media-breakpoint-up(sm) {
padding: 20px;
}
@include media-breakpoint-up(md) {
padding: 40px;
}
}
v4 alpha6 breakpoints reference
Below full options and values.
Breakpoint & up (toggle on value and above):
@include media-breakpoint-up(xs) { ... }
@include media-breakpoint-up(sm) { ... }
@include media-breakpoint-up(md) { ... }
@include media-breakpoint-up(lg) { ... }
@include media-breakpoint-up(xl) { ... }
breakpoint & up values:
// Extra small devices (portrait phones, less than 576px)
// No media query since this is the default in Bootstrap
// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }
// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }
// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }
// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }
breakpoint & down (toggle on value and down):
@include media-breakpoint-down(xs) { ... }
@include media-breakpoint-down(sm) { ... }
@include media-breakpoint-down(md) { ... }
@include media-breakpoint-down(lg) { ... }
breakpoint & down values:
// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }
// Small devices (landscape phones, less than 768px)
@media (max-width: 767px) { ... }
// Medium devices (tablets, less than 992px)
@media (max-width: 991px) { ... }
// Large devices (desktops, less than 1200px)
@media (max-width: 1199px) { ... }
// Extra large devices (large desktops)
// No media query since the extra-large breakpoint has no upper bound on its width
breakpoint only:
@include media-breakpoint-only(xs) { ... }
@include media-breakpoint-only(sm) { ... }
@include media-breakpoint-only(md) { ... }
@include media-breakpoint-only(lg) { ... }
@include media-breakpoint-only(xl) { ... }
breakpoint only values (toggle in between values only):
// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }
// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) and (max-width: 767px) { ... }
// Medium devices (tablets, 768px and up)
@media (min-width: 768px) and (max-width: 991px) { ... }
// Large devices (desktops, 992px and up)
@media (min-width: 992px) and (max-width: 1199px) { ... }
// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }
here's my 2 cents worth:
forpromise()
function forpromise(lo, hi, st, res, fn) {_x000D_
if (typeof res === 'function') {_x000D_
fn = res;_x000D_
res = undefined;_x000D_
}_x000D_
if (typeof hi === 'function') {_x000D_
fn = hi;_x000D_
hi = lo;_x000D_
lo = 0;_x000D_
st = 1;_x000D_
}_x000D_
if (typeof st === 'function') {_x000D_
fn = st;_x000D_
st = 1;_x000D_
}_x000D_
return new Promise(function(resolve, reject) {_x000D_
_x000D_
(function loop(i) {_x000D_
if (i >= hi) return resolve(res);_x000D_
const promise = new Promise(function(nxt, brk) {_x000D_
try {_x000D_
fn(i, nxt, brk);_x000D_
} catch (ouch) {_x000D_
return reject(ouch);_x000D_
}_x000D_
});_x000D_
promise._x000D_
catch (function(brkres) {_x000D_
hi = lo - st;_x000D_
resolve(brkres)_x000D_
}).then(function(el) {_x000D_
if (res) res.push(el);_x000D_
loop(i + st)_x000D_
});_x000D_
})(lo);_x000D_
_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
//no result returned, just loop from 0 thru 9_x000D_
forpromise(0, 10, function(i, next) {_x000D_
console.log("iterating:", i);_x000D_
next();_x000D_
}).then(function() {_x000D_
_x000D_
_x000D_
console.log("test result 1", arguments);_x000D_
_x000D_
//shortform:no result returned, just loop from 0 thru 4_x000D_
forpromise(5, function(i, next) {_x000D_
console.log("counting:", i);_x000D_
next();_x000D_
}).then(function() {_x000D_
_x000D_
console.log("test result 2", arguments);_x000D_
_x000D_
_x000D_
_x000D_
//collect result array, even numbers only_x000D_
forpromise(0, 10, 2, [], function(i, collect) {_x000D_
console.log("adding item:", i);_x000D_
collect("result-" + i);_x000D_
}).then(function() {_x000D_
_x000D_
console.log("test result 3", arguments);_x000D_
_x000D_
//collect results, even numbers, break loop early with different result_x000D_
forpromise(0, 10, 2, [], function(i, collect, break_) {_x000D_
console.log("adding item:", i);_x000D_
if (i === 8) return break_("ending early");_x000D_
collect("result-" + i);_x000D_
}).then(function() {_x000D_
_x000D_
console.log("test result 4", arguments);_x000D_
_x000D_
// collect results, but break loop on exception thrown, which we catch_x000D_
forpromise(0, 10, 2, [], function(i, collect, break_) {_x000D_
console.log("adding item:", i);_x000D_
if (i === 4) throw new Error("failure inside loop");_x000D_
collect("result-" + i);_x000D_
}).then(function() {_x000D_
_x000D_
console.log("test result 5", arguments);_x000D_
_x000D_
})._x000D_
catch (function(err) {_x000D_
_x000D_
console.log("caught in test 5:[Error ", err.message, "]");_x000D_
_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
_x000D_
});
_x000D_
You can try/catch PDOException
s (your configs could differ but the important part is the try/catch):
try {
$dbh = new PDO(
DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
DB_USER,
DB_PASS,
[
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE
]
);
} catch ( PDOException $e ) {
echo 'ERROR!';
print_r( $e );
}
The print_r( $e );
line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'
.
Just add this to your CSS
/* 5 Columns */
.col-xs-15,
.col-sm-15,
.col-md-15,
.col-lg-15 {
position: relative;
min-height: 1px;
padding-right: 10px;
padding-left: 10px;
}
.col-xs-15 {
width: 20%;
float: left;
}
@media (min-width: 768px) {
.col-sm-15 {
width: 20%;
float: left;
}
}
@media (min-width: 992px) {
.col-md-15 {
width: 20%;
float: left;
}
}
@media (min-width: 1200px) {
.col-lg-15 {
width: 20%;
float: left;
}
}
As sklearn.cross_validation
module was deprecated, you can use:
import numpy as np
from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5)
X_trn, X_tst, y_trn, y_tst = train_test_split(X, y, test_size=0.2, random_state=42)
Bitmap
The accepted answer will crash when the Bitmap
is too large. I believe it's a 1MB limit. The Bitmap
must be compressed into a different file format such as a JPG represented by a ByteArray
, then it can be safely passed via an Intent
.
The function is contained in a separate thread using Kotlin Coroutines because the Bitmap
compression is chained after the Bitmap
is created from an url String
. The Bitmap
creation requires a separate thread in order to avoid Application Not Responding (ANR) errors.
toBitmap()
is a Kotlin extension function requiring that library to be added to the app dependencies.Bitmap
to JPG ByteArray
after it has been created.Repository.kt
suspend fun bitmapToByteArray(url: String) = withContext(Dispatchers.IO) {
MutableLiveData<Lce<ContentResult.ContentBitmap>>().apply {
postValue(Lce.Loading())
postValue(Lce.Content(ContentResult.ContentBitmap(
ByteArrayOutputStream().apply {
try {
BitmapFactory.decodeStream(URL(url).openConnection().apply {
doInput = true
connect()
}.getInputStream())
} catch (e: IOException) {
postValue(Lce.Error(ContentResult.ContentBitmap(ByteArray(0), "bitmapToByteArray error or null - ${e.localizedMessage}")))
null
}?.compress(CompressFormat.JPEG, BITMAP_COMPRESSION_QUALITY, this)
}.toByteArray(), "")))
}
}
ViewModel.kt
//Calls bitmapToByteArray from the Repository
private fun bitmapToByteArray(url: String) = liveData {
emitSource(switchMap(repository.bitmapToByteArray(url)) { lce ->
when (lce) {
is Lce.Loading -> liveData {}
is Lce.Content -> liveData {
emit(Event(ContentResult.ContentBitmap(lce.packet.image, lce.packet.errorMessage)))
}
is Lce.Error -> liveData {
Crashlytics.log(Log.WARN, LOG_TAG,
"bitmapToByteArray error or null - ${lce.packet.errorMessage}")
}
}
})
}
ByteArray
via an Intent
.In this sample it's passed from a Fragment to a Service. It's the same concept if being shared between two Activities.
Fragment.kt
ContextCompat.startForegroundService(
context!!,
Intent(context, AudioService::class.java).apply {
action = CONTENT_SELECTED_ACTION
putExtra(CONTENT_SELECTED_BITMAP_KEY, contentPlayer.image)
})
ByteArray
back to Bitmap
.Utils.kt
fun ByteArray.byteArrayToBitmap(context: Context) =
run {
BitmapFactory.decodeByteArray(this, BITMAP_OFFSET, size).run {
if (this != null) this
// In case the Bitmap loaded was empty or there is an error I have a default Bitmap to return.
else AppCompatResources.getDrawable(context, ic_coinverse_48dp)?.toBitmap()
}
}
The simplest and most elegant way is as follows:
all(x==myList[0] for x in myList)
(Yes, this even works with the empty list! This is because this is one of the few cases where python has lazy semantics.)
Regarding performance, this will fail at the earliest possible time, so it is asymptotically optimal.
string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);
Note: the hash is important!
You can't select a range without having first selected the sheet it is in. Try to select the sheet first and see if you still get the problem:
sourceSheetSum.Select
sourceSheetSum.Range("C3").Select
If anyone else is having the same problem, this is how I did it
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Reference : Move file using Java
Flame graphs can be helpful in identifying the execution paths that are consuming the most CPU time.
In short, the following are the steps to generate flame graphs
yum -y install perf
wget https://github.com/jvm-profiling-tools/async-profiler/releases/download/v1.8.3/async-profiler-1.8.3-linux-x64.tar.gz
tar -xvf async-profiler-1.8.3-linux-x64.tar.gz
chmod -R 777 async-profiler-1.8.3-linux-x64
cd async-profiler-1.8.3-linux-x64
echo 1 > /proc/sys/kernel/perf_event_paranoid
echo 0 > /proc/sys/kernel/kptr_restrict
JAVA_PID=`pgrep java`
./profiler.sh -d 30 $JAVA_PID -f flame-graph.svg
flame-graph.svg
can be opened using browsers as well, and in short, the width of the element in stack trace specifies the number of thread dumps that contain the execution flow relatively.
There are few other approaches to generating them
-XX:+PreserveFramePointer
as the JVM options as described here-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints
as described hereBut using async-profiler without providing any options though not very accurate, can be leveraged with no changes to the running Java process with low CPU overhead to the process.
Their wiki provides details on how to leverage it. And more about flame graphs can be found here
Building on @IllidanS4 's answer, I have created a template class that allows virtually any member function with predefined arguments and class instance to be passed by reference for later calling.
template<class RET, class... RArgs> class Callback_t {
public:
virtual RET call(RArgs&&... rargs) = 0;
//virtual RET call() = 0;
};
template<class T, class RET, class... RArgs> class CallbackCalltimeArgs : public Callback_t<RET, RArgs...> {
public:
T * owner;
RET(T::*x)(RArgs...);
RET call(RArgs&&... rargs) {
return (*owner.*(x))(std::forward<RArgs>(rargs)...);
};
CallbackCalltimeArgs(T* t, RET(T::*x)(RArgs...)) : owner(t), x(x) {}
};
template<class T, class RET, class... Args> class CallbackCreattimeArgs : public Callback_t<RET> {
public:
T* owner;
RET(T::*x)(Args...);
RET call() {
return (*owner.*(x))(std::get<Args&&>(args)...);
};
std::tuple<Args&&...> args;
CallbackCreattimeArgs(T* t, RET(T::*x)(Args...), Args&&... args) : owner(t), x(x),
args(std::tuple<Args&&...>(std::forward<Args>(args)...)) {}
};
Test / example:
class container {
public:
static void printFrom(container* c) { c->print(); };
container(int data) : data(data) {};
~container() {};
void print() { printf("%d\n", data); };
void printTo(FILE* f) { fprintf(f, "%d\n", data); };
void printWith(int arg) { printf("%d:%d\n", data, arg); };
private:
int data;
};
int main() {
container c1(1), c2(20);
CallbackCreattimeArgs<container, void> f1(&c1, &container::print);
Callback_t<void>* fp1 = &f1;
fp1->call();//1
CallbackCreattimeArgs<container, void, FILE*> f2(&c2, &container::printTo, stdout);
Callback_t<void>* fp2 = &f2;
fp2->call();//20
CallbackCalltimeArgs<container, void, int> f3(&c2, &container::printWith);
Callback_t<void, int>* fp3 = &f3;
fp3->call(15);//20:15
}
Obviously, this will only work if the given arguments and owner class are still valid. As far as readability... please forgive me.
Edit: removed unnecessary malloc by making the tuple normal storage. Added inherited type for the reference. Added option to provide all arguments at calltime instead. Now working on having both....
Edit 2: As promised, both. Only restriction (that I see) is that the predefined arguments must come before the runtime supplied arguments in the callback function. Thanks to @Chipster for some help with gcc compliance. This works on gcc on ubuntu and visual studio on windows.
#ifdef _WIN32
#define wintypename typename
#else
#define wintypename
#endif
template<class RET, class... RArgs> class Callback_t {
public:
virtual RET call(RArgs... rargs) = 0;
virtual ~Callback_t() = default;
};
template<class RET, class... RArgs> class CallbackFactory {
private:
template<class T, class... CArgs> class Callback : public Callback_t<RET, RArgs...> {
private:
T * owner;
RET(T::*x)(CArgs..., RArgs...);
std::tuple<CArgs...> cargs;
RET call(RArgs... rargs) {
return (*owner.*(x))(std::get<CArgs>(cargs)..., rargs...);
};
public:
Callback(T* t, RET(T::*x)(CArgs..., RArgs...), CArgs... pda);
~Callback() {};
};
public:
template<class U, class... CArgs> static Callback_t<RET, RArgs...>* make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...));
};
template<class RET2, class... RArgs2> template<class T2, class... CArgs2> CallbackFactory<RET2, RArgs2...>::Callback<T2, CArgs2...>::Callback(T2* t, RET2(T2::*x)(CArgs2..., RArgs2...), CArgs2... pda) : x(x), owner(t), cargs(std::forward<CArgs2>(pda)...) {}
template<class RET, class... RArgs> template<class U, class... CArgs> Callback_t<RET, RArgs...>* CallbackFactory<RET, RArgs...>::make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...)) {
return new wintypename CallbackFactory<RET, RArgs...>::Callback<U, CArgs...>(owner, func, std::forward<CArgs>(cargs)...);
}
I had a similar issue but specifically in a Jenkins build environment. To fix the issue, I switched from using a copy command in the post build event to using a copy target.
I changed this:
<PropertyGroup>
<PostBuildEvent>copy $(ProjectDir)bin\BLAH.Common.xml $(ProjectDir)App_Data\BLAH.Common.xml</PostBuildEvent>
</PropertyGroup>
to this:
<Target Name="AfterBuild">
<Copy SourceFiles="$(ProjectDir)bin\BLAH.Common.xml" DestinationFolder="$(ProjectDir)App_Data\" />
</Target>
and it works fine now.
The specific error I was getting was:
(PostBuildEvent target) ->
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(4291,5): error MSB3073: The command "copy <http://1.2.3.4/job/BLAHv2/ws/Api/bin/BLAH.Common.xml> <http://1.2.3.4/job/BLAHv2/ws/Api/App_Data/BLAH.Common.xml"> exited with code 1. [<http://1.2.3.4/job/BLAHv2/ws/Api/Api.csproj]>
Here is a full example on how to transform your date in different types:
Date date = Calendar.getInstance().getTime();
// Display a date in day, month, year format
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String today = formatter.format(date);
System.out.println("Today : " + today);
// Display date with day name in a short format
formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
today = formatter.format(date);
System.out.println("Today : " + today);
// Display date with a short day and month name
formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
today = formatter.format(date);
System.out.println("Today : " + today);
// Formatting date with full day and month name and show time up to
// milliseconds with AM/PM
formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
today = formatter.format(date);
System.out.println("Today : " + today);
This program is an efficient one. I have added one more check-in if to get the square root of a number and check is it divisible or not if it's then its not a prime number. this will solve all the problems efficiently.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T; // number of test cases
T = sc.nextInt();
long[] number = new long[T];
if(1<= T && T <= 30){
for(int i =0;i<T;i++){
number[i]=sc.nextInt(); // read all the numbers
}
for(int i =0;i<T;i++){
if(isPrime(number[i]))
System.out.println("Prime");
else
System.out.println("Not prime");
}
}
else
return;
}
// is prime or not
static boolean isPrime(long num){
if(num==1)
return false;
if(num <= 3)
return true;
if(num % 2 == 0 || num % 3 == 0 || num % (int)Math.sqrt(num) == 0)
return false;
for(int i=4;i<(int)Math.sqrt(num);i++){
if(num%i==0)
return false;
}
return true;
}
README.md
or .mkdn
or .markdown
denotes that the file is markdown formatted.
Markdown is a markup language. With it you can easily display headers or have italic words, or bold or almost anything that can be done to text
To answer your extra question
:
You can set which rows should be repeated on every page using:
$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);
Now, row 1, 2, 3, 4 and 5 will be repeated.
Use css:
<style>
input[name=btnsubmit]:active {
color: green;
}
</style>
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
$("#message > span").text("your text");
or
$("#message").find("span").text("your text");
or
$("span","#message").text("your text");
or
$("#message > a.close-notify").siblings('span').text("your text");
You can easily create timed redirections with JavaScript. But I suggest you to use location.replace('url') instead of location.href. It prevents to browser to push the site into the history. I found this JavaScript redirect tool. I think you could use this.
Example code (with 5 secs delay):
<!-- Pleace this snippet right after opening the head tag to make it work properly -->
<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->
<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.com/"/>
<noscript>
<meta http-equiv="refresh" content="5;URL=https://yourdomain.com/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
var url = "https://yourdomain.com/";
var delay = "5000";
window.onload = function ()
{
setTimeout(GoToURL, delay);
}
function GoToURL()
{
if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
{
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
else { window.location.replace(url); } // All other browsers
}
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->
Other way for get a list just local branch is:
git branch -a | grep -v 'remotes'
The correct answer is
Options -Indexes
You must have been thinking of
AllowOverride All
https://httpd.apache.org/docs/2.2/howto/htaccess.html
.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.
This is my unzip method, which I use:
private boolean unpackZip(String path, String zipname)
{
InputStream is;
ZipInputStream zis;
try
{
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
while((ze = zis.getNextEntry()) != null)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
String filename = ze.getName();
FileOutputStream fout = new FileOutputStream(path + filename);
// reading and writing
while((count = zis.read(buffer)) != -1)
{
baos.write(buffer, 0, count);
byte[] bytes = baos.toByteArray();
fout.write(bytes);
baos.reset();
}
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
Use the keys CtrlK,C to comment out the line and CtrlK,U to uncomment the line.
JsonMappingException: out of START_ARRAY token
exception is thrown by Jackson object mapper as it's expecting an Object {}
whereas it found an Array [{}]
in response.
This can be solved by replacing Object
with Object[]
in the argument for geForObject("url",Object[].class)
.
References:
I have implemented this in my code.
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 31.0f)];
view1.backgroundColor = [UIColor clearColor];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view1.bounds;
UIColor *topColor = [UIColor colorWithRed:132.0/255.0 green:222.0/255.0 blue:109.0/255.0 alpha:1.0];
UIColor *bottomColor = [UIColor colorWithRed:31.0/255.0 green:150.0/255.0 blue:99.0/255.0 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[topColor CGColor], (id)[bottomColor CGColor], nil];
[view1.layer insertSublayer:gradient atIndex:0];
Now I can see a gradient on my view.
To prevent full size category images slowing page down, you can use smaller images with wp_get_attachment_image_src()
:
<?php
$thumbnail_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
// get the medium-sized image url
$image = wp_get_attachment_image_src( $thumbnail_id, 'medium' );
// Output in img tag
echo '<img src="' . $image[0] . '" alt="" />';
// Or as a background for a div
echo '<div class="image" style="background-image: url("' . $image[0] .'")"></div>';
?>
EDIT: Fixed variable name and missing quote
Use if foo
or if not foo
. There isn't any need for either ==
or is
for that.
For checking against None, is None
and is not None
are recommended. This allows you to distinguish it from False (or things that evaluate to False, like ""
and []
).
Whether get_attr
should return None
would depend on the context. You might have an attribute where the value is None, and you wouldn't be able to do that. I would interpret None
as meaning "unset", and a KeyError
would mean the key does not exist in the file.
Select Req_ID, sum(R1+R2+R3+R4+R5)/5 as Average
from Request
Group by Req_ID;
Marginally better...
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]
I think this is similar to what the last podcast discussed. The "Be liberal in what you accept" means that extra work had to be put into the Javascript parser to fix cases where semicolons were left out. Now we have a boatload of pages out there floating around with bad syntax, that might break one day in the future when some browser decides to be a little more stringent on what it accepts. This type of rule should also apply to HTML and CSS. You can write broken HTML and CSS, but don't be surprise when you get weird and hard to debug behaviors when some browser doesn't properly interpret your incorrect code.
if you still stuck or you get this
C:\\\Users\\\name of your\\\AppData\\\Local\\\Programs\\\Python\\\Python36
simply do this replace 2 \ with one
C:\Users\akshay\AppData\Local\Programs\Python\Python36
you can use like this
private dynamic defaultReminder => reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
In short:
If you are using ES6 without transpilers:
class CustomError extends Error { /* ... */}
See Extending Error in Javascript with ES6 syntax for what's the current best practice
If you are using Babel transpiler:
Option 1: use babel-plugin-transform-builtin-extend
Option 2: do it yourself (inspired from that same library)
function CustomError(...args) {
const instance = Reflect.construct(Error, args);
Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this));
return instance;
}
CustomError.prototype = Object.create(Error.prototype, {
constructor: {
value: Error,
enumerable: false,
writable: true,
configurable: true
}
});
Reflect.setPrototypeOf(CustomError, Error);
If you are using pure ES5:
function CustomError(message, fileName, lineNumber) {
const instance = new Error(message, fileName, lineNumber);
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
return instance;
}
CustomError.prototype = Object.create(Error.prototype, {
constructor: {
value: Error,
enumerable: false,
writable: true,
configurable: true
}
});
if (Object.setPrototypeOf){
Object.setPrototypeOf(CustomError, Error);
} else {
CustomError.__proto__ = Error;
}
Alternative: use Classtrophobic framework
Explanation:
Why extending the Error class using ES6 and Babel is a problem?
Because an instance of CustomError is not anymore recognized as such.
class CustomError extends Error {}
console.log(new CustomError('test') instanceof Error);// true
console.log(new CustomError('test') instanceof CustomError);// false
In fact, from the official documentation of Babel, you cannot extend any built-in JavaScript classes such as Date
, Array
, DOM
or Error
.
The issue is described here:
What about the other SO answers?
All the given answers fix the instanceof
issue but you lose the regular error console.log
:
console.log(new CustomError('test'));
// output:
// CustomError {name: "MyError", message: "test", stack: "Error? at CustomError (<anonymous>:4:19)? at <anonymous>:1:5"}
Whereas using the method mentioned above, not only you fix the instanceof
issue but you also keep the regular error console.log
:
console.log(new CustomError('test'));
// output:
// Error: test
// at CustomError (<anonymous>:2:32)
// at <anonymous>:1:5
By default, Maven only runs tests that have Test somewhere in the class name.
Rename to IntegrationTest and it'll probably work.
Alternatively you can change the Maven config to include that file but it's probably easier and better just to name your tests SomethingTest.
From Inclusions and Exclusions of Tests:
By default, the Surefire Plugin will automatically include all test classes with the following wildcard patterns:
\*\*/Test\*.java
- includes all of its subdirectory and all java filenames that start with "Test".\*\*/\*Test.java
- includes all of its subdirectory and all java filenames that end with "Test".\*\*/\*TestCase.java
- includes all of its subdirectory and all java filenames that end with "TestCase".If the test classes does not go with the naming convention, then configure Surefire Plugin and specify the tests you want to include.
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.
Some RFID chips are read-write, the majority are read-only. You can find out if your chip is read-only by checking the datasheet.
If you want a list of columns of a certain type, you can use groupby
:
>>> df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
>>> df
A B C D E
0 1 2.3456 c d 78
[1 rows x 5 columns]
>>> df.dtypes
A int64
B float64
C object
D object
E int64
dtype: object
>>> g = df.columns.to_series().groupby(df.dtypes).groups
>>> g
{dtype('int64'): ['A', 'E'], dtype('float64'): ['B'], dtype('O'): ['C', 'D']}
>>> {k.name: v for k, v in g.items()}
{'object': ['C', 'D'], 'int64': ['A', 'E'], 'float64': ['B']}
I am guessing that you are running the file using Run | Run File
(or shift-F6) rather than Run | Run Main Project
. The NetBeans 7.1 help file (F1 is your friend!) states for the Arguments parameter:
Add arguments to pass to the main class during application execution. Note that arguments cannot be passed to individual files.
I verified this with a little snippet of code:
public class Junk
{
public static void main(String[] args)
{
for (String s : args)
System.out.println("arg -> " + s);
}
}
I set Run -> Arguments to x y z
. When I ran the file by itself I got no output. When I ran the project the output was:
arg -> x
arg -> y
arg -> z
Use isinstance
, nothing else:
if isinstance(x, pd.DataFrame):
... # do something
PEP8 says explicitly that isinstance
is the preferred way to check types
No: type(x) is pd.DataFrame
No: type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)
And don't even think about
if obj.__class__.__name__ = 'DataFrame':
expect_problems_some_day()
isinstance
handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str
or unicode
), because they derive from basestring
)
if isinstance(obj, basestring):
i_am_string(obj)
Specifically for pandas
DataFrame
objects:
import pandas as pd
isinstance(var, pd.DataFrame)
That was my case. It actually links to question #4485874, but I'm going to explain it here shortly.
When you try to require path/to/script.php?parameter=value
, PHP looks for file named script.php?parameter=value
, because UNIX allows you to have paths like this.
If you are really need to pass some data to included script, just declare it as $variable=...
or $GLOBALS[]=...
or other way you like.
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
I would use inspect.currentframe().f_back.f_code.co_name
. Its use hasn't been covered in any of the prior answers which are mainly of one of three types:
inspect.stack
but it's known to be too slow.sys._getframe
which is an internal private function given its leading underscore, and so its use is implicitly discouraged.inspect.getouterframes(inspect.currentframe(), 2)[1][3]
but it's entirely unclear what [1][3]
is accessing.import inspect
from types import FrameType
from typing import cast
def caller_name() -> str:
"""Return the calling function's name."""
# Ref: https://stackoverflow.com/a/57712700/
return cast(FrameType, cast(FrameType, inspect.currentframe()).f_back).f_code.co_name
if __name__ == '__main__':
def _test_caller_name() -> None:
assert caller_name() == '_test_caller_name'
_test_caller_name()
Note that cast(FrameType, frame)
is used to satisfy mypy
.
Acknowlegement: comment by 1313e for an answer.
You have to set all \"
(quotes) carefully. The parameter \k
is used to leave the command prompt open after the execution.
1) to combine 2 commands use (for example pause
and ipconfig
)
Runtime.getRuntime()
.exec("cmd /c start cmd.exe /k \"pause && ipconfig\"", null, selectedFile.getParentFile());
2) to show the content of a file use (MORE
is a command line viewer on Windows)
File selectedFile = new File(pathToFile):
Runtime.getRuntime()
.exec("cmd /c start cmd.exe /k \"MORE \"" + selectedFile.getName() + "\"\"", null, selectedFile.getParentFile());
One nesting quote \" is for the command and the file name, the second quote \" is for the filename itself, for spaces etc. in the name particularly.
The command you have typed is /startup.sh
, if you have to start a shell script you have to fire the command as shown below:
$ cd /home/mpatil/softwares/apache-tomcat-7.0.47/bin
$ sh startup.sh
or
$ ./startup.sh
Please try that, you also have to go to your tomcat's bin-folder (by using the cd-command) to execute this shell script. In your case this is /home/mpatil/softwares/apache-tomcat-7.0.47/bin
.
As of ECMAScript 6, you can use Array.prototype.find
for this. This is implemented and working in Firefox (25.0), Chrome (45.0), Edge (12), and Safari (7.1), but not in Internet Explorer or a bunch of other old or uncommon platforms.
For example, x
below is 106
:
const x = [100,101,102,103,104,105,106,107,108,109].find(function (el) {
return el > 105;
});
console.log(x);
_x000D_
If you want to use this right now but need support for IE or other unsupporting browsers, you can use a shim. I recommend the es6-shim. MDN also offers a shim if for some reason you don't want to put the whole es6-shim into your project. For maximum compatibility you want the es6-shim, because unlike the MDN version it detects buggy native implementations of find
and overwrites them (see the comment that begins "Work around bugs in Array#find and Array#findIndex" and the lines immediately following it).
It's also useful to note that you can run the underlying MapReduce jobs with either the source or target cluster like so:
hadoop --config /path/to/hadoop/config distcp <src> <dst>
I had Lombok plugin, annotations enabled, it was compiling from command line - everything and it still did not see my project as maven (all maven dependencies were red in source files). Then I clicked SHIFT twice and searched for 'maven' and among results there was 'Reload all Maven Projects'. After running it Maven tab appeared and I was able to compile, and all red underlining in source code disappeared.
You might have not closed the the output. Close the output, clean and rebuild the file. You might be able to run the file now.
Sometimes this issue is faced when the node server stoped. So, check if your node server working ok.
Then you can use io.set('origins', 'http://yourdomain.com:PORT_NUMBER');
You can edit it. The content of the file is literally "Deny from all" which is an Apache directive: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#deny
You may find pylocker very useful. It can be used to lock a file or for locking mechanisms in general and can be accessed from multiple Python processes at once.
If you simply want to lock a file here's how it works:
import uuid
from pylocker import Locker
# create a unique lock pass. This can be any string.
lpass = str(uuid.uuid1())
# create locker instance.
FL = Locker(filePath='myfile.txt', lockPass=lpass, mode='w')
# aquire the lock
with FL as r:
# get the result
acquired, code, fd = r
# check if aquired.
if fd is not None:
print fd
fd.write("I have succesfuly aquired the lock !")
# no need to release anything or to close the file descriptor,
# with statement takes care of that. let's print fd and verify that.
print fd
You may also use the defer
attribute in the script
tag.
As long as you do not specify async
which would of course not be useful for your aim.
Example:
<script src="//other-domain.com/script.js" defer></script>
<script src="myscript.js" defer></script>
As described here:
In the above example, the browser will download both scripts in parallel and execute them just before DOMContentLoaded fires, maintaining their order.
[...] deferred scripts should run after the document had parsed, in the order they were added [...]
Related Stackoverflow discussions: How exactly does <script defer=“defer”>
work?
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
I also had this problem and it's solved as change line from res/values/styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
both solutions worked
this will clear Task(stack of activities) and begin new Task
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
System.exit(1);
No- you can definitely handle more than that.
Its important to remember that deep deep down, assuming you are running a single core machine, the CPU really only runs one instruction* at a time.
Namely, the CPU can only execute a very limited set of instructions, and it can't execute more than one instruction per clock tick (many instructions even take more than 1 tick).
Therefore, most concurrency we talk about in computer science is software concurrency. In other words, there are layers of software implementation that abstract the bottom level CPU from us and make us think we are running code concurrently.
These "things" can be processes, which are units of code that get run concurrently in the sense that each process thinks its running in its own world with its own, non-shared memory.
Another example is threads, which are units of code inside processes that allow concurrency as well.
The reason your 4 worker processes will be able to handle more than 4 requests is that they will fire off threads to handle more and more requests.
The actual request limit depends on HTTP server chosen, I/O, OS, hardware, network connection etc.
Good luck!
*instructions are the very basic commands the CPU can run. examples - add two numbers, jump from one instruction to another
Since no answer stated this:
Make sure that, if you are using a virtual environment, you have activated it before trying to run the program.
If you don't really know if you are using a virtual environment or not, check with the other contributors of the project. Or maybe try to find a file with the name activate
like this: find . -name activate
.
boolarr.sum(axis=1 or axis=0)
axis = 1 will output number of trues in a row and axis = 0 will count number of trues in columns so
boolarr[[true,true,true],[false,false,true]]
print(boolarr.sum(axis=1))
will be (3,1)
If, rather than writing new code to trim a string, you're looking at existing code that calls "strip()" and wondering why it isn't working, you might want to check whether it attempts to include something like the prototypejs framework, and make sure it's actually getting loaded.
That framework adds a strip function to all String objects, but if e.g. you upgraded it and your web pages are still referring to the old .js file it'll of course not work.
In case of an associative array or numbered array where you do not want to change the array keys:
$firstItem = array('foo' => 'bar');
$arr = $firstItem + $arr;
array_merge
does not work as it always reindexes the array.
Instead of src
you need ng-src
.
AngularJS views support binary operators
condition && true || false
So your img
tag would look like this
<img ng-src="{{interface == 'UP' && 'green-checkmark.png' || 'big-black-X.png'}}"/>
Note : the quotes (ie 'green-checkmark.png') are important here. It won't work without quotes.
plunker here (open dev tools to see the produced HTML)
In case if you don't want to use google geocoding API than you can refer to few other Free APIs for the development purpose. for example i used [mapquest] API in order to get the location name.
you can fetch location name easily by implementing this following function
const fetchLocationName = async (lat,lng) => {
await fetch(
'https://www.mapquestapi.com/geocoding/v1/reverse?key=API-Key&location='+lat+'%2C'+lng+'&outFormat=json&thumbMaps=false',
)
.then((response) => response.json())
.then((responseJson) => {
console.log(
'ADDRESS GEOCODE is BACK!! => ' + JSON.stringify(responseJson),
);
});
};
_x000D_
Best description is on: http://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en
For simple use permissions you can use this lib: http://hotchemi.github.io/PermissionsDispatcher/
You can use the find function:
if($('#popup').find('p.filled-text').length !== 0)
// Do Stuff
Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.
Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B");
}
if(j%100==0){ //Adding a line break in second loop
System.out.println();
}
}
System.out.println("");
}
Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.
I was having the same problem and I went nuts searching in my code for the answer. Finally I found my hosting recently updated the PHP version on my server and didn't correctly set up the session_save_path
parameter on the php.ini
file.
So, if someone reads this, please check php.ini
config before anything else.
It's not an error. Javascript will gladly convert a number to a string when a string is expected (for example parseInt(42)
), but in this case there is nothing that expect the number to be a string.
Here's a makeLowerCase
function. :)
function makeLowerCase(value) {
return value.toString().toLowerCase();
}
Instead of this line
if(Array[i].compareTo(Array[j])<0)
use this line
if(Array[i].trim().compareTo(Array[j].trim())<0)
and you are good to go. The reason your current code is not working is explained by other users already. This above replacement is one workaround amongst several that you could apply.
click link get example file upload clint java with apache HttpComponents
and library downalod link
https://hc.apache.org/downloads.cgi
use 4.5.3.zip it's working fine in my code
and my working code..
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet");
FileBody bin = new FileBody(new File("E:\\meter.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
I had one long table td cell, this forced the table to the edges of the browser and looked ugly. I just wanted that column to be fixed size only and break the words when it reaches the specified width. So this worked well for me:
<td><div style='width: 150px;'>Text to break here</div></td>
You don't need to specify any kind of style to table, tr elements. You may also use overflow:hidden; as suggested by other answers but it causes for the excess text to disappear.
Just close your IDE (VISUAL STUDIO/ATOM etc). It might work
Try this if you are using virtual enviroment :-
python manage.py shell
for using those command you must be inside virtual enviroment. for this use :-
workon vir_env_name
for example :-
dc@dc-comp-4:~/mysite$ workon jango
(jango)dc@dc-comp-4:~/mysite$ python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
Note :- Here mysite is my website name and jango is my virtual enviroment name
the only thing you can do is to change your signature to
public static <E> E[] appendToArray(E[] array, E item)
Important details:
Generic expressions preceding the return value always introduce (declare) a new generic type variable.
Additionally, type variables between types (ArrayUtils
) and static methods (appendToArray
) never interfere with each other.
So, what does this mean:
In my answer <E>
would hide the E
from ArrayUtils<E>
if the method wouldn't be static
. AND <E>
has nothing to do with the E
from ArrayUtils<E>
.
To reflect this fact better, a more correct answer would be:
public static <I> I[] appendToArray(I[] array, I item)
SSH based git access method can be specified in <repo_path>/.git/config
using either a full URL or an SCP-like syntax, as specified in http://git-scm.com/docs/git-clone:
URL style:
url = ssh://[user@]host.xz[:port]/path/to/repo.git/
SCP style:
url = [user@]host.xz:path/to/repo.git/
Notice that the SCP style does not allow a direct port change, relying instead on an ssh_config
host definition in your ~/.ssh/config
such as:
Host my_git_host
HostName git.some.host.org
Port 24589
User not_a_root_user
Then you can test in a shell with:
ssh my_git_host
and alter your SCP-style URI in <repo_path>/.git/config
as:
url = my_git_host:path/to/repo.git/
private void WaitNSeconds(int seconds)
{
if (seconds < 1) return;
DateTime _desired = DateTime.Now.AddSeconds(seconds);
while (DateTime.Now < _desired) {
Thread.Sleep(1);
System.Windows.Forms.Application.DoEvents();
}
}
Yes, ensure
like finally
guarantees that the block will be executed. This is very useful for making sure that critical resources are protected e.g. closing a file handle on error, or releasing a mutex.
if somebody wants the answer in swift 3
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
switch application.applicationState {
case .active:
//app is currently active, can update badges count here
break
case .inactive:
//app is transitioning from background to foreground (user taps notification), do what you need when user taps here
break
case .background:
//app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
break
default:
break
}
}
Here is a partial solution to your linked list class, I have left the rest of the implementation to you, and also left the good suggestion to add a tail node as part of the linked list to you as well.
The node file :
public class Node
{
private Object data;
private Node next;
public Node(Object d)
{
data = d ;
next = null;
}
public Object GetItem()
{
return data;
}
public Node GetNext()
{
return next;
}
public void SetNext(Node toAppend)
{
next = toAppend;
}
}
And here is a Linked List file :
public class LL
{
private Node head;
public LL()
{
head = null;
}
public void AddToEnd(String x)
{
Node current = head;
// as you mentioned, this is the base case
if(current == null) {
head = new Node(x);
head.SetNext(null);
}
// you should understand this part thoroughly :
// this is the code that traverses the list.
// the germane thing to see is that when the
// link to the next node is null, we are at the
// end of the list.
else {
while(current.GetNext() != null)
current = current.GetNext();
// add new node at the end
Node toAppend = new Node(x);
current.SetNext(toAppend);
}
}
}
$(document).on("click", function(event){
var a = $(event.target).parents();
var flaghide = true;
a.each(function(index, val){
if(val == $(container)[0]){
flaghide = false;
}
});
if(flaghide == true){
//required code
}
})
This should work, try;
Add a System Reference.
using System.Diagnostics;
Then use this code to run your command in a hiden CMD Window.
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = "Enter your command here";
cmd.Start();
Check your code for errors in my case i had an error in Kernel.php. First solve errors if any Than run composer require ....(package you wish)
I prefer to use negative margin, gives you more control
ul {
margin-left: 0;
padding-left: 20px;
list-style: none;
}
li:before {
content: "*";
display: inline;
float: left;
margin-left: -18px;
}
How to write a compound statement with if?
You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.
if %ERRORLEVEL% == 0 (
echo ErrorLevel is zero
echo A second statement
) else if %ERRORLEVEL% == 1 (
echo ErrorLevel is one
echo A second statement
) else (
echo ErrorLevel is > 1
echo A second statement
)
If the default compiler chosen by cmake
is gcc
and you have installed clang
, you can use the easy way to compile your project with clang
:
$ mkdir build && cd build
$ CXX=clang++ CC=clang cmake ..
$ make -j2
This question needs a newer answer :)
const convertTime12to24 = (time12h) => {_x000D_
const [time, modifier] = time12h.split(' ');_x000D_
_x000D_
let [hours, minutes] = time.split(':');_x000D_
_x000D_
if (hours === '12') {_x000D_
hours = '00';_x000D_
}_x000D_
_x000D_
if (modifier === 'PM') {_x000D_
hours = parseInt(hours, 10) + 12;_x000D_
}_x000D_
_x000D_
return `${hours}:${minutes}`;_x000D_
}_x000D_
_x000D_
console.log(convertTime12to24('01:02 PM'));_x000D_
console.log(convertTime12to24('05:06 PM'));_x000D_
console.log(convertTime12to24('12:00 PM'));_x000D_
console.log(convertTime12to24('12:00 AM'));
_x000D_
It's not a matter of security. The HTTP protocol defines GET-type requests as being idempotent, while POSTs may have side effects. In plain English, that means that GET is used for viewing something, without changing it, while POST is used for changing something. For example, a search page should use GET, while a form that changes your password should use POST.
Also, note that PHP confuses the concepts a bit. A POST request gets input from the query string and through the request body. A GET request just gets input from the query string. So a POST request is a superset of a GET request; you can use $_GET
in a POST request, and it may even make sense to have parameters with the same name in $_POST
and $_GET
that mean different things.
For example, let's say you have a form for editing an article. The article-id may be in the query string (and, so, available through $_GET['id']
), but let's say that you want to change the article-id. The new id may then be present in the request body ($_POST['id']
). OK, perhaps that's not the best example, but I hope it illustrates the difference between the two.
EF 4.7 actually gives a hint when you run Enable-migrations at multiple context.
More than one context type was found in the assembly 'Service.Domain'.
To enable migrations for 'Service.Domain.DatabaseContext.Context1',
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context1.
To enable migrations for 'Service.Domain.DatabaseContext.Context2',
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context2.
This one's already accepted, but if there are any other dummies out there (like me) that didn't immediately get it from the presently accepted answer, here's a bit more detail.
The model class referenced by the ForeignKey
needs to have a __unicode__
method within it, like here:
class Category(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
That made the difference for me, and should apply to the above scenario. This works on Django 1.0.2.
This is a limitation of XmlSerializer
. Note that BinaryFormatter
and DataContractSerializer
do not require this - they can create an uninitialized object out of the ether and initialize it during deserialization.
Since you are using xml, you might consider using DataContractSerializer
and marking your class with [DataContract]
/[DataMember
], but note that this changes the schema (for example, there is no equivalent of [XmlAttribute]
- everything becomes elements).
Update: if you really want to know, BinaryFormatter
et al use FormatterServices.GetUninitializedObject()
to create the object without invoking the constructor. Probably dangerous; I don't recommend using it too often ;-p See also the remarks on MSDN:
Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.
I have my own serialization engine, but I don't intend making it use FormatterServices
; I quite like knowing that a constructor (any constructor) has actually executed.
I had the same problem but now I got it: Check which API you are selecting and for that API version is CPU/ABI available or not. If it's available then your work is done. Select the device according to the windows supporting it.
Your
<img src="/home/tony/london.jpg" />
will work for a HTML file read from disk, as it will assume the URL is file:///home/...
. For a file served from a webserver though, the URL will become something like: http://www.yourdomain.com/home/tony/london.jpg
, which can be an invalid URL and not what you really mean.
For about how to serve and where to place your static files, check out this document. Basicly, if you're using django's development server, you want to show him the place where your media files live, then make your urls.py
serve those files (for example, by using some /static/
url prefix).
Will require you to put something like this in your urls.py
:
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/path/to/media'}),
In production environment you want to skip this and make your http server (apache, lighttpd, etc) serve static files.
@Boushley's answer was the closest, however there is one problem not addressed that has been pointed out. The right div takes the entire width of the browser; the content takes the expected width. To see this problem better:
<html>
<head>
<style type="text/css">
* { margin: 0; padding: 0; }
body {
height: 100%;
}
#left {
opacity: 0;
height: inherit;
float: left;
width: 180px;
background: green;
}
#right {
height: inherit;
background: orange;
}
table {
width: 100%;
background: red;
}
</style>
</head>
<body>
<div id="left">
<p>Left</p>
</div>
<div id="right">
<table><tr><td>Hello, World!</td></tr></table>
</div>
</body>
</html>
The content is in the correct place (in Firefox), however, the width incorrect. When child elements start inheriting width (e.g. the table with width: 100%
) they are given a width equal to that of the browser causing them to overflow off the right of the page and create a horizontal scrollbar (in Firefox) or not float and be pushed down (in chrome).
You can fix this easily by adding overflow: hidden
to the right column. This gives you the correct width for both the content and the div. Furthermore, the table will receive the correct width and fill the remaining width available.
I tried some of the other solutions above, they didn't work fully with certain edge cases and were just too convoluted to warrant fixing them. This works and it's simple.
If there are any problems or concerns, feel free to raise them.
I think what you want is:
select {
direction: rtl;
}
fiddled here: http://jsfiddle.net/neilheinrich/XS3yQ/
For me, I got similar error when switched between branches - one used newer ("typescriptish") version of @google-cloud/datastore
packages which returns object with Datastore constructor as one of properties of exported object and I switched to other branch for a task, an older datastore version was used there, which exports Datastore constructor "directly" as module.exports
value. I got the error because node_modules still had newer modules used by branch I switched from.
I wrote this JS function dump()
to work like PHP's var_dump()
.
To show the contents of the variable in an alert window: dump(variable)
To show the contents of the variable in the web page: dump(variable, 'body')
To just get a string of the variable: dump(variable, 'none')
/* repeatString() returns a string which has been repeated a set number of times */
function repeatString(str, num) {
out = '';
for (var i = 0; i < num; i++) {
out += str;
}
return out;
}
/*
dump() displays the contents of a variable like var_dump() does in PHP. dump() is
better than typeof, because it can distinguish between array, null and object.
Parameters:
v: The variable
howDisplay: "none", "body", "alert" (default)
recursionLevel: Number of times the function has recursed when entering nested
objects or arrays. Each level of recursion adds extra space to the
output to indicate level. Set to 0 by default.
Return Value:
A string of the variable's contents
Limitations:
Can't pass an undefined variable to dump().
dump() can't distinguish between int and float.
dump() can't tell the original variable type of a member variable of an object.
These limitations can't be fixed because these are *features* of JS. However, dump()
*/
function dump(v, howDisplay, recursionLevel) {
howDisplay = (typeof howDisplay === 'undefined') ? "alert" : howDisplay;
recursionLevel = (typeof recursionLevel !== 'number') ? 0 : recursionLevel;
var vType = typeof v;
var out = vType;
switch (vType) {
case "number":
/* there is absolutely no way in JS to distinguish 2 from 2.0
so 'number' is the best that you can do. The following doesn't work:
var er = /^[0-9]+$/;
if (!isNaN(v) && v % 1 === 0 && er.test(3.0)) {
out = 'int';
}
*/
break;
case "boolean":
out += ": " + v;
break;
case "string":
out += "(" + v.length + '): "' + v + '"';
break;
case "object":
//check if null
if (v === null) {
out = "null";
}
//If using jQuery: if ($.isArray(v))
//If using IE: if (isArray(v))
//this should work for all browsers according to the ECMAScript standard:
else if (Object.prototype.toString.call(v) === '[object Array]') {
out = 'array(' + v.length + '): {\n';
for (var i = 0; i < v.length; i++) {
out += repeatString(' ', recursionLevel) + " [" + i + "]: " +
dump(v[i], "none", recursionLevel + 1) + "\n";
}
out += repeatString(' ', recursionLevel) + "}";
}
else {
//if object
let sContents = "{\n";
let cnt = 0;
for (var member in v) {
//No way to know the original data type of member, since JS
//always converts it to a string and no other way to parse objects.
sContents += repeatString(' ', recursionLevel) + " " + member +
": " + dump(v[member], "none", recursionLevel + 1) + "\n";
cnt++;
}
sContents += repeatString(' ', recursionLevel) + "}";
out += "(" + cnt + "): " + sContents;
}
break;
default:
out = v;
break;
}
if (howDisplay == 'body') {
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre);
}
else if (howDisplay == 'alert') {
alert(out);
}
return out;
}
Many UNIX programs respect the http_proxy
environment variable, curl included. The format curl accepts is [protocol://]<host>[:port]
.
In your shell configuration:
export http_proxy http://proxy.server.com:3128
For proxying HTTPS requests, set https_proxy
as well.
Curl also allows you to set this in your .curlrc
file (_curlrc
on Windows), which you might consider more permanent:
http_proxy=http://proxy.server.com:3128
A "float" in most environments is a binary floating-point type. It can accurately store base-2 values (to a certain point), but cannot accurately store many base-10 (decimal) values. Floats are most appropriate for scientific calculations. They're not appropriate for most business-oriented math, and inappropriate use of floats will bite you. Many decimal values can't be exactly represented in base-2. 0.1
can't, for instance, and so you see strange results like 1.0 - 0.1 = 0.8999999
.
Decimals store base-10 numbers. Decimal is an good type for most business math (but any built-in "money" type is more appropriate for financial calculations), where the range of values exceeds that provided by integer types, and fractional values are needed. Decimals, as the name implies, are designed for base-10 numbers - they can accurately store decimal values (again, to a certain point).
In my case, the problem was that I sorrounded my columns selection with parenthesis by mistake:
SELECT (p.column1, p.colum2, p.column3) FROM table1 p where p.column1 = 1;
And has to be:
SELECT p.column1, p.colum2, p.column3 FROM table1 p where p.column1 = 1;
Sounds silly, but it was causing this error and it took some time to figure it out.
You can achieve this with the background-size
property, which is now supported by most browsers.
To scale the background image to fit inside the div:
background-size: contain;
To scale the background image to cover the whole div:
background-size: cover;
There also exists a filter for IE 5.5+ support, as well as vendor prefixes for some older browsers.
You can solve that using display table.
Here is the updated JSFiddle that solves your problem.
CSS
.body {
display: table;
background-color: green;
}
.left-side {
background-color: blue;
float: none;
display: table-cell;
border: 1px solid;
}
.right-side {
background-color: red;
float: none;
display: table-cell;
border: 1px solid;
}
HTML
<div class="row body">
<div class="col-xs-9 left-side">
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
</div>
<div class="col-xs-3 right-side">
asdfdf
</div>
</div>
Another way to install openssl library from source code on Ubuntu, follows steps below, here WORKDIR
is your working directory:
sudo apt-get install pkg-config
cd WORKDIR
git clone https://github.com/openssl/openssl.git
cd openssl
./config
make
sudo make install
# Open file /etc/ld.so.conf, add a new line: "/usr/local/lib" at EOF
sudo ldconfig
It seems like you want
wait $PID
which will return when $pid
finishes.
Otherwise you can use
ps -p $PID
to check if the process is still alive (this is more effective than kill -0 $pid
because it will work even if you don't own the pid).
There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).
Converting your lists to sets will tell you that they contain the same elements. But this method cannot confirm that they contain the same number of all elements. For example, your method will fail in this case:
L1 = [1,2,2,3]
L2 = [1,2,3,3]
You are likely better off sorting the two lists and comparing them:
def checkEqual(L1, L2):
if sorted(L1) == sorted(L2):
print "the two lists are the same"
return True
else:
print "the two lists are not the same"
return False
Note that this does not alter the structure/contents of the two lists. Rather, the sorting creates two new lists
I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site
package javasandbox;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {
private static String sURL;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws MalformedURLException, IOException {
sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
System.out.println(sURL);
URL url = new URL(sURL);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
//set http request headers
httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
httpCon.addRequestProperty("Connection", "keep-alive");
httpCon.addRequestProperty("Cache-Control", "max-age=0");
httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
//httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
HttpURLConnection.setFollowRedirects(false);
httpCon.setInstanceFollowRedirects(false);
httpCon.setDoOutput(true);
httpCon.setUseCaches(true);
httpCon.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
System.out.println(a.toString());
httpCon.disconnect();
}
}
Your code is very vague and not understandable, but I can provide you with an alternative.
First of all, if you want temp
to go through the whole string, you can do something like this:
char *temp;
for (temp = your_string; *temp; ++temp)
/* do something with *temp */
The term *temp
as the for
condition simply checks whether you have reached the end of the string or not. If you have, *temp
will be '\0'
(NUL
) and the for
ends.
Now, inside the for, you want to find the bits that compose *temp
. Let's say we print the bits:
for (as above)
{
int bit_index;
for (bit_index = 7; bit_index >= 0; --bit_index)
{
int bit = *temp >> bit_index & 1;
printf("%d", bit);
}
printf("\n");
}
To make it a bit more generic, that is to convert any type to bits, you can change the bit_index = 7
to bit_index = sizeof(*temp)*8-1
You can define an upstream and use it in proxy_pass
http://rohanambasta.blogspot.com/2016/02/redirect-nginx-request-to-upstream.html
server {
listen 8082;
location ~ /(.*) {
proxy_pass test_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect off;
}
}
upstream test_server
{
server test-server:8989
}
Use map function
var values = $("input[name^='card']").map(function (idx, ele) {
return $(ele).val();
}).get();
As of OpenCV3.2, life just got a bit easier, you can now rotate an image in a single line of code:
cv::rotate(image, image, cv::ROTATE_90_CLOCKWISE);
For the direction you can choose any of the following:
ROTATE_90_CLOCKWISE
ROTATE_180
ROTATE_90_COUNTERCLOCKWISE
In this case, you can do ajax call inside componentDidMount
, and then update state
export default class UserList extends React.Component {
constructor(props) {
super(props);
this.state = {person: []};
}
componentDidMount() {
this.UserList();
}
UserList() {
$.getJSON('https://randomuser.me/api/')
.then(({ results }) => this.setState({ person: results }));
}
render() {
const persons = this.state.person.map((item, i) => (
<div>
<h1>{ item.name.first }</h1>
<span>{ item.cell }, { item.email }</span>
</div>
));
return (
<div id="layout-content" className="layout-content-wrapper">
<div className="panel-list">{ persons }</div>
</div>
);
}
}
I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)
Why not just stream down the content with the correct content specifier?
That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.
Use either a simple blank *
or [:blank:]*
to remove all possible spaces at the end of the line:
sed 's/ *$//' file
Using the [:blank:]
class you are removing spaces and tabs:
sed 's/[[:blank:]]*$//' file
Note this is POSIX, hence compatible in both GNU sed and BSD.
For just GNU sed you can use the GNU extension \s*
to match spaces and tabs, as described in BaBL86's answer. See POSIX specifications on Basic Regular Expressions.
Let's test it with a simple file consisting on just lines, two with just spaces and the last one also with tabs:
$ cat -vet file
hello $
bye $
ha^I $ # there is a tab here
Remove just spaces:
$ sed 's/ *$//' file | cat -vet -
hello$
bye$
ha^I$ # tab is still here!
Remove spaces and tabs:
$ sed 's/[[:blank:]]*$//' file | cat -vet -
hello$
bye$
ha$ # tab was removed!
Calling a generic method with a type parameter known only at runtime can be greatly simplified by using a dynamic
type instead of the reflection API.
To use this technique the type must be known from the actual object (not just an instance of the Type
class). Otherwise, you have to create an object of that type or use the standard reflection API solution. You can create an object by using the Activator.CreateInstance method.
If you want to call a generic method, that in "normal" usage would have had its type inferred, then it simply comes to casting the object of unknown type to dynamic
. Here's an example:
class Alpha { }
class Beta { }
class Service
{
public void Process<T>(T item)
{
Console.WriteLine("item.GetType(): " + item.GetType()
+ "\ttypeof(T): " + typeof(T));
}
}
class Program
{
static void Main(string[] args)
{
var a = new Alpha();
var b = new Beta();
var service = new Service();
service.Process(a); // Same as "service.Process<Alpha>(a)"
service.Process(b); // Same as "service.Process<Beta>(b)"
var objects = new object[] { a, b };
foreach (var o in objects)
{
service.Process(o); // Same as "service.Process<object>(o)"
}
foreach (var o in objects)
{
dynamic dynObj = o;
service.Process(dynObj); // Or write "service.Process((dynamic)o)"
}
}
}
And here's the output of this program:
item.GetType(): Alpha typeof(T): Alpha
item.GetType(): Beta typeof(T): Beta
item.GetType(): Alpha typeof(T): System.Object
item.GetType(): Beta typeof(T): System.Object
item.GetType(): Alpha typeof(T): Alpha
item.GetType(): Beta typeof(T): Beta
Process
is a generic instance method that writes the real type of the passed argument (by using the GetType()
method) and the type of the generic parameter (by using typeof
operator).
By casting the object argument to dynamic
type we deferred providing the type parameter until runtime. When the Process
method is called with the dynamic
argument then the compiler doesn't care about the type of this argument. The compiler generates code that at runtime checks the real types of passed arguments (by using reflection) and choose the best method to call. Here there is only this one generic method, so it's invoked with a proper type parameter.
In this example, the output is the same as if you wrote:
foreach (var o in objects)
{
MethodInfo method = typeof(Service).GetMethod("Process");
MethodInfo generic = method.MakeGenericMethod(o.GetType());
generic.Invoke(service, new object[] { o });
}
The version with a dynamic type is definitely shorter and easier to write. You also shouldn't worry about performance of calling this function multiple times. The next call with arguments of the same type should be faster thanks to the caching mechanism in DLR. Of course, you can write code that cache invoked delegates, but by using the dynamic
type you get this behaviour for free.
If the generic method you want to call don't have an argument of a parametrized type (so its type parameter can't be inferred) then you can wrap the invocation of the generic method in a helper method like in the following example:
class Program
{
static void Main(string[] args)
{
object obj = new Alpha();
Helper((dynamic)obj);
}
public static void Helper<T>(T obj)
{
GenericMethod<T>();
}
public static void GenericMethod<T>()
{
Console.WriteLine("GenericMethod<" + typeof(T) + ">");
}
}
What is really great about using dynamic
object as a replacement for using reflection API is that you only lose compile time checking of this particular type that you don't know until runtime. Other arguments and the name of the method are staticly analysed by the compiler as usual. If you remove or add more arguments, change their types or rename method name then you'll get a compile-time error. This won't happen if you provide the method name as a string in Type.GetMethod
and arguments as the objects array in MethodInfo.Invoke
.
Below is a simple example that illustrates how some errors can be caught at compile time (commented code) and other at runtime. It also shows how the DLR tries to resolve which method to call.
interface IItem { }
class FooItem : IItem { }
class BarItem : IItem { }
class Alpha { }
class Program
{
static void Main(string[] args)
{
var objects = new object[] { new FooItem(), new BarItem(), new Alpha() };
for (int i = 0; i < objects.Length; i++)
{
ProcessItem((dynamic)objects[i], "test" + i, i);
//ProcesItm((dynamic)objects[i], "test" + i, i);
//compiler error: The name 'ProcesItm' does not
//exist in the current context
//ProcessItem((dynamic)objects[i], "test" + i);
//error: No overload for method 'ProcessItem' takes 2 arguments
}
}
static string ProcessItem<T>(T item, string text, int number)
where T : IItem
{
Console.WriteLine("Generic ProcessItem<{0}>, text {1}, number:{2}",
typeof(T), text, number);
return "OK";
}
static void ProcessItem(BarItem item, string text, int number)
{
Console.WriteLine("ProcessItem with Bar, " + text + ", " + number);
}
}
Here we again execute some method by casting the argument to the dynamic
type. Only verification of first argument's type is postponed to runtime. You will get a compiler error if the name of the method you're calling doesn't exist or if other arguments are invalid (wrong number of arguments or wrong types).
When you pass the dynamic
argument to a method then this call is lately bound. Method overload resolution happens at runtime and tries to choose the best overload. So if you invoke the ProcessItem
method with an object of BarItem
type then you'll actually call the non-generic method, because it is a better match for this type. However, you'll get a runtime error when you pass an argument of the Alpha
type because there's no method that can handle this object (a generic method has the constraint where T : IItem
and Alpha
class doesn't implement this interface). But that's the whole point. The compiler doesn't have information that this call is valid. You as a programmer know this, and you should make sure that this code runs without errors.
When you're calling a non-void method with a parameter of dynamic type, its return type will probably be dynamic
too. So if you'd change previous example to this code:
var result = ProcessItem((dynamic)testObjects[i], "test" + i, i);
then the type of the result object would be dynamic
. This is because the compiler don't always know which method will be called. If you know the return type of the function call then you should implicitly convert it to the required type so the rest of the code is statically typed:
string result = ProcessItem((dynamic)testObjects[i], "test" + i, i);
You'll get a runtime error if the type doesn't match.
Actually, if you try to get the result value in the previous example then you'll get a runtime error in the second loop iteration. This is because you tried to save the return value of a void function.
If you want it to be more generic and independent, you can use cookie. Iframe content can set a cookie. With jquery.cookie and a timer (or in this case javascript timer), you can check if the cookie is set each second or so.
//token should be a unique random value which is also sent to ifame to get set
iframeLoadCheckTimer = window.setInterval(function () {
cookieValue = $.cookie('iframeToken');
if (cookieValue == token)
{
window.clearInterval(iframeLoadCheckTimer );
$.cookie('iframeToken', null, {
expires: 1,
path: '/'
});
}
}, 1000);
if you use .Values while creating the matrix X and Y vectors it will fix the problem.
y=dataset.iloc[:, 4].values
X=dataset.iloc[:, 0:4].values
when you use .Values it creates a Object representation of the created matrix will be returned with the axes removed. Check the below link for more information
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html
Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.
int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
case 0: yourBool = false; break;
case 1: yourBool = true; break;
default:
throw new InvalidOperationException("Integer value is not valid");
}
The out-of-the-box Convert
won't check this; nor will yourInteger (==|!=) (0|1)
.
Compile constants can only be primitives and Strings:
15.28. Constant Expressions
A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
- Literals of primitive type and literals of type
String
- Casts to primitive types and casts to type
String
- [...] operators [...]
- Parenthesized expressions whose contained expression is a constant expression.
- Simple names that refer to constant variables.
- Qualified names of the form TypeName . Identifier that refer to constant variables.
Actually in java there is no way to protect items in an array. At runtime someone can always do FieldValues.FIELD1[0]="value3"
, therefore the array cannot be really constant if we look deeper.
Instead of instantiating the FileUpload
in your code behind file, just declare it in your markup file (.aspx file):
<asp:FileUpload ID="fileUpload" runat="server" />
Then you will be able to access all of the properties of the control, such as HasFile
.
Date.prototype.dayOfYear= function(){
var j1= new Date(this);
j1.setMonth(0, 0);
return Math.round((this-j1)/8.64e7);
}
alert(new Date().dayOfYear())
In the command line type service apache2 status
then hit enter. The result should say:
Apache2 is running (pid xxxx)