In C# 9 Microsoft will introduce a new way to have properties set only on initialization using the init;
method like so:
public class Person
{
public string firstName { get; init; }
public string lastName { get; init; }
}
This way, you can assign values when initializing a new object:
var person = new Person
{
firstname = "John",
lastName = "Doe"
}
But later on, you cannot change it:
person.lastName = "Denver"; // throws a compiler error
The tool NDepend is quoted as Quality Metric Tools but it is pretty much also a Code violation detection tool. Disclaimer: I am one of the developers of the tool
With NDepend, one can write Code Rule over LINQ Queries (what we call CQLinq). More than 200 CQLinq code rules are proposed by default. The strength of CQLinq is that it is straightforward to write a code rule, and get immediately results. Facilities are proposed to browse matched code elements. For example:
Beside that, NDepend comes with many others static analysis like features. These include:
If you include a font file (otf, ttf, etc.) in your package, you can use the font in your application via the method described here:
Oracle Java SE 6: java.awt.Font
There is a tutorial available from Oracle that shows this example:
try {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
} catch (IOException|FontFormatException e) {
//Handle exception
}
I would probably wrap this up in some sort of resource loader though as to not reload the file from the package every time you want to use it.
An answer more closely related to your original question would be to install the font as part of your application's installation process. That process will depend on the installation method you choose. If it's not a desktop app you'll have to look into the links provided.
as per @anaximander s answer but your signup action should look more like
[HttpPost]
public ActionResult SignUp(Account account)
{
if(ModelState.IsValid){
//do something with account
return RedirectToAction("Index");
}
return View("SignUp");
}
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
You can convert yourInt
to bytes by using a ByteBuffer
like this:
return ByteBuffer.allocate(4).putInt(yourInt).array();
Beware that you might have to think about the byte order when doing so.
There are no auto incrementing features in Oracle for a column. You need to create a SEQUENCE object. You can use the sequence like:
insert into table(batch_id, ...) values(my_sequence.nextval, ...)
...to return the next number. To find out the last created sequence nr (in your session), you would use:
my_sequence.currval
This site has several complete examples on how to use sequences.
You didn't add the changes. Either specifically add them via
git add filename1 filename2
or add all changes (from root path of the project)
git add .
or use the shorthand -a
while commiting:
git commit -a -m "message".
You lookup the value of the data with findData()
and then use setCurrentIndex()
QComboBox* combo = new QComboBox;
combo->addItem("100",100.0); // 2nd parameter can be any Qt type
combo->addItem .....
float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found
combo->setCurrentIndex(index);
}
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
R defines a ~
(tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:
library(datasets)
lm( myFormula, data=iris)
help("~")
or help("formula")
will teach you more.
@Spacedman has covered the basics. Let's discuss how it works.
First, being an operator, note that it is essentially a shortcut to a function (with two arguments):
> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs
That can be helpful to know for use in e.g. apply
family commands.
Second, you can manipulate the formula as text:
oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )
Third, you can manipulate it as a list:
myFormula[[2]]
myFormula[[3]]
Finally, there are some helpful tricks with formulae (see help("formula")
for more):
myFormula <- Species ~ .
For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.
When using maven project.
check pom.xml file
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>9</java.version>
</properties>
if you have jdk 8 installed in your machine,
change java.version
property from 9
to 8
in my case, datas
is an objects of Array for more information please Click Here
<% for(let [index,data] of datas.entries() || []){ %>
Index : <%=index%>
Data : <%=data%>
<%} %>
The other examples here work fine for the old versions of ui-router (>=0.3.x) but all state events, such as $stateChangeStart
, are deprecated as of 1.0. The new ui-router 1.0 code uses the $transitions service. So you need to inject $transitions
into your component then use the $transitions.onBefore method as the code below demonstrates.
$transitions.onBefore({}, function(transition) { return confirm("Are you sure you want to leave this page?"); });
This is just a super simple example. The $transitions
service can accept more complicated responses such as promises. See the HookResult type for more information.
No you don't need to check if you're in the main thread. Here is how you can do this in Swift:
runThisInMainThread { () -> Void in
runThisInMainThread { () -> Void in
// No problem
}
}
func runThisInMainThread(block: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), block)
}
Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions
sc.next().charat(0).........is the method of entering character by user based on the number entered at the run time
example: sc.next().charat(2)------------>>>>>>>>
I found this can also occur if the most of the data plotted is outside of the axis limits. In that case, adjust the axis scales accordingly.
Try creating a javascript function which runs this:
document.getElementById("youriframeid").contentWindow.location.reload(true);
Or maybe use an HTML workaround:
<html>
<body>
<center>
<a href="pagename.htm" target="middle">Refresh iframe</a>
<p>
<iframe src="pagename.htm" name="middle">
</p>
</center>
</body>
</html>
Both might be what you're looking for...
There is conditional assignment in Python 2.5 and later - the syntax is not very obvious hence it's easy to miss. Here's how you do it:
x = true_value if condition else false_value
For further reference, check out the Python 2.5 docs.
Try to run dos2unix
on your windows imported files first
I'm extending the solution by Rushi to following (which solved the puzzle for me)
var cellInfo = Grid1.SelectedCells[0];
var content = (cellInfo.Column.GetCellContent(cellInfo.Item) as TextBlock).Text;
selecting Signature Version v1 and v2 both solved the problem for me....try it
$('#availability').find('option:selected').val() // For Value
$('#availability').find('option:selected').text() // For Text
or
$('#availability option:selected').val() // For Value
$('#availability option:selected').text() // For Text
<input type='text' minlength=3 /><br />
if browser supports html5,
it will automatical be validate attributes(minlength) in tag
but Safari(iOS) doesn't working
Yes, it is possible with cmdcolor:
echo \033[32mhi \033[92mworld
hi
will be dark green, and world
- light green.
Comparable
is Fegan
.The method compareTo
you are overidding in it should have a Fegan
object as a parameter whereas you are casting it to a FoodItems
. Your compareTo
implementation should describe how a Fegan
compare to another Fegan
.
FoodItems
implement Comparable
aswell and copy paste your actual compareTo
logic in it.A short summary from my humble knowledge:
There are some easy computational problems (like finding the shortest path between two points in a graph), which can be calculated pretty fast ( O(n^k), where n is the size of the input and k is a constant (in the case of graphs, it's the number of vertexes or edges)).
Other problems, like finding a path that crosses every vertex in a graph or getting the RSA private key from the public key is harder (O(e^n)).
But CS speak tells that the problem is that we cannot 'convert' a non-deterministic Turing-machine to a deterministic one, we can, however, transform non-deterministic finite automatons (like the regex parser) into deterministic ones (well, you can, but the run-time of the machine will take long). That is, we have to try every possible path (usually smart CS professors can exclude a few ones).
It's interesting because nobody even has any idea of the solution. Some say it's true, some say it's false, but there is no consensus. Another interesting thing is that a solution would be harmful for public/private key encryptions (like RSA). You could break them as easily as generating an RSA key is now.
And it's a pretty inspiring problem.
From the example at flexboxfroggy.com:
align-content determines the spacing between lines
align-items determines how the items as a whole are aligned within the container.
When there is only one line, align-content has no effect
install pip, securely download get-pip.py
Then run the following:
python get-pip.py
On Windows, to get Pandas running,follow the step given in following link
https://github.com/svaksha/PyData-Workshop-Sprint/wiki/windows-install-pandas
Accepted answer suggest using nohup. I would rather suggest using pm2. Using pm2 over nohup has many advantages, like keeping the application alive, maintain log files for application and lot more other features. For more detail check this out.
To install pm2 you need to download npm. For Debian based system
sudo apt-get install npm
and for Redhat
sudo yum install npm
Or you can follow these instruction. After installing npm use it to install pm2
npm install pm2@latest -g
Once its done you can start your application by
$ pm2 start app.js # Start, Daemonize and auto-restart application (Node)
$ pm2 start app.py # Start, Daemonize and auto-restart application (Python)
For process monitoring use following commands:
$ pm2 list # List all processes started with PM2
$ pm2 monit # Display memory and cpu usage of each app
$ pm2 show [app-name] # Show all informations about application
Manage processes using either app name or process id or manage all processes together:
$ pm2 stop <app_name|id|'all'|json_conf>
$ pm2 restart <app_name|id|'all'|json_conf>
$ pm2 delete <app_name|id|'all'|json_conf>
Log files can be found in
$HOME/.pm2/logs #contain all applications logs
Binary executable files can also be run using pm2. You have to made a change into the jason file. Change the "exec_interpreter" : "node"
, to "exec_interpreter" : "none".
(see the attributes section).
#include <stdio.h>
#include <unistd.h> //No standard C library
int main(void)
{
printf("Hello World\n");
sleep (100);
printf("Hello World\n");
return 0;
}
Compiling above code
gcc -o hello hello.c
and run it with np2 in the background
pm2 start ./hello
Bootstrap's responsive image class sets max-width
to 100%. This limits its size, but does not force it to stretch to fill parent elements larger than the image itself. You'd have to use the width
attribute to force upscaling.
slice()
works like substring()
with a few different behaviors.
Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);
What they have in common:
start
equals stop
: returns an empty stringstop
is omitted: extracts characters to the end of the stringDistinctions of substring()
:
start > stop
, then substring
will swap those 2 arguments.NaN
, it is treated as if it were 0
.Distinctions of slice()
:
start > stop
, slice()
will return the empty string. (""
)start
is negative: sets char from the end of string, exactly like substr()
in Firefox. This behavior is observed in both Firefox and IE.stop
is negative: sets stop to: string.length – Math.abs(stop)
(original value), except bounded at 0 (thus, Math.max(0, string.length + stop)
) as covered in the ECMA specification.Source: Rudimentary Art of Programming & Development: Javascript: substr() v.s. substring()
Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.
Warning: Non-fast-forwarding has potential side effects as well. Please review https://sandofsky.com/blog/git-workflow.html, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master
.
(From nvie.com, Vincent Driessen, post "A successful Git branching model")
Incorporating a finished feature on develop
Finished features may be merged into the develop branch to add them to the upcoming release:
$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop
The
--no-ff
flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.
Jakub Narebski also mentions the config merge.ff
:
By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set tofalse
, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the--no-ff
option from the command line).
When set to 'only
', only such fast-forward merges are allowed (equivalent to giving the--ff-only
option from the command line).
The fast-forward is the default because:
But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.
In this case, you can end up setting this kind of config file:
[branch "master"]
# This is the list of cmdline options that should be added to git-merge
# when I merge commits into the master branch.
# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.
# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.
mergeoptions = --no-commit --no-ff
The OP adds in the comments:
I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?
Jefromi answers:
I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.
To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.
More generally, I add:
it really depends on your development workflow:
- if it is linear, one branch makes sense.
- If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.
See "When should you branch?"
Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".
Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.
Here's a code snippet that fixes that behavior of IE (v['date'] is a comma separated date-string, e.g. "2010,4,1"):
if($.browser.msie){
$.lst = v['date'].split(',');
$.tmp = new Date(parseInt($.lst[0]),parseInt($.lst[1])-1,parseInt($.lst[2]));
} else {
$.tmp = new Date(v['date']);
}
The previous approach didn't consider that JS Date month is ZERO based...
Sorry for not explaining too much, I'm at work and just thought this might help.
This is similar to other answers, however updated for new available apis and much cleaner. Also, does not assume you're in an Activity Context.
public class MyService extends AnyContextSubclass {
public void postToastMessage(final String message) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
}
});
}
}
It is perfectly fine if you want to go with the display: table-cell
solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;
. flex
is something which has a decent support.
.wrap {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
border: 1px solid #aaa;_x000D_
margin: 10px;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
<span>Align me to the bottom</span>_x000D_
</div>
_x000D_
In the above example, we first set the parent element to display: flex;
and later, we use align-self
to flex-end
. This helps you push the item to the end of the flex
parent.
flex
)If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell;
with vertical-align: bottom;
is enough
div {_x000D_
display: table-cell;_x000D_
vertical-align: bottom;_x000D_
border: 1px solid #f00;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
Try this :
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
This checks if jQuery is available or not, if not it will add one dynamically from path specified.
Ref: Simulate an "include_once" for jQuery
OR
include_once equivalent for js. Ref: https://raw.github.com/kvz/phpjs/master/functions/language/include_once.js
function include_once (filename) {
// http://kevin.vanzonneveld.net
// + original by: Legaev Andrey
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Michael White (http://getsprink.com)
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// - depends on: include
// % note 1: Uses global: php_js to keep track of included files (though private static variable in namespaced version)
// * example 1: include_once('http://www.phpjs.org/js/phpjs/_supporters/pj_test_supportfile_2.js');
// * returns 1: true
var cur_file = {};
cur_file[this.window.location.href] = 1;
// BEGIN STATIC
try { // We can't try to access on window, since it might not exist in some environments, and if we use "this.window"
// we risk adding another copy if different window objects are associated with the namespaced object
php_js_shared; // Will be private static variable in namespaced version or global in non-namespaced
// version since we wish to share this across all instances
} catch (e) {
php_js_shared = {};
}
// END STATIC
if (!php_js_shared.includes) {
php_js_shared.includes = cur_file;
}
if (!php_js_shared.includes[filename]) {
if (this.include(filename)) {
return true;
}
} else {
return true;
}
return false;
}
I wasted a lot of time because of this issue. Finally I found great solution myself. Before I was using .ttf font only. But I added one extra font format .eot that started to work in IE.
I used following code and it worked like charm in all browsers.
@font-face {
font-family: OpenSans;
src: url(assets/fonts/OpenSans/OpenSans-Regular.ttf),
url(assets/fonts/OpenSans/OpenSans-Regular.eot);
}
@font-face {
font-family: OpenSans Bold;
src: url(assets/fonts/OpenSans/OpenSans-Bold.ttf),
url(assets/fonts/OpenSans/OpenSans-Bold.eot);
}
I hope this will help someone.
I believe your problem is this: in your while loop, n is divided by 2, but never cast as an integer again, so it becomes a float at some point. It is then added onto y, which is then a float too, and that gives you the warning.
You should take a look at node-asyncEJS, which is explicitly designed to take the asynchronous nature of node.js into account. It even allows async code blocks inside of the template.
Here an example form the documentation:
<html>
<head>
<% ctx.hello = "World"; %>
<title><%= "Hello " + ctx.hello %></title>
</head>
<body>
<h1><%? setTimeout(function () { res.print("Async Header"); res.finish(); }, 2000) %></h1>
<p><%? setTimeout(function () { res.print("Body"); res.finish(); }, 1000) %></p>
</body>
</html>
SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
MAX([Value])
FOR [Period] IN ([2000], [2001], [2002])
) as pvt
Another way,
SELECT ACCOUNT,
MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account
Simple example:
var userID = data.id;
localStorage.setItem('userID',JSON.stringify(userID));
What you put inside the </dependencies>
tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.
However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>
. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement>
tag.
You can also use the </dependencyManagement>
to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).
Reading all the comments by you, I think you are just trying to display it in a certain format rather than changing the value / casting it to int
.
I think the easiest way to display 12.00
as "12"
would be using string format specifiers.
double val = 12.00;
string displayed_value = val.ToString("N0"); // Output will be "12"
The best part about this solution is, that it will change 1200.00
to "1,200"
(add a comma to it) which is very useful to display amount/money/price of something.
More information can be found here: https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
Use DataFrame.drop and pass it a Series of index labels:
In [65]: df
Out[65]:
one two
one 1 4
two 2 3
three 3 2
four 4 1
In [66]: df.drop(df.index[[1,3]])
Out[66]:
one two
one 1 4
three 3 2
There are multiple ways you can remove/filter the null values from a column in DataFrame.
Lets create a simple DataFrame with below code:
date = ['2016-03-27','2016-03-28','2016-03-29', None, '2016-03-30','2016-03-31']
df = spark.createDataFrame(date, StringType())
Now you can try one of the below approach to filter out the null values.
# Approach - 1
df.filter("value is not null").show()
# Approach - 2
df.filter(col("value").isNotNull()).show()
# Approach - 3
df.filter(df["value"].isNotNull()).show()
# Approach - 4
df.filter(df.value.isNotNull()).show()
# Approach - 5
df.na.drop(subset=["value"]).show()
# Approach - 6
df.dropna(subset=["value"]).show()
# Note: You can also use where function instead of a filter.
You can also check the section "Working with NULL Values" on my blog for more information.
I hope it helps.
A .mat-file is a compressed binary file. It is not possible to open it with a text editor (except you have a special plugin as Dennis Jaheruddin says). Otherwise you will have to convert it into a text file (csv for example) with a script. This could be done by python for example: Read .mat files in Python.
SELECT t1.col table1col, t2.col table2col
FROM table1 t1
JOIN table2 t2 on t1.table1Id = x and t2.table2Id = y
Having a database table without Primary Key is really and will say extremely BAD PRACTICE...so after you add one (ALTER TABLE)
Run this until you don't see any more duplicated records (that is the purpose of HAVING COUNT)
DELETE FROM [TABLE_NAME] WHERE [Id] IN
(
SELECT MAX([Id])
FROM [TABLE_NAME]
GROUP BY [TARGET_COLUMN]
HAVING COUNT(*) > 1
)
SELECT MAX([Id]),[TABLE_NAME], COUNT(*) AS dupeCount
FROM [TABLE_NAME]
GROUP BY [TABLE_NAME]
HAVING COUNT(*) > 1
MAX([Id]) will cause to delete latest records (ones added after first created) in case you want the opposite meaning that in case of requiring deleting first records and leave the last record inserted please use MIN([Id])
You can find using CLI ng --version
As I am using
angular-cli: 1.0.0-beta.28.3
node: 6.10.1
os: darwin x64
Try something like this (FIDDLE)
// record start time
var startTime = new Date();
...
// later record end time
var endTime = new Date();
// time difference in ms
var timeDiff = endTime - startTime;
// strip the ms
timeDiff /= 1000;
// get seconds (Original had 'round' which incorrectly counts 0:28, 0:29, 1:30 ... 1:59, 1:0)
var seconds = Math.round(timeDiff % 60);
// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);
// get minutes
var minutes = Math.round(timeDiff % 60);
// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);
// get hours
var hours = Math.round(timeDiff % 24);
// remove hours from the date
timeDiff = Math.floor(timeDiff / 24);
// the rest of timeDiff is number of days
var days = timeDiff ;
SELECT CONVERT(varchar(11),getdate(),101) -- mm/dd/yyyy
SELECT CONVERT(varchar(11),getdate(),103) -- dd/mm/yyyy
Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST()
function to make it as an character expression because CHARINDEX()
works on character expression.
Also I think there is no need of OR condition.
select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0
then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end
EDIT:
select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end
See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp
You can try :
echo -e "newpasswd123\nnnewpasswd123" | passwd user
ctr+alt+shift+L -> reformat whole file :)
Each resource has references to other resources, either in hierarchy or links, so it's easy to browse around. This is an advantage to the human developing the client, saving he/she from constantly consulting the docs, and offering suggestions. It also means the server can change resource names unilaterally (as long as the client software doesn't hardcode the URLs).
You can CURL your way into any part of the API or use the web browser to navigate resources. Makes debugging and testing integration much easier.
Allows you to specify actions without having to hunt the correct wording. Imagine if OOP getters and setters weren't standardized, and some people used retrieve
and define
instead. You would have to memorize the correct verb for each individual access point. Knowing there's only a handful of verbs available counters that problem.
If you GET
a resource that doesn't exist, you can be sure to get a 404
error in a RESTful API. Contrast it with a non-RESTful API, which may return {error: "Not found"}
wrapped in God knows how many layers. If you need the extra space to write a message to the developer on the other side, you can always use the body of the response.
Imagine two APIs with the same functionality, one following REST and the other not. Now imagine the following clients for those APIs:
RESTful:
GET /products/1052/reviews
POST /products/1052/reviews "5 stars"
DELETE /products/1052/reviews/10
GET /products/1052/reviews/10
HTTP:
GET /reviews?product_id=1052
POST /post_review?product_id=1052 "5 stars"
POST /remove_review?product_id=1052&review_id=10
GET /reviews?product_id=1052&review=10
Now think of the following questions:
If the first call of each client worked, how sure can you be the rest will work too?
There was a major update to the API that may or may not have changed those access points. How much of the docs will you have to re-read?
Can you predict the return of the last query?
You have to edit the review posted (before deleting it). Can you do so without checking the docs?
TL;DR: All well written web sites (/apps) must emit the header X-XSS-Protection: 0
and just forget about this feature. If you want to have extra security that better user agents can provide, use a strict Content-Security-Policy
header.
Long answer:
HTTP header X-XSS-Protection
is one of those things that Microsoft introduced in Internet Explorer 8.0 (MSIE 8) that was supposed to improve security of incorrectly written web sites.
The idea is to apply some kind of heuristics to try to detect reflection XSS attack and automatically neuter the attack.
The problematic part of this is "heuristics" and "neutering". The heuristics causes false positives and neutering cannot be safely done because it causes side-effects that can be used to implement XSS attacks and DoS attacks on perfectly safe web sites.
The bad part is that if a web site does not emit the header X-XSS-Protection
then the browser will behave as if the header X-XSS-Protection: 1
had been emitted. The worst part is that this value is the least-safe value of all possible values for this header!
For a given secure web site (that is, the site does not have reflected XSS vulnerabilities) this "XSS protection" feature allows following attacks:
X-XSS-Protection: 1
allows attacker to selectively block parts of JavaScript and keep rest of the scripts running. This is possible because the heuristics of this feature are simply "if value of any GET parameter is found in the scripting part of the page source, the script will be automatically modified in user agent dependant way". In practice, the attacker can e.g. add parameter disablexss=<script src="framebuster.js"
and the browser will automatically remove the string <script src="framebuster.js"
from the actual page source. Note that the rest of the page continues run and the attacker just removed this part of page security. In practice, any JS in the page source can be modified. For some cases, a page without XSS vulnerability having reflected content can be used to run selected JavaScript on page due the neutering incorrectly turning plain text data into executable JavaScript code. (That is, turn textual data within a normal DOM text node into content of <script>
tag and execute it!)
X-XSS-Protection: 1; mode=block
allows attacker to leak data from the page source by using the behavior of the page as side-channel. For example, if the page contains JavaScript code along the lines of var csrf_secret="521231347843"
, the attacker simply adds an extra parameter e.g. leak=var%20csrf_secret="3
and if the page is NOT blocked, the 3
was incorrect first digit. The attacker tries again, this time leak=var%20csrf_secret="5
and the page loading will be aborted. This allows the attacker to know that the first digit of the secret is 5
. The attacker then continues to guess the next digit. This allows easily brute-forcing of CSRF secrets or any other secret value in the <script>
source.
In the end, if your site is full of XSS reflection attacks, using the default value of 1
will reduce the attack surface a little bit. However, if your site is secure and you don't emit X-XSS-Protection: 0
, your site will be vulnerable with any browser that supports this feature. If you want defense in depth support from browsers against yet-unknown XSS vulnerabilities on your site, use a strict Content-Security-Policy
header and keep sending 0
for this mis-feature. That doesn't open your site to any known vulnerabilities.
Currently this feature is enabled by default in MSIE, Safari and Google Chrome. This used to be enabled in Edge but Microsoft already removed this mis-feature from Edge. Mozilla Firefox never implemented this.
See also:
https://homakov.blogspot.com/2013/02/hacking-facebook-with-oauth2-and-chrome.html https://blog.innerht.ml/the-misunderstood-x-xss-protection/ http://p42.us/ie8xss/Abusing_IE8s_XSS_Filters.pdf https://www.slideshare.net/masatokinugawa/xxn-en https://bugs.chromium.org/p/chromium/issues/detail?id=396544 https://bugs.chromium.org/p/chromium/issues/detail?id=498982
You can also restrict keys to permissible commands (in the authorized_keys file).
I.e. the user would not log in via ssh and then have a restricted set of commands but rather would only be allowed to execute those commands via ssh (e.g. "ssh somehost bin/showlogfile")
CREATE TABLE target_table SELECT * FROM source_table;
It just create a new table with same structure as of source table and also copy all rows from source_table into target_table.
CREATE TABLE target_table SELECT * FROM source_table WHERE condition;
If you need some rows to be copied into target_table, then apply a condition inside where clause
<?php
$dt = new DateTime;
if(isset($_GET['year']) && isset($_GET['week'])) {
$dt->setISODate($_GET['year'], $_GET['week']);
} else {
$dt->setISODate($dt->format('o'), $dt->format('W'));
}
$year = $dt->format('o');
$week = $dt->format('W');
?>
<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a>
<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next Week</a>
<table width="100%" style="height: 75px; border: 1px solid #00A2FF;">
<tr>
<td style="display: table-cell;
vertical-align: middle;
cursor: pointer;
width: 75px;
height: 75px;
border: 4px solid #00A2FF;
border-radius: 50%;">Employee</td>
<?php
do {
echo "<td>" . $dt->format('M') . "<br>" . $dt->format('d M Y') . "</td>\n";
$dt->modify('+1 day');
} while ($week == $dt->format('W'));
?>
</tr>
</table>
The import form and the module declaration need to agree about the shape of the module, about what it exports.
When you write (a suboptimal practice for importing JSON since TypeScript 2.9 when targeting compatible module formatssee note)
declare module "*.json" {
const value: any;
export default value;
}
You are stating that all modules that have a specifier ending in .json
have a single export named default
.
There are several ways you can correctly consume such a module including
import a from "a.json";
a.primaryMain
and
import * as a from "a.json";
a.default.primaryMain
and
import {default as a} from "a.json";
a.primaryMain
and
import a = require("a.json");
a.default.primaryMain
The first form is the best and the syntactic sugar it leverages is the very reason JavaScript has default
exports.
However I mentioned the other forms to give you a hint about what's going wrong. Pay special attention to the last one. require
gives you an object representing the module itself and not its exported bindings.
So why the error? Because you wrote
import a = require("a.json");
a.primaryMain
And yet there is no export named primaryMain
declared by your "*.json"
.
All of this assumes that your module loader is providing the JSON as the default
export as suggested by your original declaration.
Note: Since TypeScript 2.9, you can use the --resolveJsonModule
compiler flag to have TypeScript analyze imported .json
files and provide correct information regarding their shape obviating the need for a wildcard module declaration and validating the presence of the file. This is not supported for certain target module formats.
If you're using Swift, you can create a UILabel extension:
extension UILabel {
@objc var substituteFontName : String {
get { return self.font.fontName }
set { self.font = UIFont(name: newValue, size: self.font.pointSize) }
}
}
And then where you do your appearance proxying:
UILabel.appearance().substituteFontName = applicationFont
There is equivalent Objective-C code using UI_APPEARANCE_SELECTOR
on a property with the name substituteFontName
.
Addition
For the case where you'd want to set bold and regular fonts separately:
extension UILabel {
@objc var substituteFontName : String {
get { return self.font.fontName }
set {
if self.font.fontName.range(of:"Medium") == nil {
self.font = UIFont(name: newValue, size: self.font.pointSize)
}
}
}
@objc var substituteFontNameBold : String {
get { return self.font.fontName }
set {
if self.font.fontName.range(of:"Medium") != nil {
self.font = UIFont(name: newValue, size: self.font.pointSize)
}
}
}
}
Then for your UIAppearance proxies:
UILabel.appearance().substituteFontName = applicationFont
UILabel.appearance().substituteFontNameBold = applicationFontBold
Note: if you're finding that the bold substitution isn't working, it's possible the default font name doesn't contain "Medium". Switch out that string for another match as needed (thanks to Mason in the comments below) .
Nanda's answer wasn't enough in my setup. What I needed to do is:
Using $('[data-whatever="myvalue"]')
will select anything with html attributes, but in newer jQueries it seems that if you use $(...).data(...)
to attach data, it uses some magic browser thingy and does not affect the html, therefore is not discovered by .find
as indicated in the previous answer.
Verify (tested with 1.7.2+) (also see fiddle): (updated to be more complete)
var $container = $('<div><div id="item1"/><div id="item2"/></div>');
// add html attribute
var $item1 = $('#item1').attr('data-generated', true);
// add as data
var $item2 = $('#item2').data('generated', true);
// create item, add data attribute via jquery
var $item3 = $('<div />', {id: 'item3', data: { generated: 'true' }, text: 'Item 3' });
$container.append($item3);
// create item, "manually" add data attribute
var $item4 = $('<div id="item4" data-generated="true">Item 4</div>');
$container.append($item4);
// only returns $item1 and $item4
var $result = $container.find('[data-generated="true"]');
Change your And
s to AndAlso
s
A standard And
will test both expressions. If comp.Container
is Nothing
, then the second expression will raise a NullReferenceException
because you're accessing a property on a null object.
AndAlso
will short-circuit the logical evaluation. If comp.Container
is Nothing
, then the 2nd expression will not be evaluated.
Try cast result to numeric
CAST(sum(cast(datediff(second, IEC.CREATE_DATE, IEC.STATUS_DATE) as float) / 60)
AS numeric(10,2)) TotalSentMinutes
Input
1
2
3
Output
1.00
2.00
3.00
in this link i mentioned before on the comment, read this part :
A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.
this "JOIN FETCH" will have it's effect if you have (fetch = FetchType.LAZY) property for a collection inside entity(example bellow).
And it is only effect the method of "when the query should happen". And you must also know this:
hibernate have two orthogonal notions : when is the association fetched and how is it fetched. It is important that you do not confuse them. We use fetch to tune performance. We can use lazy to define a contract for what data is always available in any detached instance of a particular class.
when is the association fetched --> your "FETCH" type
how is it fetched --> Join/select/Subselect/Batch
In your case, FETCH will only have it's effect if you have department as a set inside Employee, something like this in the entity:
@OneToMany(fetch = FetchType.LAZY)
private Set<Department> department;
when you use
FROM Employee emp
JOIN FETCH emp.department dep
you will get emp
and emp.dep
. when you didnt use fetch you can still get emp.dep
but hibernate will processing another select to the database to get that set of department.
so its just a matter of performance tuning, about you want to get all result(you need it or not) in a single query(eager fetching), or you want to query it latter when you need it(lazy fetching).
Use eager fetching when you need to get small data with one select(one big query). Or use lazy fetching to query what you need latter(many smaller query).
use fetch when :
no large unneeded collection/set inside that entity you about to get
communication from application server to database server too far and need long time
you may need that collection latter when you don't have the access to it(outside of the transactional method/class)
sequence info : max value
SELECT * FROM information_schema.sequences;
sequence info : last value
SELECT * FROM <sequence_name>
Your print
is messing things up, because it resets @@ROWCOUNT
. Whenever you use @@ROWCOUNT
, my advice is to always set it immediately to a variable. So:
DECLARE @RC int;
WHILE @RC > 0 or @RC IS NULL
BEGIN
SET rowcount 5;
UPDATE TableName
SET Value = 'abc1'
WHERE Parameter1 = 'abc' AND Parameter2 = 123 AND Value <> 'abc1';
SET @RC = @@ROWCOUNT;
PRINT(@@ROWCOUNT)
END;
SET rowcount = 0;
And, another nice feature is that you don't need to repeat the update
code.
Not a queue example, but extremely simple :)
class MyHouse {
private boolean pizzaArrived = false;
public void eatPizza(){
synchronized(this){
while(!pizzaArrived){
wait();
}
}
System.out.println("yumyum..");
}
public void pizzaGuy(){
synchronized(this){
this.pizzaArrived = true;
notifyAll();
}
}
}
Some important points:
1) NEVER do
if(!pizzaArrived){
wait();
}
Always use while(condition), because
while(!pizzaExists){ wait(); }
.2) You must hold the lock (synchronized) before invoking wait/nofity. Threads also have to acquire lock before waking.
3) Try to avoid acquiring any lock within your synchronized block and strive to not invoke alien methods (methods you don't know for sure what they are doing). If you have to, make sure to take measures to avoid deadlocks.
4) Be careful with notify(). Stick with notifyAll() until you know what you are doing.
5)Last, but not least, read Java Concurrency in Practice!
You can use maxlength
to limit the length. Normally for numeric input you'd use type="number"
, however this adds a spinny box thing to scroll through numbers, which is completely useless for phone numbers. You can, however, use the pattern
attribute to limit input to numbers (and require 10 numbers too, if you want):
<input type="text" maxlength="10" pattern="\d{10}" title="Please enter exactly 10 digits" />
An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:
public static class FileInfoExtension
{
//second parameter is need to avoid collision with native MoveTo
public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) {
if (autoCreateDirectory)
{
var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));
if (!destinationDirectory.Exists)
destinationDirectory.Create();
}
file.MoveTo(destination);
}
}
Then use brand new MoveTo extension:
using <namespace of FileInfoExtension>;
...
new FileInfo("some path")
.MoveTo("target path",true);
First of all, read the warning! It says do not run composer as root! Secondly, you're probably using Xammp on your local which has the required php libraries as default.
But in your server you're missing ext-dom
. php-xml
has all the related packages you need. So, you can simply install it by running:
sudo apt-get update
sudo apt install php-xml
Most likely you are missing mbstring
too. If you get the error, install this package as well with:
sudo apt-get install php-mbstring
Then run:
composer update
composer require cviebrock/eloquent-sluggable
Here is an answer that avoids using Dictionaries. Since the OP said he is not familiar with them, this might give him a little insight into what Dictionaries do.
The downside to this answer is you have to enforce a limit on the max number in the array, and you can't have negative numbers. You'd never actually use this version in real code.
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int[] count = new int[13];
foreach(int number in array) {
// using the index of count same way you'd use a key in a dictionary
count[number]++;
}
foreach(int c in count) {
int numberCount = count[c];
if(numberCount > 0) {
Console.WriteLine(c + " occurs " + numberCount + " times");
}
}
This can be achieved using the POSIX clock_gettime
function.
In the current version of POSIX, gettimeofday
is marked obsolete. This means it may be removed from a future version of the specification. Application writers are encouraged to use the clock_gettime
function instead of gettimeofday
.
Here is an example of how to use clock_gettime
:
#define _POSIX_C_SOURCE 200809L
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
void print_current_time_with_ms (void)
{
long ms; // Milliseconds
time_t s; // Seconds
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
s = spec.tv_sec;
ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds
if (ms > 999) {
s++;
ms = 0;
}
printf("Current time: %"PRIdMAX".%03ld seconds since the Epoch\n",
(intmax_t)s, ms);
}
If your goal is to measure elapsed time, and your system supports the "monotonic clock" option, then you should consider using CLOCK_MONOTONIC
instead of CLOCK_REALTIME
.
Other answers mainly get all name of object, to get value of property, you can use yourObj[name]
, for example:
var propNames = Object.getOwnPropertyNames(yourObj);
propNames.forEach(
function(propName) {
console.log(
'name: ' + propName
+ ' value: ' + yourObj[propName]);
}
);
Convert the first date stored in a datetime field to a string, then convert the time stored in a datetime field to string, append the two and convert back to a datetime field all using known conversion formats.
Convert(datetime, Convert(char(10), MYDATETIMEFIELD, 103) + ' ' + Convert(char(8), MYTIMEFIELD, 108), 103)
String[] elements = { "a", "a","a","a" };
for( int i=0; i<elements.length-1; i++)
{
String s1 = elements[i];
String s2 = elements[i+1];
}
This is the best one I've found.
Simple change to syntax is all that is needed:
create table ImagenesUsuario (
idImagen int not null identity(1,1) primary key
)
By explicitly using the "constraint" keyword, you can give the primary key constraint a particular name rather than depending on SQL Server to auto-assign a name:
create table ImagenesUsuario (
idImagen int not null identity(1,1) constraint pk_ImagenesUsario primary key
)
Add the "CLUSTERED" keyword if that makes the most sense based on your use of the table (i.e., the balance of searches for a particular idImagen and amount of writing outweighs the benefits of clustering the table by some other index).
I assume that the text "username1" is just a placeholder for what will eventually be an actual username. Assuming that,
span
tag server-side, before sending it to the client, and then just working with the span tags.Just type mbox
then hit tab it will give you a magic shortcut to pump up a message box.
If you're looking to print specific data that you already have access to, whether it's from a Store, AJAX, or available elsewhere, you can leverage my library react-print.
https://github.com/captray/react-print
It makes creating print templates much easier (assuming you already have a dependency on react). You just need to tag your HTML appropriately.
This ID should be added higher up in your actual DOM tree to exclude everything except the "print mount" below.
<div id="react-no-print">
This is where your react-print component will mount and wrap your template that you create:
<div id="print-mount"></div>
An example looks something like this:
var PrintTemplate = require('react-print');
var ReactDOM = require('react-dom');
var React = require('react');
var MyTemplate = React.createClass({
render() {
return (
<PrintTemplate>
<p>Your custom</p>
<span>print stuff goes</span>
<h1>Here</h1>
</PrintTemplate>
);
}
});
ReactDOM.render(<MyTemplate/>, document.getElementById('print-mount'));
It's worth noting that you can create new or utilize existing child components inside of your template, and everything should render fine for printing.
In addition to dplyr::rename
in newer versions of dplyr
is rename_with()
rename_with() renames columns using a function.
You can apply a function over a tidy-select set of columns using the .cols
argument:
iris %>%
dplyr::rename_with(.fn = ~ gsub("^S", "s", .), .cols = where(is.numeric))
sepal.Length sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
The first bin in the FFT is DC (0 Hz), the second bin is Fs / N
, where Fs
is the sample rate and N
is the size of the FFT. The next bin is 2 * Fs / N
. To express this in general terms, the nth bin is n * Fs / N
.
So if your sample rate, Fs
is say 44.1 kHz and your FFT size, N
is 1024, then the FFT output bins are at:
0: 0 * 44100 / 1024 = 0.0 Hz
1: 1 * 44100 / 1024 = 43.1 Hz
2: 2 * 44100 / 1024 = 86.1 Hz
3: 3 * 44100 / 1024 = 129.2 Hz
4: ...
5: ...
...
511: 511 * 44100 / 1024 = 22006.9 Hz
Note that for a real input signal (imaginary parts all zero) the second half of the FFT (bins from N / 2 + 1
to N - 1
) contain no useful additional information (they have complex conjugate symmetry with the first N / 2 - 1
bins). The last useful bin (for practical aplications) is at N / 2 - 1
, which corresponds to 22006.9 Hz in the above example. The bin at N / 2
represents energy at the Nyquist frequency, i.e. Fs / 2
( = 22050 Hz in this example), but this is in general not of any practical use, since anti-aliasing filters will typically attenuate any signals at and above Fs / 2
.
Quick alternative
import timeit
start = timeit.default_timer()
#Your statements here
stop = timeit.default_timer()
print('Time: ', stop - start)
In JQuery:
$("#id option:selected").prop("selected", false);
$("#id").multiselect('refresh');
You could use random.sample
to generate the list with one call:
import random
my_randoms = random.sample(range(100), 10)
That generates numbers in the (inclusive) range from 0 to 99. If you want 1 to 100, you could use this (thanks to @martineau for pointing out my convoluted solution):
my_randoms = random.sample(range(1, 101), 10)
After upgrading the Application. I observed different Cordova versions.
Now i am confused, On which version basis, Google Dev Console is giving warning?
Please migrate your app(s) to Apache Cordova v.4.1.1 or higher as soon as possible and increment the version number of the upgraded APK. Beginning May 9, 2016, Google Play will block publishing of any new apps or updates that use pre-4.1.1 versions of Apache Cordova.
The vulnerabilities were addressed in Apache Cordova 4.1.1. If you’re using a 3rd party library that bundles Apache Cordova, you’ll need to upgrade it to a version that bundles Apache Cordova 4.1.1 or later.
And before upgrading. Our Application versions were these.
Try the following-sibling
axis (following-sibling::td
).
If you don't want to check on upper or lowercases you can use the following method.
String str = "India"
compareString(str)
def compareString(String str){
def str2 = "india"
if( str2.toUpperCase() == str.toUpperCase() ) {
println "same"
}else{
println "not same"
}
}
So now if you change str to "iNdIa" it'll still work, so you lower the chance that you make a typo.
function validateDays() {
if (document.getElementById("option1").checked == true) {
alert("You have selected Option 1");
}
else if (document.getElementById("option2").checked == true) {
alert("You have selected Option 2");
}
else if (document.getElementById("option3").checked == true) {
alert("You have selected Option 3");
}
else {
// DO NOTHING
}
}
When you use --user
option with pip, the package gets installed in user's folder instead of global folder and you won't need to run pip command with admin privileges.
The location of user's packages folder can be found using:
python -m site --user-site
This will print something like:
C:\Users\%USERNAME%\AppData\Roaming\Python\Python35\site-packages
When you don't use --user
option with pip, the package gets installed in global folder given by:
python -c "import site; print(site.getsitepackages())"
This will print something like:
['C:\\Program Files\\Anaconda3', 'C:\\Program Files\\Anaconda3\\lib\\site-packages'
Note: Above printed values are for On Windows 10 with Anaconda 4.x installed with defaults.
This worked for me in Kotlin class
fun hideKeyboard(activity: Activity) {
try {
val inputManager = activity
.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val currentFocusedView = activity.currentFocus
if (currentFocusedView != null) {
inputManager.hideSoftInputFromWindow(currentFocusedView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
Where do these characters occur? Do you see them if you examine the XML data in, say, notepad? Or do you see them when examining the XML data in the debugger. If it is the latter, they are only escape characters for the "
characters, and so part of the actual XML data.
Just use like this somewhere inside the form
@method('PUT')
You might have to use the version in the Lucid partner repository. I did this in Lucid (I used the version from Karmic multiverse, before I realized it had been moved to the partner repo), and it worked fine. Not sure where it went in Maverick though.
According to MSDN, it's 260 characters. It includes "<NUL>"
-the invisible terminating null character, so the actual length is 259.
But read the article, it's a bit more complicated.
Hey my steps to make this work were:
ctrl + shift+ p
and look for preferences: keyboard shortcuts
or you can use ctrl k + ctrl s
to open it directly
Look in the search box for Terminal: Focus Terminal
, I set up for myself alt + T alt + T
but you can select the combination that you want
Look in the search box for View: Focus Active Editor Group
, set up for myself alt + E alt + E
but again you can select the combination that you want
That's it, I hope this help
html using Razor:
@Html.DropDownList("test1", Model.SelectOptionList, new { id = "test1", onchange = "myFunction()" })
JS Code:
function myFunction() {
var value = document.getElementById('test1').value;
console.log("it has been changed! to " + value );
}
Another shorthand to (@maudulus's answer) to remove {maxFractionDigits}
since it's optional.
You can use {{numberExample | number : '1.2'}}
as your service is already setup, simply add a broadcast receiver in your service:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
//action for sms received
}
else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
//action for phone state changed
}
}
};
in your service's onCreate
do this:
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more
registerReceiver(receiver, filter);
and in your service's onDestroy
:
unregisterReceiver(receiver);
and you are good to go to receive broadcast for what ever filters you mention in onCreate
. Make sure to add any permission if required. for e.g.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
This is something you solve in the "controller", which is the point of logicless templating.
// some function that retreived data through ajax
function( view ){
if ( !view.avatar ) {
// DEFAULTS can be a global settings object you define elsewhere
// so that you don't have to maintain these values all over the place
// in your code.
view.avatar = DEFAULTS.AVATAR;
}
// do template stuff here
}
This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)
Another option is to do the following:
// augment view
view.hasAvatar = !!view.avatar;
view.noAvatar = !view.avatar;
And in the template:
{{#hasAvatar}}
SHOW AVATAR
{{/hasAvatar}}
{{#noAvatar}}
SHOW DEFAULT
{{/noAvatar}}
But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)
Are you using C# 3.0? You can use object initializers like so:
static MyStruct[] myArray =
new MyStruct[]{
new MyStruct() { id = 1, label = "1" },
new MyStruct() { id = 2, label = "2" },
new MyStruct() { id = 3, label = "3" }
};
df2 <- df[!names(df) %in% c("c1", "c2")]
From the Mozilla Developer Network:
There is no way to stop or break a
forEach()
loop other than by throwing an exception. If you need such behavior, theforEach()
method is the wrong tool.Early termination may be accomplished with:
- A simple loop
- A
for
...of
loopArray.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()
The other Array methods:
every()
,some()
,find()
, andfindIndex()
test the array elements with a predicate returning a truthy value to determine if further iteration is required.
Yes, right click the project. Click Run as
then Run Configurations
. You can change the parameters passed to the JVM in the Arguments
tab in the VM Arguments
box.
That configuration can then be used as the default when running the project.
I am using this simple one line code for years without a problem (it requires jQuery):
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function ap(x,y) {$("#" + y).load(x);};
function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>
Here ap() means an Ajax page and af() means an Ajax form. In a form, simply calling af() function will post the form to the URL and load the response on the desired HTML element.
<form id="form_id">
...
<input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>
You can use '';
to declaring NULL variable in Javascript
I think this will help : In Controller get the list items and selected value
public ActionResult Edit(int id)
{
ItemsStore item = itemStoreRepository.FindById(id);
ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(),
"Id", "Name",item.CategoryId);
// ViewBag to pass values to View and SelectList
//(get list of items,valuefield,textfield,selectedValue)
return View(item);
}
and in View
@Html.DropDownList("CategoryId",String.Empty)
Yeild
keyword in javaScript function makes it generator,
what is generator in javaScript?
A generator is a function that produces a sequence of results instead of a single value, i.e you generate ?a series of values
Meaning generators helps us work asynchronously with the help iterators, Oh now what the hack iterators are? really?
Iterators are mean through which we are able to access items one at a time
from where iterator help us accessing item one at a time? it help us accessing items through generator functions,
generator functions are those in which we use yeild
keyword, yield keyword help us in pausing and resuming execution of function
here is quick example
function *getMeDrink() {
let question1 = yield 'soda or beer' // execution will pause here because of yield
if (question1 == 'soda') {
return 'here you get your soda'
}
if (question1 == 'beer') {
let question2 = yield 'Whats your age' // execution will pause here because of yield
if (question2 > 18) {
return "ok you are eligible for it"
} else {
return 'Shhhh!!!!'
}
}
}
let _getMeDrink = getMeDrink() // initialize it
_getMeDrink.next().value // "soda or beer"
_getMeDrink.next('beer').value // "Whats your age"
_getMeDrink.next('20').value // "ok you are eligible for it"
_getMeDrink.next().value // undefined
let me brifly explain what is going on
you noticed execution is being paused at each yeild
keyword
and we are able to access first yield
with help of iterator .next()
this iterates to all yield
keywords one at a time and then returns undefined when there is no more yield
keywords left
in simple words you can say yield
keyword is break point where function each time pauses and only resume when call it using iterator
for our case: _getMeDrink.next()
this is example of iterator that is helping us accessing each break point in function
Example of Generators:
async/await
if you see implementation of async/await
you will see generator functions & promises
are used to make async/await
work
please point out any suggestions is welcomed
var type={
format:"DD, d MM, yy"
};
$('.classname').datepicker(type.format);
Posting this as an answer because my comments above got hidden:
List the size of a container:
du -d 2 -h /var/lib/docker/devicemapper | grep `docker inspect -f "{{.Id}}" <container_name>`
List the sizes of a container's volumes:
docker inspect -f "{{.Volumes}}" <container_name> | sed 's/map\[//' | sed 's/]//' | tr ' ' '\n' | sed 's/.*://' | xargs sudo du -d 1 -h
Edit: List all running containers' sizes and volumes:
for d in `docker ps -q`; do
d_name=`docker inspect -f {{.Name}} $d`
echo "========================================================="
echo "$d_name ($d) container size:"
sudo du -d 2 -h /var/lib/docker/devicemapper | grep `docker inspect -f "{{.Id}}" $d`
echo "$d_name ($d) volumes:"
docker inspect -f "{{.Volumes}}" $d | sed 's/map\[//' | sed 's/]//' | tr ' ' '\n' | sed 's/.*://' | xargs sudo du -d 1 -h
done
NOTE: Change 'devicemapper' according to your Docker filesystem (e.g 'aufs')
You could prove to yourself that there is no other difference by trying to define a function in a struct. I remember even my college professor who was teaching about structs and classes in C++ was surprised to learn this (after being corrected by a student). I believe it, though. It was kind of amusing. The professor kept saying what the differences were and the student kept saying "actually you can do that in a struct too". Finally the prof. asked "OK, what is the difference" and the student informed him that the only difference was the default accessibility of members.
A quick Google search suggests that POD stands for "Plain Old Data".
Did you try this in your routes.php ?
Route::group(['middleware' => ['web']], function () {
//
Route::get('/','HomeController@index');
});
Path.GetFullPath(@"c:\windows\temp\..\system32")?
OP, YOU ARE CORRECT. The else after try/except in Python is ugly. it leads to another flow-control object where none is needed:
try:
x = blah()
except:
print "failed at blah()"
else:
print "just succeeded with blah"
A totally clear equivalent is:
try:
x = blah()
print "just succeeded with blah"
except:
print "failed at blah()"
This is far clearer than an else clause. The else after try/except is not frequently written, so it takes a moment to figure what the implications are.
Just because you CAN do a thing, doesn't mean you SHOULD do a thing.
Lots of features have been added to languages because someone thought it might come in handy. Trouble is, the more features, the less clear and obvious things are because people don't usually use those bells and whistles.
Just my 5 cents here. I have to come along behind and clean up a lot of code written by 1st-year out of college developers who think they're smart and want to write code in some uber-tight, uber-efficient way when that just makes it a mess to try and read / modify later. I vote for readability every day and twice on Sundays.
We had exactly the same challenge some time ago. We wanted to go with CEF3 open source library which is WPF-based and supports .NET 3.5.
Firstly, the author of CEF himself listed binding for different languages here.
Secondly, we went ahead with open source .NET CEF3 binding which is called Xilium.CefGlue and had a good success with it. In cases where something is not working as you'd expect, author usually very responsive to the issues opened in build-in bitbucket tracker
So far it has served us well. Author updates his library to support latest CEF3 releases and bug fixes on regular bases.
Something like this should work (it did for me). The reason for wanting to use -Filter
instead of -Include
is that include takes a huge performance hit compared to -Filter
.
Below just loops each file type and multiple servers/workstations specified in separate files.
##
## This script will pull from a list of workstations in a text file and search for the specified string
## Change the file path below to where your list of target workstations reside
## Change the file path below to where your list of filetypes reside
$filetypes = gc 'pathToListOffiletypes.txt'
$servers = gc 'pathToListOfWorkstations.txt'
##Set the scope of the variable so it has visibility
set-variable -Name searchString -Scope 0
$searchString = 'whatYouAreSearchingFor'
foreach ($server in $servers)
{
foreach ($filetype in $filetypes)
{
## below creates the search path. This could be further improved to exclude the windows directory
$serverString = "\\"+$server+"\c$\Program Files"
## Display the server being queried
write-host “Server:” $server "searching for " $filetype in $serverString
Get-ChildItem -Path $serverString -Recurse -Filter $filetype |
#-Include "*.xml","*.ps1","*.cnf","*.odf","*.conf","*.bat","*.cfg","*.ini","*.config","*.info","*.nfo","*.txt" |
Select-String -pattern $searchstring | group path | select name | out-file f:\DataCentre\String_Results.txt
$os = gwmi win32_operatingsystem -computer $server
$sp = $os | % {$_.servicepackmajorversion}
$a = $os | % {$_.caption}
## Below will list again the server name as well as its OS and SP
## Because the script may not be monitored, this helps confirm the machine has been successfully scanned
write-host $server “has completed its " $filetype "scan:” “|” “OS:” $a “SP:” “|” $sp
}
}
#end script
button.setOnClickListener {
//write your code here
}
The simplest solution is :
listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
listView.setStackFromBottom(true);
My case was a database corruption after a minor upgrade in mysql basically 5.0.x to 5.1.x with the DB in myisam. The same lines on query: MySQL server has gone away Error reading result set's header
After repairing & optimizing it with mysqlcheck, it returned to normal, without the need to change the socket timeout.
one liner
$object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));
You could do like this too. It worked out for me.
<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
<select id="selectDuration" name="selectDuration[]" multiple="multiple">
<option value="1 WEEK" >Last 1 Week</option>
<option value="2 WEEK" >Last 2 Week </option>
<option value="3 WEEK" >Last 3 Week</option>
<option value="4 WEEK" >Last 4 Week</option>
<option value="5 WEEK" >Last 5 Week</option>
<option value="6 WEEK" >Last 6 Week</option>
</select>
<input type="submit"/>
</form>
Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.
$shift=$_POST['selectDuration'];
print_r($shift);
Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.
[Update] As mentioned by @Aftershock in the comments, util.pump
is gone and was replaced with a method on the Stream prototype called pipe
; the code below reflects this.
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
})
.listen(2000);
Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/
You can use ftw(3)
or nftw(3)
to walk a filesystem hierarchy in C or C++ on POSIX systems.
Just do a random click on any non input item. Keyboard will disappear.
It might be easier for you to understand using Functionoids which are expressively neater and more powerful to use, see this excellent and highly recommended C++ FAQ lite, in particular, look at section 33.12 onwards, but nonetheless, read it from the start of that section to gain a grasp and understanding of it.
To answer your question:
typedef void (*foobar)() fubarfn;
void Fun(fubarfn& baz){
fubarfn = baz;
baz();
}
Edit:
&
means the reference address*
means the value of what's contained at the reference address, called de-referencingSo using the reference, example below, shows that we are passing in a parameter, and directly modify it.
void FunByRef(int& iPtr){
iPtr = 2;
}
int main(void){
// ...
int n;
FunByRef(n);
cout << n << endl; // n will have value of 2
}
If you want to use @OverZealous' answer (https://stackoverflow.com/a/21806974/1019307) in Typescript, you need to import
instead of require
:
import * as debug from 'gulp-debug';
...
return gulp.src('./examples/*.html')
.pipe(debug({title: 'example src:'}))
.pipe(gulp.dest('./build'));
(I also added a title
).
Finally create a onBackPressedMethod as Follows:
@Override
public void onBackPressed() {
if (exitToast.getView().isShown()) {
exitToast.cancel();
finish();
} else {
exitToast.show();
}
}
This works correctly, i have tested. and I think this is much simpler.
MySQL way:
CREATE TABLE recipes_new LIKE production.recipes;
INSERT recipes_new SELECT * FROM production.recipes;
Specifying auto on width and height elements is the same as removing them, technically. Using vanilla Javascript:
images[i].style.height = "auto";
images[i].style.width = "auto";
Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.
A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt
and jshint
.
These lines add more meaning
Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.
Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:
There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.
Please Note that grunt plugin is also an npm package.
Question-1
When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json
It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.
Question-2
When should I ever install packages explicitly like that without adding them to the file that manages dependencies
It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request
, then you have two options:
OR
npm install --save request
--save
options adds the dependency to package.json file as well. If you don't specify --save
option, it will only download the package but the json file will be unaffected.
You can do this either way, there will not be a substantial difference.
For me, the most flexible way to run PowerShell script from C# was using PowerShell.Create().AddScript()
The snippet of the code is
string scriptDirectory = Path.GetDirectoryName(
ConfigurationManager.AppSettings["PathToTechOpsTooling"]);
var script =
"Set-Location " + scriptDirectory + Environment.NewLine +
"Import-Module .\\script.psd1" + Environment.NewLine +
"$data = Import-Csv -Path " + tempCsvFile + " -Encoding UTF8" +
Environment.NewLine +
"New-Registration -server " + dbServer + " -DBName " + dbName +
" -Username \"" + user.Username + "\" + -Users $userData";
_powershell = PowerShell.Create().AddScript(script);
_powershell.Invoke<User>();
foreach (var errorRecord in _powershell.Streams.Error)
Console.WriteLine(errorRecord);
You can check if there's any error by checking Streams.Error. It was really handy to check the collection. User is the type of object the PowerShell script returns.
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
Emacs would be better if it had a text editor in it... :-)
I would like to add, [ngValue]="..." support strings, but you need to add simple quotes if it represents a number, like [ngValue]="'...'". It was to complement the Günter Zöchbauer answer.
var
variables still have a type - and the compiler error message says this type must be established during the declaration.
The specific request (assigning an initial null value) can be done, but I don't recommend it. It doesn't provide an advantage here (as the type must still be specified) and it could be viewed as making the code less readable:
var x = (String)null;
Which is still "type inferred" and equivalent to:
String x = null;
The compiler will not accept var x = null
because it doesn't associate the null with any type - not even Object. Using the above approach, var x = (Object)null
would "work" although it is of questionable usefulness.
Generally, when I can't use var
's type inference correctly then
The second approach can be done by moving code into methods or functions.
Following the argument about Math.ceil(value/10d)
and (value+9)/10
I ended up coding a proper non-dead code, non-interpret mode benchmark.
I've been telling that writing micro benchmark is not an easy task. The code below illustrates this:
00:21:40.109 starting up....
00:21:40.140 doubleCeil: 19444599
00:21:40.140 integerCeil: 19444599
00:21:40.140 warming up...
00:21:44.375 warmup doubleCeil: 194445990000
00:21:44.625 warmup integerCeil: 194445990000
00:22:27.437 exec doubleCeil: 1944459900000, elapsed: 42.806s
00:22:29.796 exec integerCeil: 1944459900000, elapsed: 2.363s
The benchmark is in Java since I know well how Hotspot optimizes and ensures it's a fair result. With such results, no statistics, noise or anything can taint it.
Integer ceil is insanely much faster.
The code
package t1;
import java.math.BigDecimal;
import java.util.Random;
public class Div {
static int[] vals;
static long doubleCeil(){
int[] v= vals;
long sum = 0;
for (int i=0;i<v.length;i++){
int value = v[i];
sum+=Math.ceil(value/10d);
}
return sum;
}
static long integerCeil(){
int[] v= vals;
long sum = 0;
for (int i=0;i<v.length;i++){
int value = v[i];
sum+=(value+9)/10;
}
return sum;
}
public static void main(String[] args) {
vals = new int[7000];
Random r= new Random(77);
for (int i = 0; i < vals.length; i++) {
vals[i] = r.nextInt(55555);
}
log("starting up....");
log("doubleCeil: %d", doubleCeil());
log("integerCeil: %d", integerCeil());
log("warming up...");
final int warmupCount = (int) 1e4;
log("warmup doubleCeil: %d", execDoubleCeil(warmupCount));
log("warmup integerCeil: %d", execIntegerCeil(warmupCount));
final int execCount = (int) 1e5;
{
long time = System.nanoTime();
long s = execDoubleCeil(execCount);
long elapsed = System.nanoTime() - time;
log("exec doubleCeil: %d, elapsed: %.3fs", s, BigDecimal.valueOf(elapsed, 9));
}
{
long time = System.nanoTime();
long s = execIntegerCeil(execCount);
long elapsed = System.nanoTime() - time;
log("exec integerCeil: %d, elapsed: %.3fs", s, BigDecimal.valueOf(elapsed, 9));
}
}
static long execDoubleCeil(int count){
long sum = 0;
for(int i=0;i<count;i++){
sum+=doubleCeil();
}
return sum;
}
static long execIntegerCeil(int count){
long sum = 0;
for(int i=0;i<count;i++){
sum+=integerCeil();
}
return sum;
}
static void log(String msg, Object... params){
String s = params.length>0?String.format(msg, params):msg;
System.out.printf("%tH:%<tM:%<tS.%<tL %s%n", new Long(System.currentTimeMillis()), s);
}
}
After Commenting
// [DataType(DataType.DateTime)]
Use the Data Annotation Attribute:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
STEP-7 of the following link may help you...
http://ilyasmamunbd.blogspot.com/2014/12/jquery-datepicker-in-aspnet-mvc-5.html
Just cd
to your working folder and then start the IPython notebook server
. This way you can be mobile.
Very easy, trial and error. Go to the cell you want the month in. Type the Month, go to the next cell and type the year, something weird will come up but then go to your number section click on the little arrow in the right bottom and highlight text and it will change to the year you originally typed
Your connection string is wrong
<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
There is one rule that is set by font-awesome.css
, which you need to override.
You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline;
by default and which I've corrected here:
<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:
I've downsized the font-size of the icon above in this instance to 30px
, as it feels too big at 40px
for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:
<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:
During debugging I find it useful to put a table at the bottom of each of my pages to show all ModelState errors.
<table class="model-state">
@foreach (var item in ViewContext.ViewData.ModelState)
{
if (item.Value.Errors.Any())
{
<tr>
<td><b>@item.Key</b></td>
<td>@((item.Value == null || item.Value.Value == null) ? "<null>" : item.Value.Value.RawValue)</td>
<td>@(string.Join("; ", item.Value.Errors.Select(x => x.ErrorMessage)))</td>
</tr>
}
}
</table>
<style>
table.model-state
{
border-color: #600;
border-width: 0 0 1px 1px;
border-style: solid;
border-collapse: collapse;
font-size: .8em;
font-family: arial;
}
table.model-state td
{
border-color: #600;
border-width: 1px 1px 0 0;
border-style: solid;
margin: 0;
padding: .25em .75em;
background-color: #FFC;
}
</style>
Is this issue resolved.
I am getting this error: ERROR in node_modules/ngx-restangular/lib/ngx-restangular-http.d.ts(3,27): error TS2307: Cannot find module '@angular/common/http/src/response'.
After updating my angular to version=8
You need to edit your my.cnf
file and make sure you have the port set as in the following line:
port = 3360
Then restart your MySQL service and you should be good to go. There is no query you can run to make this change because the port
is not a dynamic variable (q.v. here for MySQL documentation showing a table of all system variables).
If you're a FP (functional programming) fan, Ramda has a neat helper function for this called defaultTo :
usage:
const result = defaultTo(30)(value)
It's more useful when dealing with undefined
boolean values:
const result2 = defaultTo(false)(dashboard.someValue)
Request.Url.Host
You can use HttpPost, there are methods to add Header to the Request.
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("header-name" , "header-value");
HttpResponse response = httpclient.execute(httpPost);
$ foo="/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
1
$ foo="[email protected]:/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
0
Yep, that would be the enumerate
function! Or more to the point, you need to do:
list(enumerate([3,7,19]))
[(0, 3), (1, 7), (2, 19)]
SearchTools-Avi said "MySQL text search, which doesn't even index words of three letters or fewer."
FYIs, The MySQL fulltext min word length is adjustable since at least MySQL 5.0. Google 'mysql fulltext min length' for simple instructions.
That said, MySQL fulltext has limitations: for one, it gets slow to update once you reach a million records or so, ...
Our HTML:
<div id="addnew">
<input type="text" id="id">
<input type="text" id="content">
<input type="button" value="Add" id="submit">
</div>
<div id="check">
<input type="text" id="input">
<input type="button" value="Search" id="search">
</div>
JS (writing to the txt file):
function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
var id = document.getElementById("id").value;
var content = document.getElementById("content").value;
writeToFile(id, content);
}
checking a particular row:
function readFile(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
var input = document.getElementById("input").value;
if (input != "") {
var text = readFile();
var lines = text.split("\r");
lines.pop();
var result;
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(new RegExp(input))) {
result = "Found: " + lines[i].split(",")[1];
}
}
if (result) { alert(result); }
else { alert(input + " not found!"); }
}
}
Put these inside a .hta
file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.
Go into the /bin directory and type:
chown -R $(whoami):admin /usr/local/bin
From MSDN:
This property returns null in the following cases:
1) if the specified key is not found;
So you can just:
NameValueCollection collection = ...
string value = collection[key];
if (value == null) // key doesn't exist
2) if the specified key is found and its associated value is null.
collection[key]
calls base.Get()
then base.FindEntry()
which internally uses Hashtable
with performance O(1).
Check your routing method:
if your routing state is like this
.state('app.register', {
url: '/register',
views: {
'menuContent': {
templateUrl: 'templates/register.html',
}
}
})
then you should use
$location.path("/app/register");
Considering that (x != x) is not always guaranteed for NaN (such as if using the -ffast-math option), I've been using:
#define IS_NAN(x) (((x) < 0) == ((x) >= 0))
Numbers can't be both < 0 and >= 0, so really this check only passes if the number is neither less than, nor greater than or equal to zero. Which is basically no number at all, or NaN.
You could also use this if you prefer:
#define IS_NAN(x) (!((x)<0) && !((x)>=0)
I'm not sure how this is affected by -ffast-math though, so your mileage may vary.
------------------in centos-------------------------
yum provides php-xml
yum install php70u-xml-7.0.14-2.ius.centos7.x86_64
DataRow[] dtr=dtPerson.select("name=Joe");
foreach(var drow in dtr)
{
drow.delete();
}
dtperson.AcceptChanges();
I hope it will help you
It’s doing integer division. You can use to_f
to force things into floating-point mode:
9.to_f / 5 #=> 1.8
9 / 5.to_f #=> 1.8
This also works if your values are variables instead of literals. Converting one value to a float is sufficient to coerce the whole expression to floating point arithmetic.
An accessed dictionary value (a list in this case) is the original value, separate from the dictionary which is used to access it. You would increment the values in the list the same way whether it's in a dictionary or not:
l = dictionary.get('C1')
for i in range(len(l)):
l[i] += 10
Just found a jsperf you may consider interesting in light of this matter. (it could be handy to keep it around to complete the picture)
It compares delete, setting null and setting undefined.
But keep in mind that it tests the case when you delete/set property many times.
In your svn\repos\YourRepo\conf folder you will find two files, authz and passwd. These are the two you need to adjust.
In the passwd file you need to add some usernames and passwords. I assume you have already done this since you have people using it:
[users]
User1=password1
User2=password2
Then you want to assign permissions accordingly with the authz file:
Create the conceptual groups you want, and add people to it:
[groups]
allaccess = user1
someaccess = user2
Then choose what access they have from both the permissions and project level.
So let's give our "all access" guys all access from the root:
[/]
@allaccess = rw
But only give our "some access" guys read-only access to some lower level project:
[/someproject]
@someaccess = r
You will also find some simple documentation in the authz and passwd files.
You can omit the -jar
option and start the jar file like this:
java -cp MyJar.jar;C:\externalJars\* mainpackage.MyMainClass
A cookie is a bit of data stored by the browser and sent to the server with every request.
A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)
Take a look at Simpleaudio, which is a relatively recent and lightweight library for this purpose:
> pip install simpleaudio
Then:
import simpleaudio as sa
wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()
Make sure to use uncompressed 16 bit PCM files.
I would recommend Apache HTTPClient.
The numpy and scipy libraries include the composite trapezoidal (numpy.trapz) and Simpson's (scipy.integrate.simps) rules.
Here's a simple example. In both trapz
and simps
, the argument dx=5
indicates that the spacing of the data along the x axis is 5 units.
from __future__ import print_function
import numpy as np
from scipy.integrate import simps
from numpy import trapz
# The y values. A numpy array is used here,
# but a python list could also be used.
y = np.array([5, 20, 4, 18, 19, 18, 7, 4])
# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=5)
print("area =", area)
# Compute the area using the composite Simpson's rule.
area = simps(y, dx=5)
print("area =", area)
Output:
area = 452.5
area = 460.0
This is called Double checked locking mechanism, first, we will check whether the instance is created or not. If not then only we will synchronize the method and create the instance. It will drastically improve the performance of the application. Performing lock is heavy. So to avoid the lock first we need to check the null value. This is also thread safe and it is the best way to achieve the best performance. Please have a look at the following code.
public sealed class Singleton
{
private static readonly object Instancelock = new object();
private Singleton()
{
}
private static Singleton instance = null;
public static Singleton GetInstance
{
get
{
if (instance == null)
{
lock (Instancelock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
Using a
instead of w
should let you update the file instead of creating a new one/overwriting everything in the existing file.
See this answer for a difference in the modes.
Might be worth checking online for the errata section for your book.
There's an example of handling this exception here http://www.dba-oracle.com/sf_ora_01403_no_data_found.htm
The list selector drawable is a StateListDrawable
— it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...
While you can retrieve the drawable using getSelector()
, I don't believe you can retrieve a specific Drawable
from a StateListDrawable
, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable
anyway.
As for setting the colour, you need a StateListDrawable
as described above. You can set this on your list using the android:listSelector
attribute, defining the drawable in XML like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:state_focused="true"
android:drawable="@drawable/item_disabled" />
<item android:state_pressed="true"
android:drawable="@drawable/item_pressed" />
<item android:state_focused="true"
android:drawable="@drawable/item_focused" />
</selector>
With
git config -l
, I now see I have acredential.helper=osxkeychain
option
That means the credential helper (initially introduced in 1.7.10) is now in effect, and will cache automatically the password for accessing a remote repository over HTTP.
(as in "GIT: Any way to set default login credentials?")
You can disable that option entirely, or only for a single repo.
e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.
See http://unixpapa.com/js/key.html for more information.
update table_name
set cod_user =
CASE
WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'?
END,date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
Google play store provides closed testing track
to test your application with a limited set of testers pre-defined in the tester's list known as Alpha Testing
. Here are some important things to be considered to use alpha testing.
Important
After publishing an alpha/beta app for the first time, it may take a few hours for your test link to be available to testers. If you publish additional changes, they may take several hours to be available for testers
CSV
file to bulk add and remove. The list of defined email addresses will be eligible for testing the app, here you can a control whom to provide the app for testing. Hence, this is known as Closed Testing
.YOUR PACKAGE NAME
stagged roll-out
. In stagged roll-out, the publisher publishes by the percentage of users, to better analyze the user response.Alpha Country Availability
. It gives more precise control over testers.I think this one is working. Recording a video or audio;
<input type="file" accept="video/*;capture=camcorder">
<input type="file" accept="audio/*;capture=microphone">
or (new method)
<device type="media" onchange="update(this.data)"></device>
<video autoplay></video>
<script>
function update(stream) {
document.querySelector('video').src = stream.url;
}
</script>
If it is not, probably will work on ios6, more detail can be found at get user media
Using wrap=virtual
in your HTML form boxes gets rid of the horizontal scrollbar at the bottom of the box:
<textarea name= "enquiry" rows="4" cols="30" wrap="virtual"></textarea>
See example here : http://jsbin.com/opube3/2 (Tested on FF and IE)
Here's some info from my blog on how I like to use formular1c1 outside of vba:
You’ve just finished writing a formula, copied it to the whole spreadsheet, formatted everything and you realize that you forgot to make a reference absolute: every formula needed to reference Cell B2 but now, they all reference different cells.
How are you going to do a Find/Replace on the cells, considering that one has B5, the other C12, the third D25, etc., etc.?
The easy way is to update your Reference Style to R1C1. The R1C1 reference works with relative positioning: R marks the Row, C the Column and the numbers that follow R and C are either relative positions (between [ ]) or absolute positions (no [ ]).
Examples:
What does it matter? Well, When you wrote your first formula back in the beginning of this post, B2 was the cell 4 rows above the cell you wrote it in, i.e. R[-4]C. When you copy it across and down, while the A1 reference changes, the R1C1 reference doesn’t. Throughout the whole spreadsheet, it’s R[-4]C. If you switch to R1C1 Reference Style, you can replace R[-4]C by R2C2 ($B$2) with a simple Find / Replace and be done in one fell swoop.
I am using this from PowerShell:
dir -directory -name -recurse > list_my_folders.txt
If the culture of the result doesn't matters or we're only talking of integer values, CONVERT
or CAST
will be fine.
However, if the result must match a specific culture, FORMAT
might be the function to go:
DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value) --> 1505.5698
SELECT FORMAT(@value, 'N2', 'en-us') --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de') --> 1.505,57
For more information on FORMAT
see here.
Of course, formatting the result should be a matter of the UI layer of the software.
This works for me:
var object = { a: 4, b: 0.5 , c: 0.35, d: 5 };
// Take all value from the object into list
var valueList = $.map(object,function(v){
return v;
});
var max = valueList.reduce(function(a, b) { return Math.max(a, b); });
var min = valueList.reduce(function(a, b) { return Math.min(a, b); });
The title of this thread asks how a subquery can be used in an update. Here's an example of that:
update [dbName].[dbo].[MyTable]
set MyColumn = 1
where
(
select count(*)
from [dbName].[dbo].[MyTable] mt2
where
mt2.ID > [dbName].[dbo].[MyTable].ID
and mt2.Category = [dbName].[dbo].[MyTable].Category
) > 0
Using ES6 solution
For those still reading this answer, if you are using ES6 the find
method was added in arrays. So assuming the same collection, the solution'd be:
const foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
foo.results.find(item => item.id === 2)
I'd totally go for this solution now, as is less tied to angular or any other framework. Pure Javascript.
Angular solution (old solution)
I aimed to solve this problem by doing the following:
$filter('filter')(foo.results, {id: 1})[0];
A use case example:
app.controller('FooCtrl', ['$filter', function($filter) {
var foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
// We filter the array by id, the result is an array
// so we select the element 0
single_object = $filter('filter')(foo.results, function (d) {return d.id === 2;})[0];
// If you want to see the result, just check the log
console.log(single_object);
}]);
Plunker: http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview
If you are using pl/sql then the following code should work :
set server output on -- to retrieve and display a buffer
DECLARE
v_text VARCHAR2(10); -- declare
BEGIN
v_text := 'Hello'; --assign
dbms_output.Put_line(v_text); --display
END;
/
-- this must be use to execute pl/sql script
echo -e "hello\c" ;sleep 1 ; echo -e "\rbye "
What the above command will do :
It will print hello and the cursor will remain at "o" (using \c)
Then it will wait for 1 sec (sleep 1)
Then it will replace hello with bye.(using \r)
NOTE : Using ";", We can run multiple command in a single go.
I would put this as a comment, but I don't have the rep for it. What Josh Crozier answered is correct, but for IE .cur and .ani are the only supported formats for this. So you should probably have a fallback just in case:
.test {
cursor:url("http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif"), url(foo.cur), auto;
}
Encoding an image to base64 will make it about 30% bigger.
See the details in the wikipedia article about the Data URI scheme, where it states:
Base64-encoded data URIs are 1/3 larger in size than their binary equivalent. (However, this overhead is reduced to 2-3% if the HTTP server compresses the response using gzip)
I think the default place for access logs is
%SystemDrive%\inetpub\logs\LogFiles
Otherwise, check under IIS Manager, select the computer on the left pane, and in the middle pane, go under "Logging" in the IIS area. There you will se the default location for all sites (this is however overridable on all sites)
You could also look into
%SystemDrive%\Windows\System32\LogFiles\HTTPERR
Which will contain similar log files that only represents errors.
You can use document.evaluate
:
Evaluates an XPath expression string and returns a result of the specified type if possible.
It is w3-standardized and whole documented: https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate
function getElementByXpath(path) {_x000D_
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;_x000D_
}_x000D_
_x000D_
console.log( getElementByXpath("//html[1]/body[1]/div[1]") );
_x000D_
<div>foo</div>
_x000D_
https://gist.github.com/yckart/6351935
There's also a great introduction on mozilla developer network: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate
Alternative version, using XPathEvaluator
:
function getElementByXPath(xpath) {_x000D_
return new XPathEvaluator()_x000D_
.createExpression(xpath)_x000D_
.evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE)_x000D_
.singleNodeValue_x000D_
}_x000D_
_x000D_
console.log( getElementByXPath("//html[1]/body[1]/div[1]") );
_x000D_
<div>foo/bar</div>
_x000D_
I'm using the following trick to stop HTML5 video. pause() the video on modal close and set currentTime = 0;
<script>
var video = document.getElementById("myVideoPlayer");
function stopVideo(){
video.pause();
video.currentTime = 0;
}
</script>
Now you can use stopVideo() method to stop HTML5 video. Like,
$("#stop").on('click', function(){
stopVideo();
});
As others explained, the toString
is not the place to be instantiating your class. Instead, the toString
method is intended to build a string representing the value of an instance of your class, reporting on at least the most important fields of data stored in that object. In most cases, toString
is used for debugging and logging, not for your business logic.
To generate text representing the value of an object for display to a user, add another method. People often name the method something like getDisplayName
. For example, DayOfWeek::getDisplayName
and Month::getDisplayName
.
StringJoiner
As of Java 8 and later, the most modern way to implement toString
would use the StringJoiner
class. As the doc says:
StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
Use like this:
@Override
public String toString ()
{
return new StringJoiner( // In Java 8 and later, StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
" | " , // Delimiter
Person.class.getSimpleName() + "[ " , // Prefix
" ]" // Suffix
)
.add( "name=" + name ) // Append
.add( "phone=" + phone ) // Append
.toString(); // Convert entire sequence to a single `String` object.
}
Person[ name=Alice | phone=555.867.5309 ]
I won't address the READ UNCOMMITTED
argument, just your original question.
Yes, you need WITH(NOLOCK)
on each table of the join. No, your queries are not the same.
Try this exercise. Begin a transaction and insert a row into table1 and table2. Don't commit or rollback the transaction yet. At this point your first query will return successfully and include the uncommitted rows; your second query won't return because table2 doesn't have the WITH(NOLOCK)
hint on it.
Print all args without the filename:
for i in range(1, len(sys.argv)):
print(sys.argv[i])
If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:
import numpy as np
a = np.arange(10).reshape(2, 5)
print len(a) == 2
This code block will return true, telling you the size of the array is 2. However, there are in fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the first dimension of the array i.e.
import numpy as np
len(a) == np.shape(a)[0]
To get the number of elements in a multi-dimensional array of arbitrary shape:
import numpy as np
size = 1
for dim in np.shape(a): size *= dim
Use java.time.Instant
class to parse text in standard ISO 8601 format, representing a moment in UTC.
Instant.parse( "2010-10-02T12:23:23Z" )
That format is defined by the ISO 8601 standard for date-time string formats.
Both:
…use ISO 8601 formats by default for parsing and generating strings.
You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.
Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
Instant instant = Instant.parse( "2010-10-02T12:23:23Z" ); // `Instant` is always in UTC.
Convert to the old class.
java.util.Date date = java.util.Date.from( instant ); // Pass an `Instant` to the `from` method.
Time Zone
If needed, you can assign a time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ); // Assign a time zone adjustment from UTC.
Convert.
java.util.Date date = java.util.Date.from( zdt.toInstant() ); // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.
UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.
Here is some example code in Joda-Time 2.8.
org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC ); // Specifying a time zone to apply, rather than implicitly assigning the JVM’s current default.
Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.
java.util.Date date = dateTime_Utc.toDate(); // The `toDate` method converts to old class.
Time Zone
If needed, you can assign a time zone.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
it should be enough to mark your aspect method like this:
@After("@annotation(com.marcot.CommitTransaction)")
public void after() {
have a look at this for a step by step guide on this.
Just to throw in another example, the generic version of Class (Class<T>
) allows one to write generic functions such as the one below.
public static <T extends Enum<T>>Optional<T> optionalFromString(
@NotNull Class<T> clazz,
String name
) {
return Optional<T> opt = Optional.ofNullable(name)
.map(String::trim)
.filter(StringUtils::isNotBlank)
.map(String::toUpperCase)
.flatMap(n -> {
try {
return Optional.of(Enum.valueOf(clazz, n));
} catch (Exception e) {
return Optional.empty();
}
});
}
Here's my quick and dirty version. I know all of my dates were using the US Eastern time zone. You can change the offset or otherwise make it smarter as you need to. I was doing a one-time migration so this was Good Enough.
CREATE FUNCTION [dbo].[ConvertToUtc]
(
@date datetime
)
RETURNS DATETIME
AS
BEGIN
-- Declare the return variable here
DECLARE @utcDate datetime;
DECLARE @offset int;
SET @offset = (SELECT CASE WHEN
@date BETWEEN '1987-04-05 02:00 AM' AND '1987-10-25 02:00 AM'
OR @date BETWEEN '1988-04-03 02:00 AM' AND '1988-10-30 02:00 AM'
OR @date BETWEEN '1989-04-02 02:00 AM' AND '1989-10-29 02:00 AM'
OR @date BETWEEN '1990-04-01 02:00 AM' AND '1990-10-28 02:00 AM'
OR @date BETWEEN '1991-04-07 02:00 AM' AND '1991-10-27 02:00 AM'
OR @date BETWEEN '1992-04-05 02:00 AM' AND '1992-10-25 02:00 AM'
OR @date BETWEEN '1993-04-04 02:00 AM' AND '1993-10-31 02:00 AM'
OR @date BETWEEN '1994-04-03 02:00 AM' AND '1994-10-30 02:00 AM'
OR @date BETWEEN '1995-04-02 02:00 AM' AND '1995-10-29 02:00 AM'
OR @date BETWEEN '1996-04-07 02:00 AM' AND '1996-10-27 02:00 AM'
OR @date BETWEEN '1997-04-06 02:00 AM' AND '1997-10-26 02:00 AM'
OR @date BETWEEN '1998-04-05 02:00 AM' AND '1998-10-25 02:00 AM'
OR @date BETWEEN '1999-04-04 02:00 AM' AND '1999-10-31 02:00 AM'
OR @date BETWEEN '2000-04-02 02:00 AM' AND '2000-10-29 02:00 AM'
OR @date BETWEEN '2001-04-01 02:00 AM' AND '2001-10-28 02:00 AM'
OR @date BETWEEN '2002-04-07 02:00 AM' AND '2002-10-27 02:00 AM'
OR @date BETWEEN '2003-04-06 02:00 AM' AND '2003-10-26 02:00 AM'
OR @date BETWEEN '2004-04-04 02:00 AM' AND '2004-10-31 02:00 AM'
OR @date BETWEEN '2005-04-03 02:00 AM' AND '2005-10-30 02:00 AM'
OR @date BETWEEN '2006-04-02 02:00 AM' AND '2006-10-29 02:00 AM'
OR @date BETWEEN '2007-03-11 02:00 AM' AND '2007-11-04 02:00 AM'
OR @date BETWEEN '2008-03-09 02:00 AM' AND '2008-11-02 02:00 AM'
OR @date BETWEEN '2009-03-08 02:00 AM' AND '2009-11-01 02:00 AM'
OR @date BETWEEN '2010-03-14 02:00 AM' AND '2010-11-07 02:00 AM'
OR @date BETWEEN '2011-03-13 02:00 AM' AND '2011-11-06 02:00 AM'
OR @date BETWEEN '2012-03-11 02:00 AM' AND '2012-11-04 02:00 AM'
OR @date BETWEEN '2013-03-10 02:00 AM' AND '2013-11-03 02:00 AM'
OR @date BETWEEN '2014-03-09 02:00 AM' AND '2014-11-02 02:00 AM'
OR @date BETWEEN '2015-03-08 02:00 AM' AND '2015-11-01 02:00 AM'
OR @date BETWEEN '2016-03-13 02:00 AM' AND '2016-11-06 02:00 AM'
OR @date BETWEEN '2017-03-12 02:00 AM' AND '2017-11-05 02:00 AM'
OR @date BETWEEN '2018-03-11 02:00 AM' AND '2018-11-04 02:00 AM'
OR @date BETWEEN '2019-03-10 02:00 AM' AND '2019-11-03 02:00 AM'
OR @date BETWEEN '2020-03-08 02:00 AM' AND '2020-11-01 02:00 AM'
OR @date BETWEEN '2021-03-14 02:00 AM' AND '2021-11-07 02:00 AM'
THEN 4
ELSE 5 END);
SELECT @utcDate = DATEADD(hh, @offset, @date)
RETURN @utcDate;
END