This occurs when you specify the different name for repository table name and database table name. Please check your table name with database and repository.
You can use Apache Commons Math:
Precision.round(double x, int scale)
To DELETE, without changing the references, you should first delete or otherwise alter (in a manner suitable for your purposes) all relevant rows in other tables.
To TRUNCATE you must remove the references. TRUNCATE is a DDL statement (comparable to CREATE and DROP) not a DML statement (like INSERT and DELETE) and doesn't cause triggers, whether explicit or those associated with references and other constraints, to be fired. Because of this, the database could be put into an inconsistent state if TRUNCATE was allowed on tables with references. This was a rule when TRUNCATE was an extension to the standard used by some systems, and is mandated by the the standard, now that it has been added.
To determine if there are any results you can do any of the following:
if ($mentor->first()) { }
if (!$mentor->isEmpty()) { }
if ($mentor->count()) { }
if (count($mentor)) { }
if ($mentor->isNotEmpty()) { }
Notes / References
->first()
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_first
isEmpty()
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_isEmpty
->count()
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count
count($mentors)
works because the Collection implements Countable and an internal count() method:
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count
isNotEmpty()
https://laravel.com/docs/5.7/collections#method-isnotempty
So what you can do is :
if (!$mentors->intern->employee->isEmpty()) { }
You can't return because you're not in a function. You can exit
though.
import sys
sys.exit(0)
0 (the default) means success, non-zero means failure.
Try overriding and returning true from either onInterceptTouchEvent() and/or onTouchEvent(), which will consume touch events on the pager.
From the jQuery page about .hide():
"The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline."
So if it's important that you're able to revert to the previous value of display
, you'd better use hide()
because that way the previous state is remembered. Apart from that there's no difference.
$(function() {_x000D_
$('.hide').click(function(){_x000D_
$('.toggle').hide();_x000D_
setDisplayValue();_x000D_
});_x000D_
$('.show').click(function(){_x000D_
$('.toggle').show();_x000D_
setDisplayValue();_x000D_
});_x000D_
});_x000D_
_x000D_
function setDisplayValue() {_x000D_
var display = $('.toggle')[0].style.display;_x000D_
$('.displayvalue').text(display);_x000D_
}
_x000D_
div {_x000D_
display: table-cell;_x000D_
border: 1px solid;_x000D_
padding: 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p>_x000D_
<button class="hide">Hide</button>_x000D_
<button class="show">Show</button>_x000D_
</p>_x000D_
_x000D_
<div class="toggle">Lorem Ipsum</div>_x000D_
_x000D_
<p>_x000D_
The display value of the div is:_x000D_
<span class="displayvalue"></span>_x000D_
</p>
_x000D_
In terms of the XML format for log4net, you need not worry about ex.ToString() for the logs. Simply pass the exception object itself and log4net does the rest do give you all of the details in its pre-configured XML format. The only thing I run into on occasion is new line formatting, but that's when I'm reading the files raw. Otherwise parsing the XML works great.
Be careful when checking directory only with option -d !
if variable $1 is empty the check will still be successfull. To be sure, check also that the variable is not empty.
#! /bin/bash
is_directory(){
if [[ -d $1 ]] && [[ -n $1 ]] ; then
return 0
else
return 1
fi
}
#Test
if is_directory $1 ; then
echo "Directory exist"
else
echo "Directory does not exist!"
fi
If the properties are for XML or HTML, it's safest to use XML entities. They're uglier to read, but it means that the properties file can be treated as straight ASCII, so nothing will get mangled.
Note that HTML has entities that XML doesn't, so I keep it safe by using straight XML: http://www.w3.org/TR/html4/sgml/entities.html
preventDefault
is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:
if (typeof Event.prototype.preventDefault === 'undefined') {
Event.prototype.preventDefault = function (e, callback) {
this.returnValue = false;
};
}
This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault
with no problem.
Another option which may be easier to remember would be to place marks on the two lines with ma and mb, then run :'a,'byank
.
Many different ways to accomplish this task, just offering another.
I did test your code and the only problem I could see was the lack of permission given to the directory you try to write the file in to.
Give "write" permission to the directory you need to put the file. In your case it is the current directory.
Use "chmod" in linux.
Add "Everyone" with "write" enabled to the security tab of the directory if you are in Windows.
See here: http://docs.python.org/using/windows.html
pythonw.exe "This suppresses the terminal window on startup."
Just to add,
if you're using many of them then you can import all using
import 'rxjs/Rx';
as mentioned by @Thierry Templier. But I think If you are using limited operator then you should import individual operator like
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/observable/of';
as mentioned by @uksz.
Because 'rxjs/Rx' will import all the Rx components which definitely cost performance.
As the other answer correctly notes, you cannot use dynamic functions as a default value. You could use TIMESTAMP
with the CURRENT_TIMESTAMP
attribute, but this is not always possible, for example if you want to keep both a creation and updated timestamp, and you'd need the only allowed TIMESTAMP
column for the second.
In this case, use a trigger instead.
One of the ways to use git diff is:
git diff <commit> <path>
And a common way to refer one commit of the last commit is as a relative path to the actual HEAD. You can reference previous commits as HEAD^ (in your example this will be 123abc) or HEAD^^ (456def in your example), etc ...
So the answer to your question is:
git diff HEAD^^ myfile
Some receivers expect EOL sequence, which is typically two characters \r\n
, so try in your code replace the line
unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};
with
unsigned char cmd[] = "INIT\r\n";
BTW, the above way is probably more efficient. There is no need to quote every character.
I removed my .classpath
file in my project directory to correct this issue. No need to remove the Maven Nature from the project in Eclipse.
The specific error I was getting was: Project 'my-project-name' is missing required Java project: 'org.some.package-9.3.0 But my project wasn't dependent on org.some.package
in any way.
Perhaps an old version of the project relied on it and Maven wasn't properly updating the .classpath
file.
You have to use now the new XLSX-Driver from Access-Redist (32/64-Bit). The current XLS-Driver are corrupted since last cumulative update.
try this one http://code.google.com/p/geckofx/ hope it ain't dupe or this one i think is better http://webkitdotnet.sourceforge.net/
TRY THIS
IF EXISTS
(
SELECT name FROM master.dbo.sysdatabases
WHERE name = N'New_Database'
)
BEGIN
SELECT 'Database Name already Exist' AS Message
END
ELSE
BEGIN
CREATE DATABASE [New_Database]
SELECT 'New Database is Created'
END
Say suppose, you have
File f = new File("SomeFile");
f.length();
You need not close the File
s, because its just the representation of a path.
You should always consider to close only reader/writers and in fact streams.
In addition to Boaz's answer ....
@UniqueConstraint
allows you to name the constraint, while @Column(unique = true)
generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq
).
Sometimes it can be helpful to know what table a constraint is associated with. E.g.:
@Table(
name = "product_serial_group_mask",
uniqueConstraints = {
@UniqueConstraint(
columnNames = {"mask", "group"},
name="uk_product_serial_group_mask"
)
}
)
Echoing above on not messing with OS X install. Have been faced with a couple of reinstalls thinking I could beat the system. The 3.1 install Scott Griffiths offers above works fine with Yosemite, for any Beta testers out there.. Yosemite has Python 2.7.6 as part of OS install, and typing "python3.1" from terminal launches Python 3.1. Same for Python 3.4 (install here).
Actually you can use a varchar for a telephone number. You do not need an int because you are not going to perform arithmetic on the numbers.
we had similar header issue with Amazon (AWS) S3 presigned Post failing on some browsers.
point was to tell bucket CORS to expose header <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>
more details in this answer: https://stackoverflow.com/a/37465080/473040
Think I figured out how to do it:
- (void)drawRect:(NSRect)dirtyRect {
// Fill in background Color
CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
CGContextSetRGBFillColor(context, 0.227,0.251,0.337,0.8);
CGContextFillRect(context, NSRectToCGRect(dirtyRect));
}
First, post a message in a chat where your bot is included (channel, group mentioning the bot, or one-to-one chat). Then, just run:
curl https://api.telegram.org/bot<TOKEN>/getUpdates | jq
Feel free to remove the | jq
part if your dont have jq installed, it's only useful for pretty printing. You should get something like this:
You can see the chat ID in the returned json object, together with the chat name and associated message.
thead {
position: fixed;
height: 10px; /* This is whatever height you want */
}
tbody {
position: fixed;
margin-top: 10px; /* This has to match the height of thead */
height: 300px; /* This is whatever height you want */
}
I have gone through all the posts above but I am convinced that the implementation of the Tournament algorithm is the best approach. Let us consider the following algorithm posted by @Gumbo
largest := numbers[0];
secondLargest := null
for i=1 to numbers.length-1 do
number := numbers[i];
if number > largest then
secondLargest := largest;
largest := number;
else
if number > secondLargest then
secondLargest := number;
end;
end;
end;
It is very good in case we are going to find the second largest number in an array. It has (2n-1) number of comparisons. But what if you want to calculate the third largest number or some kth largest number. The above algorithm doesn't work. You got to another procedure.
So, I believe tournament algorithm approach is the best and here is the link for that.
DLL is a File Extension & Known As “dynamic link library” file format used for holding multiple codes and procedures for Windows programs. Software & Games runs on the bases of DLL Files; DLL files was created so that multiple applications could use their information at the same time.
IF you want to get more information about DLL Files or facing any error read the following post. https://www.bouncegeek.com/fix-dll-errors-windows-586985/
It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send
in your each REST block...
So you can do something like this as a simple next()
example:
app.get("/", (req, res, next) => {
console.log("req:", req, "res:", res);
res.send(["data": "whatever"]);
next();
},(req, res) =>
console.log("it's all done!");
);
It's also very useful when you'd like to have a middleware in your app...
To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).
var express = require('express');
var app = express();
var myLogger = function (req, res, next) {
console.log('LOGGED');
next();
}
app.use(myLogger);
app.get('/', function (req, res) {
res.send('Hello World!');
})
app.listen(3000);
This also works:
^([1-9]|[0-1][0-2])$
[1-9]
matches single digits between 1 and 9
[0-1][0-2]
matches double digits between 10 and 12
There are some good examples here
To switch to C99 mode in CodeBlocks, follow the next steps:
Click Project/Build options, then in tab Compiler Settings choose subtab Other options, and place -std=c99
in the text area, and click Ok.
This will turn C99 mode on for your Compiler.
I hope this will help someone!
If you're using Apache just add:
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>
in your configuration. This will cause all responses from your webserver to be accessible from any other site on the internet. If you intend to only allow services on your host to be used by a specific server you can replace the *
with the URL of the originating server:
Header set Access-Control-Allow-Origin: http://my.origin.host
too many ) parenthesis remove one of them.
Casting never needs a new
:
Collection<T> collection = myList;
You don't even make the cast explicit, because Collection
is a super-type of List
, so it will work just like this.
307 came about because user agents adopted as a de facto behaviour to take POST requests that receive a 302 response and send a GET request to the Location response header.
That is the incorrect behaviour — only a 303 should cause a POST to turn into a GET. User agents should (but don't) stick with the POST method when requesting the new URL if the original POST request returned a 302.
307 was introduced to allow servers to make it clear to the user agent that a method change should not be made by the client when following the Location response header.
Following up on the answer and link from AlexMart, something like this works:
.controller('MyCtrl', function($scope) {
$scope.$on('$ionicView.enter', function() {
// Code you want executed every time view is opened
console.log('Opened!')
})
})
This might not be applicable to all scenarios, but I found that the position: sticky
(same thing with position: fixed
) only works on old iPhones when the scrolling container is not the body, but inside something else.
Example pseudo html:
body <- scrollbar
relative div
sticky div
The sticky div will be sticky on desktop browsers, but with certain devices, tested with: Chromium: dev tools: device emultation: iPhone 6/7/8, and with Android 4 Firefox, it will not.
What will work, however, is
body
div overflow=auto <- scrollbar
relative div
sticky div
The error you quote has nothing to do with pg_hba.conf
; it's failing to connect, not failing to authorize the connection.
Do what the error message says:
Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections
You haven't shown the command that produces the error. Assuming you're connecting on localhost
port 5432
(the defaults for a standard PostgreSQL install), then either:
PostgreSQL isn't running
PostgreSQL isn't listening for TCP/IP connections (listen_addresses
in postgresql.conf
)
PostgreSQL is only listening on IPv4 (0.0.0.0
or 127.0.0.1
) and you're connecting on IPv6 (::1
) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.
PostgreSQL is listening on a different port to the one you're connecting on
(unlikely) there's an iptables
rule blocking loopback connections
(If you are not connecting on localhost
, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).
So ... check those:
ps -f -u postgres
should list postgres
processes
sudo lsof -n -u postgres |grep LISTEN
or sudo netstat -ltnp | grep postgres
should show the TCP/IP addresses and ports PostgreSQL is listening on
BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:
$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 12345?
The best solution I've found in this is to create a lookup table with the possible values as a primary key, and create a foreign key to the lookup table.
The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".
If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.
Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.
Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.
So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.
A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.
The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.
In the default settings, VS Code uses the following fonts (14 pt) in descending order:
How to verify: VS Code runs in a browser. In the first version, you could hit F12 to open the Developer Tools. Inspecting the DOM, you can find a containing several s that make up that line of code. Inspecting one of those spans, you can see that font-family is just the list above.
If you intend to use it for realtime system, perhaps java isnt the best choice to get the timestamp. But if youre going to use if for unique key, then Jason Smith's answer will do enough. But just in case, to anticipate 2 item end up getting the same timestamp (its possible if those 2 were processed almost simultaneously), you can loop until the last timestamp not equals with the current timestamp.
String timestamp = new String();
do {
timestamp = String.valueOf(MicroTimestamp.INSTANCE.get());
item.setTimestamp(timestamp);
} while(lasttimestamp.equals(timestamp));
lasttimestamp = item.getTimestamp();
usually __iter__()
just return self if you have already define the next() method (generator object):
here is a Dummy example of a generator :
class Test(object):
def __init__(self, data):
self.data = data
def next(self):
if not self.data:
raise StopIteration
return self.data.pop()
def __iter__(self):
return self
but __iter__()
can also be used like this:
http://mail.python.org/pipermail/tutor/2006-January/044455.html
First, make sure you have libcurl
(see: http://curl.haxx.se) installed. Then make sure your copy of PHP has been compiled with the --with-curl[=DIR]
flag. For more info see:
If XAMPP comes pre-compiled with cURL you may just need to enable the extension in your php.ini file (usually by removing a semicolon at the start of the line which includes the extension).
In case you want to cast to a class and not just a string:
YourClass model = await request.Content.ReadAsAsync<YourClass>();
try background-position:center;
EDIT: since this question is getting lots of views, its worth adding some extra info:
text-align: center
will not work because the background image is not part of the document and is therefore not part of the flow.
background-position:center
is shorthand for background-position: center center
; (background-position: horizontal vertical
);
This will take care of names like "Firstname Z. Lastname" and "First Z Last"
SELECT
CASE
WHEN CHARINDEX(' ',name) = 0 THEN name
WHEN CHARINDEX(' ',name) = PATINDEX('% _[., ]%',name) THEN RTRIM(SUBSTRING(name, 1, CHARINDEX(' ',name) + 2))
ELSE SUBSTRING(name,1, CHARINDEX(' ',name))
END [firstname]
,CASE
WHEN CHARINDEX(' ',name) = 0 THEN ''
WHEN CHARINDEX(' ',name) = PATINDEX('% _[., ]%',name) THEN LTRIM(SUBSTRING(name, CHARINDEX(' ',name) + 3,1000))
ELSE SUBSTRING(name,CHARINDEX(' ',name)+1,1000)
END [lastname]
FROM [myTable]
I found that when I made my binding more specific, it began to work on iOS. I had:
$(document).on('click tap', 'span.clickable', function(e){ ... });
When I changed it to:
$("div.content").on('click tap', 'span.clickable', function(e){ ... });
iOS began responding.
You're not parsing a string, you're parsing an already-parsed object :)
var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
// ^ ^
// if you want to parse, the input should be a string
var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.
Try to use document.createEvent
described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent
The code for function that simulates click should look something like this:
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var a = document.getElementById("gift-close");
a.dispatchEvent(evt);
}
after generating XML you can just Replace your XML <Marks>... content here </Marks>
tags with <SubjectMarks>... content here </SubjectMarks>tag
. and pass updated XML to your DB.
Edit: I here explain complete process here.
Your XML Generate Like as below.
<NewDataSet>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>80</Marks>
</StudentMarks>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>79</Marks>
</StudentMarks>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>88</Marks>
</StudentMarks>
</NewDataSet>
Here you can assign XML to string variable like as
string strXML = DataSet.GetXML();
strXML = strXML.Replace ("<Marks>","<SubjectMarks>");
strXML = strXML.Replace ("<Marks/>","<SubjectMarks/>");
and now pass strXML To your DB. Hope it will help for you.
adding express.urlencoded({ extended: true })
to the route solves the problem.
router.post('/save',express.urlencoded({ extended: true }), "your route");
Try this:
<div id="div"></div>
<script language="javascript" type="text/javascript">
var div = document.getElementById('div');
for (var i = 0; i < 10; i++) {
var f = function() {
var link = document.createElement('a');
var j = i; // this j is scoped to our anonymous function
// while i is scoped outside the anonymous function,
// getting incremented by the for loop
link.setAttribute('href', '#');
link.innerHTML = j + '';
link.onclick= function() { onClickLink(j+'');};
div.appendChild(link);
div.appendChild(document.createElement('br')); // lower case BR, please!
}(); // call the function immediately
}
function onClickLink(text) {
alert('Link ' + text + ' clicked');
return false;
}
</script>
As numpy.convolve is pretty slow, those who need a fast performing solution might prefer an easier to understand cumsum approach. Here is the code:
cumsum_vec = numpy.cumsum(numpy.insert(data, 0, 0))
ma_vec = (cumsum_vec[window_width:] - cumsum_vec[:-window_width]) / window_width
where data contains your data, and ma_vec will contain moving averages of window_width length.
On average, cumsum is about 30-40 times faster than convolve.
This is my working example of our simple Vue component.
<template functional>
<div v-html="require('!!html-loader!./../svg/logo.svg')"></div>
</template>
Load fs
:
const fs = require('fs');
Read files async:
fs.readdir('./dir', function (err, files) {
// "files" is an Array with files names
});
Read files sync:
var files = fs.readdirSync('./dir');
Elements that are floated are taken out of the normal flow layout, and block elements, such as DIV's, no longer span the width of their parent. The rules change in this situation. Instead of reinventing the wheel, check out this site for some possible solutions to create the two column layout you are after: http://www.maxdesign.com.au/presentation/page_layouts/
Specifically, the "Liquid Two-Column layout".
Cheers!
The better practice is to use for-each
. Besides violating the Keep It Simple, Stupid principle, the new-fangled forEach()
has at least the following deficiencies:
Object prev = null; for(Object curr : list) { if( prev != null ) foo(prev, curr); prev = curr; }
Can't handle checked exceptions. Lambdas aren't actually forbidden from throwing checked exceptions, but common functional interfaces like Consumer
don't declare any. Therefore, any code that throws checked exceptions must wrap them in try-catch
or Throwables.propagate()
. But even if you do that, it's not always clear what happens to the thrown exception. It could get swallowed somewhere in the guts of forEach()
Limited flow-control. A return
in a lambda equals a continue
in a for-each, but there is no equivalent to a break
. It's also difficult to do things like return values, short circuit, or set flags (which would have alleviated things a bit, if it wasn't a violation of the no non-final variables rule). "This is not just an optimization, but critical when you consider that some sequences (like reading the lines in a file) may have side-effects, or you may have an infinite sequence."
Might execute in parallel, which is a horrible, horrible thing for all but the 0.1% of your code that needs to be optimized. Any parallel code has to be thought through (even if it doesn't use locks, volatiles, and other particularly nasty aspects of traditional multi-threaded execution). Any bug will be tough to find.
Might hurt performance, because the JIT can't optimize forEach()+lambda to the same extent as plain loops, especially now that lambdas are new. By "optimization" I do not mean the overhead of calling lambdas (which is small), but to the sophisticated analysis and transformation that the modern JIT compiler performs on running code.
If you do need parallelism, it is probably much faster and not much more difficult to use an ExecutorService. Streams are both automagical (read: don't know much about your problem) and use a specialized (read: inefficient for the general case) parallelization strategy (fork-join recursive decomposition).
Makes debugging more confusing, because of the nested call hierarchy and, god forbid, parallel execution. The debugger may have issues displaying variables from the surrounding code, and things like step-through may not work as expected.
Streams in general are more difficult to code, read, and debug. Actually, this is true of complex "fluent" APIs in general. The combination of complex single statements, heavy use of generics, and lack of intermediate variables conspire to produce confusing error messages and frustrate debugging. Instead of "this method doesn't have an overload for type X" you get an error message closer to "somewhere you messed up the types, but we don't know where or how." Similarly, you can't step through and examine things in a debugger as easily as when the code is broken into multiple statements, and intermediate values are saved to variables. Finally, reading the code and understanding the types and behavior at each stage of execution may be non-trivial.
Sticks out like a sore thumb. The Java language already has the for-each statement. Why replace it with a function call? Why encourage hiding side-effects somewhere in expressions? Why encourage unwieldy one-liners? Mixing regular for-each and new forEach willy-nilly is bad style. Code should speak in idioms (patterns that are quick to comprehend due to their repetition), and the fewer idioms are used the clearer the code is and less time is spent deciding which idiom to use (a big time-drain for perfectionists like myself!).
As you can see, I'm not a big fan of the forEach() except in cases when it makes sense.
Particularly offensive to me is the fact that Stream
does not implement Iterable
(despite actually having method iterator
) and cannot be used in a for-each, only with a forEach(). I recommend casting Streams into Iterables with (Iterable<T>)stream::iterator
. A better alternative is to use StreamEx which fixes a number of Stream API problems, including implementing Iterable
.
That said, forEach()
is useful for the following:
Atomically iterating over a synchronized list. Prior to this, a list generated with Collections.synchronizedList()
was atomic with respect to things like get or set, but was not thread-safe when iterating.
Parallel execution (using an appropriate parallel stream). This saves you a few lines of code vs using an ExecutorService, if your problem matches the performance assumptions built into Streams and Spliterators.
Specific containers which, like the synchronized list, benefit from being in control of iteration (although this is largely theoretical unless people can bring up more examples)
Calling a single function more cleanly by using forEach()
and a method reference argument (ie, list.forEach (obj::someMethod)
). However, keep in mind the points on checked exceptions, more difficult debugging, and reducing the number of idioms you use when writing code.
Articles I used for reference:
EDIT: Looks like some of the original proposals for lambdas (such as http://www.javac.info/closures-v06a.html Google Cache) solved some of the issues I mentioned (while adding their own complications, of course).
Using the -X
flag with whatever HTTP verb you want:
curl -X PUT -d arg=val -d arg2=val2 localhost:8080
This example also uses the -d
flag to provide arguments with your PUT request.
I would think so. Why not? Wouldn't be much of a CDN w/o offering the CSS to support the script files
This link suggests that they are:
We find it particularly exciting that the jQuery UI CSS themes are now hosted on Google's Ajax Libraries CDN.
parent.abc() will only work on same domain due to security purposes. i tried this workaround and mine worked perfectly.
<head>
<script>
function abc() {
alert("sss");
}
// window of the iframe
var innerWindow = document.getElementById('myFrame').contentWindow;
innerWindow.abc= abc;
</script>
</head>
<body>
<iframe id="myFrame">
<a onclick="abc();" href="#">Click Me</a>
</iframe>
</body>
Hope this helps. :)
There are few modes to open file (read, write etc..)
If you want to read from file you should type file = open("File.txt","r")
, if write than file = open("File.txt","w")
. You need to give the right permission regarding your usage.
more modes:
In bootstrap 4 use:
<ul class="nav navbar-nav ml-auto">
This will push the navbar to the right. Use mr-auto to push it to the left, this is the default behaviour.
Never mind, it's req.session.destroy();
I was able to get it working without putting in the username and password:
conda config --set proxy_servers.https https://address:port
Apart from standard Heap parameters -Xms
and -Xmx
it's also good to know -XX:PermSize
and -XX:MaxPermSize
, which is used to specify size of Perm Gen space because even though you could have space in other generation in heap you can run out of memory if your perm gen space gets full. This link also has nice overview of some important JVM parameters.
Ok I was running into the same issue. What I failed to notice is that I was using json_decode() instead of using json_encode() so for those who are going to come here please make sure you are using the right function, which is json_encode()
Note: Depends on what you are working on but make sure you are using the right function.
If you use the Anaconda python distribution, you can use the conda list
command to see what was installed by what method:
user@pc:~ $ conda list
# packages in environment at /anaconda3:
#
# Name Version Build Channel
_ipyw_jlab_nb_ext_conf 0.1.0 py36h2fc01ae_0
alabaster 0.7.10 py36h174008c_0
amqp 2.2.2 <pip>
anaconda 5.1.0 py36_2
anaconda-client 1.6.9 py36_0
To grab the entries installed by pip
(including possibly pip
itself):
user@pc:~ $ conda list | grep \<pip
amqp 2.2.2 <pip>
astroid 1.6.2 <pip>
billiard 3.5.0.3 <pip>
blinker 1.4 <pip>
ez-setup 0.9 <pip>
feedgenerator 1.9 <pip>
Of course you probably want to just select the first column, which you can do with (excluding pip
if needed):
user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}'
amqp
astroid
billiard
blinker
ez-setup
feedgenerator
Finally you can grab these values and pip uninstall all of them using the following:
user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}' | xargs pip uninstall -y
Note the use of the -y
flag for the pip uninstall
to avoid having to give confirmation to delete.
I put a getchar()
at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar
, getch
, or getc
I found this question when looking for a way to really read a local file instead of reading a file from the web server, which I'd rather call a "remote file".
Just call require
:
const content = require('../../path_of_your.json');
The Angular-CLI source code inspired me: I found out that they include component templates by replacing the templateUrl
property by template
and the value by a require
call to the actual HTML resource.
If you use the AOT compiler you have to add the node type definitons by adjusting tsconfig.app.json
:
"compilerOptions": {
"types": ["node"],
...
},
...
Since PHP 5.4.0 you can use getallheaders
function which returns all request headers as an associative array:
var_dump(getallheaders());
// array(8) {
// ["Accept"]=>
// string(63) "text/html[...]"
// ["Accept-Charset"]=>
// string(31) "ISSO-8859-1[...]"
// ["Accept-Encoding"]=>
// string(17) "gzip,deflate,sdch"
// ["Accept-Language"]=>
// string(14) "en-US,en;q=0.8"
// ["Cache-Control"]=>
// string(9) "max-age=0"
// ["Connection"]=>
// string(10) "keep-alive"
// ["Host"]=>
// string(9) "localhost"
// ["User-Agent"]=>
// string(108) "Mozilla/5.0 (Windows NT 6.1; WOW64) [...]"
// }
Earlier this function worked only when PHP was running as an Apache/NSAPI module.
time after 30 min, this easiest solution in php
date('Y-m-d H:i:s', strtotime("+30 minutes"));
for DateTime class (PHP 5 >= 5.2.0, PHP 7)
$dateobj = new DateTime();
$dateobj ->modify("+30 minutes");
select * from test;
a1 a2 a3
1 1 2
1 2 2
2 1 2
select t1.a3 from test t1, test t2 where t1.a1 = t2.a1 and t2.a2 = t1.a2 and t1.a1 = t2.a2
a3
1
You can try same thing using Joins too..
I'm sure there's a more efficient way to do it, but I would probably do this:
string getTenDigitNumber(string input)
{
StringBuilder sb = new StringBuilder();
for(int i - 0; i < input.Length; i++)
{
int junk;
if(int.TryParse(input[i], ref junk))
sb.Append(input[i]);
}
return sb.ToString();
}
Recent versions of Chrome cache very aggressively. Even cache-busting techniques such as "http://url?updated=datecode" stopped working. You must clear the cache or launch an incognito window every time (and make sure data-saver is off).
It is an old post, but I will try to update it with a new information.
To use custom events you need to bind it to some DOM element and to trigger it. So you need to use
.on() method takes an event type and an event handling function as arguments. Optionally, it can also receive event-related data as its second argument, pushing the event handling function to the third argument. Any data that is passed will be available to the event handling function in the data property of the event object. The event handling function always receives the event object as its first argument.
and
.trigger() method takes an event type as its argument. Optionally, it can also take an array of values. These values will be passed to the event handling function as arguments after the event object.
The code looks like this:
$(document).on("getMsg", {
msg: "Hello to everyone",
time: new Date()
}, function(e, param) {
console.log( e.data.msg );
console.log( e.data.time );
console.log( param );
});
$( document ).trigger("getMsg", [ "Hello guys"] );
Nice explanation can be found here and here. Why exactly this can be useful? I found how to use it in this excellent explanation from twitter engineer.
P.S. In plain javascript you can do this with new CustomEvent, but beware of IE and Safari problems.
Well, here's what worked for me. I tried every possible solution on StackOverflow that there was. I tried changing my source location in the debug menu, I installed the m2e Eclipse plugin, I changed from embedded Maven, and I installed the run-jetty-run and nothing worked. Now, I will caveat that I was not trying to view an external person's source code, I just wanted to see my OWN code, but every time I "stepped in" to my methods that I wrote that were in MY project, I got the "Source now found" error.
After finally asking an expert, my issue was that the first thing Eclipse was doing was calling a ClassLoader, which you can see from the debug stack. All I had to do was F6 (step over) and then it took me back to my original call and then F5 (step in). And there was my code. Sigh...such a simple fix but an hour wasted.
int i = 0; // Counter used to determine when you're at the 3rd gun
for (Gun g : gunList) { // For each gun in your list
System.out.println(g); // Print out the gun
if (i == 2) { // If you're at the third gun
ArrayList<Bullet> bullets = g.getBullet(); // Get the list of bullets in the gun
for (Bullet b : bullets) { // Then print every bullet
System.out.println(b);
}
i++; // Don't forget to increment your counter so you know you're at the next gun
}
Paste this into command line
FOR /F "tokens=5 delims= " %P IN ('netstat -ano ^| find "LISTENING" ^| find ":8080 "') DO (TASKKILL /PID %P)
If you want to use it in a batch pu %%P
instead of %P
You can just delete .git. Typically:
rm -rf .git
Then, recreate as the right user.
Another case:
It could be possible to get a status code of 0
if you have sent an AJAX call and a refresh of the browser was triggered before getting the AJAX response. The AJAX call will be cancelled and you will get this status.
i had a kind of similar problem. i tried to copy from a server to my desktop and always got the same message for the local path. the problem was, i already was logged in to my server per ssh, so it was searching for the local path in the server path.
solution: i had to log out and run the command again and it worked
You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:
SELECT TO_CHAR(
TO_DATE('15/August/2009,4:30 PM'
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM DUAL;
15-08-2009
For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:
SELECT TO_CHAR(
TO_DATE(MYDATESTRING
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM MYTABLE;
If you don't want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name selected, no custom directives are necessary:
ng:class="{true:'selected', false:''}[$index==selectedIndex]"
Please note the old syntax with colon.
There is also a new better way of applying classes conditionally, like:
ng-class="{selected: $index==selectedIndex}"
Angular now supports expressions that return an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.
However these ways are not functionally equal. Here is an example:
ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"
We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time keep CSS classes out of Controller code.
td[rowspan] {
vertical-align: top;
text-align: left;
}
See: CSS attribute selectors.
I've just encountered the same problem but within my own application. I didn't like the solution with copying the dll since it's not very convenient so I did some research and came up with the following programmatic solution.
Basically, before doing any connections to SQL server, you have to add the sqljdbc_auth.dll
to path.. which is easy to say:
PathHelper.appendToPath("C:\\sqljdbc_6.2\\enu\\auth\\x64");
once you know how to do it:
import java.lang.reflect.Field;
public class PathHelper {
public static void appendToPath(String dir){
String path = System.getProperty("java.library.path");
path = dir + ";" + path;
System.setProperty("java.library.path", path);
try {
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
}
catch (Exception ex){
throw new RuntimeException(ex);
}
}
}
Now integration authentication works like a charm :).
Credits to https://stackoverflow.com/a/21730111/1734640 for letting me figure this out.
Try this:
private void txtEntry_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string trimText;
trimText = this.txtEntry.Text.Replace("\r\n", "").ToString();
this.txtEntry.Text = trimText;
btnEnter.PerformClick();
}
}
I would recommend you to make use of the $.post
or $.get
syntax of jQuery for simple cases:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
});
If you need to catch the fail cases, just do this:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
Additionally, if you always send a JSON string, you can use $.getJSON or $.post with one more parameter at the very end.
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}, 'json');
if you are not using model as per your question you can do like this
@Html.Hidden("hdnFlag" , new {id = "hdnFlag", value = "hdnFlag_value" })
else if you are using model (considering passing model has hdnFlag property), you can use this approch
@Html.HiddenFor(model => model.hdnFlag, new { value = Model.hdnFlag})
My select2 element was not firing the onchange
event as the drop down list offered only one value, making it impossible to change the value.
The value not having changed, no event was fired and the handler could not execute.
I then added another handler to clear the value, with the select2-open
handler being executed before the onchange
handler.
The source code now looks like:
el.on("select2-open", function(e) {
$(this).val('');
});
el.on('change', function() {
...
});
The first handler clears the value, allowing the second handler to fire up even if selecting the same value.
I don't believe Eclipse has a JavaScript debugger - those breakpoints are for Java code (I'm guessing you are editing a JSP file?)
Use Firebug to debug Javascript code, it's an excellent add-on that all web developers should have in their toolbox.
chsh -s $(which zsh)
You'll be prompted for your password, but once you update your settings any new iTerm/Terminal sessions you start on that machine will default to zsh.
Start by turning the text into a list of lists. That will take care of the parsing part:
lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))
The rest can be done with indexed lookups:
d = dict()
key = lol[6][0] # cell A7
value = lol[6][3] # cell D7
d[key] = value # add the entry to the dictionary
...
For an uglier version of unshift
use splice
:
TheArray.splice(0, 0, TheNewObject);
Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)
example:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new WebBrowser());
}
}
You can do this in 2 steps:
1: Change the input type(In your EditText
field) in the layout file to android:inputType="number"
2: Use int a = Integer.parseInt(yourEditTextObject.getText().toString());
teststr=$'test1\n'
teststr+=$'test2\n'
echo "$teststr"
If you can turn your datatable into an IEnumerable this should work for you...
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FileName.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(ExampleClass.ConvertToCSV(GetListOfObject(), typeof(object)));
Response.Flush();
Response.End();
public static string ConvertToCSV(IEnumerable col, Type type)
{
StringBuilder sb = new StringBuilder();
StringBuilder header = new StringBuilder();
// Gets all properies of the class
PropertyInfo[] pi = type.GetProperties();
// Create CSV header using the classes properties
foreach (PropertyInfo p in pi)
{
header.Append(p.Name + ",");
}
sb.AppendLine(header.ToString().Remove(header.Length));
foreach (object t in col)
{
StringBuilder body = new StringBuilder();
// Create new item
foreach (PropertyInfo p in pi)
{
object o = p.GetValue(t, null);
body.Append(o.ToString() + ",");
}
sb.AppendLine(body.ToString().Remove(body.Length));
}
return sb.ToString();
}
Try as
String s = "ABC[ This is to extract ]";
Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
Matcher m = p.matcher(s);
m.find();
String text = m.group(1);
System.out.println(text);
Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";
// use the built in Json deserializer to convert the string to a list of Person objects
var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);
foreach (var person in people)
{
Console.WriteLine(person.Name + " is " + person.Age + " years old.");
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}
}
For jQuery with twitter bootstrap
Check caps locked for the following characters:
uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';', '*', '''
lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ',', '+', '#'
/* check for CAPS LOCK on all password fields */
$("input[type='password']").keypress(function(e) {
var kc = e.which; // get keycode
var isUpperCase = ((kc >= 65 && kc <= 90) || (kc >= 33 && kc <= 34) || (kc >= 36 && kc <= 39) || (kc >= 40 && kc <= 42) || kc == 47 || (kc >= 58 && kc <= 59) || kc == 61 || kc == 63 || kc == 167 || kc == 196 || kc == 214 || kc == 220) ? true : false; // uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';'
var isLowerCase = ((kc >= 97 && kc <= 122) || (kc >= 48 && kc <= 57) || kc == 35 || (kc >= 43 && kc <= 44) || kc == 46 || kc == 228 || kc == 223 || kc == 246 || kc == 252) ? true : false; // lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ','
// event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
var isShift = (e.shiftKey) ? e.shiftKey : ((kc == 16) ? true : false); // shift is pressed
// uppercase w/out shift or lowercase with shift == caps lock
if ((isUpperCase && !isShift) || (isLowerCase && isShift)) {
$(this).next('.form-control-feedback').show().parent().addClass('has-warning has-feedback').next(".capsWarn").show();
} else {
$(this).next('.form-control-feedback').hide().parent().removeClass('has-warning has-feedback').next(".capsWarn").hide();
}
}).after('<span class="glyphicon glyphicon-warning-sign form-control-feedback" style="display:none;"></span>').parent().after("<span class='capsWarn text-danger' style='display:none;'>Is your CAPSLOCK on?</span>");
You must ensure the URL contains embed rather watch as the /embed
endpoint allows outside requests, whereas the /watch
endpoint does not.
<iframe width="420" height="315" src="https://www.youtube.com/embed/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>
values timestampdiff (16, char(
timestamp(current timestamp + 1 year + 2 month - 3 day)-
timestamp(current timestamp)))
1
=
422
values timestampdiff (16, char(
timestamp('2012-03-08-00.00.00')-
timestamp('2011-12-08-00.00.00')))
1
=
90
---------- EDIT BY galador
SELECT TIMESTAMPDIFF(16, CHAR(CURRENT TIMESTAMP - TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD'))
FROM CHCART00
WHERE CHSTAT = '05'
EDIT
As it has been pointed out by X-Zero, this function returns only an estimate. This is true. For accurate results I would use the following to get the difference in days between two dates a and b:
SELECT days (current date) - days (date(TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD')))
FROM CHCART00
WHERE CHSTAT = '05';
<div class="ai">a b c d e f</div> // something like ~100px
<div class="ai">a b c d e</div> // ~80
<div class="ai">a b c d</div> // ~60
<script>
function _reWidthAll_div(classname) {
var _maxwidth = 0;
$(classname).each(function(){
var _width = $(this).width();
_maxwidth = (_width >= _maxwidth) ? _width : _maxwidth; // define max width
});
$(classname).width(_maxwidth); // return all div same width
}
_reWidthAll_div('.ai');
</script>
Point to Eclipse Juno Site, If not available add the site "Juno - http://download.eclipse.org/releases/juno"
Select and expand general purpose tools
R Studio (and Eclipse + StatET): Highlight the text and use CTRL+SHIFT+C to comment multiple lines in Windows. Or, command+SHIFT+C in OS-X.
You can separate multiple classes with the space:
$("p").addClass("myClass yourClass");
Correct solution is to copy or install to /usr/local/bin
not /usr/bin
.This is due to System Integrity Protection (SIP). SIP makes /usr/bin
read-only but leaves /usr/local
as read-write.
SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.
As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."
Since arrays must be indexed with integers, the maximum length of an array is Integer.MAX_INT
(231-1, or 2 147 483 647). This is assuming you have enough memory to hold an array of that size, of course.
You can use routerLink in the following manner,
<input type="button" value="Add Bulk Enquiry" [routerLink]="['../addBulkEnquiry']" class="btn">
or use <button [routerLink]="['./url']">
in your case, for more info you could read the entire stacktrace on github https://github.com/angular/angular/issues/9471
the other methods are also correct but they create a dependency on the component file.
Hope your concern is resolved.
try FileSaver.js
library. it might help.
Without looping
I am using this if I simply want to strip the extension from a filename or variable (without listing any directories or existing files):
for %%f in ("%filename%") do set filename=%%~nf
If you want to strip the extension from a full path, use %%dpnf
instead:
for %%f in ("%path%") do set path=%%~dpnf
Example:
(Use directly in the console)
@for %f in ("file name.dat") do @echo %~nf
@for %f in ("C:\Dir\file.dat") do @echo %~dpnf
OUTPUT:
file name
C:\Dir\file
You can also do string concat with template literals. I updated the other posters' JSPerf tests to include it.
for (var res = '', i = 0; i < data.length; i++) {
res = `${res}${data[i]}`;
}
For laravel 5.* try these.
return redirect()->intended('/');
or
return Redirect::intended('/');
Since 2014b, Matlab has these normalization routines embedded natively in the histogram
function (see the help file for the 6 routines this function offers). Here is an example using the PDF normalization (the sum of all the bins is 1).
data = 2*randn(5000,1) + 5; % generate normal random (m=5, std=2)
h = histogram(data,'Normalization','pdf') % PDF normalization
The corresponding PDF is
Nbins = h.NumBins;
edges = h.BinEdges;
x = zeros(1,Nbins);
for counter=1:Nbins
midPointShift = abs(edges(counter)-edges(counter+1))/2;
x(counter) = edges(counter)+midPointShift;
end
mu = mean(data);
sigma = std(data);
f = exp(-(x-mu).^2./(2*sigma^2))./(sigma*sqrt(2*pi));
The two together gives
hold on;
plot(x,f,'LineWidth',1.5)
An improvement that might very well be due to the success of the actual question and accepted answer!
EDIT - The use of hist
and histc
is not recommended now, and histogram
should be used instead. Beware that none of the 6 ways of creating bins with this new function will produce the bins hist
and histc
produce. There is a Matlab script to update former code to fit the way histogram
is called (bin edges instead of bin centers - link). By doing so, one can compare the pdf
normalization methods of @abcd (trapz
and sum
) and Matlab (pdf
).
The 3 pdf
normalization method give nearly identical results (within the range of eps
).
TEST:
A = randn(10000,1);
centers = -6:0.5:6;
d = diff(centers)/2;
edges = [centers(1)-d(1), centers(1:end-1)+d, centers(end)+d(end)];
edges(2:end) = edges(2:end)+eps(edges(2:end));
figure;
subplot(2,2,1);
hist(A,centers);
title('HIST not normalized');
subplot(2,2,2);
h = histogram(A,edges);
title('HISTOGRAM not normalized');
subplot(2,2,3)
[counts, centers] = hist(A,centers); %get the count with hist
bar(centers,counts/trapz(centers,counts))
title('HIST with PDF normalization');
subplot(2,2,4)
h = histogram(A,edges,'Normalization','pdf')
title('HISTOGRAM with PDF normalization');
dx = diff(centers(1:2))
normalization_difference_trapz = abs(counts/trapz(centers,counts) - h.Values);
normalization_difference_sum = abs(counts/sum(counts*dx) - h.Values);
max(normalization_difference_trapz)
max(normalization_difference_sum)
The maximum difference between the new PDF normalization and the former one is 5.5511e-17.
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
I usually insert a blockquote and add a Unicode character(memo which is(U+1F4DD
)) inside it.
...
Syntax | Demo |
---|---|
> bla bla ... |
|
> ```` bla bla |
|
> ** bla bla |
|
Of course, if you do not like you can search you like. I am sure there will be one in it is your satisfaction!
find more emoji: https://emojipedia.org/
just search you like icon and copy-paste then done(since it is a character, so it suitable for every device)
If you don't like copy paste and want to type yourself, you can consider searching the Unicode.
p.s. You can also pay attention to the emoji version (usually it is the same as the Unicode version), and more icons may appear in the future to your satisfaction.
WebStorm 10.0.4
For wrapping text/code line by deafault, but for all types of file: File -> Settings -> Editor -> General -> section "Soft Wraps" -> checkbox "Use soft wraps in editor"
(imho)
you can use
reader.GetInt32(3);
to read an 32 bit int from the data reader.
If you know the type of your data I think its better to read using the Get*
methods which are strongly typed rather than just reading an object and casting.
Have you considered using
reader.GetInt32(reader.GetOrdinal(columnName))
rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.
The underlying problem here is the 1st level cache of JPA. From the JPA spec Version 2.2 section 3.1. emphasise is mine:
An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance.
This is important because JPA tracks changes to that entity in order to flush them to the database. As a side effect it also means within a single persistence context an entity gets only loaded once. This why reloading the changed entity doesn't have any effect.
You have a couple of options how to handle this:
Evict the entity from the EntityManager
.
This may be done by calling EntityManager.detach
, annotating the updating method with @Modifying(clearAutomatically = true)
which evicts all entities.
Make sure changes to these entities get flushed first or you might end up loosing changes.
Use a different persistence context to load the entity.
The easiest way to do this is to do it in a separate transaction.
With Spring this can be done by having separate methods annotated with @Transactional
on beans called from a bean not annotated with @Transactional
.
Another way is to use a TransactionTemplate
which works especially nicely in tests where it makes transaction boundaries very visible.
Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:
"
git push --recurse-submodules
" learned to optionally look into the histories of submodules bound to the superproject and push them out.
Probably done after this patch and the --on-demand
option:
recurse-submodules=<check|on-demand>::
Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.
- If
check
is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
Otherwise the push will be aborted and exit with non-zero status.- If
on-demand
is used, all submodules that changed in the revisions to be pushed will be pushed.
If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.
So you could push everything in one go with (from the parent repo) a:
git push --recurse-submodules=on-demand
This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.
With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.
See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe
).
(Merged by Junio C Hamano -- gitster
-- in commit 5d35d72, 21 Dec 2015)
push
: addrecurseSubmodules
config optionThe
--recurse-submodules
command line parameter has existed for some time but it has no config file equivalent.Following the style of the corresponding parameter for
git fetch
, let's inventpush.recurseSubmodules
to provide a default for this parameter.
This also requires the addition of--recurse-submodules=no
to allow the configuration to be overridden on the command line when required.The most straightforward way to implement this appears to be to make
push
use code insubmodule-config
in a similar way tofetch
.
The git config
doc now include:
push.recurseSubmodules
:Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.
- If the value is '
check
', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.- If the value is '
on-demand
' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -- If the value is '
no
' then default behavior of ignoring submodules when pushing is retained.You may override this configuration at time of push by specifying '
--recurse-submodules=check|on-demand|no
'.
So:
git config push.recurseSubmodules on-demand
git push
Git 2.12 (Q1 2017)
git push --dry-run --recurse-submodules=on-demand
will actually work.
See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 12cf113, 16 Dec 2016)
push run with --dry-run
doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.Teach
push
to respect the--dry-run
option when configured to recursively push submodules 'on-demand'.
This is done by passing the--dry-run
flag to the child process which performs a push for a submodules when performing a dry-run.
And still in Git 2.12, you now havea "--recurse-submodules=only
" option to push submodules out without pushing the top-level superproject.
See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 792e22e, 31 Jan 2017)
This is how I do it:
str(1).zfill(len(str(total)))
Basically zfill takes the number of leading zeros you want to add, so it's easy to take the biggest number, turn it into a string and get the length, like this:
Python 3.6.5 (default, May 11 2018, 04:00:52) [GCC 8.1.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> total = 100 >>> print(str(1).zfill(len(str(total)))) 001 >>> total = 1000 >>> print(str(1).zfill(len(str(total)))) 0001 >>> total = 10000 >>> print(str(1).zfill(len(str(total)))) 00001 >>>
Here's my short summary.
If you want to write a unit test, don't use a Spring applicationContext because you don't want any real dependencies injected in the class you are unit testing. Instead use mocks, either with the @RunWith(MockitoJUnitRunner.class)
annotation on top of the class, or with MockitoAnnotations.initMocks(this)
in the @Before method.
If you want to write an integration test, use:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("yourTestApplicationContext.xml")
To set up your application context with an in-memory database for example.
Normally you don't use mocks in integration tests, but you could do it by using the MockitoAnnotations.initMocks(this)
approach described above.
You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f
immediately after the string and then the list of variables separated by commas.
Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}
(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)
Here's a function I have been using - tested and works on any basic data type:
// SwapBytes.h
//
// Function to perform in-place endian conversion of basic types
//
// Usage:
//
// double d;
// SwapBytes(&d, sizeof(d));
//
inline void SwapBytes(void *source, int size)
{
typedef unsigned char TwoBytes[2];
typedef unsigned char FourBytes[4];
typedef unsigned char EightBytes[8];
unsigned char temp;
if(size == 2)
{
TwoBytes *src = (TwoBytes *)source;
temp = (*src)[0];
(*src)[0] = (*src)[1];
(*src)[1] = temp;
return;
}
if(size == 4)
{
FourBytes *src = (FourBytes *)source;
temp = (*src)[0];
(*src)[0] = (*src)[3];
(*src)[3] = temp;
temp = (*src)[1];
(*src)[1] = (*src)[2];
(*src)[2] = temp;
return;
}
if(size == 8)
{
EightBytes *src = (EightBytes *)source;
temp = (*src)[0];
(*src)[0] = (*src)[7];
(*src)[7] = temp;
temp = (*src)[1];
(*src)[1] = (*src)[6];
(*src)[6] = temp;
temp = (*src)[2];
(*src)[2] = (*src)[5];
(*src)[5] = temp;
temp = (*src)[3];
(*src)[3] = (*src)[4];
(*src)[4] = temp;
return;
}
}
You can set the IP while running it.
docker run --cap-add=NET_ADMIN -dit imagename /bin/sh -c "/sbin/ip addr add 172.17.0.12 dev eth0; bash"
See my example at https://github.com/RvdGijp/mariadb-10.1-galera
Here is another take, "stolen" from a comment at can't compare datetime.datetime to datetime.date ... convert the date to a datetime using this construct:
datetime.datetime(d.year, d.month, d.day)
Suggestion:
from datetime import datetime
def ensure_datetime(d):
"""
Takes a date or a datetime as input, outputs a datetime
"""
if isinstance(d, datetime):
return d
return datetime.datetime(d.year, d.month, d.day)
def datetime_cmp(d1, d2):
"""
Compares two timestamps. Tolerates dates.
"""
return cmp(ensure_datetime(d1), ensure_datetime(d2))
Following Python code worked for me. To check the ODBC connection, I first created a 4 line C# console application as listed below.
Python Code
import pandas as pd
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_DW;")
df = pd.read_sql_query('select TOP 10 * from dbo.Table WHERE Patient_Key > 1000', cnxn)
df.head()
Calling a Stored Procedure
dfProcResult = pd.read_sql_query('exec dbo.usp_GetPatientProfile ?', cnxn, params=['MyParam'] )
C# Program to Check ODBC Connection
static void Main(string[] args)
{
string connectionString = "Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_DW;";
OdbcConnection cn = new OdbcConnection(connectionString);
cn.Open();
cn.Close();
}
Resize the image to fit the div size.
With CSS3 you can do this:
/* with CSS 3 */
#yourdiv {
background: url('bgimage.jpg') no-repeat;
background-size: 100%;
}
How Do you Stretch a Background Image in a Web Page:
About opacity
#yourdiv {
opacity: 0.4;
filter: alpha(opacity=40); /* For IE8 and earlier */
}
Or look at CSS Image Opacity / Transparency
This happened to me by having a link to external js outside the head just before the end of the body section. You know, one of these:
<script src="http://somesite.net/js/somefile.js">
It did not have anything to do with JQuery.
You would probably see the same doing something like this:
var script = $("<script></script>");
script.attr("src", basepath + "someotherfile.js");
$(document.body).append(script);
But I haven't tested that idea.
I realize this is an old post, but it ranks high in Google, so I'm adding what I figured out for MY problem. If you have a mix of table types (e.g. MyISAM and InnoDB), you will get this error as well. In this case, InnoDB is the default table type, but one table needed fulltext searching so it was migrated to MyISAM. In this situation, you cannot create a foreign key in the InnoDB table that references the MyISAM table.
I have tried the most upvoted one, but it did not work for me, but below works well.
$('#mytable tr').last().after('<tr><td></td></tr>');
Which will work even there is a tobdy there.
$ mysql -u root -p -e "grant all privileges on dbTest.* to
`{user}`@`{host}` identified by '{long-password}'; flush privileges;"
ignore -p option, if mysql user has no password or just press "[Enter]" button to by-pass. strings surrounded with curly braces need to replaced with actual values.
You need to add the new line character \n
:
console.log('line one \nline two')
would display:
line one
line two
You can use the onload=""
HTML attribute and use JavaScript to adjust the opacity style of your element.
Leave your CSS as you proposed. Edit your HTML code to:
<body onload="document.getElementById(test).style.opacity='1'">
<div id="test">
<p>?This is a test</p>
</div>
</body>
This also works to fade-in the complete page when finished loading:
HTML:
<body onload="document.body.style.opacity='1'">
</body>
CSS:
body{
opacity: 0;
transition: opacity 2s;
-webkit-transition: opacity 2s; /* Safari */
}
Check the W3Schools website: transitions and an article for changing styles with JavaScript.
I recommend CsvHelper from Nuget.
PS: Regarding other more upvoted answers, I'm sorry but adding a reference to Microsoft.VisualBasic
is:
Go to Project > properties > Debug Tab and set the Launch to "Project"
We can make a plugin pretty easily:
$.fn.filterData = function(key, value) {
return this.filter(function() {
return $(this).data(key) == value;
});
};
Usage (checking a radio button):
$('input[name=location_id]').filterData('my-data','data-val').prop('checked',true);
Calling child component in parent
<component :is="my_component" ref="my_comp"></component>
<v-btn @click="$refs.my_comp.alertme"></v-btn>
in Child component
mycomp.vue
methods:{
alertme(){
alert("alert")
}
}
You can use the List.addAll() method. It accepts a Collection as an argument, and your set is a Collection.
List<String> mainList = new ArrayList<String>();
mainList.addAll(set);
EDIT: as respond to the edit of the question.
It is easy to see that if you want to have a Map
with List
s as values, in order to have k different values, you need to create k different lists.
Thus: You cannot avoid creating these lists at all, the lists will have to be created.
Possible work around:
Declare your Map
as a Map<String,Set>
or Map<String,Collection>
instead, and just insert your set.
To push your existing repo into different, you need to:
Clone the original repo first.
git clone https://git.fedorahosted.org/cgit/rhq/rhq.git
Push the cloned sources to your new repository:
cd rhq
git push https://github.com/user/example master:master
You may change master:master
into source:destination
branch.
If you want to push specific commit (branch), then do:
On the original repo, create and checkout a new branch:
git checkout -b new_branch
Choose and reset to the point which you want to start with:
git log # Find the interesting hash
git reset 4b62bdc9087bf33cc01d0462bf16bbf396369c81 --hard
Alternatively select the commit by git cherry-pick
to append into existing HEAD.
Then push to your new repo:
git push https://github.com/user/example new_branch:master
If you're rebasing, use -f
for force push (not recommended). Run git reflog
to see history of changes.
Here is the list of classes and functions:
open System
open System.Collections.Generic
open System.Linq
open System.Threading.Tasks
open Microsoft.AspNetCore.Mvc
open Microsoft.Extensions.Logging
open Microsoft.AspNetCore.Authorization
open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Authentication.JwtBearer
open Microsoft.IdentityModel.Tokens
open System.IdentityModel.Tokens
open System.IdentityModel.Tokens.Jwt
open Microsoft.IdentityModel.JsonWebTokens
open System.Text
open Newtonsoft.Json
open System.Security.Claims
let theKey = "VerySecretKeyVerySecretKeyVerySecretKey"
let securityKey = SymmetricSecurityKey(Encoding.UTF8.GetBytes(theKey))
let credentials = SigningCredentials(securityKey, SecurityAlgorithms.RsaSsaPssSha256)
let expires = DateTime.UtcNow.AddMinutes(123.0) |> Nullable
let token = JwtSecurityToken(
"lahoda-pro-issuer",
"lahoda-pro-audience",
claims = null,
expires = expires,
signingCredentials = credentials
)
let tokenString = JwtSecurityTokenHandler().WriteToken(token)
APF. You are eprobably lucky enough never to have heard of this nightmare. It was an expensive add on to IBMs mainframe hierachical database/transaction monitor IMS system. Where to start.
There was no support for arrays. If you had an array of ten items well you coded ITEM1, ITEM2 etc. and wrote ten lines of code to process each item.
Your code was stored in the database and interprated at run time. Do to the internal stucture of the thing your code was broken up and stored in several records. It was absurdly easy to overwrite someone elses code.
Some of you code was associated with the transaction (IMS speak for a service) but some of you code was assoicated with the database record -- if you got it wrong bits of your program ran every time someone accessed a record.
No debugger, the "compiler" only did basic syntax checking most errors appared at run time, with one of it four error messsages.
One of these error messages was 'INVALID DATA TYPE' -- thats all, no variable name, no line number, no clue.
Just plain horrible.
You can use below code sample also for achieving the same
ViewCompat.setElevation(sourceView, ViewCompat.getElevation(mCardView)+1);
This is backward compatible.
Here mCardView
is a view which should be below sourceView
.
Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.
NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)
Here is a link with the appropriate formulas.
The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))
More information on the Index/Match formula
Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.
I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.
Good luck! Hope this helps.
Updated
How to implement page refresh in Angular 2+ note this is done within your component:
location.reload();
While probably not as clean looking as the IConvertible
approach, you could always use the straightforward checking typeof(T)
to return a T
:
public static T ReturnType<T>(string stringValue)
{
if (typeof(T) == typeof(int))
return (T)(object)1;
else if (typeof(T) == typeof(FooBar))
return (T)(object)new FooBar(stringValue);
else
return default(T);
}
public class FooBar
{
public FooBar(string something)
{}
}
You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()
you have to do like this in your project level gradle file
allprojects {
repositories {
jcenter()
maven { url "http://dl.appnext.com/" }
maven { url "https://maven.google.com" }
}
}
Add a inline wrapper.
<div style='display:flex'>
<form>
<p>Read this sentence</p>
<input type='submit' value='or push this button' />
</form>
<div>
<p>Message here</p>
</div>
You can calculate with Dates.
var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25
Arguments and parameters are different in that parameters are used to different values in the program and The arguments are passed the same value in the program so they are used in c++. But no difference in c. It is the same for arguments and parameters in c.
Guard statement going to do . it is couple of different
1) it is allow me to reduce nested if statement
2) it is increase my scope which my variable accessible
if Statement
func doTatal(num1 : Int?, num2: Int?) {
// nested if statement
if let fistNum = num1 where num1 > 0 {
if let lastNum = num2 where num2 < 50 {
let total = fistNum + lastNum
}
}
// don't allow me to access out of the scope
//total = fistNum + lastNum
}
Guard statement
func doTatal(num1 : Int?, num2: Int?) {
//reduce nested if statement and check positive way not negative way
guard let fistNum = num1 where num1 > 0 else{
return
}
guard let lastNum = num2 where num2 < 50 else {
return
}
// increase my scope which my variable accessible
let total = fistNum + lastNum
}
try this code :
private GoogleMap mMap;
LocationManager locationManager;
private static final String TAG = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
arrayPoints = new ArrayList<LatLng>();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
LatLng myPosition;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
LatLng coordinate = new LatLng(latitude, longitude);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 19);
mMap.animateCamera(yourLocation);
}
}
}
Dont forget to add permissions on AndroidManifest.xml.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Something like this?
int[][] pixels = new int[w][h];
for( int i = 0; i < w; i++ )
for( int j = 0; j < h; j++ )
pixels[i][j] = img.getRGB( i, j );
Create a C# class that maps to your Json and use Newsoft JsonConvert
to Deserialise it.
For example:
public Class MyResponse
{
public Meta Meta { get; set; }
public Response Response { get; set; }
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global
keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global
.
config.php
global $variable;
$variable = 5;
other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS
as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
use text untold class from android:
TextUtils.substring (charsequence source, int start, int end)
Another great free parser - http://bncscripts.com/free-php-rss-parser/ It's very light ( only 3kb ) and simple to use!
You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.
I had to transform the divs to list items otherwise all my divs would get that class and only the generated ones should get it Thanks everyone, I love this site and the helpful people on it !!!! You can follow the newbie school project at http://low-budgetwebservice.be/project/webbuilder.html suggestions are always welcome :). So this worked for me:
/* Add Class Heading*/
$(document).ready(function() {
$( document ).on( 'click', 'ul#items li', function () {
$('ul#items li').removeClass('active');
$(this).addClass('active');
});
});
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps
Here is a much better solution. http://bavotasan.com/2011/html5-placeholder-jquery-fix/ I've adopted it a bit to work only with browsers under IE10
<!DOCTYPE html>
<!--[if lt IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]><html class="no-js lt-ie10 lt-ie9" lang="en"> <![endif]-->
<!--[if IE 9]><html class="no-js lt-ie10" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en"><!--<![endif]-->
<script>
// Placeholder fix for IE
$('.lt-ie10 [placeholder]').focus(function() {
var i = $(this);
if(i.val() == i.attr('placeholder')) {
i.val('').removeClass('placeholder');
if(i.hasClass('password')) {
i.removeClass('password');
this.type='password';
}
}
}).blur(function() {
var i = $(this);
if(i.val() == '' || i.val() == i.attr('placeholder')) {
if(this.type=='password') {
i.addClass('password');
this.type='text';
}
i.addClass('placeholder').val(i.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
//if($(this).validationEngine('validate')) { // If using validationEngine
$(this).find('[placeholder]').each(function() {
var i = $(this);
if(i.val() == i.attr('placeholder'))
i.val('');
i.removeClass('placeholder');
})
//}
});
</script>
...
</html>
SELECT REGEXP_SUBSTR('STRING_EXAMPLE','[^_]+',1,1) from dual
is the right answer, as posted by user1717270
If you use INSTR
, it will give you the position for a string that assumes it contains "_" in it. What if it doesn't? Well the answer will be 0. Therefore, when you want to print the string, it will print a NULL
.
Example: If you want to remove the domain from a "host.domain". In some cases you will only have the short name, i.e. "host". Most likely you would like to print "host". Well, with INSTR
it will give you a NULL
because it did not find any ".", i.e. it will print from 0 to 0. With REGEXP_SUBSTR
you will get the right answer in all cases:
SELECT REGEXP_SUBSTR('HOST.DOMAIN','[^.]+',1,1) from dual;
HOST
and
SELECT REGEXP_SUBSTR('HOST','[^.]+',1,1) from dual;
HOST
Import by using the import
keyword:
import package.myclass;
But since it's the default package and same, you just create a new instance like:
elf ob = new elf(); //Instance of elf class
Parse
throws an exception if it cannot parse the value, whereas TryParse
returns a bool
indicating whether it succeeded.
TryParse
does not just try
/catch
internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse
method will call TryParse
and then throw an exception if it returns false
.
In a nutshell, use Parse
if you are sure the value will be valid; otherwise use TryParse
.
And was the code helpful? Because the code you are writing should do the thing:
driver.findElement("locator").clear();
If it does not help, then try this:
WebElement toClear = driver.findElement("locator");
toClear.sendKeys(Keys.CONTROL + "a");
toClear.sendKeys(Keys.DELETE);
maybe you will have to do some convert of the Keys.CONTROL + "a"
to CharSequence, but the first approach should do the magic
You can use the command wget
to download from command line. Specifically, you could use
wget http://download.oracle.com/otn-pub/java/jdk/7u10-b18/jdk-7u10-linux-x64.tar.gz
However because Oracle requires you to accept a license agreement this may not work (and I am currently unable to test it).
Based on the best answers of this question I have made a prototype for String called padLeft (exactly like we have in C#):
String.prototype.padLeft = function (paddingChar, totalWidth) {
if (this.toString().length >= totalWidth)
return this.toString();
var array = new Array(totalWidth);
for (i = 0; i < array.length; i++)
array[i] = paddingChar;
return (array.join("") + this.toString()).slice(-array.length);
}
Usage:
var str = "12345";
console.log(str.padLeft("0", 10)); //Result is: "0000012345"
public static void writeStringAsFile(final String fileContents, String fileName) {
Context context = App.instance.getApplicationContext();
try {
FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
out.write(fileContents);
out.close();
} catch (IOException e) {
Logger.logError(TAG, e);
}
}
public static String readFileAsString(String fileName) {
Context context = App.instance.getApplicationContext();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) stringBuilder.append(line);
} catch (FileNotFoundException e) {
Logger.logError(TAG, e);
} catch (IOException e) {
Logger.logError(TAG, e);
}
return stringBuilder.toString();
}
this command posted by Daniel works like charm
C:\xampp\mysql\bin>mysql -u {DB_USER} -p {DB_NAME} < path/to/file/ab.sql
just put the db username and db name without those backets
**NOTE: Make sure your database file is reside inside the htdocs folder, else u'll get an Access denied error
Here is the Simplest Method.
This is the String value: "5/13/2012"
DateTime _date;
string day = "";
_date = DateTime.Parse("5/13/2012");
day = _date.ToString("dd-MMM-yyyy");
It will output as: 13-May-2012
Here's an example of how to create a ColorList
programmatically in Kotlin:
val colorList = ColorStateList(
arrayOf(
intArrayOf(-android.R.attr.state_enabled), // Disabled
intArrayOf(android.R.attr.state_enabled) // Enabled
),
intArrayOf(
Color.BLACK, // The color for the Disabled state
Color.RED // The color for the Enabled state
)
)
The value of a button element isn't the displayed text, contrary to what happens to input
elements of type button.
You can do this :
b.appendChild(document.createTextNode('test value'));
That code gets you the IP address of your server not the address of the client who is accessing your website. Use the HttpContext.Current.Request.UserHostAddress property to the client's IP address.
It is to mark the parameter as optional.
If I get 'someObject', say via
someObject <- myMagicFunction(...)
then I usually proceed by
class(someObject)
str(someObject)
which can be followed by head(), summary(), print(), ... depending on the class you have.
With jQuery 1.6 version you can use the .promise()
method.
$(selector).fadeOut('slow');
$(selector).promise().done(function(){
// will be called when all the animations on the queue finish
});
distinct
is not a function. It always operates on all columns of the select list.
Your problem is a typical "greatest N per group" problem which can easily be solved using a window function:
select ...
from (
select IDNo,
FirstName,
LastName,
....,
row_number() over (partition by lower(idno) order by firstname) as rn
from people
) t
where rn = 1;
Using the order by
clause you can select which of the duplicates you want to pick.
The above can be used in a left join, see below:
select ...
from x
left join (
select IDNo,
FirstName,
LastName,
....,
row_number() over (partition by lower(idno) order by firstname) as rn
from people
) p on p.idno = x.idno and p.rn = 1
where ...
Try this code:
s = input()
a = int(input())
b = s.replace(s[a],'')
print(b)
If you're on OSX using Homebrew, you can install old Firefox versions via brew cask:
brew tap goldcaddy77/firefox
brew cask install firefox-46 # or whatever version you want
After installing, you'll just need to rename your FF executable in the Applications directory to "Firefox".
More info can be found at the git repo homebrew-firefox. Props to smclernon for creating the original cask.
This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.
There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.
You can do it with a pivot
query, like this:
select * from (
select LOAN_NUMBER, DOCUMENT_TYPE, DOCUMENT_ID
from my_table t
)
pivot
(
MIN(DOCUMENT_ID)
for DOCUMENT_TYPE in ('Voters ID','Pan card','Drivers licence')
)
Here is a demo on sqlfiddle.com.
Opacity changes the context of your z-index, as does the static positioning. Either add opacity to the element that doesn't have it or remove it from the element that does. You'll also have to either make both elements static positioned or specify relative or absolute position. Here's some background on contexts: http://philipwalton.com/articles/what-no-one-told-you-about-z-index/
You can view which modules (compiled in) are available via terminal through php -m
My awk version is 3.1.5.
Yes, the input file is space separated, no tabs.
According to arutaku's answer, here's what I tried that worked:
awk '$8 ~ "ClNonZ"{ print $3; }' test
0.180467091
0.010615711
0.492569002
$ awk '$8 ~ "ClNonZ" { print $3}' test
0.180467091
0.010615711
0.492569002
What didn't work(I don't know why and maybe due to my awk version:),
$awk '$8 ~ "^ClNonZ$"{ print $3; }' test
$awk '$8 == "ClNonZ" { print $3 }' test
Thank you all for your answers, comments and help!
If your compiler supports C++11 standard, there is a constructor inheritance using using
(pun intended). For more see Wikipedia C++11 article. You write:
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
using A::A;
};
This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.
Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.
Had the same issue, because I forgot to go into my virtual machine. If I go to my local directory like this:
cd /www/homestead/my_project
php artisan migrate
that error will appear. But it works on my virtual machine
cd ~/homestead
vagrant ssh
cd /www/homestead/my_project
php artisan migrate
You're going to have to do something like that i think (convert it into a more concrete type).
Maybe take it into a List of T rather than ArrayList, so that you get type safety and more options for how you implement the comparer.
The .zip file provided by the authors is not a valid R package, and they do state that the source is for "direct use" in R (by which I assume they mean it's necessary to load the included functions manually). The non-zero exit status
simply indicates that there was an error during the installation of the "package".
You can extract the archive manually and then load the functions therein with, e.g., source('bivpois.table.R')
, or you can download the .RData file they provide and load that into the workspace with load('.RData')
. This does not install the functions as part of a package; rather, it loads the functions into your global environment, making them temporarily available.
You can download, extract, and load the .RData from R as follows:
download.file('http://stat-athens.aueb.gr/~jbn/papers/files/14/14_bivpois_RDATA.zip',
f <- tempfile())
unzip(f, exdir=tempdir())
load(file.path(tempdir(), '.RData'))
If you want the .RData file to be available in the current working directory, to be loaded in the future, you could use the following instead:
download.file('http://stat-athens.aueb.gr/~jbn/papers/files/14/14_bivpois_RDATA.zip',
f <- tempfile())
unzip(f, exdir=tempdir())
file.copy(file.path(tempdir(), '.RData'), 'bivpois.RData')
# the above copies the .RData file to a file called bivpois.RData in your current
# working directory.
load('bivpois.RData')
In future R sessions, you can just call load('bivpois.RData')
.
Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.
To change the priority of the connections:
Now - no
Prior to Java 7:
Yes, sequence is as follows:
So, if there's code in a static block, it will be executed. But there's no point in doing that.
How to test that:
public final class Test {
static {
System.out.println("FOO");
}
}
Then if you try to run the class (either form command line with java Test
or with an IDE), the result is:
FOO
java.lang.NoSuchMethodError: main
You have to add the FormHttpMessageConverter to your applicationContext.xml to be able to post multipart files.
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
</list>
</property>
</bean>
See http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/converter/FormHttpMessageConverter.html for examples.
As is defined in RFC 1341:
In the Extended BNF notation of RFC 822, a Content-Type header field value is defined as follows:
Content-Type := type "/" subtype *[";" parameter]
type := "application" / "audio" / "image" / "message" / "multipart" / "text" / "video" / x-token
x-token := < The two characters "X-" followed, with no intervening white space, by any token >
subtype := token
parameter := attribute "=" value
attribute := token
value := token / quoted-string
token := 1*
tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in / "," / ";" / ":" / "\" / <"> ; quoted-string, / "/" / "[" / "]" / "?" / "." ; to use within / "=" ; parameter values
And a list of known MIME types that can follow it (or, as Joe remarks, the IANA source).
As you can see the list is way too big for you to validate against all of them. What you can do is validate against the general format and the type
attribute to make sure that is correct (the set of options is small) and just assume that what follows it is correct (and of course catch any exceptions you might encounter when you put it to actual use).
Also note the comment above:
If another primary type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid any potential conflict with a future official name.
You'll notice that a lot of HTTP requests/responses include an X-
header of some sort which are self defined, keep this in mind when validating the types.