Bootstrap default "contextual backgrounds" helper classes to change the background color:
.bg-primary
.bg-default
.bg-info
.bg-warning
.bg-danger
If you need set custom background color then, you can write your own custom classes in style.css( a custom css file) example below
.bg-pink
{
background-color: #CE6F9E;
}
Most answers here are pretty old.
In the past when un managed nand was the most popular storage technology, yaffs2 was the most common file system. This days there are few devices using un-managed nand, and those still in use are slowly migrating to ubifs.
Today most common storage is emmc (managed nand), for such devices ext4 is far more popular, but, this file system is slowly clears its way for f2fs (flash friendly fs).
Edit: f2fs will probably won't make it as the common fs for flash devices (including android)
Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)
sub myhandler(eventsource)
process(eventsource.value)
end sub
for each cell
cell.setEventHandler(myHandler)
But i dont know the syntax for achieving this in VB/VBA, or if is even possible.
cleanText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
Distilled from this website (web.achive).
This regex looks for <
, an optional slash /
, one or more characters that are not >
, then either >
or $
(the end of the line)
Examples:
'<div>Hello</div>' ==> 'Hello'
^^^^^ ^^^^^^
'Unterminated Tag <b' ==> 'Unterminated Tag '
^^
But it is not bulletproof:
'If you are < 13 you cannot register' ==> 'If you are '
^^^^^^^^^^^^^^^^^^^^^^^^
'<div data="score > 42">Hello</div>' ==> ' 42">Hello'
^^^^^^^^^^^^^^^^^^ ^^^^^^
If someone is trying to break your application, this regex will not protect you. It should only be used if you already know the format of your input. As other knowledgable and mostly sane people have pointed out, to safely strip tags, you must use a parser.
If you do not have acccess to a convenient parser like the DOM, and you cannot trust your input to be in the right format, you may be better off using a package like sanitize-html, and also other sanitizers are available.
You may have forgot to remove the semicolon to uncomment that line. For the date.timezone = "US/Central"
line, be sure that there's no semicolon in front of that line.
I think str_replace(array("\\r\\n", "\\r", "\\n"), " ", $string);
will work.
Initializations with (...)
in the class body is not allowed. Use {..}
or = ...
. Unfortunately since the respective constructor is explicit
and vector
has an initializer list constructor, you need a functional cast to call the wanted constructor
vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);
As an alternative you can use constructor initializer lists
Attribute():name(5), val(5, 0) {}
On Debian the best way to do it would be
sudo apt-get install python-pip
$("div.test:not(:first)").hide();
or:
$("div.test:not(:eq(0))").hide();
or:
$("div.test").not(":eq(0)").hide();
or:
$("div.test:gt(0)").hide();
or: (as per @Jordan Lev's comment):
$("div.test").slice(1).hide();
and so on.
See:
This works for me without throwing an exception:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date parsed = format.parse("20110210");
java.sql.Date sql = new java.sql.Date(parsed.getTime());
}
}
1) Direct Answer: Try this:
sudo updatedb
locate OpenCVConfig.cmake
For me, I get:
/home/pkarasev3/source/opencv/build/OpenCVConfig.cmake
To see the version, you can try:
cat /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake
giving
....
SET(OpenCV_VERSION 2.3.1)
....
2) Better Answer:
"sudo make install" is your enemy, don't do that when you need to compile/update the library often and possibly debug step through it's internal functions. Notice how my config file is in a local build directory, not in /usr/something. You will avoid this confusion in the future, and can maintain several different versions even (debug and release, for example).
Edit: the reason this questions seems to arise often for OpenCV as opposed to other libraries is that it changes rather dramatically and fast between versions, and many of the operations are not so well-defined / well-constrained so you can't just rely on it to be a black-box like you do for something like libpng or libjpeg. Thus, better to not install it at all really, but just compile and link to the build folder.
I know my answer it's too late, but it might helpful to other's
Try,
Void Main()
{
string filename = @"test.txt";
string filePath= AppDomain.CurrentDomain.BaseDirectory + filename ;
Console.WriteLine(filePath);
}
You can access the elements in a list-of-lists by first specifying which list you're interested in and then specifying which element of that list you want. For example, 17
is element 2
in list 0
, which is list1[0][2]
:
>>> list1 = [[10,13,17],[3,5,1],[13,11,12]]
>>> list1[0][2]
17
So, your example would be
50 - list1[0][0] + list1[0][1] - list1[0][2]
READ THIS IF YOU USE Crashlytics AND ARE HAVING THIS ISSUE...
I was having the same issue as above Command /bin/sh failed with exit code 1
more specifically [31merror: Could not fetch upload-symbols settings: An unknown error occurred fetching settings.[0m
The first solution (enabling the run script only when installing) allowed me to build my target in the simulator, but I could not archive my build.
I solved this Archive issue by enabling Crashlytics on firebase. I am still used to Fabric where Crashlytics is automatically enabled. Once I enabled Crashlytics in the firebase console for the corresponding GoogleService-Info.plist I was able to Archive without this error.
ToList
will create a brand new list.
If the items in the list are value types, they will be directly updated, if they are reference types, any changes will be reflected back in the referenced objects.
For me, this code looks more explicit:
CAST(@SomeDate AS datetime) + CAST(@SomeTime AS datetime)
All answers above are correct, However People who are coming from other programming language. The easiest approach to follow will be.
variable = 1
print("length " + format(variable))
Actually it might be too late for this answer but you can now do this:
class Box {
public x: number;
public y: number;
public height: number;
public width: number;
constructor();
constructor(obj: IBox);
constructor(obj?: IBox) {
this.x = !obj ? 0 : obj.x;
this.y = !obj ? 0 : obj.y;
this.height = !obj ? 0 : obj.height;
this.width = !obj ? 0 : obj.width;
}
}
so instead of static methods you can do the above. I hope it will help you!!!
The following code works for me :
var valueList = [10,4,17,9,3];
var maxValue = valueList.reduce(function(a, b) { return Math.max(a, b); });
var minValue = valueList.reduce(function(a, b) { return Math.min(a, b); });
element.get_attribute('innerHTML')
Swift 3
I set myButton width and height to 40 and my padding from EdgeInsetsMake is 15 all sides. I suggest to add a background color to your button to see the actual padding.
myButton.backgroundColor = UIColor.gray // sample color to check padding
myButton.imageView?.contentMode = .scaleAspectFit
myButton.imageEdgeInsets = UIEdgeInsetsMake(15, 15, 15, 15)
To let MySql generate sequence numbers for an AUTO_INCREMENT
field you have three options:
...No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.
These three statements will produce the same result:
$insertQuery = "INSERT INTO workorders (`priority`, `request_type`) VALUES('$priority', '$requestType', ...)";
$insertQuery = "INSERT INTO workorders VALUES(NULL, '$priority', ...)";
$insertQuery = "INSERT INTO workorders VALUES(0, '$priority', ...";
Just put the full directory location in the File object.
File file = new File("z:\\results.txt");
Consider some pros and cons of the second approach:
0 {{lastUpdated}}
instead of {{timerData.lastUpdated}}
, which could just as easily be {{timer.lastUpdated}}
, which I might argue is more readable (but let's not argue... I'm giving this point a neutral rating so you decide for yourself)
+1 It may be convenient that the controller acts as a sort of API for the markup such that if somehow the structure of the data model changes you can (in theory) update the controller's API mappings without touching the html partial.
-1 However, theory isn't always practice and I usually find myself having to modify markup and controller logic when changes are called for, anyway. So the extra effort of writing the API negates it's advantage.
-1 Furthermore, this approach isn't very DRY.
-1 If you want to bind the data to ng-model
your code become even less DRY as you have to re-package the $scope.scalar_values
in the controller to make a new REST call.
-0.1 There's a tiny performance hit creating extra watcher(s). Also, if data properties are attached to the model that don't need to be watched in a particular controller they will create additional overhead for the deep watchers.
-1 What if multiple controllers need the same data models? That means that you have multiple API's to update with every model change.
$scope.timerData = Timer.data;
is starting to sound mighty tempting right about now... Let's dive a little deeper into that last point... What kind of model changes were we talking about? A model on the back-end (server)? Or a model which is created and lives only in the front-end? In either case, what is essentially the data mapping API belongs in the front-end service layer, (an angular factory or service). (Note that your first example--my preference-- doesn't have such an API in the service layer, which is fine because it's simple enough it doesn't need it.)
In conclusion, everything does not have to be decoupled. And as far as decoupling the markup entirely from the data model, the drawbacks outweigh the advantages.
Controllers, in general shouldn't be littered with $scope = injectable.data.scalar
's. Rather, they should be sprinkled with $scope = injectable.data
's, promise.then(..)
's, and $scope.complexClickAction = function() {..}
's
As an alternative approach to achieve data-decoupling and thus view-encapsulation, the only place that it really makes sense to decouple the view from the model is with a directive. But even there, don't $watch
scalar values in the controller
or link
functions. That won't save time or make the code any more maintainable nor readable. It won't even make testing easier since robust tests in angular usually test the resulting DOM anyway. Rather, in a directive demand your data API in object form, and favor using just the $watch
ers created by ng-bind
.
Example http://plnkr.co/edit/MVeU1GKRTN4bqA3h9Yio
<body ng-app="ServiceNotification">
<div style="border-style:dotted" ng-controller="TimerCtrl1">
TimerCtrl1<br/>
Bad:<br/>
Last Updated: {{lastUpdated}}<br/>
Last Updated: {{calls}}<br/>
Good:<br/>
Last Updated: {{data.lastUpdated}}<br/>
Last Updated: {{data.calls}}<br/>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script type="text/javascript">
var app = angular.module("ServiceNotification", []);
function TimerCtrl1($scope, Timer) {
$scope.data = Timer.data;
$scope.lastUpdated = Timer.data.lastUpdated;
$scope.calls = Timer.data.calls;
};
app.factory("Timer", function ($timeout) {
var data = { lastUpdated: new Date(), calls: 0 };
var updateTimer = function () {
data.lastUpdated = new Date();
data.calls += 1;
console.log("updateTimer: " + data.lastUpdated);
$timeout(updateTimer, 500);
};
updateTimer();
return {
data: data
};
});
</script>
</body>
UPDATE: I've finally come back to this question to add that I don't think that either approach is "wrong". Originally I had written that Josh David Miller's answer was incorrect, but in retrospect his points are completely valid, especially his point about separation of concerns.
Separation of concerns aside (but tangentially related), there's another reason for defensive copying that I failed to consider. This question mostly deals with reading data directly from a service. But what if a developer on your team decides that the controller needs to transform the data in some trivial way before the view displays it? (Whether controllers should transform data at all is another discussion.) If she doesn't make a copy of the object first she might unwittingly cause regressions in another view component which consumes the same data.
What this question really highlights are architectural shortcomings of the typical angular application (and really any JavaScript application): tight coupling of concerns, and object mutability. I have recently become enamored with architecting application with React and immutable data structures. Doing so solves the following two problems wonderfully:
Separation of concerns: A component consumes all of it's data via props and has little-to-no reliance on global singletons (such as Angular services), and knows nothing about what happened above it in the view hierarchy.
Mutability: All props are immutable which eliminates the risk of unwitting data mutation.
Angular 2.0 is now on track to borrow heavily from React to achieve the two points above.
You can try something like this. Special Characters range for alphabets starts from 192, so you can avoid such characters in the result.
String name = "A função";
StringBuilder result = new StringBuilder();
for(char val : name.toCharArray()) {
if(val < 192) result.append(val);
}
System.out.println("Result "+result.toString());
You could make a recursive function do the work
L = size(M)
idx = zeros(L,1)
length(L)
as the maximum depthfor idx(depth) = 1:L(depth)
length(L)
, do the element operation, else call the function again with depth+1
Not as fast as vectorized methods if you want to check all the points, but if you don't need to evaluate most of them it can be quite a time saver.
After doing a "devenv.exe /resetuserdata", my VAssistX fails, so, actually, this reminds me that VAssistX can resolve the problem by Goto Implementation (Alt+G).
It sounds like you want something like:
var query = from order in workOrders
join plan in plans
on order.WorkOrderNumber equals plan.WorkOrderNumber
select new
{
order.WorkOrderNumber,
order.Description,
plan.ScheduledDate
};
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.filter("toArray", function () {_x000D_
return function (obj) {_x000D_
var result = [];_x000D_
angular.forEach(obj, function (val, key) {_x000D_
result.push(val);_x000D_
});_x000D_
return result;_x000D_
};_x000D_
});_x000D_
_x000D_
_x000D_
myApp.controller("mainCtrl", function ($scope) {_x000D_
_x000D_
$scope.logData = [_x000D_
{ event: 'Payment', created_at: '10/10/2019 6:47 PM PST' },_x000D_
{ event: 'Payment', created_at: '20/10/2019 12:47 AM PST' },_x000D_
{ event: 'Payment', created_at: '30/10/2019 1:50 PM PST' }_x000D_
]; _x000D_
_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="mainCtrl">_x000D_
_x000D_
<h4>Descending</h4>_x000D_
<ul>_x000D_
<li ng-repeat="logs in logData | toArray | orderBy:'created_at':true" >_x000D_
{{logs.event}} - Date : {{logs.created_at}}_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
<br>_x000D_
_x000D_
_x000D_
<h4>Ascending</h4>_x000D_
<ul>_x000D_
<li ng-repeat="logs in logData | toArray | orderBy:'created_at':false" >_x000D_
{{logs.event}} - Date : {{logs.created_at}}_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
</div>
_x000D_
You can use the stream api and a StringReader wrapped in a BufferedReader which got a lines() stream output in java 8:
import java.util.stream.*;
import java.io.*;
class test {
public static void main(String... a) {
String s = "this is a \nmultiline\rstring\r\nusing different newline styles";
new BufferedReader(new StringReader(s)).lines().forEach(
(line) -> System.out.println("one line of the string: " + line)
);
}
}
Gives
one line of the string: this is a
one line of the string: multiline
one line of the string: string
one line of the string: using different newline styles
Just like in BufferedReader's readLine, the newline character(s) themselves are not included. All kinds of newline separators are supported (in the same string even).
You can use slicing:
for item in some_list[2:]:
# do stuff
This will start at the third element and iterate to the end.
Off the top of my head and not guaranteed to be correct: I believe the second will be faster in this case.
IN
will short-circuit as soon as it finds a match.We can assign a variable for curl using single quote '
and wrap some other variables in double-single-double quote "'"
for substitution inside curl-variable. Then easily we can use that curl-variable which here is MERGE
.
Example:
# other variables ...
REF_NAME="new-branch";
# variable for curl using single quote => ' not double "
MERGE='{
"repository": "tmp",
"command": "git",
"args": [
"pull",
"origin",
"'"$REF_NAME"'"
],
"options": {
"cwd": "/home/git/tmp"
}
}';
notice this line:
"'"$REF_NAME"'"
and then calling curl as usual:
curl -s -X POST localhost:1365/M -H 'Content-Type: application/json' --data "$MERGE"
Do something like this, which also prevents SQL injection attacks
statement = con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
From you own project.
npx nodemon [your-app.js]
With a local installation, nodemon will not be available in your system path. Instead, the local installation of nodemon can be run by calling it from within an npm script (such as npm start
) or using npx nodemon
.
OR
Create a simple symbolik link
ln -s /Users/YourUsername/.npm-global/bin/nodemon /usr/local/bin
ln -s [from: where is you install 'nodemon'] [to: folder where are general module for node]
node : v12.1.0
npm : 6.9.0
I tried everything else and found helpless but this indeed worked for me "To update your credentials, go to Control Panel -> Credential Manager -> Generic Credentials. Find the credentials related to your git account and edit them to use the updated passwords".
Above Solution found in this link: https://cmatskas.com/how-to-update-your-git-credentials-on-windows/
For anyone who is still having issues after trying all the answers on this page, the following (finally) worked:
sudo apt-get install libgmp3-dev
gem install pg
This was after doing everything else mentioned on this page.
postgresql 9.5.8
Ubuntu 16.10
In PHP you simply can convert a value to a boolean by using double not operator (!!
):
var_dump(!! true); // true
var_dump(!! "Hello"); // true
var_dump(!! 1); // true
var_dump(!! [1, 2]); // true
var_dump(!! false); // false
var_dump(!! null); // false
var_dump(!! []); // false
var_dump(!! 0); // false
var_dump(!! ''); // false
A workaround of mine is to manipulate a model variable just for the ng-class toggling:
For example, I want to toggle class according to the state of my list:
1) Whenever my list is empty, I update my model:
$scope.extract = function(removeItemId) {
$scope.list= jQuery.grep($scope.list, function(item){return item.id != removeItemId});
if (!$scope.list.length) {
$scope.liststate = "empty";
}
}
2) Whenever my list is not empty, I set another state
$scope.extract = function(item) {
$scope.list.push(item);
$scope.liststate = "notempty";
}
3) When my list is not ever touched, I want to give another class (this is where the page is initiated):
$scope.liststate = "init";
3) I use this additional model on my ng-class:
ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty', 'bg-init': liststate = 'init'}"
getBadgeClasses() {
let classes = "badge m-2 ";
classes += (this.state.count === 0) ? "badge-warning" : "badge-primary";
return classes;
}
<span className={this.getBadgeClasses()}>Total Count</span>
I've run into the very same issue, when mistakenly named variable with the very same name, as function.
So this:
isLive = isLive(data);
failed, generating OP's mentioned error message.
Fix to this was as simple as changing above line to:
isItALive = isLive(data);
I don't know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.
try this property with your linear layout it will help
tools:context=".youractivity"
You can give it a try.. Added a working example. When focus is on input, turning on caps lock makes the led go red otherwise green. (Haven't tested on mac/linux)
NOTE: Both versions are working for me. Thanks for constructive inputs in the comments.
OLD VERSION: https://jsbin.com/mahenes/edit?js,output
Also, here is a modified version (can someone test on mac and confirm)
NEW VERSION: https://jsbin.com/xiconuv/edit?js,output
NEW VERSION:
function isCapslock(e) {
const IS_MAC = /Mac/.test(navigator.platform);
const charCode = e.charCode;
const shiftKey = e.shiftKey;
if (charCode >= 97 && charCode <= 122) {
capsLock = shiftKey;
} else if (charCode >= 65 && charCode <= 90
&& !(shiftKey && IS_MAC)) {
capsLock = !shiftKey;
}
return capsLock;
}
OLD VERSION:
function isCapslock(e) {
e = (e) ? e : window.event;
var charCode = false;
if (e.which) {
charCode = e.which;
} else if (e.keyCode) {
charCode = e.keyCode;
}
var shifton = false;
if (e.shiftKey) {
shifton = e.shiftKey;
} else if (e.modifiers) {
shifton = !!(e.modifiers & 4);
}
if (charCode >= 97 && charCode <= 122 && shifton) {
return true;
}
if (charCode >= 65 && charCode <= 90 && !shifton) {
return true;
}
return false;
}
For international characters, additional check can be added for the following keys as needed. You have to get the keycode range for characters you are interested in, may be by using a keymapping array which will hold all the valid use case keys you are addressing...
uppercase A-Z or 'Ä', 'Ö', 'Ü', lowercase a-Z or 0-9 or 'ä', 'ö', 'ü'
The above keys are just sample representation.
You can use closures to pass parameters:
iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);
However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):
document.getElementById("myFrame").contentDocument.addEventListener(...);
Maven working terminology having phases and goals.
Phase:Maven phase is a set of action which is associated with 2 or 3 goals
exmaple:- if you run mvn clean
this is the phase will execute the goal mvn clean:clean
Goal:Maven goal bounded with the phase
for reference http://books.sonatype.com/mvnref-book/reference/lifecycle-sect-structure.html
You can load the property file suing the following way:
InputStream is = new Test().getClass().getClassLoader().getResourceAsStream("app.properties");
Properties props = new Properties();
props.load(is);
And then you can iterate over the map using a lambda expression like:
props.stringPropertyNames().forEach(key -> {
System.out.println("Key is :"+key + " and Value is :"+props.getProperty(key));
});
You must be in the same directory of Gemfile
Found transport-attribute in binding-element which tells us that this is the WSDL 1.1 binding for the SOAP 1.1 HTTP binding.
ex.
<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
Not only Inside methods, it can be used inside classes also.
class Calculator
{
public static int Sum(int x,int y) => x + y;
public static Func<int, int, int> Add = (x, y) => x + y;
public static Action<int,int> DisplaySum = (x, y) => Console.WriteLine(x + y);
}
This should help you get rid of body margins and default top margin of <h1>
tag
body{
margin: 0px;
padding: 0px;
}
h1 {
margin-top: 0px;
}
If you have more than one version of java, it may interfere with your program.
I suggest you download JCreator.
When you do, click configure, options, and JDK Profiles. Delete the old versions of Java from the list. Then click the play button. Your program should appear.
If it doesn't, press ctrl+alt+O and then press the play button again.
You could put a crontab file in /etc/cron.d
which would run a script that would run your command and then delete the crontab file in /etc/cron.d
. Of course, that means your script would need to run as root.
If you want to make multiple operation use
select (sel1.s1+sel2+s2)
(select sum(hours) s1 from resource) sel1
join
(select sum(hours) s2 from projects-time)sel2
on sel1.s1=sel2.s2
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
Just found myself with the same question. This works for me:
form :focus {
outline: none;
}
This turns out to be a very interesting question. With over a hundred properties being set, you'd think that you'd be allowed to type .clickable { onclick : "alert('hi!');" ; } in your CSS, and it'd work. It's intuitive, it makes so much sense. This would be amazingly useful in monkey-patching dynamically-generated massive UIs.
The problem:
The CSS police, in their infinite wisdom, have drawn a Chinese wall between presentation and behavior. Any HTML properly labeled on-whatever is intentionally not supported by CSS. (Full Properties Table)
The best way around this is to use jQuery, which sets up an interpreted engine in the background to execute what you were trying to do with the CSS anyway. See this page: Add Javascript Onclick To .css File.
Good luck.
It took me a while to create a solution to this problem I was happy with:
Problem:
An SVG sprite of icons - say 80px x 3200px
We want to scale each use of them in content selectors (:before/:after) in various places over various sizes without re-defining the co-ords of each sprite based on the size used.
So this solution allows you to use the same sprite co-ords in a <button>
as a <menuitem>
whilst still scaling it.
[data-command]::before {
content: '';
position: absolute;
background-image: url("images/sprite.svgz");
background-repeat: no-repeat;
background-size: cover;
}
button[data-command]::before {
width: 32px;
height: 32px;
}
menuitem[data-command]::before {
width: 24px;
height: 24px;
}
[data-command="cancel"]::before {
background-position: 0% 35%;
}
[data-command="logoff"]::before {
background-position: 0% 37.5%;
}
By using percentages (to 2 decimal places) in background-position rather than background-size as suggested by others here, you can scale the same icon declaration to any size, without needing to redeclare it.
The position-y percentage is the original sprite height/icon height as a % - in our case here 80px*100/3200px == each sprite is represented by a y-position of 2.5%.
If you have hover/mouseover states you can double the width of the sprite and specify in the position-x coordinate.
The disadvantage of this approach is that adding more icons at a later date will change the sprite height and so y-position %, but if you don't do that then your sprite co-ordinates will need change for each scaled resolution you require.
This works for me
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;
When using immutable linked lists, consider using Python's tuple directly.
ls = (1, 2, 3, 4, 5)
def first(ls): return ls[0]
def rest(ls): return ls[1:]
Its really that ease, and you get to keep the additional funcitons like len(ls), x in ls, etc.
I ran into this on a friend's HTML code and in his case, he was missing quotes.
For example:
<form action="formHandler.php" name="yourForm" id="theForm" method="post">
<input type="text" name="fname" id="fname" style="width:90;font-size:10>
<input type="submit" value="submit"/>
</form>
In this example, a missing quote on the input text fname will simply render the submit button un-usable and the form will not submit.
Of course, this is a bad example because I should be using CSS in the first place ;) but anyways, check all your single and double quotes to see that they are closing properly.
Also, if you have any tags like center, move them out of the form.
<form action="formHandler.php" name="yourForm" id="theForm" method="post">
<center> <-- bad
As strange it may seems, it can have an impact.
From DimitriDushkin on GitHub:
import { browserHistory } from 'react-router';
/**
* @param {Object} query
*/
export const addQuery = (query) => {
const location = Object.assign({}, browserHistory.getCurrentLocation());
Object.assign(location.query, query);
// or simple replace location.query if you want to completely change params
browserHistory.push(location);
};
/**
* @param {...String} queryNames
*/
export const removeQuery = (...queryNames) => {
const location = Object.assign({}, browserHistory.getCurrentLocation());
queryNames.forEach(q => delete location.query[q]);
browserHistory.push(location);
};
or
import { withRouter } from 'react-router';
import { addQuery, removeQuery } from '../../utils/utils-router';
function SomeComponent({ location }) {
return <div style={{ backgroundColor: location.query.paintRed ? '#f00' : '#fff' }}>
<button onClick={ () => addQuery({ paintRed: 1 })}>Paint red</button>
<button onClick={ () => removeQuery('paintRed')}>Paint white</button>
</div>;
}
export default withRouter(SomeComponent);
SET FOREIGN_KEY_CHECKS=0;
TRUNCATE table1;
TRUNCATE table2;
SET FOREIGN_KEY_CHECKS=1;
reference - truncate foreign key constrained table
Working for me in MYSQL
You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.
Sometimes we need to do a list with dates, like
today with hour
yesterday with yesterday
other days with 23/06/2017
To make this we need to compare current time with our data.
Public class DateUtil {
Public static int getDateDayOfMonth (Date date) {
Calendar calendar = Calendar.getInstance ();
Calendar.setTime (date);
Return calendar.get (Calendar.DAY_OF_MONTH);
}
Public static int getCurrentDayOfMonth () {
Calendar calendar = Calendar.getInstance ();
Return calendar.get (Calendar.DAY_OF_MONTH);
}
Public static String convertMillisSecondsToHourString (long millisSecond) {
Date date = new Date (millisSecond);
Format formatter = new SimpleDateFormat ("HH: mm");
Return formatter.format (date);
}
Public static String convertMillisSecondsToDateString (long millisSecond) {
Date date = new Date (millisSecond);
Format formatter = new SimpleDateFormat ("dd / MM / yyyy");
Return formatter.format (date);
}
Public static long convertToMillisSecond (Date date) {
Return date.getTime ();
}
Public static String compare (String stringData, String yesterday) {
String result = "";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss");
Date date = null;
Try {
Date = simpleDateFormat.parse (stringData);
} Catch (ParseException e) {
E.printStackTrace ();
}
Long millisSecond = convertToMillisSecond (date);
Long currencyMillisSecond = System.currentTimeMillis ();
If (currencyMillisSecond> millisSecond) {
Long diff = currencyMillisSecond - millisSecond;
Long day = 86400000L;
If (diff <day && getCurrentDayOfMonth () == getDateDayOfMonth (date)) {
Result = convertMillisSecondsToHourString (millisSecond);
} Else if (diff <(day * 2) && getCurrentDayOfMonth () -1 == getDateDayOfMonth (date)) {
Result = yesterday;
} Else {
Result = convertMillisSecondsToDateString (millisSecond);
}
}
Return result;
}
}
You can use the old Stupid Scanner trick oneliner to do that without any additional dependency like guava:
String text = new Scanner(AppropriateClass.class.getResourceAsStream("foo.txt"), "UTF-8").useDelimiter("\\A").next();
Guys, don't use 3rd party stuff unless you really need that. There is a lot of functionality in the JDK already.
You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.
Please see the following link on how to download a file/folder: https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html
I had the same problem but changeing max_allowed_packet in the my.ini/my.cnf file under [mysqld] made the trick.
add a line
max_allowed_packet=500M
now restart the MySQL service once you are done.
Just found this one (don't know it, not tested, check yourself)
As you only need this for curiosity you could look into the source of this applet.
It does OCR of handwritten characters with a neural network
Left joins in LINQ are possible with the DefaultIfEmpty() method. I don't have the exact syntax for your case though...
Actually I think if you just change pets to pets.DefaultIfEmpty() in the query it might work...
EDIT: I really shouldn't answer things when its late...
I think its too late to reply on this thread. But I would like to share my idea or way to resolve text size problem over difference resolution devices. Many android developer sites suggest that we have to use sp unit for text size which will handle text size for difference resolution devices. But I am always unable to get the desired result. So I have found one solution which I am using from my last 4-5 projects and its working fine. As per my suggestion, you have to place the text size for each resolution devices, which is bit tedious work, but it will fulfill your requirement. Each developer has must listen about the ratio like 4:6:8:12 (h:xh:xxh:xxxh respectively). Now inside your project res folder you have to create 4 folder with dimens file e.g.
Now inside dimens.xml file you have to place text sizes. I am showing you code for values-hdpi, similarly you have to place code for other resolution values/dimens.xml file.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="text_size">4px</dimen>
</resources>
For other resolutions it is like xhdpi : 6px, xxhdpi : 8px, xxxhdpi : 12px. This is calculated with the ratio (3:4:6:8:12) I have written above. Lets discuss other text size example with above ratio. If you want to take text size of 12px in hdpi, then in other resolution it would be
This is the simple solution to implement required text size for all resolutions. I am not considering values-mdpi resolution devices here. If any one want to include text size for this resolution then ration is like 3:4:6:8:12. In any query please let me know. Hope it will help you people out.
Might be better choice:
@Override
public String toString() {
return new GsonBuilder().create().toJson(this, Producto.class);
}
GregorianCalendar c = GregorianCalendar.from((LocalDate.parse("2016-06-22")).atStartOfDay(ZoneId.systemDefault()));
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
You can use isin
method:
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
If you're accessing this via a View then try sp_recompile
or refreshing views.
sp_recompile
:
Causes stored procedures, triggers, and user-defined functions to be recompiled the next time that they are run. It does this by dropping the existing plan from the procedure cache forcing a new plan to be created the next time that the procedure or trigger is run. In a SQL Server Profiler collection, the event SP:CacheInsert is logged instead of the event SP:Recompile.
Arguments
[ @objname= ] 'object'
The qualified or unqualified name of a stored procedure, trigger, table, view, or user-defined function in the current database. object is nvarchar(776), with no default. If object is the name of a stored procedure, trigger, or user-defined function, the stored procedure, trigger, or function will be recompiled the next time that it is run. If object is the name of a table or view, all the stored procedures, triggers, or user-defined functions that reference the table or view will be recompiled the next time that they are run.
Return Code Values
0 (success) or a nonzero number (failure)
Remarks
sp_recompile
looks for an object in the current database only.
The queries used by stored procedures, or triggers, and user-defined functions are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures, triggers, and user-defined functions may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries.
Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines
It's better to avoid any kind of loops, just remove all elements directly like this:
$("#mytable > tbody").html("");
Dim f as Range
Set f=ActiveSheet.Cells.Find(...)
If Not f Is Nothing then
msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
msgbox "value not found!"
End If
Paint your two canvases onto a third canvas.
I had this same problem and none of the solutions here solved my problem. I had one opaque canvas with another transparent canvas above it. The opaque canvas was completely invisible but the background of the page body was visible. The drawings from the transparent canvas on top were visible while the opaque canvas below it was not.
1 & 2
myVar = 8; //not dynamically allocated. Can't call delete on it.
myPointer = new int; //dynamically allocated, can call delete on it.
The first variable was allocated on the stack. You can call delete only on memory you allocated dynamically (on the heap) using the new
operator.
3.
myPointer = NULL;
delete myPointer;
The above did nothing at all. You didn't free anything, as the pointer pointed at NULL.
The following shouldn't be done:
myPointer = new int;
myPointer = NULL; //leaked memory, no pointer to above int
delete myPointer; //no point at all
You pointed it at NULL, leaving behind leaked memory (the new int you allocated).
You should free the memory you were pointing at. There is no way to access that allocated new int
anymore, hence memory leak.
The correct way:
myPointer = new int;
delete myPointer; //freed memory
myPointer = NULL; //pointed dangling ptr to NULL
The better way:
If you're using C++, do not use raw pointers. Use smart pointers instead which can handle these things for you with little overhead. C++11 comes with several.
Simply put these codes at top of your PHP/index file:
error_reporting(E_ALL); // Error/Exception engine, always use E_ALL
ini_set('ignore_repeated_errors', TRUE); // always use TRUE
ini_set('display_errors', FALSE); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment
ini_set('log_errors', TRUE); // Error/Exception file logging engine.
ini_set('error_log', 'your/path/to/errors.log'); // Logging file path
Here is my code
# -*- coding: utf-8 -*-
import socket
class SubnetTest(object):
def __init__(self, network):
self.network, self.netmask = network.split('/')
self._network_int = int(socket.inet_aton(self.network).encode('hex'), 16)
self._mask = ((1L << int(self.netmask)) - 1) << (32 - int(self.netmask))
self._net_prefix = self._network_int & self._mask
def match(self, ip):
'''
????? IP ???? Network ?? IP
'''
ip_int = int(socket.inet_aton(ip).encode('hex'), 16)
return (ip_int & self._mask) == self._net_prefix
st = SubnetTest('100.98.21.0/24')
print st.match('100.98.23.32')
Use the Ant war task
Re Jonathan Wood's suggestion. I don't have the option of wrapping tables with a new div as i'm using a CMS. Using JQuery here's what i did:
$( "table" ).wrap( "<div class='table-overflow'></div>" );
This wraps table elements with a new div with the class "table-overflow".
You can then simply add the following definition in your css file:
.table-overflow { overflow: auto; }
Roughly you can do it like that :
try
{
//do something
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
if (!Page.IsStartupScriptRegistered("myErrorScript"))
{
Page.ClientScript.RegisterStartupScript("myErrorScript", script);
}
}
But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.
This is just a suggestion, it might not work and I'm prepared to be called on this.
This will generate false positives, but hopefully not false negatives.
Resize both of the images so that they are the same size (I assume that the ratios of widths to lengths are the same in both images).
Compress a bitmap of both images with a lossless compression algorithm (e.g. gzip).
Find pairs of files that have similar file sizes. For instance, you could just sort every pair of files you have by how similar the file sizes are and retrieve the top X.
As I said, this will definitely generate false positives, but hopefully not false negatives. You can implement this in five minutes, whereas the Porikil et. al. would probably require extensive work.
Just use special `
var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;
You can see more examples here.
One alternative - and more lightweight approach to your problem - might be, just editing the array temporarily and then assigning the whole array back to your variable. Because as Vue does not watch individual items it will watch the whole variable being updated.
So you this should work as well:
var tempArray[];
tempArray = this.items;
tempArray[targetPosition] = value;
this.items = tempArray;
This then should also update your DOM.
It seems like your problem may be arising at
while(in.read(outputByte,0,4096)!=-1){
where it might go into an infinite loop for not advancing the offset (which is 0 always in the call). Try
while(in.read(outputByte)!=-1){
which will by default try to read upto outputByte.length into the byte[]
. This way you dont have to worry about the offset. See FileInputStrem's read method
In other thread I commented a solution for this issue in two ways:
First method:
func Find(slice interface{}, f func(value interface{}) bool) int {
s := reflect.ValueOf(slice)
if s.Kind() == reflect.Slice {
for index := 0; index < s.Len(); index++ {
if f(s.Index(index).Interface()) {
return index
}
}
}
return -1
}
Use example:
type UserInfo struct {
UserId int
}
func main() {
var (
destinationList []UserInfo
userId int = 123
)
destinationList = append(destinationList, UserInfo {
UserId : 23,
})
destinationList = append(destinationList, UserInfo {
UserId : 12,
})
idx := Find(destinationList, func(value interface{}) bool {
return value.(UserInfo).UserId == userId
})
if idx < 0 {
fmt.Println("not found")
} else {
fmt.Println(idx)
}
}
Second method with less computational cost:
func Search(length int, f func(index int) bool) int {
for index := 0; index < length; index++ {
if f(index) {
return index
}
}
return -1
}
Use example:
type UserInfo struct {
UserId int
}
func main() {
var (
destinationList []UserInfo
userId int = 123
)
destinationList = append(destinationList, UserInfo {
UserId : 23,
})
destinationList = append(destinationList, UserInfo {
UserId : 123,
})
idx := Search(len(destinationList), func(index int) bool {
return destinationList[index].UserId == userId
})
if idx < 0 {
fmt.Println("not found")
} else {
fmt.Println(idx)
}
}
If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)
<select chosen="{width: '100%'}" ng-
model="modelName" class="form-control input-
sm"
ng-
options="persons.persons as
persons.persons for persons in
jsonData"
ng-
change="anyFunction(anyParam)"
required>
<option value=""> </option>
</select>
<style>
.chosen-container .chosen-drop {
border-bottom: 0;
border-top: 1px solid #aaa;
top: auto;
bottom: 40px;
}
.chosen-container.chosen-with-drop .chosen-single {
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
background-image: none;
}
.chosen-container.chosen-with-drop .chosen-drop {
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
box-shadow: none;
margin-bottom: -16px;
}
</style>
For development you can disable password policy if no other profile was set (i.e. disable password expiration in default one):
ALTER PROFILE "DEFAULT" LIMIT PASSWORD_VERIFY_FUNCTION NULL;
Then, reset password and unlock user account. It should never expire again:
alter user user_name identified by new_password account unlock;
It depends on the size of the file! The solutions above tend to use convenient shorthands to copy the entire file into memory, which will work in many cases.
For very large files you may need to use a streaming design where read the file by line or in chucks, process the chunks, then discard them from memory.
See the answer on reading line by line with perl if that's what you need.
This is a start may be :
- hosts: all
gather_facts: no
tasks:
- shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
register: ps
- local_action: command echo item
with_items: ps.stdout_lines
NOTE: Docs regarding ps.stdout_lines
are covered here: ('Register Variables' chapter).
No, you can't LIMIT subqueries arbitrarily (you can do it to a limited extent in newer MySQLs, but not for 5 results per group).
This is a groupwise-maximum type query, which is not trivial to do in SQL. There are various ways to tackle that which can be more efficient for some cases, but for top-n in general you'll want to look at Bill's answer to a similar previous question.
As with most solutions to this problem, it can return more than five rows if there are multiple rows with the same rate
value, so you may still need a quantity of post-processing to check for that.
You could use a .before with a content with a unicode symbol for a circle (25CF).
.circle:before {_x000D_
content: ' \25CF';_x000D_
font-size: 200px;_x000D_
}
_x000D_
<span class="circle"></span>
_x000D_
I suggest this as border-radius won't work in IE8 and below (I recognize the fact that the suggestion is a bit mental).
{
"version": "2.0.0",
"tasks": [
{
"label": "Open Chrome",
"type": "process",
"windows": {
"command": "${config:chrome.executable}"
},
"args": ["--user-data-dir=${config:chrome.profileDir}", "${input:url}"],
"problemMatcher": []
}
],
"inputs": [
{
"id": "url",
"description": "Which URL?",
"default": "http://localhost:8080",
"type": "promptString"
}
]
}
{
"label": "Open active file in Chrome",
"type": "process",
"command": "chrome.exe",
"windows": {
"command": "${config:chrome.executable}"
},
"args": ["--user-data-dir=${config:chrome.profileDir}", "${file}"],
"problemMatcher": []
},
windows
property by other OS${config:chrome.executable}
with your custom chrome location, e.g. "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
${config:chrome.profileDir}
with your custome chrome profile directory, e.g.
"C:/My/Data/chrome/profile"
or leave it outsettings.json
- user or workspace - , adjust paths to your needs:"chrome.executable": "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
"chrome.profileDir": "C:/My/Data/chrome/profile"
launch.json
for debugging purposes: "runtimeExecutable": "${config:chrome.executable}"
If you need exact your example, you should add format to ToString()
string test = DateTime.ParseExact(DateTime.Now.ToString("dd.MM.yyyy"), "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
But it's better to use straight formatting:
string test = DateTime.Now.ToString("yyyy-MM-dd")
At first check the file address, it must be beside your .java
file or in any address that you define in classpath
environment variable. When you check this then try below.
you must use a file name by it's extension in File object constructor, as an example:
File myFile = new File("test.txt");
but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:
Scanner sc = new Scanner(Paths.get("test.txt"));
in this way you must import java.nio.file.Paths
as well.
The rules of C# are very different from that of Java and C++.
When you are in the constructor for some object in C#, that object exists in a fully initialized (just not "constructed") form, as its fully derived type.
namespace Demo
{
class A
{
public A()
{
System.Console.WriteLine("This is a {0},", this.GetType());
}
}
class B : A
{
}
// . . .
B b = new B(); // Output: "This is a Demo.B"
}
This means that if you call a virtual function from the constructor of A, it will resolve to any override in B, if one is provided.
Even if you intentionally set up A and B like this, fully understanding the behavior of the system, you could be in for a shock later. Say you called virtual functions in B's constructor, "knowing" they would be handled by B or A as appropriate. Then time passes, and someone else decides they need to define C, and override some of the virtual functions there. All of a sudden B's constructor ends up calling code in C, which could lead to quite surprising behavior.
It is probably a good idea to avoid virtual functions in constructors anyway, since the rules are so different between C#, C++, and Java. Your programmers may not know what to expect!
There is no support for array in sql server but there are several ways by which you can pass collection to a stored proc .
The below link may help you
package-lock.json is re-generated whenever you run npm i
.
Try
private boolean hasKey(JSONObject jsonObject, String key) {
return jsonObject != null && jsonObject.has(key);
}
try {
JSONObject jsonObject = new JSONObject(yourJson);
if (hasKey(jsonObject, "labelData")) {
JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
if (hasKey(labelDataJson, "video")) {
String video = labelDataJson.getString("video");
}
}
} catch (JSONException e) {
}
Technically possible. You would probably reference employees_ce in deductions and employees_sn. But why don't you merge employees_sn and employees_ce? I see no reason why you have two table. No one to many relationship. And (not in this example) many columns.
If you do two references for one column, an employee must have an entry in both tables.
Possibly something has changed in recent TensorFlow builds, because for me, running
sess = tf.Session()
sess.run(tf.local_variables_initializer())
before fitting any models seems to do the trick. Most older examples and comments seem to suggest tf.global_variables_initializer()
.
This is an addition to what prateek has answered.There seems to be a glitch in the code in IE so i decided to modify it a bit nothing fancy(just another condition)
$('document').ready(function() {
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
console.log("down")
}
else if(st == lastScrollTop)
{
//do nothing
//In IE this is an important condition because there seems to be some instances where the last scrollTop is equal to the new one
}
else {
console.log("up")
}
lastScrollTop = st;
});});
If you want a DOM-like API - that is, one where the XML parser turns the document into a tree of Element and Attribute nodes - then there are at least four to choose from: DOM itself, JDOM, DOM4J, and XOM. The only possible reason to use DOM is because it's perceived as a standard and is supplied in the JDK: in all other respects, the others are all superior. My own preference, for its combination of simplicity, power, and performance, is XOM.
And of course, there are other styles of processing: low-level parser interfaces (SAX and StAX), data-object binding interfaces (JAXB), and high-level declarative languages (XSLT, XQuery, XPath). Which is best for you depends on your project requirements and your personal taste.
This eclipse documentation has details on the markups in .project
file: The project description file
It describes the .project
file as:
When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"
Basing on Ilya's data, I wrote a Vanilla JS library for supporting modifier keys on Mac: https://github.com/MichaelZelensky/jsLibraries/blob/master/macKeys.js
Just use it like this, e.g.:
document.onclick = function (event) {
if (event.shiftKey || macKeys.shiftKey) {
//do something interesting
}
}
Tested on Chrome, Safari, Firefox, Opera on Mac. Please check if it works for you.
$("#element").validate().valid()
Z=np.array([1.0,1.0,1.0,1.0])
def func(TempLake,Z):
A=TempLake
B=Z
return A*B
Nlayers=Z.size
N=3
TempLake=np.zeros((N+1,Nlayers))
kOUT=np.vectorize(func)(TempLake,Z)
This works too , instead of looping , just vectorize however read below notes from the scipy documentation : https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html
The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.
If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if cache is True to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive.
If you're pulling this value directly from a SQL Database and the value is null in there, it will actually be the DBNull
object rather than null. Either place a check prior to your conversion & use a default value in the event of DBNull
, or replace your null check afterwards with a check on rdrSelect[23]
for DBNull
.
This question is specific to ASP .NET however I am sure some of you will benefit of system agnostic javascript which is beneficial in many situations.
UPDATE: The way to get url formed outside of the page itself is well described in answers above.
Or you could do a oneliner like following:
new UrlHelper(actionExecutingContext.RequestContext).Action(
"SessionTimeout", "Home",
new {area = string.Empty},
actionExecutingContext.Request.Url!= null?
actionExecutingContext.Request.Url.Scheme : "http"
);
from filter or:
new UrlHelper(this.Request.RequestContext).Action(
"Details",
"Journey",
new { area = productType },
this.Request.Url!= null? this.Request.Url.Scheme : "http"
);
However quite often one needs to get the url of current page, for those cases using Html.Action
and putting he name and controller of page you are in to me feels awkward. My preference in such cases is to use JavaScript instead. This is especially good in systems that are half re-written MVT half web-forms half vb-script half God knows what - and to get URL of current page one needs to use different method every time.
One way is to use JavaScript to get URL is window.location.href
another - document.URL
It seems that google-services:4.1.0
has an issue. Either downgrade it to
classpath 'com.google.gms:google-services:4.0.0'
or upgrade it to
classpath 'com.google.gms:google-services:4.2.0'
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0-alpha08'
classpath 'com.google.gms:google-services:4.2.0'
/*classpath 'com.google.gms:google-services:4.1.0' <-- this was the problem */
}
Hope it helps
If possible, let us locate/identify the busy process, kill that process and then unmount
the samba share/ drive to minimize damage:
lsof | grep '<mountpoint of /dev/sda1>'
(or whatever the mounted device is)
pkill target_process
(kills busy proc. by name | kill PID
| killall target_process
)
umount /dev/sda1
(or whatever the mounted device is)
Basically, there are two ways to clear the cache:
<form autocomplete="off"></form>
or
$('#Textfiledid').attr('autocomplete', 'off');
On Mac OS X,
git difftool -t diffuse
does the job for me in the git folder. For installing diffuse, one can use port -
sudo port install diffuse
I take it you can modify MyScript.ps1
. Then try to change it like so:
$(
Here is your current script
) *>&1 > output.txt
I just tried this with PowerShell 3. You can use all the redirect options as in Nathan Hartley's answer.
You can either set the timeout when running your test:
mocha --timeout 15000
Or you can set the timeout for each suite or each test programmatically:
describe('...', function(){
this.timeout(15000);
it('...', function(done){
this.timeout(15000);
setTimeout(done, 15000);
});
});
For more info see the docs.
You can configure property inclusion, and numerous other settings, via application.properties
:
spring.jackson.default-property-inclusion=non_null
There's a table in the documentation that lists all of the properties that can be used.
If you want more control, you can also customize Spring Boot's configuration programatically using a Jackson2ObjectMapperBuilderCustomizer
bean, as described in the documentation:
The context’s
Jackson2ObjectMapperBuilder
can be customized by one or moreJackson2ObjectMapperBuilderCustomizer
beans. Such customizer beans can be ordered (Boot’s own customizer has an order of 0), letting additional customization be applied both before and after Boot’s customization.
Lastly, if you don't want any of Boot's configuration and want to take complete control over how the ObjectMapper
is configured, declare your own Jackson2ObjectMapperBuilder
bean:
@Bean
Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
// Configure the builder to suit your needs
return builder;
}
-(void)kundanselect
{
NSMutableArray *allControllers = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
NSArray *allControllersCopy = [allControllers copy];
if ([[allControllersCopy lastObject] isKindOfClass: [kundanViewController class]])
{
[[NSNotificationCenter defaultCenter]postNotificationName:@"kundanViewControllerHide"object:nil userInfo:nil];
}
else
{
[[NSUserDefaults standardUserDefaults] setInteger:4 forKey:@"selected"];
[self performSegueWithIdentifier:@"kundansegue" sender:self];
}
}
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ApparelsViewControllerHide) name:@"ApparelsViewControllerHide" object:nil];
You can handle the fds yourself. The exec in java returns a Process object. Intermittently check if the process is still running. Once it has completed close the processes STDERR, STDIN, and STDOUT streams (e.g. proc.getErrorStream.close()). That will mitigate the leaks.
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
No need to increase the MaxConnections & InitialConnections. Just close your connections after after doing your work. For example if you are creating connection:
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1/"+dbname,user,pass);
} catch (SQLException e) {
e.printStackTrace();
return;
}
After doing your work close connection:
try {
connection.commit();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
Make sure your computer is connected to the internet, then click on the link that comes with the error message i.e "install missing platform(s) and sync project". Give it a few seconds especially if your computer has low specs, it will bring up a window called SDK Quickfix Installation and everything is straightforward from there.
And how I implemented this
<script type="text/javascript">
!(window.ActiveXObject) && "ActiveXObject"
function isIE11(){
return !!navigator.userAgent.match(/Trident.*rv[ :]*11\./);
}
</script>
Change the
private static final long serialVersionUID = 1L;
to any other value like
private static final long serialVersionUID = 102831973239L;
also you can generate it automatically in eclipse.
It is because each servlet in a app has a unique id.and tomcat causes problem with two servlets having same id...
// just pass your tested function name instead of myFunctionName
if ( $.isFunction($.fn.myFunctionName) ) {
console.log( 'write your code here.' );
}
The value disappears since the read command is run in a separate subshell: Bash FAQ 24
99% of the cases you might simply use:
sys.calls()[[1]] [[2]]
It will not work for crazy calls where the script is not the first argument, i.e., source(some args, file="myscript")
. Use @hadley's in these fancy cases.
long
can only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float
the value before calling the long
. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int
to provide the key as well.
So, the answer is long(float('234.89'))
or it could just be int(float('234.89'))
if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int
Here's a summary of Dimitris Andreou's link.
Remember sum of i-th powers, where i=1,2,..,k. This reduces the problem to solving the system of equations
a1 + a2 + ... + ak = b1
a12 + a22 + ... + ak2 = b2
...
a1k + a2k + ... + akk = bk
Using Newton's identities, knowing bi allows to compute
c1 = a1 + a2 + ... ak
c2 = a1a2 + a1a3 + ... + ak-1ak
...
ck = a1a2 ... ak
If you expand the polynomial (x-a1)...(x-ak) the coefficients will be exactly c1, ..., ck - see Viète's formulas. Since every polynomial factors uniquely (ring of polynomials is an Euclidean domain), this means ai are uniquely determined, up to permutation.
This ends a proof that remembering powers is enough to recover the numbers. For constant k, this is a good approach.
However, when k is varying, the direct approach of computing c1,...,ck is prohibitely expensive, since e.g. ck is the product of all missing numbers, magnitude n!/(n-k)!. To overcome this, perform computations in Zq field, where q is a prime such that n <= q < 2n - it exists by Bertrand's postulate. The proof doesn't need to be changed, since the formulas still hold, and factorization of polynomials is still unique. You also need an algorithm for factorization over finite fields, for example the one by Berlekamp or Cantor-Zassenhaus.
High level pseudocode for constant k:
For varying k, find a prime n <= q < 2n using e.g. Miller-Rabin, and perform the steps with all numbers reduced modulo q.
EDIT: The previous version of this answer stated that instead of Zq, where q is prime, it is possible to use a finite field of characteristic 2 (q=2^(log n)). This is not the case, since Newton's formulas require division by numbers up to k.
This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
where content
is your encoded content. You also should include correct Content-type header.
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
The problem is that jQuery doesn't trigger the native click
event for <a>
elements so that navigation doesn't happen (the normal behavior of an <a>
), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).
To trigger it manually, try:
var a = $("<a>")
.attr("href", "http://i.stack.imgur.com/L8rHf.png")
.attr("download", "img.png")
.appendTo("body");
a[0].click();
a.remove();
DEMO: http://jsfiddle.net/HTggQ/
Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
Type in cmd.exe Powershell -Help
and see the examples.
As per this the default is 2 MB for your <Connector>
.
maxPostSize = The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).
Edit Tomcat's server.xml. In the <Connector>
element, add an attribute maxPostSize
and set a larger value (in bytes) to increase the limit.
Having said that, if this is the issue, you should have got an exception on the lines of
Post data too big
in tomcat
UPDATE sourcecodes_tags
SET sourcecode_id = NULL
WHERE sourcecode_id NOT IN (
SELECT id FROM sourcecodes);
should help to get rid of those IDs. Or if null
is not allowed in sourcecode_id
, then remove those rows or add those missing values to the sourcecodes
table.
For java 11+ you can use Objects.nonNull(Object obj)
if(nonNull(foo)){
//
}
@sedit was on the right path, but it's a bit awkward to define a variable.
The way to do this in bash is to put a dollar sign in front of your single quoted string.
$ echo -e '1\n2\n3'
1
2
3
$ echo -e '1\n2\n3' | sed 's/.*/\t&/g'
t1
t2
t3
$ echo -e '1\n2\n3' | sed $'s/.*/\t&/g'
1
2
3
If your string needs to include variable expansion, you can put quoted strings together like so:
$ timestamp=$(date +%s)
$ echo -e '1\n2\n3' | sed "s/.*/$timestamp"$'\t&/g'
1491237958 1
1491237958 2
1491237958 3
In bash $'string'
causes "ANSI-C expansion". And that is what most of us expect when we use things like \t
, \r
, \n
, etc. From: https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html#ANSI_002dC-Quoting
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded...
The expanded result is single-quoted, as if the dollar sign had not been present.
I personally think most efforts to avoid bash are silly because avoiding bashisms does NOT* make your code portable. (Your code will be less brittle if you shebang it to bash -eu
than if you try to avoid bash and use sh
[unless you are an absolute POSIX ninja].) But rather than have a religious argument about that, I'll just give you the BEST* answer.
$ echo -e '1\n2\n3' | sed "s/.*/$(printf '\t')&/g"
1
2
3
* BEST answer? Yes, because one example of what most anti-bash shell scripters would do wrong in their code is use echo '\t'
as in @robrecord's answer. That will work for GNU echo, but not BSD echo. That is explained by The Open Group at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html#tag_20_37_16 And this is an example of why trying to avoid bashisms usually fail.
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate < endDate){
// Do something
}
That should do it I think
This if clause easily checks if location services are available in my opinion:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
//All location services are disabled
}
Generally, The DNS Domain of the URL MUST match the Certificate Subject of the certificate.
In former times this could be either by setting the domain as cn of the certificate or by having the domain set as a Subject Alternative Name.
Support for cn was deprecated for a long time (since 2000 in RFC 2818) and Chrome browser will not even look at the cn anymore so today you need to have the DNS Domain of the URL as a Subject Alternative Name.
RFC 6125 which forbids checking the cn if SAN for DNS Domain is present, but not if SAN for IP Address is present. RFC 6125 also repeats that cn is deprecated which was already said in RFC 2818. And the Certification Authority Browser Forum to be present which in combination with RFC 6125 essentially means that cn will never be checked for DNS Domain name.
In Perl 6 there is, the say
function
EBS is like the virtual disk of a VM:
Instance storage is:
Third solution:
I would set ws
to a sheet of workbook wb
as the use of Sheet("name")
always refers to the active workbook, which might change as your code develops.
sub kl()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
'be aware as this might produce an error, if Shet "name" does not exist
Set ws = wb.Sheets("name")
' if wb is other than the active workbook
wb.activate
ws.Select
End Sub
hr {_x000D_
display: block;_x000D_
height: 1px;_x000D_
border: 0;_x000D_
border-top: 1px solid #ccc;_x000D_
margin: 1em 0;_x000D_
padding: 0;_x000D_
}
_x000D_
<div>Hello</div>_x000D_
<hr/>_x000D_
<div>World</div>
_x000D_
There's now a C/C++ language extension from Microsoft. You can install it by going to the "quick open" thing (Ctrl+p) and typing:
ext install cpptools
You can read about it here:
https://blogs.msdn.microsoft.com/vcblog/2016/03/31/cc-extension-for-visual-studio-code/
It's very basic, as of May 2016.
The ALTER TABLE
statement presented by Chris should work, but first you need to declare the columns NOT NULL
. All parts of a primary key need to be NOT NULL
.
The escape code "
can also be used instead of "
.
The assignment does not remove the newline characters, it's actually the echo
doing this. You need simply put quotes around the string to maintain those newlines:
echo "$testvar"
This will give the result you want. See the following transcript for a demo:
pax> cat num1.txt ; x=$(cat num1.txt)
line 1
line 2
pax> echo $x ; echo '===' ; echo "$x"
line 1 line 2
===
line 1
line 2
The reason why newlines are replaced with spaces is not entirely to do with the echo
command, rather it's a combination of things.
When given a command line, bash
splits it into words according to the documentation for the IFS
variable:
IFS: The Internal Field Separator that is used for word splitting after expansion ... the default value is
<space><tab><newline>
.
That specifies that, by default, any of those three characters can be used to split your command into individual words. After that, the word separators are gone, all you have left is a list of words.
Combine that with the echo
documentation (a bash
internal command), and you'll see why the spaces are output:
echo [-neE] [arg ...]: Output the args, separated by spaces, followed by a newline.
When you use echo "$x"
, it forces the entire x
variable to be a single word according to bash
, hence it's not split. You can see that with:
pax> function count {
...> echo $#
...> }
pax> count 1 2 3
3
pax> count a b c d
4
pax> count $x
4
pax> count "$x"
1
Here, the count
function simply prints out the number of arguments given. The 1 2 3
and a b c d
variants show it in action.
Then we try it with the two variations on the x
variable. The one without quotes shows that there are four words, "test"
, "1"
, "test"
and "2"
. Adding the quotes makes it one single word "test 1\ntest 2"
.
Urls should not have spaces in them. If you need to address one that does, use its encoded value of %20
My json file was formatted exactly as the one in the question but none of the solutions here worked out. Finally I found a workaround on another Stackoverflow thread. Since this post is the first link in Google search, I put the that answer here so that other people come to this post in the future will find it more easily.
As it's been said there the valid json file needs "[" in the beginning and "]" in the end of file. Moreover, after each json item instead of "}" there must be a "},". All brackets without quotations! This piece of code just modifies the malformed json file into its correct format.
Have a look at ?options
and use warn
:
options( warn = -1 )
Here is a program to compare the two ways suggested so far
import (
"fmt"
"github.com/bradfitz/iter"
)
func p(i int) {
fmt.Println(i)
}
func plain() {
for i := 0; i < 10; i++ {
p(i)
}
}
func with_iter() {
for i := range iter.N(10) {
p(i)
}
}
func main() {
plain()
with_iter()
}
Compile like this to generate disassembly
go build -gcflags -S iter.go
Here is plain (I've removed the non instructions from the listing)
setup
0035 (/home/ncw/Go/iter.go:14) MOVQ $0,AX
0036 (/home/ncw/Go/iter.go:14) JMP ,38
loop
0037 (/home/ncw/Go/iter.go:14) INCQ ,AX
0038 (/home/ncw/Go/iter.go:14) CMPQ AX,$10
0039 (/home/ncw/Go/iter.go:14) JGE $0,45
0040 (/home/ncw/Go/iter.go:15) MOVQ AX,i+-8(SP)
0041 (/home/ncw/Go/iter.go:15) MOVQ AX,(SP)
0042 (/home/ncw/Go/iter.go:15) CALL ,p+0(SB)
0043 (/home/ncw/Go/iter.go:15) MOVQ i+-8(SP),AX
0044 (/home/ncw/Go/iter.go:14) JMP ,37
0045 (/home/ncw/Go/iter.go:17) RET ,
And here is with_iter
setup
0052 (/home/ncw/Go/iter.go:20) MOVQ $10,AX
0053 (/home/ncw/Go/iter.go:20) MOVQ $0,~r0+-24(SP)
0054 (/home/ncw/Go/iter.go:20) MOVQ $0,~r0+-16(SP)
0055 (/home/ncw/Go/iter.go:20) MOVQ $0,~r0+-8(SP)
0056 (/home/ncw/Go/iter.go:20) MOVQ $type.[]struct {}+0(SB),(SP)
0057 (/home/ncw/Go/iter.go:20) MOVQ AX,8(SP)
0058 (/home/ncw/Go/iter.go:20) MOVQ AX,16(SP)
0059 (/home/ncw/Go/iter.go:20) PCDATA $0,$48
0060 (/home/ncw/Go/iter.go:20) CALL ,runtime.makeslice+0(SB)
0061 (/home/ncw/Go/iter.go:20) PCDATA $0,$-1
0062 (/home/ncw/Go/iter.go:20) MOVQ 24(SP),DX
0063 (/home/ncw/Go/iter.go:20) MOVQ 32(SP),CX
0064 (/home/ncw/Go/iter.go:20) MOVQ 40(SP),AX
0065 (/home/ncw/Go/iter.go:20) MOVQ DX,~r0+-24(SP)
0066 (/home/ncw/Go/iter.go:20) MOVQ CX,~r0+-16(SP)
0067 (/home/ncw/Go/iter.go:20) MOVQ AX,~r0+-8(SP)
0068 (/home/ncw/Go/iter.go:20) MOVQ $0,AX
0069 (/home/ncw/Go/iter.go:20) LEAQ ~r0+-24(SP),BX
0070 (/home/ncw/Go/iter.go:20) MOVQ 8(BX),BP
0071 (/home/ncw/Go/iter.go:20) MOVQ BP,autotmp_0006+-32(SP)
0072 (/home/ncw/Go/iter.go:20) JMP ,74
loop
0073 (/home/ncw/Go/iter.go:20) INCQ ,AX
0074 (/home/ncw/Go/iter.go:20) MOVQ autotmp_0006+-32(SP),BP
0075 (/home/ncw/Go/iter.go:20) CMPQ AX,BP
0076 (/home/ncw/Go/iter.go:20) JGE $0,82
0077 (/home/ncw/Go/iter.go:20) MOVQ AX,autotmp_0005+-40(SP)
0078 (/home/ncw/Go/iter.go:21) MOVQ AX,(SP)
0079 (/home/ncw/Go/iter.go:21) CALL ,p+0(SB)
0080 (/home/ncw/Go/iter.go:21) MOVQ autotmp_0005+-40(SP),AX
0081 (/home/ncw/Go/iter.go:20) JMP ,73
0082 (/home/ncw/Go/iter.go:23) RET ,
So you can see that the iter solution is considerably more expensive even though it is fully inlined in the setup phase. In the loop phase there is an extra instruction in the loop, but it isn't too bad.
I'd use the simple for loop.
Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw
for width: 100%
to get rid of the horizontal scrollbar.
I was looking for the same thing today and finally got a way to do it. I was hinted that it was possible due to the use of sconfig, which ask you if you want to change the computer name after joining it to a domain. Here is my raw code line. It might be enhanced but to tired to think about it for now.
$strCompName = Read-host 'Name '
$strAdmin = read-host "Authorized user for this operation "
$strDomain = read-host "Name of the domain to be joined "
add-computer -DomainName $strDomain -Credential $strAdmin
Rename-computer -newname $strCompName -DomainCredential $strAdmin
First include the file in head tag of html , then call the function in script tags under body tags e.g.
Js file function to be called
function tryMe(arg) {
document.write(arg);
}
HTML FILE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='object.js'> </script>
<title>abc</title><meta charset="utf-8"/>
</head>
<body>
<script>
tryMe('This is me vishal bhasin signing in');
</script>
</body>
</html>
finish
This https://github.com/rails/strong_parameters seems like the relevant section of the docs:
The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.
To declare that the value in params must be an array of permitted scalar values map the key to an empty array:
params.permit(:id => [])
In my app, the category_ids are passed to the create action in an array
"category_ids"=>["", "2"],
Therefore, when declaring strong parameters, I explicitly set category_ids to be an array
params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids => [])
Works perfectly now!
(IMPORTANT: As @Lenart notes in the comments, the array declarations must be at the end of the attributes list, otherwise you'll get a syntax error.)
Sorted() solution can give you some unexpected results with other strings.
List of other solutions:
>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower())))
' belou'
>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s)))
' Bbelou'
>>> s = "Bubble Bobble"
>>> ''.join(sorted(s))
' BBbbbbeellou'
If you want to get rid of the space in the result, add strip() function in any of those mentioned cases:
>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower()))).strip()
'belou'
Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.
You only need to make sure that the button inputs have type="submit"
as in <input type="submit">
and <button type="submit">
and not type="button"
, which only renders a "dead" button purely for onclick
stuff and all.
E.g.
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" name="button1" value="Button 1" />
<input type="submit" name="button2" value="Button 2" />
<input type="submit" name="button3" value="Button 3" />
</form>
with
@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MyClass myClass = new MyClass();
if (request.getParameter("button1") != null) {
myClass.method1();
} else if (request.getParameter("button2") != null) {
myClass.method2();
} else if (request.getParameter("button3") != null) {
myClass.method3();
} else {
// ???
}
request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
}
}
Alternatively, use <button type="submit">
instead of <input type="submit">
, then you can give them all the same name, but an unique value. The value of the <button>
won't be used as label, you can just specify that yourself as child.
E.g.
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<button type="submit" name="button" value="button1">Button 1</button>
<button type="submit" name="button" value="button2">Button 2</button>
<button type="submit" name="button" value="button3">Button 3</button>
</form>
with
@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MyClass myClass = new MyClass();
String button = request.getParameter("button");
if ("button1".equals(button)) {
myClass.method1();
} else if ("button2".equals(button)) {
myClass.method2();
} else if ("button3".equals(button)) {
myClass.method3();
} else {
// ???
}
request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
}
}
JavaScript 1.2 was introduced with Netscape Navigator 4 in 1997. That version number only ever had significance for Netscape browsers. For example, Microsoft's implementation (as used in Internet Explorer) is called JScript, and has its own version numbering which bears no relation to Netscape's numbering.
While value types have default values and can not be null, they also need to be explicitly initialized in order to be used. You can think of these two rules as side by side rules.
Value types can not be null ? the compiler guarantees that. If you ask how, the error message you got is the answer. Once you call their constructors, they got initialized with their default values.
int tmpCnt; // Not accepted
int tmpCnt = new Int(); // Default value applied tmpCnt = 0
Like this:
#!/bin/bash
a=2462620
b=2462620
if [ "$a" -eq "$b" ]; then
echo "They're equal";
fi
Integers can be compared with these operators:
-eq # equal
-ne # not equal
-lt # less than
-le # less than or equal
-gt # greater than
-ge # greater than or equal
See this cheatsheet: https://devhints.io/bash#conditionals
In first activity u can send intent using startActivityForResult()
and then get result from second activity after it finished using setResult
.
MainActivity.class
public class MainActivity extends AppCompatActivity {
private static final int SECOND_ACTIVITY_RESULT_CODE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// Start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
// send intent for result
startActivityForResult(intent, SECOND_ACTIVITY_RESULT_CODE);
}
// This method is called when the second activity finishes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_RESULT_CODE) {
if (resultCode == RESULT_OK) {
// get String data from Intent
String returnString = data.getStringExtra("keyName");
// set text view with string
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(returnString);
}
}
}
}
SecondActivity.class
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
// "Send text back" button click
public void onButtonClick(View view) {
// get the text from the EditText
EditText editText = (EditText) findViewById(R.id.editText);
String stringToPassBack = editText.getText().toString();
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.putExtra("keyName", stringToPassBack);
setResult(RESULT_OK, intent);
finish();
}
}
You could use the JavaScriptSerializer class, check this article to build an useful extension method.
Code from article:
namespace ExtensionMethods
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}
Usage:
using ExtensionMethods;
...
List<Person> people = new List<Person>{
new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
};
string jsonString = people.ToJSON();
Let's say in Swift 4 you have a button set up for a segue as an IBAction
like this @IBAction func nextLevel(_ sender: UIButton) {}
and you have other actions occurring within your app (i.e. a timer, gamePlay, etc.). Rather than disabling the segue button, you might want to give your user the option to use that segue while the other actions are still occurring and WITHOUT CRASHING THE APP. Here's how:
var appMode = 0
@IBAction func mySegue(_ sender: UIButton) {
if appMode == 1 { // avoid crash if button pressed during other app actions and/or conditions
let conflictingAction = sender as UIButton
conflictingAction.isEnabled = false
}
}
Please note that you will likely have other conditions within if appMode == 0
and/or if appMode == 1
that will still occur and NOT conflict with the mySegue
button. Thus, AVOIDING A CRASH.
Inspired by the work of Josien, I wondered about a simplification.
Would this also work? Much shorter:
SELECT SUBSTRING(col, CHARINDEX ('/', col) + 1, CHARINDEX ('.', col) - CHARINDEX ('/', col) - 1);
(I can't test right now because of right issues at my company SQL server, which is a problem in its own right)
The easiest thing would be to change your database to use datetime2 instead of datetime. The compatibility works nicely, and you won't get your errors.
You'll still want to do a bunch of testing...
The error is probably because you're trying to set a date to year 0 or something - but it all depends on where you have control to change stuff.
If you only want to follow actual directories, and not symbolic links,
grep -r "thingToBeFound" directory
If you want to follow symbolic links as well as actual directories (be careful of infinite recursion),
grep -R "thing to be found" directory
Since you're trying to grep recursively, the following options may also be useful to you:
-H: outputs the filename with the line
-n: outputs the line number in the file
So if you want to find all files containing Darth Vader in the current directory or any subdirectories and capture the filename and line number, but do not want the recursion to follow symbolic links, the command would be
grep -rnH "Darth Vader" .
If you want to find all mentions of the word cat in the directory
/home/adam/Desktop/TomAndJerry
and you're currently in the directory
/home/adam/Desktop/WorldDominationPlot
and you want to capture the filename but not the line number of any instance of the string "cats", and you want the recursion to follow symbolic links if it finds them, you could run either of the following
grep -RH "cats" ../TomAndJerry #relative directory
grep -RH "cats" /home/adam/Desktop/TomAndJerry #absolute directory
Source:
running "grep --help"
A short introduction to symbolic links, for anyone reading this answer and confused by my reference to them: https://www.nixtutor.com/freebsd/understanding-symbolic-links/
aString = "hello world"
aString.startswith("hello")
More info about startswith
.
There are some cases, when textbox will not handle enter key. I think it may be when you have accept button set on form. In that case, instead of KeyDown
event you should use textbox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
C90 does not support the boolean data type.
C99 does include it with this include:
#include <stdbool.h>
it works
first use: git reflog
find your SHA of your previus state and make (HEAD@{1} is an example)
git reset --hard HEAD@{1}
From The Java™ Tutorials - Abstract Classes Compared to Interfaces
Which should you use, abstract classes or interfaces?
- Consider using abstract classes if any of these statements apply to your situation:
- You want to share code among several closely related classes.
- You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
- You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
- Consider using interfaces if any of these statements apply to your situation:
- You expect that unrelated classes would implement your interface. For example, the interfaces
Comparable
andCloneable
are implemented by many unrelated classes.- You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
- You want to take advantage of multiple inheritance of type.
An example of an abstract class in the JDK is
AbstractMap
, which is part of the Collections Framework. Its subclasses (which includeHashMap
,TreeMap
, andConcurrentHashMap
) share many methods (includingget
,put
,isEmpty
,containsKey
, andcontainsValue
) thatAbstractMap
defines.
You can change your model method to property and use it in serializer with this approach.
class Foo(models.Model):
. . .
@property
def my_field(self):
return stuff
. . .
class FooSerializer(ModelSerializer):
my_field = serializers.ReadOnlyField(source='my_field')
class Meta:
model = Foo
fields = ('my_field',)
Edit: With recent versions of rest framework (I tried 3.3.3), you don't need to change to property. Model method will just work fine.
It is done to maintain the arrangement of bytes which is sent in the network(Endianness). Depending upon architecture of your device,data can be arranged in the memory either in the big endian format or little endian format. In networking, we call the representation of byte order as network byte order and in our host, it is called host byte order. All network byte order is in big endian format.If your host's memory computer architecture is in little endian format,htons() function become necessity but in case of big endian format memory architecture,it is not necessary.You can find endianness of your computer programmatically too in the following way:->
int x = 1;
if (*(char *)&x){
cout<<"Little Endian"<<endl;
}else{
cout<<"Big Endian"<<endl;
}
and then decide whether to use htons() or not.But in order to avoid the above line,we always write htons() although it does no changes for Big Endian based memory architecture.
The -not
test should fire if a property doesn't exist:
$prop = (Get-ItemProperty $regkey).$name
if (-not $prop)
{
New-ItemProperty -Path $regkey -Name $name -Value "X"
}
I came across this issue today and none of the solutions described worked for me. So here is another possible cause:
If you have something like
AddHandler x-mapp-php6 .php3 .php4 .php .phtml
in a .htaccess
file of your web content folder, it can cause your PHP scripts to stop working. In my case the server did not know the x-mapp-php6
type, since that .htaccess
file was something I imported from a different web host when I transferred the website content.
Just removing the AddHandler
line from the .htaccess
file solved it for me.
s=''.join(i for i in s if i.isdigit())
Another generator variant.
It appears that it's a bug in the Facebook app that was reported in April 2011 and has still yet to be fixed by the Android Facebook developers.
The only work around for the moment is to use their SDK.
You can also use Arrays.copyOfRange
.
Example:
public static void main(String[] args) {
int[] a = {1,2,3};
int[] b = Arrays.copyOfRange(a, 0, a.length);
a[0] = 5;
System.out.println(Arrays.toString(a)); // [5,2,3]
System.out.println(Arrays.toString(b)); // [1,2,3]
}
This method is similar to Arrays.copyOf
, but it's more flexible. Both of them use System.arraycopy
under the hood.
See:
You are incorrectly using the super
and this
keyword. Here is an example of how they work:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
move(meters: number) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Horse extends Animal {
move() {
console.log(super.name + " is Galloping...");
console.log(this.name + " is Galloping...");
super.move(45);
}
}
var tom: Animal = new Horse("Tommy the Palomino");
Animal.prototype.name = 'horseee';
tom.move(34);
// Outputs:
// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.
Explanation:
super.name
, this refers to the prototype chain of the object tom
, not the object tom
self. Because we have added a name property on the Animal.prototype
, horseee will be outputted.this.name
, the this
keyword refers to the the tom object itself. move
method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);
. Using the super
keyword in this context will look for a move
method on the prototype chain which is found on the Animal prototype.Remember TS still uses prototypes under the hood and the class
and extends
keywords are just syntactic sugar over prototypical inheritance.
I typed this in my URL bar:
javascript:{ var col = 'screwdriver'; var x = '<option value="' + col + '"' + ((col == 'screwdriver') ? ' selected' : '') + '>Very roomy</option>'; alert(x); }
In your Custom_Dialog.java class add requestWindowFeature(Window.FEATURE_NO_TITLE)
public class Custom_Dialog extends Dialog {
protected Custom_Dialog(Context context, int theme) {
super(context, theme);
// TODO Auto-generated constructor stub
requestWindowFeature(Window.FEATURE_NO_TITLE); //This line
}
}
you could deserialize your json string into a dictionary and then add new properties then serialize it.
var jsonString = @"{}";
var jsonDoc = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonString);
jsonDoc.Add("Name", "Khurshid Ali");
Console.WriteLine(JsonSerializer.Serialize(jsonDoc));
We have function total_seconds() with Python 2.7 Please see below code for python 2.6
import datetime
import time
def diffdates(d1, d2):
#Date format: %Y-%m-%d %H:%M:%S
return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))
d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)
If you don't want use external package , Just add the following function in your utilities :
var params=function(req){
let q=req.url.split('?'),result={};
if(q.length>=2){
q[1].split('&').forEach((item)=>{
try {
result[item.split('=')[0]]=item.split('=')[1];
} catch (e) {
result[item.split('=')[0]]='';
}
})
}
return result;
}
Then , in createServer
call back , add attribute params
to request
object :
http.createServer(function(req,res){
req.params=params(req); // call the function above ;
/**
* http://mysite/add?name=Ahmed
*/
console.log(req.params.name) ; // display : "Ahmed"
})
In order to protect the security of information being sent to and from your web server, it's a good idea to enable encryption of the communication between clients and the server. This is often called SSL.
So let's set up HTTPS with a self-signed certificate on Apache2. I am going to list the steps which you should follow:
sudo apt-get install apache2
sudo service apache2 status
It should output
Verify that you get default page for apache2 like this.
openssl req -x509 -newkey rsa:2048 -keyout mykey.key -out mycert.pem -days 365 -nodes
Please fill the information accordingly as shown below.
mykey.key and mycert.pem should be created in your present working directory.
sudo cp mycert.pem /etc/ssl/certs
sudo cp mykey.key /etc/ssl/private
sudo a2enmod ssl
It should output like this
sudo vi /etc/apache2/sites-available/default-ssl.conf
Please find these two lines and replace them with your cert and key paths.
Initial
Final
cd /etc/apache2/sites-available/
sudo a2ensite default-ssl.conf
sudo service apache2 restart
It should output something like this with a warning that page you are about to view is not secure because we have configured the server with self-signed certificate.
I had the same problem, the above solutions are not worked for me.
What I did is uninstalled the wamp and logout the Skype and re-installed wamp.
Then It got worked. I think the port used by wamp and Skype is same.
Hope this input will help.
Cheers :)
For GET parameters, you can grab them from document.location.search
:
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
document.write($_GET["test"]);
For POST parameters, you can serialize the $_POST
object in JSON format into a <script>
tag:
<script type="text/javascript">
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["test"]);
</script>
While you're at it (doing things on server side), you might collect the GET parameters on PHP as well:
var $_GET = <?php echo json_encode($_GET); ?>;
Note: You'll need PHP version 5 or higher to use the built-in json_encode
function.
Update: Here's a more generic implementation:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var $_GET = getQueryParams(document.location.search);
Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of
So you should prevent the default behaviour of the button click
$('#btnSave').click(function (e) {
// prevent the default event behaviour
e.preventDefault();
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
// perform your save call here
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
div.test td, div.test caption, div.test th
works for me.
The child selector > does not work in IE6.
Similar with @Michael-Neal.
I had named the controller as singular. app/controllers/product_controller.rb
When I renamed it as plural, error solved. app/controllers/products_controller.rb
Try
SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]
You can accomplish this in css under certain circumstances, but it is brittle and context-dependent.
css font-sizes can accept relative sizes to the screen. IF the containing element for your header is sized relative to the screen size, you can accomplish this by simply setting font-size: 3vw
or an appropriate size so that the text fits on one-line. If the screen is resized, the text will follow suit. Note that the width will depend on the exact text contents, and if you add characters to text that used to fit on a single line, you may need to adjust your font-size.
See this fiddle: https://jsfiddle.net/mguk8v27/
In addition to Mathias answer.
Although not mentioned in OP, if you also need to see the Powershell specific/related internal variables, you need to use Get-Variable
:
$ Get-Variable
Name Value
---- -----
$ name
? True
^ gci
args {}
ChocolateyTabSettings @{AllCommands=False}
ConfirmPreference High
DebugPreference SilentlyContinue
EnabledExperimentalFeatures {}
Error {System.Management.Automation.ParseException: At line:1 char:1...
ErrorActionPreference Continue
ErrorView NormalView
ExecutionContext System.Management.Automation.EngineIntrinsics
false False
FormatEnumerationLimit 4
...
These also include stuff you may have set in your profile startup script.