InnerHTML should be innerHTML:
document.getElementById('LblAboutMeCount').innerHTML = charsleft;
You should bind your checkLength
function to your textarea with jQuery rather than calling it inline and rather intrusively:
$(document).ready(function() {
$('textarea[name=text]').keypress(function(e) {
checkLength($(this),512,$('#LblTextCount'));
}).focus(function() {
checkLength($(this),512,$('#LblTextCount'));
});
});
You can neaten up checkLength by using more jQuery, and I wouldn't use 'object' as a formal parameter:
function checkLength(obj, maxlength, label) {
charsleft = (maxlength - obj.val().length);
// never allow to exceed the specified limit
if( charsleft < 0 ) {
obj.val(obj.val().substring(0, maxlength-1));
}
// I'm trying to set the value of charsleft into the label
label.text(charsleft);
$('#LblAboutMeCount').html(charsleft);
}
So if you apply the above, you can change your markup to:
<textarea name="text"></textarea>
Firstly, as Etienne says, float
in C# is Single
. It is just the C# keyword for that data type.
So you can definitely do this:
float f = 13.5f;
string s = f.ToString("R");
Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal
, which does maintain its own precision; however, calling simply decimal.ToString
should have the effect you want in that case.
How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?
try {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setData(Uri.parse("smsto:" + Uri.encode(number)));
smsIntent.putExtra("address", number);
smsIntent.putExtra("sms_body", message);
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> resInfo = pm.queryIntentActivities(smsIntent, 0);
for (int i = 0; i < resInfo.size(); i++) {
ResolveInfo ri = resInfo.get(i);
String packageName = ri.activityInfo.packageName;
if (packageName.contains("sms")) {
//Log.d("TAG", packageName + " : " + ri.activityInfo.name);
smsIntent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
}
}
activity.startActivity(smsIntent);
} catch (Exception e) {
// Handle Error
}
Best way of doing this.
use document.activeElement.blur();
example at http://jsfiddle.net/vGGdV/5/ that shows the currently focused element as well.
Keep a note though that calling blur()
on the body element in IE will make the IE lose focus
var values = [];
var count = 0;
$("#tblName").on("click", "tbody tr", function (event) {
$(this).find("td").each(function () {
values[count] = $(this).text();
count++;
});
});
Now values array contain all the cell values of that row can be used like values[0] first cell value of clicked row
Actually, I figured out what's wrong. For the code to work the page <head>
should have this tag:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Or, as suggested in comments, if server sends HTTP Content-Encoding
header, it should work as well.
Then results from different browsers are consistent.
Here is an example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>mini string length test</title>
</head>
<body>
<script type="text/javascript">
document.write('<div style="font-size:100px">'
+ (unescape(encodeURIComponent("???! Naïve?")).length) + '</div>'
);
</script>
</body>
</html>
Note: I suspect that specifying any (accurate) encoding would fix the encoding problem. It is just a coincidence that I need UTF-8.
Here's a great scripted solution for logging people out remotely or locally. I'm using qwinsta to get session information and building an array out of the given output. This makes it really easy to iterate through each entry and log out only the actual users, and not the system or RDP listener itself which usually just throws an access denied error anyway.
$serverName = "Name of server here OR localhost"
$sessions = qwinsta /server $serverName| ?{ $_ -notmatch '^ SESSIONNAME' } | %{
$item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device"
$item.Active = $_.Substring(0,1) -match '>'
$item.SessionName = $_.Substring(1,18).Trim()
$item.Username = $_.Substring(19,20).Trim()
$item.Id = $_.Substring(39,9).Trim()
$item.State = $_.Substring(48,8).Trim()
$item.Type = $_.Substring(56,12).Trim()
$item.Device = $_.Substring(68).Trim()
$item
}
foreach ($session in $sessions){
if ($session.Username -ne "" -or $session.Username.Length -gt 1){
logoff /server $serverName $session.Id
}
}
In the first line of this script give $serverName the appropriate value or localhost if running locally. I use this script to kick users before an automated process attempts to move some folders around. Prevents "file in use" errors for me. Another note, this script will have to be ran as an administrator user otherwise you can get accessed denied trying to log someone out. Hope this helps!
Update (2017): The following two libraries have now become the most common drop-down libraries used with Javascript. While they are jQuery-native, they have been customized to work with everything from AngularJS 1.x to having custom CSS for Bootstrap. (Chosen JS, the original answer here, seems to have dropped to #3 in popularity.)
Obligatory screenshots below.
Original answer (2012): I think that the Chosen library might also be useful. Its available in jQuery, Prototype and MooTools versions.
Attached is a screenshot of how the multi-select functionality looks in Chosen.
Beside missing Order
and Allow
directives mentioned in other answers be aware that a non-matching regular expression of a DirectoryMatch
directive may also cause this error.
If the requested path is /home/user-foo1bar/www/myproject/
the folloing matcher won't match
<DirectoryMatch "/home/user-[a-z]+/www/myproject/">
...
</DirectoryMatch>
thus, even a valid access configuration might cause this error.
Typical default display properties for ul
ul {
display: block;
list-style-type: disc;
margin-before: 1em;
margin-after: 1em;
margin-start: 0;
margin-end: 0;
padding-start: 40px;
}
That is a problem of security protocol. I am using TLSv1 but the host accept only TLSv1.1 and TLSv1.2 then I changed the protocol in Java with the instruction below:
System.setProperty("https.protocols", "TLSv1.1")
;
I put together a little test here:
\documentclass[10pt,twocolumn]{article}
\title{Article Title}
\author{
First Author\\
Department\\
school\\
email@edu
\and
Second Author\\
Department\\
school\\
email@edu
\and
Third Author\\
Department\\
school\\
email@edu
\and
Fourth Author\\
Department\\
school\\
email@edu
}
\date{\today}
\begin{document}
\maketitle
\begin{abstract}
\ldots
\end{abstract}
\section{Introduction}
\ldots
\end{document}
Things to note, the title, author and date fields are declared before \begin{document}
. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn
in the document class.
This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}
. Here's a more detailed article on \LaTeX
font sizes:
https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont
To italicize you can use {\it First Name}
or \textit{First Name}
.
Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.
I'm afraid you have to do it manually. Get the date's current day of week, calculate the offset and add the offset to the date.
$current = date("w", $date)
$offset = $day - $current
$new_date = new DateTime($date)
->add(
new DateInterval($offset."D")
)->format('Y-m-d')
I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).
e.g. (from the doc)
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
I think here is a simple and yet faster way, I tested it on the live server in comparison with a few above answer and it was faster.
SELECT * FROM `table_name` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table_name` ) ORDER BY id LIMIT 30;
//Took 0.0014secs against a table of 130 rows
SELECT * FROM `table_name` WHERE 1 ORDER BY RAND() LIMIT 30
//Took 0.0042secs against a table of 130 rows
SELECT name
FROM random AS r1 JOIN
(SELECT CEIL(RAND() *
(SELECT MAX(id)
FROM random)) AS id)
AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 30
//Took 0.0040secs against a table of 130 rows
SELECT
, INSERT
, UPDATE
, and DELETE
commands frequently include WHERE clauses to specify filters that define the conditions each row in the source tables must meet to qualify for an SQL command. Parameters provide the filter values in the WHERE clauses.
You can use parameter markers to dynamically provide parameter values. The rules for which parameter markers and parameter names can be used in the SQL statement depend on the type of connection manager that the Execute SQL uses.
The following table lists examples of the SELECT command by connection manager type. The INSERT, UPDATE, and DELETE statements are similar. The examples use SELECT to return products from the Product table in AdventureWorks2012 that have a ProductID greater than and less than the values specified by two parameters.
EXCEL, ODBC, and OLEDB
SELECT* FROM Production.Product WHERE ProductId > ? AND ProductID < ?
ADO
SELECT * FROM Production.Product WHERE ProductId > ? AND ProductID < ?
ADO.NET
SELECT* FROM Production.Product WHERE ProductId > @parmMinProductID
AND ProductID < @parmMaxProductID
The examples would require parameters that have the following names: The EXCEL and OLED DB connection managers use the parameter names 0 and 1. The ODBC connection type uses 1 and 2. The ADO connection type could use any two parameter names, such as Param1 and Param2, but the parameters must be mapped by their ordinal position in the parameter list. The ADO.NET connection type uses the parameter names @parmMinProductID and @parmMaxProductID.
Email address: RFC 2822 Format
Matches a normal email address. Does not check the top-level domain.
Requires the "case insensitive" option to be ON.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Usage :
bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
Dot grammar maybe more swift!
@(intValueDemo).stringValue
for example
int intValueDemo = 1;
//or
NSInteger intValueDemo = 1;
//So you can use dot grammar
NSLog(@"%@",@(intValueDemo).stringValue);
Open extensions menu (Ctrl+Shift+X), and search .NuGet Package Manager.
As Craig said, no.
But, regarding your comment as to why:
It might be easier to use 1 <form>
with the inputs and the "Update" button, and use copy hidden inputs with the "Submit Order" button in a another <form>
.
You could subscribe for the change and keyup events:
$(function() {
$(':input').change(myFunction).keyup(myFunction);
});
where myFunction
is the function you would like executed:
function myFunction() {
alert( 'something happened!' );
}
In httpd.conf
LoadModule headers_module modules/mod_headers.so
LoadModule rewrite_module modules/mod_rewrite.so
<Directory "**/usr/local/PATH**">
AllowOverride None
Require all granted
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
Header always set Access-Control-Expose-Headers "Content-Security-Policy, Location"
Header always set Access-Control-Max-Age "600"
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</Directory>
If running outside container, you may need to restart apache service.
Very nice way to print formatted array in php, using the var_dump function.
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
This question remains valid today, however the technology has changed. The old Urchin tracker is deprecated and obsolete. The new asynchronous Google Analytics tracking code uses slightly different code to achieve the same results.
ga.js
The current syntax for setting the tracking domain to none on google analytics looks like this:
_gaq.push(['_setDomainName', 'none']);
Google analytics will then fire off the _utm.gif tracker request on localhost. You can verify this by opening the developer tools in your favorite browser and watching the network requests during page load. If it is working you will see a request for _utm.gif in the network requests list.
analytics.js
Google released a new version of analytics called "Universal Analytics" (late 2012 or early 2013). As I write, this the program is still in BETA so the above code is still recommended for most users with existing installations of Google Analytics.
However, for new developments using the new analytics.js
code, the Google Analytics, Advanced Configuration - Web Tracking Documentation shows that we can test Universal Analytics on localhost with this new code:
ga('create', 'UA-XXXX-Y', {
'cookieDomain': 'none'
});
Check out the linked documentation for more details on advanced configuration of Universal Analytics.
Both Global Site Tag - gtag.js
and Universal Analytics - analytics.js
will detect localhost
automatically. You do not need to make any change to the configuration.
If gtag.js detects that you're running a server locally (e.g.
localhost
), it automatically sets thecookie_domain
to'none'
.
Check out pyinotify.
inotify replaces dnotify (from an earlier answer) in newer linuxes and allows file-level rather than directory-level monitoring.
In case you want to run only tests from a specific class:
if __name__ == "__main__":
unittest.main(MyCase())
It works for me in Python 3.6.
A much shorter and safer answer - don't write your own password mechanism at all, use a tried and tested mechanism.
Most programmers just don't have the expertise to write crypto related code safely without introducing vulnerabilities.
Quick self-test: what is password stretching and how many iterations should you use? If you don't know the answer, you should use password_hash()
, as password stretching is now a critical feature of password mechanisms due to much faster CPUs and the use of GPUs and FPGAs to crack passwords at rates of billions of guesses per second (with GPUs).
For example, you can crack all 8-character Windows passwords in 6 hours using 25 GPUs installed in 5 desktop PCs. This is brute-forcing i.e. enumerating and checking every 8-character Windows password, including special characters, and is not a dictionary attack. That was in 2012, as of 2018 you could use fewer GPUs, or crack faster with 25 GPUs.
There are also many rainbow table attacks on Windows passwords that run on ordinary CPUs and are very fast. All this is because Windows still doesn't salt or stretch its passwords, even in Windows 10 - don't make the same mistake as Microsoft did!
See also:
password_hash()
or phpass
are the best way to go.Built off the above but with dynamic creation and a vector image, not drawing.
function svgztruck() {
tok = "{d path value}"
return tok;
}
function buildsvg( eid ) {
console.log("building");
var zvg = "svg" + eid;
var vvg = eval( zvg );
var raw = vvg();
var svg = document.getElementById( eid );
svg.setAttributeNS(null,"d", raw );
svg.setAttributeNS(null,"fill","green");
svg.setAttributeNS(null,"onlick", eid + ".style.fill=#FF0000");
return;
}
You could call with:
<img src="" onerror="buildscript">
Now you can add colors by sub element and manipulate all elements of the dom directly. It is important to implement your viewbox and height width first on the svg html, not done in the example above.
There is no need to make your code 10 pages when it could be one... but who am I to argue. Better use PHP
while your at it.
The inner element that svg builds on is a simple <svg lamencoding id=parenteid><path id=eid><svg>
with nothing else.
They're two phrases that describe the same thing from (very slightly) different viewpoints. Parallel programming is describing the situation from the viewpoint of the hardware -- there are at least two processors (possibly within a single physical package) working on a problem in parallel. Concurrent programming is describing things more from the viewpoint of the software -- two or more actions may happen at exactly the same time (concurrently).
The problem here is that people are trying to use the two phrases to draw a clear distinction when none really exists. The reality is that the dividing line they're trying to draw has been fuzzy and indistinct for decades, and has grown ever more indistinct over time.
What they're trying to discuss is the fact that once upon a time, most computers had only a single CPU. When you executed multiple processes (or threads) on that single CPU, the CPU was only really executing one instruction from one of those threads at a time. The appearance of concurrency was an illusion--the CPU switching between executing instructions from different threads quickly enough that to human perception (to which anything less than 100 ms or so looks instantaneous) it looked like it was doing many things at once.
The obvious contrast to this is a computer with multiple CPUs, or a CPU with multiple cores, so the machine is executing instructions from multiple threads and/or processes at exactly the same time; code executing one can't/doesn't have any effect on code executing in the other.
Now the problem: such a clean distinction has almost never existed. Computer designers are actually fairly intelligent, so they noticed a long time ago that (for example) when you needed to read some data from an I/O device such as a disk, it took a long time (in terms of CPU cycles) to finish. Instead of leaving the CPU idle while that happened, they figured out various ways of letting one process/thread make an I/O request, and let code from some other process/thread execute on the CPU while the I/O request completed.
So, long before multi-core CPUs became the norm, we had operations from multiple threads happening in parallel.
That's only the tip of the iceberg though. Decades ago, computers started providing another level of parallelism as well. Again, being fairly intelligent people, computer designers noticed that in a lot of cases, they had instructions that didn't affect each other, so it was possible to execute more than one instruction from the same stream at the same time. One early example that became pretty well known was the Control Data 6600. This was (by a fairly wide margin) the fastest computer on earth when it was introduced in 1964--and much of the same basic architecture remains in use today. It tracked the resources used by each instruction, and had a set of execution units that executed instructions as soon as the resources on which they depended became available, very similar to the design of most recent Intel/AMD processors.
But (as the commercials used to say) wait--that's not all. There's yet another design element to add still further confusion. It's been given quite a few different names (e.g., "Hyperthreading", "SMT", "CMP"), but they all refer to the same basic idea: a CPU that can execute multiple threads simultaneously, using a combination of some resources that are independent for each thread, and some resources that are shared between the threads. In a typical case this is combined with the instruction-level parallelism outlined above. To do that, we have two (or more) sets of architectural registers. Then we have a set of execution units that can execute instructions as soon as the necessary resources become available. These often combine well because the instructions from the separate streams virtually never depend on the same resources.
Then, of course, we get to modern systems with multiple cores. Here things are obvious, right? We have N (somewhere between 2 and 256 or so, at the moment) separate cores, that can all execute instructions at the same time, so we have clear-cut case of real parallelism--executing instructions in one process/thread doesn't affect executing instructions in another.
Well, sort of. Even here we have some independent resources (registers, execution units, at least one level of cache) and some shared resources (typically at least the lowest level of cache, and definitely the memory controllers and bandwidth to memory).
To summarize: the simple scenarios people like to contrast between shared resources and independent resources virtually never happen in real life. With all resources shared, we end up with something like MS-DOS, where we can only run one program at a time, and we have to stop running one before we can run the other at all. With completely independent resources, we have N computers running MS-DOS (without even a network to connect them) with no ability to share anything between them at all (because if we can even share a file, well, that's a shared resource, a violation of the basic premise of nothing being shared).
Every interesting case involves some combination of independent resources and shared resources. Every reasonably modern computer (and a lot that aren't at all modern) has at least some ability to carry out at least a few independent operations simultaneously, and just about anything more sophisticated than MS-DOS has taken advantage of that to at least some degree.
The nice, clean division between "concurrent" and "parallel" that people like to draw just doesn't exist, and almost never has. What people like to classify as "concurrent" usually still involves at least one and often more different types of parallel execution. What they like to classify as "parallel" often involves sharing resources and (for example) one process blocking another's execution while using a resource that's shared between the two.
People trying to draw a clean distinction between "parallel" and "concurrent" are living in a fantasy of computers that never actually existed.
I would just to like to add that the directory is not necessarily C:\Users\[username]\.ssh. It is the directory in which you created your public key in.
For instance my home directory in Windows was changed to C:\[username]. Your home directory in a .ssh sub-folder is the best and most likely place you may have created your keys. You can check your home directory in Windows with the command:
echo %HOMEPATH%
You can use
timestamp=`date --rfc-3339=seconds`
This delivers in the format 2014-02-01 15:12:35-05:00
The back-tick (`
) characters will cause what is between them to be evaluated and have the result included in the line. date --help
has other options.
I know this is an old post, but in case someone else happens upon this question, one good option is Virtual Serial Port Emulator (VSPE) from Eterlogic
It provides an API for creating kernel mode virtual comport devices, i.e. connectors, mappers, splitters etc.
However, some of the advertised capabilities were really not capabilities at all.
EDIT
A much better choice, Eltima. This product is fully baked. Good developer tech support. The product did all it claimed to do. Product options include both desktop applications, as well as software development kits with APIs.
Neither of these products are open source, or free. However, as other posts here have pointed out, there are other options. Here is a list of various serial utilities:
com0com (current)
com0com - With Signed Driver (old version)
Yet another place for com0com with Signed Driver (Pete's Blog)
Tactical Software
Termite
COM Port Serial Emulator
Kermit (obsolete, but still downloadable)
HWVSP3
HHD Software (free edition)
For folks searching for solution to set spacing between N
divs, here is another approach using pseudo selectors:
div:not(:last-child) {
margin-right: 40px;
}
You can also combine child pseudo selectors:
div:not(:first-child):not(:last-child) {
margin-left: 20px;
margin-right: 20px;
}
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1" to an int -> no problem
Cast the String "abc" to an int -> raises a ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because its a dog.
Cat c = (Dog) a; // Raises class cast exception; you can't cast a dog to a cat.
With AutoEventWireup
which is turned on by default on a page you can just add methods prepended with **Page_***event* and have ASP.NET connect to the events for you.
In the case of Unload the method signature is:
protected void Page_Unload(object sender, EventArgs e)
For details see the MSDN article.
With the current version of Bootstrap (3.3.7), it is possible to color a single cell of a table like so:
<td class = 'text-center col-md-4 success'>
Here's the technical answer (expanding on Rowland Shaw's answer).
The Is keyword checks whether the two operands are references to the same object memory, and only returns true if this is the case. I believe it is functionally equivalent to Object.ReferenceEquals. The IsNot keyword is simply shorthand syntax for writing Not ... Is ...
, nothing more.
The = (equality) operator compares values and in this case (as in many others) is equivalent to String.Equals. Now, the <> (inequality) operator does not quite have the same analogy as the Is and IsNot keywords, since it can be overriden separately from the = operator depending on the class. I believe the case should always be that it returns the logical inverse of the = operator (and certainly is in the case of String), and just allows for a more efficient comparison to made when testing for inequality rather than equality.
When dealing with strings, unless you actually mean to compare references, always use the = operator (or String.Equals I suppose). In your case, because you are testing for null (Nothing), it seems you need to use the Is or IsNot keyword (the equality operator will fail because it can't compare the values of null objects). Syntactically, the IsNot keyword is a bit nicer here, so go with that.
I have a cell which is linked to online stock database and updated frequently. I want to trigger a macro whenever the cell value is updated.
I believe this is similar to cell value change by a program or any external data update but above examples somehow do not work for me. I think the problem is because excel internal events are not triggered, but thats my guess.
I did the following,
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Target.Worksheets("Symbols").Range("$C$3")) Is Nothing Then
'Run Macro
End Sub
In my opinion the simplest and most elegant way to achieve what you need is this:
ip route get 8.8.8.8 | tr -s ' ' | cut -d' ' -f7
ip route get [host]
- gives you the gateway used to reach a remote host e.g.:
8.8.8.8 via 192.168.0.1 dev enp0s3 src 192.168.0.109
tr -s ' '
- removes any extra spaces, now you have uniformity e.g.:
8.8.8.8 via 192.168.0.1 dev enp0s3 src 192.168.0.109
cut -d' ' -f7
- truncates the string into ' 'space separated fields, then selects the field #7 from it e.g.:
192.168.0.109
For me on iOS 5.1.1 on a iPhone 3GS I had to clear the styling of a search field and the set it to the style intended
input[type="search"] {-webkit-appearance: none; border-radius: 0 3px 3px 0;}
Doing -webkit-border-radius: 0;
alone did not clear the native styling. This was also for a webview on a native app.
Google used to recommend putting it just before the </body>
tag, because the original method they provided for loading ga.js
was blocking. The newer async syntax, though, can safely be put in the head with minimal blockage, so the current recommendation is just before the </head>
tag.
<head>
will add a little latency; in the footer will reduce the number of pageviews recorded at some small margin. It's a tradeoff. ga.js
is heavily cached and present on a large percentage of sites across the web, so its often served from the cache, reducing latency to almost nil.
As a matter of personal preference, I like to include it in the <head>
, but its really a matter of preference.
The purpose of raw.github.com
is to allow users to view the contents of a file, so for text based files this means (for certain content types) you can get the wrong headers and things break in the browser.
When this question was asked (in 2012) SVGs didn't work. Since then Github has implemented various improvements. Now (at least for SVG), the correct Content-Type headers are sent.
All of the ways stated below will work.
I copied the SVG image from the question to a repo on github in order to create the examples below
Code
![Alt text](./controllers_brief.svg)
<img src="./controllers_brief.svg">
Result
See the working example on github.com.
Code
![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">
Result
?sanitize=true
Code
![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true">
Result
Code
![Alt text](https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">
Result
Some comments regarding changes that happened along the way:
Github has implemented a feature which makes it possible for SVG's to be used with the Markdown image syntax. The SVG image will be sanitized and displayed with the correct HTTP header. Certain tags (like <script>
) are removed.
To view the sanitized SVG or to achieve this effect from other places (i.e. from markdown files not hosted in repos on http://github.com/) simply append ?sanitize=true
to the SVG's raw URL.
As stated by AdamKatz in the comments, using a source other than github.io can introduce potentially privacy and security risks. See the answer by CiroSantilli and the answer by DavidChambers for more details.
The issue to resolve this was opened on Github on October 13th 2015 and was resolved on August 31th 2017
If you're only running the commands in one shot then you can just use subprocess.check_output
convenience function:
def subprocess_cmd(command):
output = subprocess.check_output(command, shell=True)
print output
You can still use the Screen class from a WPF app. You just need to reference the System.Windows.Forms assembly from your application. Once you've done that, (and referenced System.Drawing for the example below):
Rectangle workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
...works just fine.
Have you considered setting your main window property WindowStartupLocation to CenterScreen?
You may want to try out xd http://github.com/jiqingtang/xd, which is GUI wrapper for GIT/SVN diff. It is NOT a diff tool itself. You run xd
when you want to run git diff
or svn diff
and it will show you a list of files, a preview window and you can launch any diff tool you like, including tkdiff, xxdiff, gvimdiff, emacs(ediff), xemacs(ediff), meld, diffuse, kompare and kdiff3. You can also run any custom tool.
Unfortunately the tool doesn't support Windows.
Disclosure: I am the author of this tool.
Nice article explaining the basics (does not cover line breaks, however).
A Whole Bunch of Amazing Stuff Pseudo Elements Can Do
If you need to have two inline elements where one breaks into the next line within another element, you can accomplish this by adding a pseudo-element :after with content:'\A' and white-space: pre
HTML
<h3>
<span class="label">This is the main label</span>
<span class="secondary-label">secondary label</span>
</h3>
CSS
.label:after {
content: '\A';
white-space: pre;
}
When the lists aren't extremely long, this is the best way I know:
function getIndex(val) {
for (var i = 0; i < imageList.length; i++) {
if (imageList[i] === val) {
return i;
}
}
}
var imageList = [100, 200, 300, 400, 500];
var index = getIndex(200);
java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/
This exception has two causes:
In your case, I'd expect to see a database name at the end of the connection string. For example (use create=true
if you want the database to be created if it doesn't exist):
jdbc:derby://localhost:1527/dbname;create=true
Databases are created by default in the directory where the Network Server was started up. But you can also specify an absolute path to the database location:
jdbc:derby://localhost:1527//home/pascal/derbyDBs/dbname;create=true
And just in case, check that derbyclient.jar is on the class path and that you are loading the appropriate driver org.apache.derby.jdbc.ClientDriver
when working in server mode.
Optional value allows you to show absence of value. Little bit like NULL in SQL or NSNull in Objective-C. I guess this will be an improvement as you can use this even for "primitive" types.
// Reimplement the Swift standard library's optional type
enum OptionalValue<T> {
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/gb/jEUH0.l
I had the following problem:
I had a Android phone without drivers, and it could not be recognized by the Windows 8.1. Neither as phone, neither as USB storage device.
I searched Device manager.
I opened Device manager, I right click on Android Phone->Android Composite Interface.
I selected "Update Driver Software"
I choose "Browse My Computer for Driver Software"
Then I choose "Let me pick from a list of devices"
I selected "USB Composite Device"
A new USB device is added to the list, and I can connect to my phone using adb and Android SDK.
Also I can use the phone as storage device.
Good luck
Try this:
#myelement {
background-position: 100% 50%;
margin-right: 5px;
}
Note though that the code above will move the whole element (not the background image only) 5px from the right. This might be ok for your case.
If you only care about unimodal distributions, consider sth. like this.
public static Optional<Integer> mode(Stream<Integer> stream) {
Map<Integer, Long> frequencies = stream
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return frequencies.entrySet().stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.map(Map.Entry::getKey);
}
You can use the folowing code:
def float_range(initVal, itemCount, step):
for x in xrange(itemCount):
yield initVal
initVal += step
[x for x in float_range(1, 3, 0.1)]
In short, it's because of the IE8 parsing engine.
Guess why Microsoft has trouble working with the new HTML5 tags (like "section") too? It's because MS decided that they will not use regular XML parsing, like the rest of the world. Yes, that's right - they did a ton of propaganda on XML but in the end, they fall back on a "stupid" parsing engine looking for "known tags" and messing stuff up when something new comes around.
Same goes for IE8 and the jquery issue with "load", "get" and "post". Again, Microsoft decided to "walk their own path" with version 8. Hoping that they solve(d) this in IE9, the only current option is to fall back on IE7 parsing with <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
.
Oh well... what a surprise that Microsoft made us post stuff on forums again. ;)
history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.title);
});
This script will overwrite attempts to navigate back and forth with the state of the current page.
Update:
Some users have reported better success with using document.URL
instead of document.title
:
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
I'm outdated I know.. But a little workaround would be to put your checkbox inside a label tag, then style the label with a border:
<label class='hasborder'><input type='checkbox' /></label>
then style the label:
.hasborder { border:1px solid #F00; }
just use inheritance,Extend parent class in child class and declare constructor with parent class parameter and this parameter use in super().
1.parent class
@Component({
selector: 'teams-players-box',
templateUrl: '/maxweb/app/app/teams-players-box.component.html'
})
export class TeamsPlayersBoxComponent {
public _userProfile:UserProfile;
public _user_img:any;
public _box_class:string="about-team teams-blockbox";
public fullname:string;
public _index:any;
public _isView:string;
indexnumber:number;
constructor(
public _userProfilesSvc: UserProfiles,
public _router:Router,
){}
2.child class
@Component({
selector: '[teams-players-eligibility]',
templateUrl: '/maxweb/app/app/teams-players-eligibility.component.html'
})
export class TeamsPlayersEligibilityComponent extends TeamsPlayersBoxComponent{
constructor (public _userProfilesSvc: UserProfiles,
public _router:Router) {
super(_userProfilesSvc,_router);
}
}
You will have to either use a loop, or create a collection wrapper like Arrays.asList
which works on primitive char arrays (or directly on strings).
List<Character> list = new ArrayList<Character>();
Set<Character> unique = new HashSet<Character>();
for(char c : "abc".toCharArray()) {
list.add(c);
unique.add(c);
}
Here is an Arrays.asList
like wrapper for strings:
public List<Character> asList(final String string) {
return new AbstractList<Character>() {
public int size() { return string.length(); }
public Character get(int index) { return string.charAt(index); }
};
}
This one is an immutable list, though. If you want a mutable list, use this with a char[]
:
public List<Character> asList(final char[] string) {
return new AbstractList<Character>() {
public int size() { return string.length; }
public Character get(int index) { return string[index]; }
public Character set(int index, Character newVal) {
char old = string[index];
string[index] = newVal;
return old;
}
};
}
Analogous to this you can implement this for the other primitive types. Note that using this normally is not recommended, since for every access you would do a boxing and unboxing operation.
The Guava library contains similar List wrapper methods for several primitive array classes, like Chars.asList, and a wrapper for String in Lists.charactersOf(String).
If you want to use JDKs downloaded from Oracle's site, what worked for me (using Mint) is using update-alternatives:
I ran:
sudo update-alternatives --install /usr/bin/java java /home/aqeel/development/jdk/jdk1.6.0_35/bin/java 1
Now you can execute sudo update-alternatives --config java
and choose your java version.
export JAVA_HOME="/home/aqeel/development/jdk/jdk1.6.0_35"
statementNow, I had two JDKs downloaded (let's say the second has been extracted to /home/aqeel/development/jdk/jdk-10.0.1).
How can we change the JAVA_HOME dynamically based on the current java being used?
My solution is not very elegant, I'm pretty sure there are better options out there, but anyway:
To change the JAVA_HOME dynamically based on the chosen java alternative, I added this snippet to the ~/.bashrc:
export JAVA_HOME=$(update-alternatives --query java | grep Value: | awk -F'Value: ' '{print $2}' | awk -F'/bin/java' '{print $1}')
Finally (this is out of the scope) if you have to change the java version constantly, you might want to consider:
Adding an alias to your ~./bash_aliases:
alias change-java="sudo update-alternatives --config java"
(You might have to create the file and maybe uncomment the section related to this in ~/.bashrc)
There are two ways to accomplish this textbox effect:
Either using the graphic user interface (GUI); or with code
Using the Graphic User Interface:
Go to: "Properties" Tab; then set the following properties:
However; the best way is to create this by code. See example below.
AutoCompleteStringCollection sourceName = new AutoCompleteStringCollection();
foreach (string name in listNames)
{
sourceName.Add(name);
}
txtName.AutoCompleteCustomSource = sourceName;
txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
Does it really have to be a thread, or can it be a task too?
if so, the easiest way is:
Task.Factory.StartNew(() => SecondFoo())
You can try changing the flag's value
np.load(training_image_names_array,allow_pickle=True)
commands
also works.
import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result
It works on linux, python 2.7.
Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.
You can refer to it as "snippets" or more accurately "collection of snippets" . The term I think was coined from the press and printing industry, where they used actual "plates" and then re-used them as chunks again.. In modern-day internet it is a part of an ongoing (annoying IMHO) trend of using fancy terms for simple things in order to look more trendy and sophisticated . see RESPONSIVE = adaptable / fluid.
May I recommend you corn-httpclient. It's simple,fast and enough for most cases.
HttpForm form = new HttpForm(new URI("http://localhost:8080/test/formtest.jsp"));
//Authentication form.setCredentials("user1", "password");
form.putFieldValue("input1", "your value");
HttpResponse response = form.doPost();
assertFalse(response.hasError());
assertNotNull(response.getData());
assertTrue(response.getData().contains("received " + val));
maven dependency
<dependency>
<groupId>net.sf.corn</groupId>
<artifactId>corn-httpclient</artifactId>
<version>1.0.0</version>
</dependency>
All settings listed here are correct, but here are the most optimal and sufficient solution:
[mysqld]
init_connect='SET collation_connection = utf8_unicode_ci'
character-set-server = utf8
collation-server = utf8_unicode_ci
[client]
default-character-set = utf8
Add these to /etc/mysql/my.cnf
.
Please note, I choose utf8_unicode_ci type of collation due to the performance issue.
The result is:
mysql> SHOW VARIABLES LIKE 'character%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
mysql> SHOW VARIABLES LIKE 'collation%';
+----------------------+-----------------+
| Variable_name | Value |
+----------------------+-----------------+
| collation_connection | utf8_unicode_ci |
| collation_database | utf8_unicode_ci |
| collation_server | utf8_unicode_ci |
+----------------------+-----------------+
And this is when you connect as non-SUPER user!
For example, the difference between connection as SUPER and non-SUPER user (of course in case of utf8_unicode_ci collation):
user with SUPER priv.:
mysql> SHOW VARIABLES LIKE 'collation%';
+----------------------+-----------------+
| Variable_name | Value |
+----------------------+-----------------+
| collation_connection | utf8_general_ci | <---
| collation_database | utf8_unicode_ci |
| collation_server | utf8_unicode_ci |
+----------------------+-----------------+
user with non-SUPER priv.:
mysql> SHOW VARIABLES LIKE 'collation%';
+----------------------+-----------------+
| Variable_name | Value |
+----------------------+-----------------+
| collation_connection | utf8_unicode_ci |
| collation_database | utf8_unicode_ci |
| collation_server | utf8_unicode_ci |
+----------------------+-----------------+
I wrote a comprehensive article (rus) explaining in details why you should use one or the other option. All types of Character Sets and Collations are considered: for server, for database, for connection, for table and even for column.
I hope this and the article will help to clarify unclear moments.
Here is an alternative way to solve this using a DIV and the 'contenteditable' property:
HTML:
<div contenteditable = "true" class = "fluidInput" data-placeholder = ""></div>
CSS: (to give the DIV some dimensions and make it easier to see)
.fluidInput {
display : inline-block;
vertical-align : top;
min-width : 1em;
height : 1.5em;
font-family : Arial, Helvetica, sans-serif;
font-size : 0.8em;
line-height : 1.5em;
padding : 0px 2px 0px 2px;
border : 1px solid #aaa;
cursor : text;
}
.fluidInput * {
display : inline;
}
.fluidInput br {
display : none;
}
.fluidInput:empty:before {
content : attr(data-placeholder);
color : #ccc;
}
Note: If you are planning on using this inside of a FORM element that you plan to submit, you will need to use Javascript / jQuery to catch the submit event so that you can parse the 'value' ( .innerHTML
or .html()
respectively) of the DIV.
Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.
$("#button_1, #button_2").on("click", function(e) {
e.preventDefault();
$.ajax({type: "POST",
url: "/pages/test/",
data: { id: $(this).val(), access_token: $("#access_token").val() },
success:function(result) {
alert('ok');
},
error:function(result) {
alert('error');
}
});
});
I've created the API "generator-excel" to create an Excel file, below the dependecy:
<dependency>
<groupId>com.github.bld-commons.excel</groupId>
<artifactId>generator-excel</artifactId>
<version>3.1.0</version>
</dependency>
This library can to configure the styles, the functions, the charts, the pivot table and etc. through a series of annotations.
You can write rows by getting data from a datasource trough a query with or without parameters.
Below an example to develop
package bld.generator.report.junit.entity;
import java.util.Date;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import bld.generator.report.excel.RowSheet;
import bld.generator.report.excel.annotation.ExcelCellLayout;
import bld.generator.report.excel.annotation.ExcelColumn;
import bld.generator.report.excel.annotation.ExcelDate;
import bld.generator.report.excel.annotation.ExcelImage;
import bld.generator.report.excel.annotation.ExcelRowHeight;
@ExcelRowHeight(height = 3)
public class UtenteRow implements RowSheet {
@ExcelColumn(columnName = "Id", indexColumn = 0)
@ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
private Integer idUtente;
@ExcelColumn(columnName = "Nome", indexColumn = 2)
@ExcelCellLayout
private String nome;
@ExcelColumn(columnName = "Cognome", indexColumn = 1)
@ExcelCellLayout
private String cognome;
@ExcelColumn(columnName = "Data di nascita", indexColumn = 3)
@ExcelCellLayout(horizontalAlignment = HorizontalAlignment.CENTER)
@ExcelDate
private Date dataNascita;
@ExcelColumn(columnName = "Immagine", indexColumn = 4)
@ExcelCellLayout
@ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
private byte[] image;
@ExcelColumn(columnName = "Path", indexColumn = 5)
@ExcelCellLayout
@ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
private String path;
public UtenteRow() {
}
public UtenteRow(Integer idUtente, String nome, String cognome, Date dataNascita) {
super();
this.idUtente = idUtente;
this.nome = nome;
this.cognome = cognome;
this.dataNascita = dataNascita;
}
public Integer getIdUtente() {
return idUtente;
}
public void setIdUtente(Integer idUtente) {
this.idUtente = idUtente;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public Date getDataNascita() {
return dataNascita;
}
public void setDataNascita(Date dataNascita) {
this.dataNascita = dataNascita;
}
public byte[] getImage() {
return image;
}
public String getPath() {
return path;
}
public void setImage(byte[] image) {
this.image = image;
}
public void setPath(String path) {
this.path = path;
}
}
package bld.generator.report.junit.entity;
import org.apache.poi.ss.usermodel.DataConsolidateFunction;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import bld.generator.report.excel.RowSheet;
import bld.generator.report.excel.annotation.ExcelCellLayout;
import bld.generator.report.excel.annotation.ExcelColumn;
import bld.generator.report.excel.annotation.ExcelFont;
import bld.generator.report.excel.annotation.ExcelSubtotal;
import bld.generator.report.excel.annotation.ExcelSubtotals;
@ExcelSubtotals(labelTotalGroup = "Total",endLabel = "total")
public class SalaryRow implements RowSheet {
@ExcelColumn(columnName = "Name", indexColumn = 0)
@ExcelCellLayout
private String name;
@ExcelColumn(columnName = "Amount", indexColumn = 1)
@ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
@ExcelSubtotal(dataConsolidateFunction = DataConsolidateFunction.SUM,excelCellLayout = @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT,font=@ExcelFont(bold = true)))
private Double amount;
public SalaryRow() {
super();
}
public SalaryRow(String name, Double amount) {
super();
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
}
package bld.generator.report.junit.entity;
import javax.validation.constraints.Size;
import bld.generator.report.excel.QuerySheetData;
import bld.generator.report.excel.annotation.ExcelHeaderLayout;
import bld.generator.report.excel.annotation.ExcelMarginSheet;
import bld.generator.report.excel.annotation.ExcelQuery;
import bld.generator.report.excel.annotation.ExcelSheetLayout;
@ExcelSheetLayout
@ExcelHeaderLayout
@ExcelMarginSheet(bottom = 1.5, left = 1.5, right = 1.5, top = 1.5)
@ExcelQuery(select = "SELECT id_utente, nome, cognome, data_nascita,image,path "
+ "FROM utente "
+ "WHERE cognome=:cognome "
+ "order by cognome,nome")
public class UtenteSheet extends QuerySheetData<UtenteRow> {
public UtenteSheet(@Size(max = 31) String sheetName) {
super(sheetName);
}
}
package bld.generator.report.junit.entity;
import javax.validation.constraints.Size;
import bld.generator.report.excel.SheetData;
import bld.generator.report.excel.annotation.ExcelHeaderLayout;
import bld.generator.report.excel.annotation.ExcelMarginSheet;
import bld.generator.report.excel.annotation.ExcelSheetLayout;
@ExcelSheetLayout
@ExcelHeaderLayout
@ExcelMarginSheet(bottom = 1.5,left = 1.5,right = 1.5,top = 1.5)
public class SalarySheet extends SheetData<SalaryRow> {
public SalarySheet(@Size(max = 31) String sheetName) {
super(sheetName);
}
}
package bld.generator.report.junit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import bld.generator.report.excel.BaseSheet;
import bld.generator.report.excel.GenerateExcel;
import bld.generator.report.excel.data.ReportExcel;
import bld.generator.report.junit.entity.AutoreLibriSheet;
import bld.generator.report.junit.entity.CasaEditrice;
import bld.generator.report.junit.entity.GenereSheet;
import bld.generator.report.junit.entity.SalaryRow;
import bld.generator.report.junit.entity.SalarySheet;
import bld.generator.report.junit.entity.TotaleAutoreLibriRow;
import bld.generator.report.junit.entity.TotaleAutoreLibriSheet;
import bld.generator.report.junit.entity.UtenteSheet;
import bld.generator.report.utils.ExcelUtils;
/**
* The Class ReportTest.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@ConfigurationProperties
@ComponentScan(basePackages = {"bld.generator","bld.read"})
@EnableTransactionManagement
public class ReportTestJpa {
/** The Constant PATH_FILE. */
private static final String PATH_FILE = "/mnt/report/";
/** The generate excel. */
@Autowired
private GenerateExcel generateExcel;
/**
* Sets the up.
*
* @throws Exception the exception
*/
@Before
public void setUp() throws Exception {
}
/**
* Test.
*
* @throws Exception the exception
*/
@Test
public void test() throws Exception {
List<BaseSheet> listBaseSheet = new ArrayList<>();
UtenteSheet utenteSheet=new UtenteSheet("Utente");
utenteSheet.getMapParameters().put("cognome", "Rossi");
listBaseSheet.add(utenteSheet);
CasaEditrice casaEditrice = new CasaEditrice("Casa Editrice","Mondadori", new GregorianCalendar(1955, Calendar.MAY, 10), "Roma", "/home/francesco/Documents/git-project/dev-excel/linux.jpg","Drammatico");
listBaseSheet.add(casaEditrice);
AutoreLibriSheet autoreLibriSheet = new AutoreLibriSheet("Libri d'autore","Test label");
TotaleAutoreLibriSheet totaleAutoreLibriSheet=new TotaleAutoreLibriSheet();
totaleAutoreLibriSheet.getListRowSheet().add(new TotaleAutoreLibriRow("Totale"));
autoreLibriSheet.setSheetFunctionsTotal(totaleAutoreLibriSheet);
listBaseSheet.add(autoreLibriSheet);
GenereSheet genereSheet=new GenereSheet("Genere");
listBaseSheet.add(genereSheet);
SalarySheet salarySheet=new SalarySheet("salary");
salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
listBaseSheet.add(salarySheet);
ReportExcel excel = new ReportExcel("Mondadori JPA", listBaseSheet);
byte[] byteReport = this.generateExcel.createFileXlsx(excel);
ExcelUtils.writeToFile(PATH_FILE,excel.getTitle(), ".xlsx", byteReport);
}
}
logging:
level:
root: WARN
org:
springframework:
web: DEBUG
hibernate: ERROR
spring:
datasource:
url: jdbc:postgresql://localhost:5432/excel_db
username: ${EXCEL_USER_DB}
password: ${EXCEL_PASSWORD_DB}
jpa:
show-sql: true
properties:
hibernate:
default_schema: public
jdbc:
lob:
non_contextual_creation: true
format_sql: true
ddl-auto: auto
database-platform: org.hibernate.dialect.PostgreSQLDialect
generate-ddl: true
below the link of the project on github:
an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers...
This worked for me
CAST(Tbl.date as DATETIME) + CAST(Tbl.TimeFrom AS TIME)
(on SQL 2008 R2)
.Text is the formatted cell's displayed value; .Value is the value of the cell possibly augmented with date or currency indicators; .Value2 is the raw underlying value stripped of any extraneous information.
range("A1") = Date
range("A1").numberformat = "yyyy-mm-dd"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2
'results from Immediate window
2018-06-14
6/14/2018
43265
range("A1") = "abc"
range("A1").numberformat = "_(_(_(@"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2
'results from Immediate window
abc
abc
abc
range("A1") = 12
range("A1").numberformat = "0 \m\m"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2
'results from Immediate window
12 mm
12
12
If you are processing the cell's value then reading the raw .Value2 is marginally faster than .Value or .Text. If you are locating errors then .Text will return something like #N/A
as text and can be compared to a string while .Value and .Value2 will choke comparing their returned value to a string. If you have some custom cell formatting applied to your data then .Text may be the better choice when building a report.
You don't have access to the navigation backButtonItem with the way you want, you need to create your own back button like below:
- (void)loadView
{
[super loadView];
UIButton *backButton = [[UIButton alloc] initWithFrame: CGRectMake(0, 0, 44.0f, 30.0f)];
[backButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(popVC) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
}
And off course:
- (void) popVC{
[self.navigationController popViewControllerAnimated:YES];
}
I had the same problem when I upgraded jquery UI to 1.8.1 without upgrading the corresponding theme. Only is needed to upgrade the theme too and "auto" works again.
You don't need an array to do it.
var ItemNode = this.state.data.map(function(itemData) {
return (
<ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
);
});
I wonder what about this:
template <class something>
inline std::function<void()> templateLamda() {
return [](){ std::cout << something.memberfunc() };
}
I used similar code like this, to generate a template and wonder if the compiler will optimize the "wrapping" function out.
or you can also do ( for pem file )
scp -r -i file.pem [email protected]:/home/backup /home/user/Desktop/
You need
ALTER TABLE YourTable ALTER COLUMN YourColumn <<new_datatype>> [NULL | NOT NULL]
But remember to specify NOT NULL
explicitly if desired.
ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NOT NULL;
If you leave it unspecified as below...
ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500);
Then the column will default to allowing nulls even if it was originally defined as NOT NULL
. i.e. omitting the specification in an ALTER TABLE ... ALTER COLUMN
is always treated as.
ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NULL;
This behaviour is different from that used for new columns created with ALTER TABLE
(or at CREATE TABLE
time). There the default nullability depends on the ANSI_NULL_DFLT
settings.
Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:
Subject: Claiming (?P...) regex syntax extensions
From: Guido van Rossum ([email protected])
Date: Dec 10, 1997 3:36:19 pm
I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.
You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)
As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:
(?P<foo>...)
Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".
(?P=foo)
Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)
to which Larry Wall replied:
[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)
Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]
So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.
I was able to get the list mapping to work with just using @SerializedName
for all fields.. no logic around Type
was necessary.
Running the code - in step #4 below - through the debugger, I am able to observe that the List<ContentImage> mGalleryImages
object populated with the JSON data
Here's an example:
1. The JSON
{
"name": "Some House",
"gallery": [
{
"description": "Nice 300sqft. den.jpg",
"photo_url": "image/den.jpg"
},
{
"description": "Floor Plan",
"photo_url": "image/floor_plan.jpg"
}
]
}
2. Java class with the List
public class FocusArea {
@SerializedName("name")
private String mName;
@SerializedName("gallery")
private List<ContentImage> mGalleryImages;
}
3. Java class for the List items
public class ContentImage {
@SerializedName("description")
private String mDescription;
@SerializedName("photo_url")
private String mPhotoUrl;
// getters/setters ..
}
4. The Java code that processes the JSON
for (String key : focusAreaKeys) {
JsonElement sectionElement = sectionsJsonObject.get(key);
FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
}
Expression: "Total Count: " + (DT_WSTR, 5)@[User::Cnt]
This also works.
Javascript:
var app = angular.module('angularApp', []);
app.controller('MainCtrl', function($scope, name, id) {
$scope.id = id;
$scope.name = name;
// and more init
});
Html:
<!DOCTYPE html>
<html ng-app="angularApp">
<head lang="en">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="app.js"></script>
<script>
app.value("name", "James").value("id", "007");
</script>
</head>
<body ng-controller="MainCtrl">
<h1>I am {{name}} {{id}}</h1>
</body>
</html>
{:a=>"a", :b=>"b", :c=>"c"}.map{ |x,v| "#{x}=#{v}" }.reduce{|x,v| "#{x}&#{v}" }
"a=a&b=b&c=c"
Here's another way. For simple queries.
Using your data:
test_data <- data.frame(
var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
Dates = seq.Date(as.Date("2002-01-01"), by="1 month", length.out=100))
I create a stacked version which is what ggplot()
would like to work with:
stacked <- with(test_data,
data.frame(value = c(var0, var1),
variable = factor(rep(c("Var0","Var1"),
each = NROW(test_data))),
Dates = rep(Dates, 2)))
In this case producing stacked
was quite easy as we only had to do a couple of manipulations, but reshape()
and the reshape
and reshape2
might be useful if you have a more complex real data set to manipulate.
Once the data are in this stacked form, it only requires a simple ggplot()
call to produce the plot you wanted with all the extras (one reason why higher-level plotting packages like lattice
and ggplot2
are so useful):
require(ggplot2)
p <- ggplot(stacked, aes(Dates, value, colour = variable))
p + geom_line()
I'll leave it to you to tidy up the axis labels, legend title etc.
HTH
Well i have the same problem, my way to fix it was to stop and disable the "application experience" service in Windows.
This is the way i calculated the slope: Source: http://classroom.synonym.com/calculate-trendline-2709.html
class Program
{
public double CalculateTrendlineSlope(List<Point> graph)
{
int n = graph.Count;
double a = 0;
double b = 0;
double bx = 0;
double by = 0;
double c = 0;
double d = 0;
double slope = 0;
foreach (Point point in graph)
{
a += point.x * point.y;
bx = point.x;
by = point.y;
c += Math.Pow(point.x, 2);
d += point.x;
}
a *= n;
b = bx * by;
c *= n;
d = Math.Pow(d, 2);
slope = (a - b) / (c - d);
return slope;
}
}
class Point
{
public double x;
public double y;
}
Here is a solution using boxplot.stats
# create a dummy data frame with outliers
df = data.frame(y = c(-100, rnorm(100), 100))
# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))
# compute lower and upper whiskers
ylim1 = boxplot.stats(df$y)$stats[c(1, 5)]
# scale y limits based on ylim1
p1 = p0 + coord_cartesian(ylim = ylim1*1.05)
I've just run into this issue and it was because I had updated a view in my DB and not refreshed the schema in my mapping.
assemble[Variant]
would generate the APK for you on disk although it should not be necessary to use it to debug the app.
Run the following command in the root directory of the project:
$ ./gradlew clean build assemble[Variant]
GL
<div>
—the generic flow container we all know and love. It’s a block-level element with no additional semantic meaning (W3C:Markup, WhatWG)
<section>
—a generic document or application section. A normally has a heading (title) and maybe a footer too. It’s a chunk of related content, like a subsection of a long article, a major part of the page (eg the news section on the homepage), or a page in a webapp’s tabbed interface. (W3C:Markup, WhatWG)
My suggestion: div: used lower version( i think 4.01 to still) html element(lot of designers handled that). section: recently comming (html5) html element.
HTML5 has a built-in combo box. You create a text input
and a datalist
. Then you add a list
attribute to the input
, with a value of the id
of the datalist
.
Update: As of March 2019 all major browsers (now including Safari 12.1 and iOS Safari 12.3) support datalist
to the level needed for this functionality. See caniuse for detailed browser support.
It looks like this:
<input type="text" list="cars" />_x000D_
<datalist id="cars">_x000D_
<option>Volvo</option>_x000D_
<option>Saab</option>_x000D_
<option>Mercedes</option>_x000D_
<option>Audi</option>_x000D_
</datalist>
_x000D_
Once installed in windows Followed the instructions starting from Run SQL Command Line (command prompt)
then... v. SQL> connect /as sysdba
Connected. [SQL prompt response]
vi. SQL> alter user SYS identified by "newpassword";
User altered. [SQL prompt response]
Thank you. This minimized a headache
The Boa is good for your needs, see the example which extends Python tensorflow keras.Sequential
class in JavaScript.
const fs = require('fs');
const boa = require('@pipcook/boa');
const { tuple, enumerate } = boa.builtins();
const tf = boa.import('tensorflow');
const tfds = boa.import('tensorflow_datasets');
const { keras } = tf;
const { layers } = keras;
const [
[ train_data, test_data ],
info
] = tfds.load('imdb_reviews/subwords8k', boa.kwargs({
split: tuple([ tfds.Split.TRAIN, tfds.Split.TEST ]),
with_info: true,
as_supervised: true
}));
const encoder = info.features['text'].encoder;
const padded_shapes = tuple([
[ null ], tuple([])
]);
const train_batches = train_data.shuffle(1000)
.padded_batch(10, boa.kwargs({ padded_shapes }));
const test_batches = test_data.shuffle(1000)
.padded_batch(10, boa.kwargs({ padded_shapes }));
const embedding_dim = 16;
const model = keras.Sequential([
layers.Embedding(encoder.vocab_size, embedding_dim),
layers.GlobalAveragePooling1D(),
layers.Dense(16, boa.kwargs({ activation: 'relu' })),
layers.Dense(1, boa.kwargs({ activation: 'sigmoid' }))
]);
model.summary();
model.compile(boa.kwargs({
optimizer: 'adam',
loss: 'binary_crossentropy',
metrics: [ 'accuracy' ]
}));
The complete example is at: https://github.com/alibaba/pipcook/blob/master/example/boa/tf2/word-embedding.js
I used Boa in another project Pipcook, which is to address the machine learning problems for JavaScript developers, we implemented ML/DL models upon the Python ecosystem(tensorflow,keras,pytorch) by the boa library.
Shortcut doing this on Mac: Press command+Shift+A (Action) and type "class count to use import with *" Press Enter. Enter a higher number there like 999
Even though call
and apply
achive the same thing, I think there is atleast one place where you cannot use call
but can only use apply
. That is when you want to support inheritance and want to call the constructor.
Here is a function allows you to create classes which also supports creating classes by extending other classes.
function makeClass( properties ) {
var ctor = properties['constructor'] || function(){}
var Super = properties['extends'];
var Class = function () {
// Here 'call' cannot work, only 'apply' can!!!
if(Super)
Super.apply(this,arguments);
ctor.apply(this,arguments);
}
if(Super){
Class.prototype = Object.create( Super.prototype );
Class.prototype.constructor = Class;
}
Object.keys(properties).forEach( function(prop) {
if(prop!=='constructor' && prop!=='extends')
Class.prototype[prop] = properties[prop];
});
return Class;
}
//Usage
var Car = makeClass({
constructor: function(name){
this.name=name;
},
yourName: function() {
return this.name;
}
});
//We have a Car class now
var carInstance=new Car('Fiat');
carInstance.youName();// ReturnsFiat
var SuperCar = makeClass({
constructor: function(ignore,power){
this.power=power;
},
extends:Car,
yourPower: function() {
return this.power;
}
});
//We have a SuperCar class now, which is subclass of Car
var superCar=new SuperCar('BMW xy',2.6);
superCar.yourName();//Returns BMW xy
superCar.yourPower();// Returns 2.6
Using coalesce() converts null to 0:
$query = Model::where('field1', 1)
->whereNull('field2')
->where(DB::raw('COALESCE(datefield_at,0)'), '<', $date)
;
Check the output before the statement that caused current transaction is aborted
. This typically means that database threw an exception that your code had ignored and now expecting next queries to return some data.
So you now have a state mismatch between your application, which considers things are fine, and database, that requires you to rollback and re-start your transaction from the beginning.
You should catch all exceptions and rollback transactions in such cases.
You could do it in one document if you had a conditional based on params sent over. Eg:
if (isset($_GET['secret_param'])) {
<run script>
} else {
<display button>
}
I think the best way though is to have two files.
Lock and synchronize block both serves the same purpose but it depends on the usage. Consider the below part
void randomFunction(){
.
.
.
synchronize(this){
//do some functionality
}
.
.
.
synchronize(this)
{
// do some functionality
}
} // end of randomFunction
In the above case , if a thread enters the synchronize block, the other block is also locked. If there are multiple such synchronize block on the same object, all the blocks are locked. In such situations , java.util.concurrent.Lock can be used to prevent unwanted locking of blocks
ld
is trying to find libcrypto.so
which is not present as seen in your locate
output.
You can make a copy of the libcrypto.so.0.9.8
and name it as libcrypto.so
. Put this is your ld path. ( If you do not have root access then you can put it in a local path and specify the path manually )
As of PHP 5.3.0 you can use __DIR__
for this purpose.
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__ FILE__).
See PHP Magic constants.
C:\www>php --version
PHP 5.5.6 (cli) (built: Nov 12 2013 11:33:44)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
C:\www>php -r "echo __DIR__;"
C:\www
I know this answer is too late considering the question is dated 2010 but I came across this question as I was facing a similar problem myself. As already stated in the answer, normed=True means that the total area under the histogram is equal to 1 but the sum of heights is not equal to 1. However, I wanted to, for convenience of physical interpretation of a histogram, make one with sum of heights equal to 1.
I found a hint in the following question - Python: Histogram with area normalized to something other than 1
But I was not able to find a way of making bars mimic the histtype="step" feature hist(). This diverted me to : Matplotlib - Stepped histogram with already binned data
If the community finds it acceptable I should like to put forth a solution which synthesises ideas from both the above posts.
import matplotlib.pyplot as plt
# Let X be the array whose histogram needs to be plotted.
nx, xbins, ptchs = plt.hist(X, bins=20)
plt.clf() # Get rid of this histogram since not the one we want.
nx_frac = nx/float(len(nx)) # Each bin divided by total number of objects.
width = xbins[1] - xbins[0] # Width of each bin.
x = np.ravel(zip(xbins[:-1], xbins[:-1]+width))
y = np.ravel(zip(nx_frac,nx_frac))
plt.plot(x,y,linestyle="dashed",label="MyLabel")
#... Further formatting.
This has worked wonderfully for me though in some cases I have noticed that the left most "bar" or the right most "bar" of the histogram does not close down by touching the lowest point of the Y-axis. In such a case adding an element 0 at the begging or the end of y achieved the necessary result.
Just thought I'd share my experience. Thank you.
We can easily do this with in swift 5.1
setup 1
subview width height set using float
view.addSubview(myView1)
myView1.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
myView1.centerXAnchor.constraint(equalTo: view.centerXAnchor),
myView1.centerYAnchor.constraint(equalTo: view.centerYAnchor),
myView1.widthAnchor.constraint(equalToConstant: 100),
myView1.heightAnchor.constraint(equalToConstant: 100),
])
setup 2
subview width set using view width height
view.addSubview(myView2)
myView2.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
myView2.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: 16),
myView2.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,constant: 16),
myView2.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.3),
myView2.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3)
])
As Sagi stated in their answer DataTable.Load is a good solution. If you are trying to load multiple tables from a single reader you do not need to call DataReader.NextResult. The DataTable.Load method also advances the reader to the next result set (if any).
// Read every result set in the data reader.
while (!reader.IsClosed)
{
DataTable dt = new DataTable();
// DataTable.Load automatically advances the reader to the next result set
dt.Load(reader);
items.Add(dt);
}
Most applications are simple enough to be solved in normal OO ways
OO ways have not always been "normal." This decade's standard was last decade's marginalized concept.
Functional programming is math. Paul Graham on Lisp (substitute functional programming for Lisp):
So the short explanation of why this 1950s language is not obsolete is that it was not technology but math, and math doesn’t get stale. The right thing to compare Lisp to is not 1950s hardware, but, say, the Quicksort algorithm, which was discovered in 1960 and is still the fastest general-purpose sort.
The ContextSwitchDeadlock
doesn't necessarily mean your code has an issue, just that there is a potential. If you go to Debug > Exceptions
in the menu and expand the Managed Debugging Assistants
, you will find ContextSwitchDeadlock
is enabled. If you disable this, VS will no longer warn you when items are taking a long time to process. In some cases you may validly have a long-running operation. It's also helpful if you are debugging and have stopped on a line while this is processing - you don't want it to complain before you've had a chance to dig into an issue.
To see both the normal distribution and your actual data you should plot your data as a histogram, then draw the probability density function over this. See the example on https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.normal.html for exactly how to do this.
There is no bidirectional map in the Java Standard API. Either you can maintain two maps yourself or use the BidiMap from Apache Collections.
Within the range 0 = c < 128, yes the '
is the only difference for CPython 2.6.
>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])
Outside of this range the two types are not exchangeable.
>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)
>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode
On Python 3.x, the string_escape
encoding no longer exists, since str
can only store Unicode.
The only time I've seen something like this happen is when I have a bad connection, or when somebody is closing the socket that I am using from a different thread context.
Animuson gives a decent way to do it, but no help on understanding it. I kept looking and came across a forum thread with this commands:
Echo Off
IF Not EXIST n:\dbfs\doekasp.txt GOTO DoNothing
copy n:\dbfs\doekasp.txt n:\history\doekasp.txt
Rem rename command is done twice (2) to allow for 1 or 2 digit hour,
Rem If before 10am (1digit) hour Rename starting at location (0) for (2) chars,
Rem will error out, as location (0) will have a space
Rem and space is invalid character for file name,
Rem so second remame will be used.
Rem
Rem if equal 10am or later (2 digit hour) then first remame will work and second will not
Rem as doekasp.txt will not be found (remamed)
ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_@_%time:~0,2%h%time:~3,2%m%time:~6,2%s%.txt
ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_@_%time:~1,1%h%time:~3,2%m%time:~6,2%s%.txt
I always name year first YYYYMMDD, but wanted to add time. Here you will see that he has given a reason why 0,2 will not work and 1,1 will, because (space) is an invalid character. This opened my eyes to the issue. Also, by default you're in 24hr mode.
I ended up with:
ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~0,2%%time:~3,2%.txt
ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~1,1%%time:~3,2%.txt
Output:
Logs-20121707_1019
I'm confused by one thing: You're planning to create a new naming convention for a new project. Generally you should have a naming convention that is company- or team-wide. If you already have projects that have any form of naming convention, you should not change the convention for a new project. If the convention above is just codification of your existing practices, then you are golden. The more it differs from existing de facto standards the harder it will be to gain mindshare in the new standard.
About the only suggestion I would add is I've taken a liking to _t at the end of types in the style of uint32_t and size_t. It's very C-ish to me although some might complain it's just "reverse" Hungarian.
From manual: Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
Here's a more concise approach...
df['a_bsum'] = df.groupby('A')['B'].transform(sum)
df.sort(['a_bsum','C'], ascending=[True, False]).drop('a_bsum', axis=1)
The first line adds a column to the data frame with the groupwise sum. The second line performs the sort and then removes the extra column.
Result:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
NOTE: sort
is deprecated, use sort_values
instead
The name of the DOM function is actually getElementsByClassName
, not getElementByClassName
, simply because more than one element on the page can have the same class, hence: Elements
.
The return value of this will be a NodeList instance, or a superset of the NodeList
(FF, for instance returns an instance of HTMLCollection
). At any rate: the return value is an array-like object:
var y = document.getElementsByClassName('foo');
var aNode = y[0];
If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:
var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);
As yckart suggested querySelector('.foo')
and querySelectorAll('.foo')
would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
Clearly you aren't sending the data with ObjectOutputStream:
you are just writing the bytes.
readObject()
you must write with writeObject().
readUTF()
you must write with writeUTF().
readXXX()
you must write with writeXXX(),
for most values of XXX.On rails 4.2.2, go to application.rb
and use config.time_zone='city'
(e.g.:'London' or 'Bucharest' or 'Amsterdam' and so on).
It should work just fine. It worked for me.
Dim wsh as new wshshell
chdir "Directory of Batch File"
wsh.run "Full Path of Batch File",vbnormalfocus, true
Done Son
For sorting narrow range of integers try Counting sort, which has a complexity of O(range + n)
, where n
is number of items to be sorted. If you'd like to sort something not discrete use optimal n*log(n) algorithms (quicksort, heapsort, mergesort). Merge sort is also used in a method already mentioned by other responses Arrays.sort
. There is no simple way how to recommend some algorithm or function call, because there are dozens of special cases, where you would use some sort, but not the other.
So please specify the exact purpose of your application (to learn something (well - start with the insertion sort or bubble sort), effectivity for integers (use counting sort), effectivity and reusability for structures (use n*log(n) algorithms), or zou just want it to be somehow sorted - use Arrays.sort :-)). If you'd like to sort string representations of integers, than u might be interrested in radix sort....
If you're tired of this error. You can make Chrome not act out like this. I'm not saying it's the best way just saying it's a way.
As a workaround, a Windows registry key can be created to allow Google Chrome to use the commonName of a server certificate to match a hostname if the certificate is missing a subjectAlternativeName extension, as long as it successfully validates and chains to a locally-installed CA certificates.
Data type: Boolean [Windows:REG_DWORD] Windows registry location: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome Windows/Mac/Linux/Android preference name: EnableCommonNameFallbackForLocalAnchors Value: 0x00000001 (Windows), true(Linux), true (Android), (Mac) To create a Windows registry key, simply follow these steps:
Open Notepad Copy and paste the following content into notepad Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome] "EnableCommonNameFallbackForLocalAnchors"=dword:00000001 Go to File > Save as Filename: any_filename.reg Save as type: All Files
Select a preferred location for the file
Click on Save
Double click on the saved file to run
Click on Yes on the Registry Editor warning
Found this information on Symantec support page: https://support.symantec.com/en_US/article.TECH240507.html
myClub.distance = Console.ReadLine();
should be
myClub.mydistance = Console.ReadLine();
use your public properties that you have defined for others as well instead of the protected field members.
In First activity:
ArrayList<ContactBean> fileList = new ArrayList<ContactBean>();
Intent intent = new Intent(MainActivity.this, secondActivity.class);
intent.putExtra("FILES_TO_SEND", fileList);
startActivity(intent);
In receiver activity:
ArrayList<ContactBean> filelist = (ArrayList<ContactBean>)getIntent().getSerializableExtra("FILES_TO_SEND");`
If (1) you need a favicon that is different for some parts of the domain, or (2) you want this to work with IE 8 or older (haven't tested any newer version), then you have to edit the html to specify the favicon
Building upon Daniel Q's and Patrick Artner's excellent suggestions, here is an even more generalized solution.
# Assuming Python3
import sys
class ValidationError(ValueError): # thanks Patrick Artner
pass
def validate_input(prompt, cast=str, cond=(lambda x: True), onerror=None):
if onerror==None: onerror = {}
while True:
try:
data = cast(input(prompt))
if not cond(data): raise ValidationError
return data
except tuple(onerror.keys()) as e: # thanks Daniel Q
print(onerror[type(e)], file=sys.stderr)
I opted for explicit if
and raise
statements instead of an assert
,
because assertion checking may be turned off,
whereas validation should always be on to provide robustness.
This may be used to get different kinds of input, with different validation conditions. For example:
# No validation, equivalent to simple input:
anystr = validate_input("Enter any string: ")
# Get a string containing only letters:
letters = validate_input("Enter letters: ",
cond=str.isalpha,
onerror={ValidationError: "Only letters, please!"})
# Get a float in [0, 100]:
percentage = validate_input("Percentage? ",
cast=float, cond=lambda x: 0.0<=x<=100.0,
onerror={ValidationError: "Must be between 0 and 100!",
ValueError: "Not a number!"})
Or, to answer the original question:
age = validate_input("Please enter your age: ",
cast=int, cond=lambda a:0<=a<150,
onerror={ValidationError: "Enter a plausible age, please!",
ValueError: "Enter an integer, please!"})
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
This effect can occur on non-input elements, too. I've found the following works as a more general solution
:focus {
outline-color: transparent;
outline-style: none;
}
Update: You may not have to use the :focus
selector. If you have an element, say <div id="mydiv">stuff</div>
, and you were getting the outer glow on this div element, just apply like normal:
#mydiv {
outline-color: transparent;
outline-style: none;
}
int val_to_check = 5
bool in_range = Enumerable.Range(0, 13).Contains(val_to_check);
The second parameter is the "count" not the end or high number.
I.E.
int low_num = 0
int high_num = 12
int val_to_check = 5
bool in_range = Enumerable.Range(low_num , high_num - low_num + 1).Contains(val_to_check);
Checks if the val_to_check is between 0 and 12
Simple and with little changes. And also hide load more when entire list is loaded.
jsFiddle here.
$(document).ready(function () {
// Load the first 3 list items from another HTML file
//$('#myList').load('externalList.html li:lt(3)');
$('#myList li:lt(3)').show();
$('#showLess').hide();
var items = 25;
var shown = 3;
$('#loadMore').click(function () {
$('#showLess').show();
shown = $('#myList li:visible').size()+5;
if(shown< items) {$('#myList li:lt('+shown+')').show();}
else {$('#myList li:lt('+items+')').show();
$('#loadMore').hide();
}
});
$('#showLess').click(function () {
$('#myList li').not(':lt(3)').hide();
});
});
ADDITION :
Swift has no DEFINED ORDER for Set and Dictionary.For that reason you should use sorted() method to prevent from getting unexpected results such as your array can be like ["a","b"] or ["b","a"] and you do not want this.
TO FIX THIS:
FOR SETS
var example:Set = ["a","b","c"]
let makeExampleArray = [example.sorted()]
makeExampleArray
Result: ["a","b","c"]
Without sorted()
It can be:
["a","b","c"] or ["b","c","a",] or ["c","a","b"] or ["a","c","b"] or ["b","a","c"] or ["c","b","a"]
simple math : 3! = 6
Whenever you are trying to return JSON response for API or else make sure you have proper headers and also make sure you return a valid JSON data.
Here is the sample script which helps you to return JSON response from PHP array or from JSON file.
PHP Script (Code):
<?php
// Set required headers
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
/**
* Example: First
*
* Get JSON data from JSON file and retun as JSON response
*/
// Get JSON data from JSON file
$json = file_get_contents('response.json');
// Output, response
echo $json;
/** =. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =. */
/**
* Example: Second
*
* Build JSON data from PHP array and retun as JSON response
*/
// Or build JSON data from array (PHP)
$json_var = [
'hashtag' => 'HealthMatters',
'id' => '072b3d65-9168-49fd-a1c1-a4700fc017e0',
'sentiment' => [
'negative' => 44,
'positive' => 56,
],
'total' => '3400',
'users' => [
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'rayalrumbel',
'text' => 'Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'mikedingdong',
'text' => 'Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'ScottMili',
'text' => 'Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'yogibawa',
'text' => 'Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
],
];
// Output, response
echo json_encode($json_var);
JSON File (JSON DATA):
{
"hashtag": "HealthMatters",
"id": "072b3d65-9168-49fd-a1c1-a4700fc017e0",
"sentiment": {
"negative": 44,
"positive": 56
},
"total": "3400",
"users": [
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "rayalrumbel",
"text": "Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
},
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "mikedingdong",
"text": "Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
},
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "ScottMili",
"text": "Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
},
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "yogibawa",
"text": "Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
}
]
}
JSON Screeshot:
string.Format("{0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow)
returns 2017-02-10T08:12:39.483Z
Three types of commenting are supported
Hash base single line commenting using #
Select * from users ; # this will list users
Select * from users ; -- this will list users
Note : Its important to have single white space just after --
3) Multi line commenting using /* */
Select * from users ; /* this will list users */
An alternative is to use StreamReader.
public void FunctionName(HttpPostedFileBase file)
{
string result = new StreamReader(file.InputStream).ReadToEnd();
}
$("#wizard li").click(function () {
console.log( $(this).index() );
});
However rather than attaching one click handler for each list item it is better (performance wise) to use delegate
which would look like this:
$("#wizard").delegate('li', 'click', function () {
console.log( $(this).index() );
});
In jQuery 1.7+, you should use on
. The below example binds the event to the #wizard
element, working like a delegate event:
$("#wizard").on("click", "li", function() {
console.log( $(this).index() );
});
I would suggest mine solution that you can find in this GitHub repo. This works also for IE8 and IE9 with a custom arrow that comes from an icon font.
Examples of Custom Cross Browser Drop-down in action: check them with all your browsers to see the cross-browser feature.
Anyway, let's start with the modern browsers and then we will see the solution for the older ones.
For these browser, it is easy to set the same background image for the drop-down in order to have the same arrow.
To do so, you have to reset the browser's default style for the select
tag and set new background rules (like suggested before).
select {
/* you should keep these firsts rules in place to maintain cross-browser behaviour */
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
appearance: none;
background-image: url('<custom_arrow_image_url_here>');
background-position: 98% center;
background-repeat: no-repeat;
outline: none;
...
}
The appearance
rules are set to none to reset browsers default ones, if you want to have the same aspect for each arrow, you should keep them in place.
The background
rules in the examples are set with SVG inline images that represent different arrows. They are positioned 98% from left to keep some margin to the right border (you can easily modify the position as you wish).
In order to maintain the correct cross-browser behavior, the only other rule that have to be left in place is the outline
. This rule resets the default border that appears (in some browsers) when the element is clicked. All the others rules can be easily modified if needed.
This is the harder part... Or maybe not.
There is no standard rule to hide the default arrows for these browsers (like the select::-ms-expand
for IE10+). The solution is to hide the part of the drop-down that contains the default arrow and insert an arrow icon font (or a SVG, if you prefer) similar to the SVG that is used in the other browsers (see the select
CSS rule for more details about the inline SVG used).
The very first step is to set a class that can recognize the browser: this is the reason why I have used the conditional IE IFs at the beginning of the code. These IFs are used to attach specific classes to the html
tag to recognize the older IE browser.
After that, every select
in the HTML have to be wrapped by a div
(or whatever tag that can wraps an element). At this wrapper just add the class that contains the icon font.
<div class="selectTagWrapper prefix-icon-arrow-down-fill">
...
</div>
In easy words, this wrapper is used to simulate the select
tag.
To act like a drop-down, the wrapper must have a border, because we hide the one that comes from the select
.
Notice that we cannot use the select
border because we have to hide the default arrow lengthening it 25% more than the wrapper. Consequently its right border should not be visible because we hide this 25% more by the overflow: hidden
rule applied to the select
itself.
The custom arrow icon-font is placed in the pseudo class :before
where the rule content
contains the reference for the arrow (in this case it is a right parenthesis).
We also place this arrow in an absolute position to center it as much as possible (if you use different icon fonts, remember to adjust them opportunely by changing top and left values and the font size).
.ie8 .prefix-icon-arrow-down-fill:before,
.ie9 .prefix-icon-arrow-down-fill:before {
content: ")";
position: absolute;
top: 43%;
left: 93%;
font-size: 6px;
...
}
You can easily create and substitute the background arrow or the icon font arrow, with every one that you want simply changing it in the background-image
rule or making a new icon font file by yourself.
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
The following is a nice expedient solution that works with GitHub for checking out the PR branch from another user's fork. You need to know the pull request ID (which GitHub displays along with the PR title).
Example:
Fixing your insecure code #8
alice wants to merge 1 commit into your_repo:master
from her_repo:branch
git checkout -b <branch>
git pull origin pull/8/head
Substitute your remote if different from origin
.
Substitute 8
with the correct pull request ID.
###Quick solution:
With this kind of error, I usually start by raising the postBuffer
size by:
git config --global http.postBuffer 524288000
(some comments below report having to double the value):
git config --global http.postBuffer 1048576000
(For npm publish
, Martin Braun reports in the comments setting it to no more than 50 000 000 instead of the default 1 000 000)
###More information:
From the git config
man page, http.postBuffer
is about:
Maximum size in bytes of the buffer used by smart HTTP transports when POSTing data to the remote system.
For requests larger than this buffer size, HTTP/1.1 andTransfer-Encoding: chunked
is used to avoid creating a massive pack file locally. Default is 1 MiB, which is sufficient for most requests.
Even for the clone, that can have an effect, and in this instance, the OP Joe reports:
[clone] works fine now
Note: if something went wrong on the server side, and if the server uses Git 2.5+ (Q2 2015), the error message might be more explicit.
See "Git cloning: remote end hung up unexpectedly, tried changing postBuffer
but still failing".
Kulai (in the comments) points out to this Atlassian Troubleshooting Git page, which adds:
Error code 56
indicates a curl receive the error ofCURLE_RECV_ERROR
which means there was some issue that prevented the data from being received during the cloning process.
Typically this is caused by a network setting, firewall, VPN client, or anti-virus that is terminating the connection before all data has been transferred.
It also mentions the following environment variable, order to help with the debugging process.
# Linux
export GIT_TRACE_PACKET=1
export GIT_TRACE=1
export GIT_CURL_VERBOSE=1
#Windows
set GIT_TRACE_PACKET=1
set GIT_TRACE=1
set GIT_CURL_VERBOSE=1
With Git 2.25.1 (Feb. 2020), you know more about this http.postBuffer
"solution".
See commit 7a2dc95, commit 1b13e90 (22 Jan 2020) by brian m. carlson (bk2204
).
(Merged by Junio C Hamano -- gitster
-- in commit 53a8329, 30 Jan 2020)
(Git Mailing list discussion)
docs
: mention when increasing http.postBuffer is valuableSigned-off-by: brian m. carlson
Users in a wide variety of situations find themselves with HTTP push problems.
Oftentimes these issues are due to antivirus software, filtering proxies, or other man-in-the-middle situations; other times, they are due to simple unreliability of the network.
However, a common solution to HTTP push problems found online is to increase http.postBuffer.
This works for none of the aforementioned situations and is only useful in a small, highly restricted number of cases: essentially, when the connection does not properly support HTTP/1.1.
Document when raising this value is appropriate and what it actually does, and discourage people from using it as a general solution for push problems, since it is not effective there.
So the documentation for git config http.postBuffer
now includes:
http.postBuffer
Maximum size in bytes of the buffer used by smart HTTP transports when POSTing data to the remote system.
For requests larger than this buffer size, HTTP/1.1 and Transfer-Encoding: chunked is used to avoid creating a massive pack file locally.
Default is 1 MiB, which issufficient for most requests.
Note that raising this limit is only effective for disabling chunked transfer encoding and therefore should be used only where the remote server or a proxy only supports HTTP/1.0 or is noncompliant with the HTTP standard.
Raising this is not, in general, an effective solution for most push problems, but can increase memory consumption significantly since the entire buffer is allocated even for small pushes.
An evolved version of ossek solution
Custom filter is more appropriate, then you can use it anywhere in the project
js file
var myApp = angular.module('myApp',[]);
myApp.filter('utcdate', ['$filter','$locale', function($filter, $locale){
return function (input, format) {
if (!angular.isDefined(format)) {
format = $locale['DATETIME_FORMATS']['medium'];
}
var date = new Date(input);
var d = new Date()
var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return $filter('date')(_utc, format)
};
}]);
in template
<p>This will convert UTC time to local time<p>
<span>{{dateTimeInUTC | utcdate :'MMM d, y h:mm:ss a'}}</span>
If you are using the Python wrappers, then (assuming your matrix name is mat):
mat.shape gives you an array of the type- [height, width, channels]
mat.size gives you the size of the array
Sample Code:
import cv2
mat = cv2.imread('sample.png')
height, width, channel = mat.shape[:3]
size = mat.size
I am not convinced that you'll need an external sorting program in Bash.
Here is my implementation for the simple bubble-sort algorithm.
function bubble_sort()
{ #
# Sorts all positional arguments and echoes them back.
#
# Bubble sorting lets the heaviest (longest) element sink to the bottom.
#
local array=($@) max=$(($# - 1))
while ((max > 0))
do
local i=0
while ((i < max))
do
if [ ${array[$i]} \> ${array[$((i + 1))]} ]
then
local t=${array[$i]}
array[$i]=${array[$((i + 1))]}
array[$((i + 1))]=$t
fi
((i += 1))
done
((max -= 1))
done
echo ${array[@]}
}
array=(a c b f 3 5)
echo " input: ${array[@]}"
echo "output: $(bubble_sort ${array[@]})"
This shall print:
input: a c b f 3 5
output: 3 5 a b c f
This XML file does not appear to have any style information associated with it. The document tree is shown below.
You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml
instead of text/html
and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.
In case of JSF/Facelets files which have the default extension of .xhtml
, that can in turn happen if the HTTP request hasn't invoked the FacesServlet
and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml
file extension which is in your Firefox configuration apparently by default interpreted as text/xml
.
You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern>
of the FacesServlet
as registered in webapp's web.xml
, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf
, then you need to open the page by /some.jsf
instead of /some.xhtml
. Alternatively, you can also just change the <url-pattern>
to *.xhtml
. This way you never need to fiddle with virtual URLs.
Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.
#include <bits/stdc++.h>
using namespace std;
#define Max 1000
vector <int> adj[Max];
bool visited[Max];
void bfs_recursion_utils(queue<int>& Q) {
while(!Q.empty()) {
int u = Q.front();
visited[u] = true;
cout << u << endl;
Q.pop();
for(int i = 0; i < (int)adj[u].size(); ++i) {
int v = adj[u][i];
if(!visited[v])
Q.push(v), visited[v] = true;
}
bfs_recursion_utils(Q);
}
}
void bfs_recursion(int source, queue <int>& Q) {
memset(visited, false, sizeof visited);
Q.push(source);
bfs_recursion_utils(Q);
}
int main(void) {
queue <int> Q;
adj[1].push_back(2);
adj[1].push_back(3);
adj[1].push_back(4);
adj[2].push_back(5);
adj[2].push_back(6);
adj[3].push_back(7);
bfs_recursion(1, Q);
return 0;
}
Remove :
npm uninstall -g angular-cli
Reinstall (with yarn)
# npm install --global yarn
yarn global add @angular/cli@latest
ng set --global packageManager=yarn # This will help ng-cli to use yarn
Reinstall (with npm)
npm install --global @angular/cli@latest
Another way is to not use global install, and add /node_modules/.bin
folder in the PATH, or use npm scripts. It will be softer to upgrade.
Try swich fetchType from LAZY to EAGER
...
@OneToMany(fetch=FetchType.EAGER)
private Set<NodeValue> nodeValues;
...
But in this case your app will fetch data from DB anyway. If this query very hard - this may impact on performance. More here: https://docs.oracle.com/javaee/6/api/javax/persistence/FetchType.html
==> 73
Simply pass the sorted items from the dictionary to the plot()
function. concentration.items()
returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.
You can take advantage of list unpacking (with *
) to pass the sorted data directly to zip, and then again to pass it into plot()
:
import matplotlib.pyplot as plt
concentration = {
0: 0.19849878712984576,
5000: 0.093917341754771386,
10000: 0.075060643507712022,
20000: 0.06673074282575861,
30000: 0.057119318961966224,
50000: 0.046134834546203485,
100000: 0.032495766396631424,
200000: 0.018536317451599615,
500000: 0.0059499290585381479}
plt.plot(*zip(*sorted(concentration.items())))
plt.show()
sorted()
sorts tuples in the order of the tuple's items so you don't need to specify a key
function because the tuples returned by dict.item()
already begin with the key value.
its
selenium.getTable("tablename".rowNumber.colNumber)
not
selenium.getTable("tablename".colNumber.rowNumber)
Try closing all the FileOutputStream/FileInputStream
you've opened earlier in other methods ,then try deleting ,worked like a charm.
Is there no possibility to iterate over all-but the last element, and treat the last one outside of the loop? After all, a loop is created to do something similar to all elements you loop over; if one element needs something special, it shouldn't be in the loop.
(see also this question: does-the-last-element-in-a-loop-deserve-a-separate-treatment)
EDIT: since the question is more about the "in between", either the first element is the special one in that it has no predecessor, or the last element is special in that it has no successor.
What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!
As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you set — Official Documentation
Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!
How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.
Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.
Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…
First Approach: Are your files gzipped?
Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.
How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.
const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())
Second Approach:: Analyze your Angular bundle
If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.
It’s super easy to get this graph.
npm install -g webpack-bundle-analyzer
ng build --stats-json
(don’t use flag --prod
). By enabling --stats-json
you will get an additional file stats.jsonwebpack-bundle-analyzer ./dist/stats.json
and your browser will pop up the page at localhost:8888. Have fun with it.ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours
The other answers here clearly explained what does it mean.I like to explain its use.
You can select an element in the elements
tab and switch to console
tab in chrome. Just type $0 or $1
or whatever number and press enter and the element will be displayed in the console for your use.
You can use the -quit
option of find
:
find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit
If you're using ES6, you can do this:
if (['afshin', 'saeed', 'larry'].includes(varName)) {
alert('Hey');
} else {
alert('Default case');
}
Or for earlier versions of JavaScript, you can do this:
if (['afshin', 'saeed', 'larry'].indexOf(varName) !== -1) {
alert('Hey');
} else {
alert('Default case');
}
Note that this won't work in older IE browsers, but you could patch things up fairly easily. See the question determine if string is in list in javascript for more information.
In simple terms just use "defer" in the script tag.
.....The dependencies must be applied as shown below to solve this issue :
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:support-v4:27.1.0'
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:recyclerview-v7:27.1.0'
}
Please do not use the version of :
v7:28.0.0-alpha1
There are a number of reasons why the analysis portion of a compiler is normally separated into lexical analysis and parsing ( syntax analysis) phases.
resource___Compilers (2nd Edition) written by- Alfred V. Abo Columbia University Monica S. Lam Stanford University Ravi Sethi Avaya Jeffrey D. Ullman Stanford University
The folder is part of the URL you set when you create request
: "ftp://www.contoso.com/test.htm"
. If you use "ftp://www.contoso.com/wibble/test.htm"
then the file will be uploaded to a folder named wibble
.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory
to make the wibble
folder if it doesn't already exist.
There is a specific example that "_" be used:
type StringMatcher = String => (String => Boolean)
def starts: StringMatcher = (prefix:String) => _ startsWith prefix
may be equal to :
def starts: StringMatcher = (prefix:String) => (s)=>s startsWith prefix
Applying “_” in some scenarios will automatically convert to “(x$n) => x$n ”
timer.scheduleAtFixedRate( new Task(), 1000,3000);
I strongly recommend BOUML which:
It's a simple concept. Redux creates a ubiquitous state object (a store) from the actions in the reducers. Like a React component, this state doesn't have to be explicitly coded anywhere, but it helps developers to see a default state object in the reducer file to visualise what is happening. You import the reducer in the component to access the file. Then mapStateToProps selects only the key/value pairs in the store that its component needs. Think of it like Redux creating a global version of a React component's
this.state = ({
cats = [],
dogs = []
})
It is impossible to change the structure of the state by using mapStateToProps(). What you are doing is choosing only the store's key/value pairs that the component needs and passing in the values (from a list of key/values in the store) to the props (local keys) in your component. You do this one value at a time in a list. No structure changes can occur in the process.
P.S. The store is local state. Reducers usually also pass state along to the database with Action Creators getting into the mix, but understand this simple concept first for this specific posting.
P.P.S. It is good practice to separate the reducers into separate files for each one and only import the reducer that the component needs.
Here is what I learned: PYTHONPATH is a directory to add to the Python import search path "sys.path", which is made up of current dir. CWD, PYTHONPATH, standard and shared library, and customer library. For example:
% python3 -c "import sys;print(sys.path)"
['',
'/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
where the first path '' denotes the current dir., the 2nd path is via
%export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite
which can be added to ~/.bashrc to make it permanent, and the rest are Python standard and dynamic shared library plus third-party library such as django.
As said not to mess with PYTHONHOME, even setting it to '' or 'None' will cause python3 shell to stop working:
% export PYTHONHOME=''
% python3
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'
Current thread 0x00007f18a44ff740 (most recent call first):
Aborted (core dumped)
Note that if you start a Python script, the CWD will be the script's directory. For example:
username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
==== Printing sys.path ====
/home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages
You can also append a path to sys.path at run-time: Suppose you have a file Fibonacci.py in ~/Documents/Python directory:
username@bud:~/Documents/DjangoTutorial% python3
>>> sys.path.append("/home/username/Documents")
>>> print(sys.path)
['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages',
'/home/username/Documents']
>>> from Python import Fibonacci as fibo
or via
% PYTHONPATH=/home/username/Documents:$PYTHONPATH
% python3
>>> print(sys.path)
['',
'/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> from Python import Fibonacci as fibo
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
I got the very same error when trying to access the child FragmentManager
before the fragment was fully initialized (i.e. attached to the Activity or at least onCreateView()
called). Else the FragmentManager
gets initialized with a null
Activity causing the aforementioned exception.
I used Fiddler as a proxy. Fiddler redirects localhost calls to a external server.
I configured Firefox to use manual proxy (127.0.0.1 port 8888). Fiddler capture the calls and redirect them to another server, by using URL filters.
for the React Native, there is library to open Hyperlinks in App. https://www.npmjs.com/package/react-native-hyperlink
In addition to this, i suppose you will need to check url and best approach is Regex. https://www.npmjs.com/package/url-regex
For me, simply adding the current directory worked.
Using the following structure:
+-- myproject
+-- a.py
+-- b.py
a.py:
from b import some_object
# returns ModuleNotFound error
from myproject.b import some_object
# works
To install Docker for Mac with homebrew:
brew cask install docker
To install the command line completion:
brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion
I wrote a post on how to mitigate the problem of calling a constructor without the new keyword.
It's mostly didactic, but it shows how you can create constructors that work with or without new
and doesn't require you to add boilerplate code to test this
in every constructor.
http://js-bits.blogspot.com/2010/08/constructors-without-using-new.html
Here's the gist of the technique:
/**
* Wraps the passed in constructor so it works with
* or without the new keyword
* @param {Function} realCtor The constructor function.
* Note that this is going to be wrapped
* and should not be used directly
*/
function ctor(realCtor){
// This is going to be the actual constructor
return function wrapperCtor(){
var obj; // object that will be created
if (this instanceof wrapperCtor) {
// Called with new
obj = this;
} else {
// Called without new. Create an empty object of the
// correct type without running that constructor
surrogateCtor.prototype = wrapperCtor.prototype;
obj = new surrogateCtor();
}
// Call the real constructor function
realCtor.apply(obj, arguments);
return obj;
}
function surrogateCtor() {}
}
Here's how to use it:
// Create our point constructor
Point = ctor(function(x,y){
this.x = x;
this.y = y;
});
// This is good
var pt = new Point(20,30);
// This is OK also
var pt2 = Point(20,30);
Developer Tools > Elements > Computed > Rendered Fonts
The picture you attached to your question shows the Style
tab. If you change to the next tab, Computed
, you can check the Rendered Fonts, that shows the actual font-family rendered.
All of the other answers were either deprecated or didn't work for HttpClient 4.3.
Here is a way to allow all hostnames when building an http client.
CloseableHttpClient httpClient = HttpClients
.custom()
.setHostnameVerifier(new AllowAllHostnameVerifier())
.build();
Or if you are using version 4.4 or later, the updated call looks like this:
CloseableHttpClient httpClient = HttpClients
.custom()
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
One simple way is to append your list items in a StringBuilder
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
StringBuilder b = new StringBuilder();
list.forEach(b::append);
System.out.println(b);
you can also try:
String s = list.stream().map(e -> e.toString()).reduce("", String::concat);
Explanation: map converts Integer stream to String stream, then its reduced as concatenation of all the elements.
Note: This is normal reduction
which performs in O(n2)
for better performance use a StringBuilder
or mutable reduction
similar to F. Böller's answer.
String s = list.stream().map(Object::toString).collect(Collectors.joining(","));
Ref: Stream Reduction
Technically, putting null or 0, or just some random value there works (since you are not using the return value). However, why are you using this construct instead of the if
construct? It is less obvious what you are trying to do when you write code this way, as you may confuse people with the no-op (null in your case).
Try something like :
SELECT
CAST (AVG(val) AS DECIMAL(10,4))
FROM
(
SELECT
val,
ROW_NUMBER() OVER( ORDER BY val ) -1 AS rn,
COUNT(1) OVER () -1 AS cnt
FROM STATION
) as tmp
WHERE rn IN (FLOOR(cnt/2),CEILING (cnt/2))
**
Note : The reason for -1 is to make it zero indexed..i.e row number now starts from 0 instead of 1
**
If you use NetBeans IDE right click form then
Properties ->Code -> check out Generate Center
In my case (ASP.NET MVC 4 application), the Global.asax
file was missing. It was appearing in Solution explorer with an exclamation mark. I replaced it and the error went away.
This should give you the roles, users and permissions granted on a directory:
SELECT *
FROM all_tab_privs
WHERE table_name = 'your_directory'; --> needs to be upper case
And yes, it IS in the all_TAB_privs view ;-) A better name for that view would be something like "ALL_OBJECT_PRIVS", since it also includes PL/SQL objects and their execute permissions as well.
It's easy
// MARK: - Gradient
extension CAGradientLayer {
enum Point {
case topLeft
case centerLeft
case bottomLeft
case topCenter
case center
case bottomCenter
case topRight
case centerRight
case bottomRight
var point: CGPoint {
switch self {
case .topLeft:
return CGPoint(x: 0, y: 0)
case .centerLeft:
return CGPoint(x: 0, y: 0.5)
case .bottomLeft:
return CGPoint(x: 0, y: 1.0)
case .topCenter:
return CGPoint(x: 0.5, y: 0)
case .center:
return CGPoint(x: 0.5, y: 0.5)
case .bottomCenter:
return CGPoint(x: 0.5, y: 1.0)
case .topRight:
return CGPoint(x: 1.0, y: 0.0)
case .centerRight:
return CGPoint(x: 1.0, y: 0.5)
case .bottomRight:
return CGPoint(x: 1.0, y: 1.0)
}
}
}
convenience init(start: Point, end: Point, colors: [CGColor], type: CAGradientLayerType) {
self.init()
self.startPoint = start.point
self.endPoint = end.point
self.colors = colors
self.locations = (0..<colors.count).map(NSNumber.init)
self.type = type
}
}
Use like this:-
let fistColor = UIColor.white
let lastColor = UIColor.black
let gradient = CAGradientLayer(start: .topLeft, end: .topRight, colors: [fistColor.cgColor, lastColor.cgColor], type: .radial)
gradient.frame = yourView.bounds
yourView.layer.addSublayer(gradient)
My understanding from my testing (and the PostgreSQL dox) is that the quotes need to be done differently from the other answers, and should also include "day" like this:
SELECT Table.date
FROM Table
WHERE date > current_date - interval '10 day';
Demonstrated here (you should be able to run this on any Postgres db):
SELECT DISTINCT current_date,
current_date - interval '10' day,
current_date - interval '10 days'
FROM pg_language;
Result:
2013-03-01 2013-03-01 00:00:00 2013-02-19 00:00:00
In one line, using a lambda
:
timestamps.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)
Passing a function to list.sort
:
def foo(x):
return time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6]
timestamps.sort(key=foo, reverse=True)
Yes basically this is what virtualenv do , and this is what the activate
command is for, from the doc here:
activate script
In a newly created virtualenv there will be a bin/activate shell script, or a Scripts/activate.bat batch file on Windows.
This will change your $PATH to point to the virtualenv bin/ directory. Unlike workingenv, this is all it does; it's a convenience. But if you use the complete path like /path/to/env/bin/python script.py you do not need to activate the environment first. You have to use source because it changes the environment in-place. After activating an environment you can use the function deactivate to undo the changes.
The activate script will also modify your shell prompt to indicate which environment is currently active.
so you should just use activate
command which will do all that for you:
> \path\to\env\bin\activate.bat
For Access 2010 - multiple steps required; I followed the same pattern as posted above, but thought I could help someone in Access. Worked great for me, I didn't have to keep a seeded table of dates.
Create a table called DUAL (similar to how the Oracle DUAL table works)
Create a query named "ZeroThru9Q"; manually enter the following syntax:
SELECT 0 AS a
FROM dual
UNION ALL
SELECT 1
FROM dual
UNION ALL
SELECT 2
FROM dual
UNION ALL
SELECT 3
FROM dual
UNION ALL
SELECT 4
FROM dual
UNION ALL
SELECT 5
FROM dual
UNION ALL
SELECT 6
FROM dual
UNION ALL
SELECT 7
FROM dual
UNION ALL
SELECT 8
FROM dual
UNION ALL
SELECT 9
FROM dual;
Create a query named "TodayMinus1KQ" (for dates before today); manually enter the following syntax:
SELECT date() - (a.a + (10 * b.a) + (100 * c.a)) AS MyDate
FROM
(SELECT *
FROM ZeroThru9Q) AS a,
(SELECT *
FROM ZeroThru9Q) AS b,
(SELECT *
FROM ZeroThru9Q) AS c
Create a query named "TodayPlus1KQ" (for dates after today); manually enter the following syntax:
SELECT date() + (a.a + (10 * b.a) + (100 * c.a)) AS MyDate
FROM
(SELECT *
FROM ZeroThru9Q) AS a,
(SELECT *
FROM ZeroThru9Q) AS b,
(SELECT *
FROM ZeroThru9Q) AS c;
Create a union query named "TodayPlusMinus1KQ" (for dates +/- 1000 days):
SELECT MyDate
FROM TodayMinus1KQ
UNION
SELECT MyDate
FROM TodayPlus1KQ;
Now you can use the query:
SELECT MyDate
FROM TodayPlusMinus1KQ
WHERE MyDate BETWEEN #05/01/2014# and #05/30/2014#
Swift 3 / Swift 4 solution that also works with NIBs/XIB files in iOS 10+:
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = []
}
The best way to use is white-space: nowrap;
This will align the text to one line.
I prefer ^[-+]?([1-9]\d*|0)$
because ^[-+]?[0-9]+$
allows the string starting with 0
.
RE_INT = re.compile(r'^[-+]?([1-9]\d*|0)$')
class TestRE(unittest.TestCase):
def test_int(self):
self.assertFalse(RE_INT.match('+'))
self.assertFalse(RE_INT.match('-'))
self.assertTrue(RE_INT.match('1'))
self.assertTrue(RE_INT.match('+1'))
self.assertTrue(RE_INT.match('-1'))
self.assertTrue(RE_INT.match('0'))
self.assertTrue(RE_INT.match('+0'))
self.assertTrue(RE_INT.match('-0'))
self.assertTrue(RE_INT.match('11'))
self.assertFalse(RE_INT.match('00'))
self.assertFalse(RE_INT.match('01'))
self.assertTrue(RE_INT.match('+11'))
self.assertFalse(RE_INT.match('+00'))
self.assertFalse(RE_INT.match('+01'))
self.assertTrue(RE_INT.match('-11'))
self.assertFalse(RE_INT.match('-00'))
self.assertFalse(RE_INT.match('-01'))
self.assertTrue(RE_INT.match('1234567890'))
self.assertTrue(RE_INT.match('+1234567890'))
self.assertTrue(RE_INT.match('-1234567890'))
This is pretty much an exact copy of the top answer, but instead of a link, it's just the part of the code that matters, translated to be IMO more readable and easier to understand. A few other small changes include using cloneNode(), and not putting html into a js string. Small stuff, but you can copy and paste this as is and it will work.
The way it works is by making two invisible divs fill the element you're watching, and then putting a trigger in each, and setting a scroll position that will lead to triggering a scroll change if the size changes.
All real credit goes to Marc J, but if you're just looking for the relevant code, here it is:
window.El = {}
El.resizeSensorNode = undefined;
El.initResizeNode = function() {
var fillParent = "display: block; position: absolute; left: 0; top: 0; right: 0; bottom: 0; overflow: hidden; z-index: -1; visibility: hidden;";
var triggerStyle = "position: absolute; left: 0; top: 0; transition: 0s;";
var resizeSensor = El.resizeSensorNode = document.createElement("resizeSensor");
resizeSensor.style = fillParent;
var expandSensor = document.createElement("div");
expandSensor.style = fillParent;
resizeSensor.appendChild(expandSensor);
var trigger = document.createElement("div");
trigger.style = triggerStyle;
expandSensor.appendChild(trigger);
var shrinkSensor = expandSensor.cloneNode(true);
shrinkSensor.firstChild.style = triggerStyle + " width: 200%; height: 200%";
resizeSensor.appendChild(shrinkSensor);
}
El.onSizeChange = function(domNode, fn) {
if (!domNode) return;
if (domNode.resizeListeners) {
domNode.resizeListeners.push(fn);
return;
}
domNode.resizeListeners = [];
domNode.resizeListeners.push(fn);
if(El.resizeSensorNode == undefined)
El.initResizeNode();
domNode.resizeSensor = El.resizeSensorNode.cloneNode(true);
domNode.appendChild(domNode.resizeSensor);
var expand = domNode.resizeSensor.firstChild;
var expandTrigger = expand.firstChild;
var shrink = domNode.resizeSensor.childNodes[1];
var reset = function() {
expandTrigger.style.width = '100000px';
expandTrigger.style.height = '100000px';
expand.scrollLeft = 100000;
expand.scrollTop = 100000;
shrink.scrollLeft = 100000;
shrink.scrollTop = 100000;
};
reset();
var hasChanged, frameRequest, newWidth, newHeight;
var lastWidth = domNode.offsetWidth;
var lastHeight = domNode.offsetHeight;
var onResized = function() {
frameRequest = undefined;
if (!hasChanged) return;
lastWidth = newWidth;
lastHeight = newHeight;
var listeners = domNode.resizeListeners;
for(var i = 0; listeners && i < listeners.length; i++)
listeners[i]();
};
var onScroll = function() {
newWidth = domNode.offsetWidth;
newHeight = domNode.offsetHeight;
hasChanged = newWidth != lastWidth || newHeight != lastHeight;
if (hasChanged && !frameRequest) {
frameRequest = requestAnimationFrame(onResized);
}
reset();
};
expand.addEventListener("scroll", onScroll);
shrink.addEventListener("scroll", onScroll);
}
Lots of others have already advised you to rethink your code to make it more testable - good advice and usually simpler than what I'm about to suggest.
If you can't change the code to make it more testable, PowerMock: https://code.google.com/p/powermock/
PowerMock extends Mockito (so you don't have to learn a new mock framework), providing additional functionality. This includes the ability to have a constructor return a mock. Powerful, but a little complicated - so use it judiciously.
You use a different Mock runner. And you need to prepare the class that is going to invoke the constructor. (Note that this is a common gotcha - prepare the class that calls the constructor, not the constructed class)
@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class})
Then in your test set-up, you can use the whenNew method to have the constructor return a mock
whenNew(Second.class).withAnyArguments().thenReturn(mock(Second.class));
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript">
function omtCallFromAjax(urlVariable)
{
alert("omt:"+urlVariable);
$("#omtDiv").load("omtt.php?"+urlVariable);
}
</script>
try this it work for me
import javax.swing.*;
class Demo extends JFrame
{
String str1;
Demo(String s1)
{
str1=s1;
JOptionPane.showMessageDialog(null,"your message : "+str1);
}
public static void main (String ar[])
{
new Demo("Java");
}
}
select *
from {Table_Name}
where {x_column_name}=(
select d.{x_column_name}
from (
select rownum as rno,{x_column_name}
from {Table_Name})d
where d.rno=(
select count(*)
from {Table_Name}));
Here is the working code for the same.. its a recursion on each step checking possibility of each combinations on occurrence of same digit in a series....I am not sure if there is any better solution then this from complexity point of view.....
Please let me know for any issues....
import java.util.ArrayList;
public class phonenumbers {
/**
* @param args
*/
public static String mappings[][] = {
{"0"}, {"1"}, {"A", "B", "C"}, {"D", "E", "F"}, {"G", "H", "I"},
{"J", "K", "L"}, {"M", "N", "O"}, {"P", "Q", "R", "S"},
{"T", "U", "V"}, {"W", "X", "Y", "Z"}
};
public static void main(String[] args) {
// TODO Auto-generated method stub
String phone = "3333456789";
ArrayList<String> list= generateAllnums(phone,"",0);
}
private static ArrayList<String> generateAllnums(String phone,String sofar,int j) {
// TODO Auto-generated method stub
//System.out.println(phone);
if(phone.isEmpty()){
System.out.println(sofar);
for(int k1=0;k1<sofar.length();k1++){
int m=sofar.toLowerCase().charAt(k1)-48;
if(m==-16)
continue;
int i=k1;
while(true && i<sofar.length()-2){
if(sofar.charAt(i+1)==' ')
break;
else if(sofar.charAt(i+1)==sofar.charAt(k1)){
i++;
}else{
break;
}
}
i=i-k1;
//System.out.print(" " + m +", " + i + " ");
System.out.print(mappings[m][i%3]);
k1=k1+i;
}
System.out.println();
return null;
}
int num= phone.charAt(j);
int k=0;
for(int i=j+1;i<phone.length();i++){
if(phone.charAt(i)==num){
k++;
}
}
if(k!=0){
int p=0;
ArrayList<String> list2= generateAllnums(phone.substring(p+1), sofar+phone.charAt(p)+ " ", 0);
ArrayList<String> list3= generateAllnums(phone.substring(p+1), sofar+phone.charAt(p), 0);
}
else{
ArrayList<String> list1= generateAllnums(phone.substring(1), sofar+phone.charAt(0), 0);
}
return null;
}
}
Just a note:
You are facing the problem of your non-latin characters is showing as ?????????
, you asked a question, and it got closed with a reference to this canonical question, you tried everything and no matter what you do you still get ??????????
from MySQL
.
That is mostly because you are testing on your old data which has been inserted to the database using the wrong charset and got converted and stored to actually the question mark characters ?
. Which means you lost your original text forever and no matter what you try you will get ???????
.
re applying what you have learned from the answers of this question on a fresh data could solve your problem.
@Martijn your order of function calls is slightly off. Try this instead:
x=-3:0.1:3;
y = x.^3;
plot(x,y), hold on
plot([-3 3], [0 0], 'k:')
hold off
Use @Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});
[Mac only]
If you need to delete your authentication, use
git credential-osxkeychain erase
host=github.com
protocol=https
on Mac.
See https://help.github.com/articles/updating-credentials-from-the-osx-keychain/
PRINT_SUM PROC NEAR
CMP AL, 0
JNE PRINT_AX
PUSH AX
MOV AL, '0'
MOV AH, 0EH
INT 10H
POP AX
RET
PRINT_AX:
PUSHA
MOV AH, 0
CMP AX, 0
JE PN_DONE
MOV DL, 10
DIV DL
CALL PRINT_AX
MOV AL, AH
ADD AL, 30H
MOV AH, 0EH
INT 10H
PN_DONE:
POPA
RET
PRINT_SUM ENDP
In native Hibernate XML mappings, you can accomplish this by declaring a one-to-one mapping with the constrained attribute set to true. I am not sure what the Hibernate/JPA annotation equivalent of that is, and a quick search of the doc provided no answer, but hopefully that gives you a lead to go on.