It's because you're calling doGet()
without actually implementing doGet()
. It's the default implementation of doGet() that throws the error saying the method is not supported.
There's something wrong. You have written:
string source_dir = @"E:\\Debug\\VipBat\\{0}";
and the error was
Could not find a part of the path E\Debug\VCCSBat
This is not the same directory.
In your code there's a problem, you have to use:
string source_dir = @"E:\Debug\VipBat"; // remove {0} and the \\ if using @
or
string source_dir = "E:\\Debug\\VipBat"; // remove {0} and the @ if using \\
Alternatives:
>>> map(a.__getitem__, b)
[1, 5, 5]
>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)
You're applying transitions only to the :hover
pseudo-class, and not to the element itself.
.item {
height:200px;
width:200px;
background:red;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-ms-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}
.item:hover {
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
Demo: http://jsfiddle.net/7uR8z/6/
If you don't want the transition to affect the mouse-over
event, but only mouse-out
, you can turn transitions off for the :hover
state :
.item:hover {
-webkit-transition: none;
-moz-transition: none;
-ms-transition: none;
-o-transition: none;
transition: none;
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
Hope below answer in this link will help, Multiple Value Filter
And take a look into the fiddle with example
arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}
Only using Session.Clear() when a user logs out can pose a security hole. As the session is still valid as far as the Web Server is concerned. It is then a reasonably trivial matter to sniff, and grab the session Id, and hijack that session.
For this reason, when logging a user out it would be safer and more sensible to use Session.Abandon() so that the session is destroyed, and a new session created (even though the logout UI page would be part of the new session, the new session would not have any of the users details in it and hijacking the new session would be equivalent to having a fresh session, hence it would be mute).
I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.
Here are a few links that might help:
Disable back button in android
MyActivity.java =>
@Override
public void onBackPressed() {
return;
}
How can I disable 'go back' to some activity?
AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>
You could use emscripten to compile C++ code into js.
You can do this with JSON in more recent MySQL versions. It's a blast. We will have a quick preparation to create a numbers table. Then first we create an intermediary table to convert the comma delimited strings into a json array then we will use json_extract
to blast them apart. I am encapsulating the strings in quotes carefully escaping existing quotes because I had semicolon separated strings containing commas.
So to create the numbers table, hopefully you have more clients than courses, choose an adequately big table if not.
CREATE TABLE numbers (n int PRIMARY KEY);
INSERT INTO numbers
SELECT @row := @row + 1
FROM clients JOIN (select @row:=0) t2;
Add LIMIT 50 if you know you only have 50 courses. Now, that was easy, wasn't it? Now on to the real work, honestly it's the quotes that make it uglier but at least it's more generic that way:
CREATE TABLE json_coursenames
SELECT clientId,clientName,CONCAT('["', REPLACE(REPLACE(courseName,'"','\\"'), ',', '","'), '"]') AS a
FROM clients;
CREATE TABLE extracted
SELECT clientId,clientName,REPLACE(TRIM(TRIM('"' FROM JSON_EXTRACT(a, concat('$[', n, ']')))), '\\"', '"')
FROM json_coursenames
INNER JOIN numbers ON n < JSON_LENGTH(a);
Wheee!
The meat here are these two: the CONCAT('["', REPLACE(coursename, ',', '","'), '"]')
(I dropped the second REPLACE
to make it more visible) will convert foo,bar,bar
into "foo","bar","baz"
. The other trick is JSON_EXTRACT(a, concat('$[', n, ']')
will become JSON_EXTRACT(a, $[12])
and that's the 13th element in the array, see JSON Path syntax.
Use boolean
rather than Boolean
every time you can. This will avoid many NullPointerException
s and make your code more robust.
Boolean
is useful, for example
MessageFormat.format()
.For those who want to be notified of download completion of a single image that gets requested after $(window).load
fires, you can use the image element's load
event.
e.g.:
// create a dialog box with an embedded image
var $dialog = $("<div><img src='" + img_url + "' /></div>");
// get the image element (as a jQuery object)
var $imgElement = $dialog.find("img");
// wait for the image to load
$imgElement.load(function() {
alert("The image has loaded; width: " + $imgElement.width() + "px");
});
In my experience, Oracle is very good at pushing simple predicates around. The following test was made on Oracle 11.2. I'm fairly certain it produces the same execution plan on all releases of 10g as well.
(Please people, feel free to leave a comment if you run an earlier version and tried the following)
create table table1(a number, b number);
create table table2(a number, b number);
explain plan for
select *
from (select a,b from table1
union
select a,b from table2
)
where a > 1;
select *
from table(dbms_xplan.display(format=>'basic +predicate'));
PLAN_TABLE_OUTPUT
---------------------------------------
| Id | Operation | Name |
---------------------------------------
| 0 | SELECT STATEMENT | |
| 1 | VIEW | |
| 2 | SORT UNIQUE | |
| 3 | UNION-ALL | |
|* 4 | TABLE ACCESS FULL| TABLE1 |
|* 5 | TABLE ACCESS FULL| TABLE2 |
---------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
4 - filter("A">1)
5 - filter("A">1)
As you can see at steps (4,5), the predicate is pushed down and applied before the sort (union).
I couldn't get the optimizer to push down an entire sub query such as
where a = (select max(a) from empty_table)
or a join. With proper PK/FK constraints in place it might be possible, but clearly there are limitations :)
you have have strange characters in your heading # % -- or ,
I have issue with itextsharp and itextsharp.xmlworker dlls for exception-from-hresult-0x80131040 so I have removed those both dlls from references and downloaded new dlls directly from nuget packages, which resolved my issue.
May be this method can be useful to resolved the issue to other people.
Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.
First, click Slide Show > Set Up Show.
Put a checkmark to Loop continuously until 'Esc'.
Click Ok. Now, Click Slide Show > Custom Shows. Click New.
Select the slide you are looping, click Add. Click Ok and Close.
Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.
Right click on the thumbnail of the current slide, select Hide Slide.
Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"
This has worked for me.
If your $_GET is multidimensional, this might be what you're wanting:
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
//handling for multidimensional arrays
if(decode(arguments[1]).indexOf("[]") > 0){
var newName = decode(arguments[1]).substring(0, decode(arguments[1]).length - 2);
if(typeof $_GET[newName] == 'undefined'){
$_GET[newName] = new Array();
}
$_GET[newName].push(decode(arguments[2]));
}else{
$_GET[decode(arguments[1])] = decode(arguments[2]);
}
});
you are not using the $scope you must use $ctrl.area or $scope.area instead of area
In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.
INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.
For example:
INSERT INTO MyTable
( Column1, Column2, Column3 )
VALUES
('John', 123, 'Lloyds Office'),
('Jane', 124, 'Lloyds Office'),
('Billy', 125, 'London Office'),
('Miranda', 126, 'Bristol Office');
//div[@id='..' and @class='...]
should do the trick. That's selecting the div
operators that have both attributes of the required value.
It's worth using one of the online XPath testbeds to try stuff out.
brew help
will show you the list of commands that are available.
brew list
will show you the list of installed packages. You can also append formulae, for example brew list postgres
will tell you of files installed by postgres (providing it is indeed installed).
brew search <search term>
will list the possible packages that you can install. brew search post
will return multiple packages that are available to install that have post in their name.
brew info <package name>
will display some basic information about the package in question.
You can also search http://searchbrew.com or https://brewformulas.org (both sites do basically the same thing)
For anyone using the Node.js driver instead of Mongoose, you'll want to use {returnOriginal:false}
instead of {new:true}
.
I realise this answer is not a direct response to the problem described by the OP, but I found this question as a result of searching for the same error message. I thought it worth posting my experience here just in case anybody is muddling over the same thing...
You can encounter the error in question as a result of a poorly formatted for
loop over an associative array. In a fit of bone-headedness, I was using -> instead of => in my for
statement:
foreach ($object->someArray as $key->$val) {
// do something
}
Of course, I should have had:
foreach ($object->someArray as $key=>$val) {
// do something
}
I confused myself at first, thinking the reported error was referring to the someArray property!
Note: This is not a duplicate, because the OP is aware that the image from cv2.imread
is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)
To illustrate, I've opened up this same color JPEG image:
once using the conversion
img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
and another by loading it in gray scale mode
img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom
I've summed up the diff too to see
import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image
I tried all cv2.imread()
modes
Among all the IMREAD_
modes for cv2.imread()
, only IMREAD_COLOR
and IMREAD_ANYCOLOR
can be converted using COLOR_BGR2GRAY
, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE
The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)
Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.
In brief, let's not mix the versions and types in the processing pipeline.
So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)
This will create mp4 video from all the jpg files from current directory.
echo exec("ffmpeg -framerate 1/5 -i photo%d.jpg -r 25 -pix_fmt yuv420p output.mp4");
Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
This is the simplest way for an amateur like me who is studying C++ on their own:
First Unzip the boost library to any directory of your choice. I recommend c:\directory
.
c:\boost_1_57_0
.Then go over to the link library were you experienced your problems.
c:\boost_1_57_0
.booststrap.bat
(don't bother to type on the command window just wait and don't close the window that is the place I had my problem that took me two weeks to solve. After a while the booststrap
will run and produce the same file, but now with two different names: b2
, and bjam
.b2
and wait it to run.bjam
and wait it to run. Then a folder will be produce called stage
.c:\boost_1_57_0\stage\lib
.And you are good to go!
Collected ideas from multiple C++ sources and put it into a nice, still quite simple example for getters/setters in C++:
class Canvas { public:
void resize() {
cout << "resize to " << width << " " << height << endl;
}
Canvas(int w, int h) : width(*this), height(*this) {
cout << "new canvas " << w << " " << h << endl;
width.value = w;
height.value = h;
}
class Width { public:
Canvas& canvas;
int value;
Width(Canvas& canvas): canvas(canvas) {}
int & operator = (const int &i) {
value = i;
canvas.resize();
return value;
}
operator int () const {
return value;
}
} width;
class Height { public:
Canvas& canvas;
int value;
Height(Canvas& canvas): canvas(canvas) {}
int & operator = (const int &i) {
value = i;
canvas.resize();
return value;
}
operator int () const {
return value;
}
} height;
};
int main() {
Canvas canvas(256, 256);
canvas.width = 128;
canvas.height = 64;
}
Output:
new canvas 256 256
resize to 128 256
resize to 128 64
You can test it online here: http://codepad.org/zosxqjTX
PS: FO Yvette <3
Of course there is! Win CMD can do a lot more than just split text files :)
Split a text file into separate files of 'max' lines each:
Split text file (max lines each):
: Initialize
set input=file.txt
set max=10000
set /a line=1 >nul
set /a file=1 >nul
set out=!file!_%input%
set /a max+=1 >nul
echo Number of lines in %input%:
find /c /v "" < %input%
: Split file
for /f "tokens=* delims=[" %i in ('type "%input%" ^| find /v /n ""') do (
if !line!==%max% (
set /a line=1 >nul
set /a file+=1 >nul
set out=!file!_%input%
echo Writing file: !out!
)
REM Write next file
set a=%i
set a=!a:*]=]!
echo:!a:~1!>>out!
set /a line+=1 >nul
)
If above code hangs or crashes, this example code splits files faster (by writing data to intermediate files instead of keeping everything in memory):
eg. To split a file with 7,600 lines into smaller files of maximum 3000 lines.
set
command to be fed to /g
flag of findstr
list1.txt
\[[0-9]\]
\[[0-9][0-9]\]
\[[0-9][0-9][0-9]\]
\[[0-2][0-9][0-9][0-9]\]
list2.txt
\[[3-5][0-9][0-9][0-9]\]
list3.txt
\[[6-9][0-9][0-9][0-9]\]
type "%input%" | find /v /n "" | findstr /b /r /g:list1.txt > file1.txt type "%input%" | find /v /n "" | findstr /b /r /g:list2.txt > file2.txt type "%input%" | find /v /n "" | findstr /b /r /g:list3.txt > file3.txt
for /f "tokens=* delims=[" %i in ('type "%cd%\file1.txt"') do ( set a=%i set a=!a:*]=]! echo:!a:~1!>>file_1.txt)
Notes:
Works with leading whitespace, blank lines & whitespace lines.
Tested on Win 10 x64 CMD, on 4.4GB text file, 5651982 lines.
The ISO file that suggested in the accepted answer is still not complete. The very complete offline installer is about 24GB! There is only one way to get it. follow these steps:
temp
folderC:\VS Community\
C:\VS
Community\
with this argument: /Layout .
Good Luck
In your controller use:
var path = HttpContext.Server.MapPath("~/Data/data.html");
This allows you to test the controller with Moq like so:
var queryString = new NameValueCollection();
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(r => r.QueryString).Returns(queryString);
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(c => c.Request).Returns(mockRequest.Object);
var server = new Mock<HttpServerUtilityBase>();
server.Setup(m => m.MapPath("~/Data/data.html")).Returns("path/to/test/data");
mockHttpContext.Setup(m => m.Server).Returns(server.Object);
var mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);
var controller = new MyTestController();
controller.ControllerContext = mockControllerContext.Object;
TRY THIS
SELECT E.ename,E.empno,ISNULL(E.ename,'NO MANAGER') AS MANAGER FROM emp e
INNER JOIN emp M
ON M.empno=E.empno
Instaed of subquery use self join
Use:
To check if property is undefined:
if (typeof something === "undefined") {
alert("undefined");
}
To check if property is not undefined:
if (typeof something !== "undefined") {
alert("not undefined");
}
I used this at the end of the web.php
or api.php
file and it worked perfectly:
URL::forceScheme('https');
or in perl (for completeness...):
perl -npe 'chomp; /null/ and print "$_ - Line number : $.\n" and $i++;$_="";END{print "Total null count : $i\n"}'
This works for me (reference):
# PHP error handling for production servers
# Disable display of startup errors
php_flag display_startup_errors off
# Disable display of all other errors
php_flag display_errors off
# Disable HTML markup of errors
php_flag html_errors off
# Enable logging of errors
php_flag log_errors on
# Disable ignoring of repeat errors
php_flag ignore_repeated_errors off
# Disable ignoring of unique source errors
php_flag ignore_repeated_source off
# Enable logging of PHP memory leaks
php_flag report_memleaks on
# Preserve most recent error via php_errormsg
php_flag track_errors on
# Disable formatting of error reference links
php_value docref_root 0
# Disable formatting of error reference links
php_value docref_ext 0
# Specify path to PHP error log
php_value error_log /home/path/public_html/domain/PHP_errors.log
# Specify recording of all PHP errors
# [see footnote 3] # php_value error_reporting 999999999
php_value error_reporting -1
# Disable max error string length
php_value log_errors_max_len 0
# Protect error log by preventing public access
<Files PHP_errors.log>
Order allow,deny
Deny from all
Satisfy All
</Files>
i got this image by right clicking the canvas element in firefox and saving as.
var img = new Image();
img.onload = function () {
console.debug(this.width,this.height);
var canvas = document.createElement('canvas'), ctx;
canvas.width = 188;
canvas.height = 150;
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
ctx.drawImage(img,0,0,188,150);
};
img.src = 'original.jpg';
so anyway, here is a 'fixed' version of your example:
var img = new Image();
// added cause it wasnt defined
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
var canvasCopy = document.createElement("canvas");
// adding it to the body
document.body.appendChild(canvasCopy);
var copyContext = canvasCopy.getContext("2d");
img.onload = function()
{
var ratio = 1;
// defining cause it wasnt
var maxWidth = 188,
maxHeight = 150;
if(img.width > maxWidth)
ratio = maxWidth / img.width;
else if(img.height > maxHeight)
ratio = maxHeight / img.height;
canvasCopy.width = img.width;
canvasCopy.height = img.height;
copyContext.drawImage(img, 0, 0);
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
// the line to change
// ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
// the method signature you are using is for slicing
ctx.drawImage(canvasCopy, 0, 0, canvas.width, canvas.height);
};
// changed for example
img.src = 'original.jpg';
You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.
public class ImageButton extends Parent {
private static final Image NORMAL_IMAGE = ...;
private static final Image PRESSED_IMAGE = ...;
private final ImageView iv;
public ImageButton() {
this.iv = new ImageView(NORMAL_IMAGE);
this.getChildren().add(this.iv);
this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(PRESSED_IMAGE);
}
});
// TODO other event handlers like mouse up
}
}
List indexes of -x mean the xth item from the end of the list, so n[-1]
means the last item in the list n
. Any good Python tutorial should have told you this.
It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1]
to access the last item of a list.
kubi, thanks. Your code worked. Just to be explicit (for newbies like) as you say you have to set the UITextField
's delegate
to be equal to the ViewController in which the text field resides. You can do this wherever you please. I chose the viewDidLoad
method.
- (void)viewDidLoad
{
// sets the textField delegates to equal this viewController ... this allows for the keyboard to disappear after pressing done
daTextField.delegate = self;
}
Add maven directory /bin
to System variables under the name Path
.
To check this, you can echo %PATH%
I found the following to be a working solution::
npm install aws-sdk
Once you've installed the aws-sdk , use the following code replacing values with your where needed.
var AWS = require('aws-sdk');
var fs = require('fs');
var s3 = new AWS.S3();
// Bucket names must be unique across all S3 users
var myBucket = 'njera';
var myKey = 'jpeg';
//for text file
//fs.readFile('demo.txt', function (err, data) {
//for Video file
//fs.readFile('demo.avi', function (err, data) {
//for image file
fs.readFile('demo.jpg', function (err, data) {
if (err) { throw err; }
params = {Bucket: myBucket, Key: myKey, Body: data };
s3.putObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Successfully uploaded data to myBucket/myKey");
}
});
});
I found the complete tutorial on the subject here in case you're looking for references ::
Use following link to sign .exe (setup/ installer)file (sign exe/setup file without using Microsoft setup signtool)
https://ebourg.github.io/jsign/#files
sample command java -jar jsign-2.0.jar --keystore keystore.jks" --alias alias --storepass password MyInstaller.exe
Worked for me :)
Just put a '!' in front of the boolean expression
I did not test it myself, but the documentation states that you can now override those methods: supportedInterfaceOrientations
and preferredInterfaceOrientationForPresentation
.
You can probably achieve what you want y setting only the orientation that you want in those methods.
Another solution I've used to create lighter fontawesome icons, similar to the webkit-text-stroke
approach but more portable, is to set the color of the icon to the same as the background (or transparent) and use text-shadow to create an outline:
.fa-outline-dark-gray {
color: #fff;
text-shadow: -1px -1px 0 #999,
1px -1px 0 #999,
-1px 1px 0 #999,
1px 1px 0 #999;
}
It doesn't work in ie <10, but at least it's not restricted to webkit browsers.
You can use the AND or OR operators, depending on what you want the search to return.
SELECT title FROM pages WHERE my_col LIKE %$param1% AND another_col LIKE %$param2%;
Both clauses have to match for a record to be returned. Alternatively:
SELECT title FROM pages WHERE my_col LIKE %$param1% OR another_col LIKE %$param2%;
If either clause matches then the record will be returned.
For more about what you can do with MySQL SELECT queries, try the documentation.
I don't like and understand things, which can be explained visually, by words.
That’s probably everyone’s first thought. But it’s a little bit more difficult. See Chris Shiflett’s article SERVER_NAME
Versus HTTP_HOST
.
It seems that there is no silver bullet. Only when you force Apache to use the canonical name you will always get the right server name with SERVER_NAME
.
So you either go with that or you check the host name against a white list:
$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
exit;
}
If you look this file Namespace is not the first statement.
<?php
class BulletProofException extends Exception{}
namespace BulletProof;
You can try to move the namespace over the class definition.
If you are coming from Microsoft Excel, the following functions will be similar to LEFT()
, RIGHT()
, and MID()
functions.
# This counts from the left and then extract n characters
str_left <- function(string, n) {
substr(string, 1, n)
}
# This counts from the right and then extract n characters
str_right <- function(string, n) {
substr(string, nchar(string) - (n - 1), nchar(string))
}
# This extract characters from the middle
str_mid <- function(string, from = 2, to = 5){
substr(string, from, to)
}
Examples:
x <- "some text in a string"
str_left(x, 4)
[1] "some"
str_right(x, 6)
[1] "string"
str_mid(x, 6, 9)
[1] "text"
According to this link: signature help
APK Signature Scheme v2 offers:
Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files. By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing.
It is recommended to use APK Signature Scheme v2 but is not mandatory.
Although we recommend applying APK Signature Scheme v2 to your app, this new scheme is not mandatory. If your app doesn't build properly when using APK Signature Scheme v2, you can disable the new scheme.
Since you are using .NET, which all compiles to MSIL, just reference Microsoft.VisualBasic, and use Microsoft's built-in Strings.Right
method:
using Microsoft.VisualBasic;
...
string input = "PER 343573";
string output = Strings.Right(input, 6);
No need to create a custom extension method or other work. The result is achieved with one reference and one simple line of code.
As further info on this, using Visual Basic methods with C# has been documented elsewhere. I personally stumbled on it first when trying to parse a file, and found this SO thread on using the Microsoft.VisualBasic.FileIO.TextFieldParser
class to be extremely useful for parsing .csv files.
I can tell you that the best answer I found is to put a "driver" script just after the </body>
command. It is the easiest and, probably, more universal than some of the solutions, above.
The plan: On my page is a table. I write the page with the table out to the browser, then sort it with JS. The user can resort it by clicking column headers.
After the table is ended a </tbody>
command, and the body is ended, I use the following line to invoke the sorting JS to sort the table by column 3. I got the sorting script off of the web so it is not reproduced here. For at least the next year, you can see this in operation, including the JS, at static29.ILikeTheInternet.com
. Click "here" at the bottom of the page. That will bring up another page with the table and scripts. You can see it put up the data then quickly sort it. I need to speed it up a little but the basics are there now.
</tbody></body><script type='text/javascript'>sortNum(3);</script></html>
MakerMikey
Add the following command in .htaccess file. And place that file in your htdocs folder.
Order Deny,Allow
Deny from all
Allow from <your ip>
Allow from <another ip>
In your JSON format, it do not have starting JSON object
Like :
{
"info" : <!-- this is starting JSON object -->
{
"caller":"getPoiById",
"results":
{
"indexForPhone":0,
"indexForEmail":"NULL",
.
.
}
}
}
Above Json starts with info
as JSON object. So while executing :
JSONObject json = new JSONObject(result); // create JSON obj from string
JSONObject json2 = json.getJSONObject("info"); // this will return correct
Now, we can access result
field :
JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"
I think this was missing and so the problem was solved while we use JSONTokener
like answer of yours.
Your answer is very fine. Just i think i add this information so i answered
Thank you
In Windows you can use a Powershell Script with CompareObject
compare-object -IncludeEqual -ExcludeDifferent -PassThru (get-content A.txt) (get-content B.txt)> MATCHING.txt | Out-Null #Find Matching Lines
CompareObject:
If you don't want to import csv
module for that, you can write a list of lists to a csv file using only Python built-ins
with open("output.csv", "w") as f:
for row in a:
f.write("%s\n" % ','.join(str(col) for col in row))
This is a part from a REST-Service I´ve written recently.
var select = $("#productSelect")
for (var prop in data) {
var option = document.createElement('option');
option.innerHTML = data[prop].ProduktName
option.value = data[prop].ProduktName;
select.append(option)
}
The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.
Ken's answer is basically right but I'd like to chime in on the "why would you want to use one over the other?" part of your question.
The base interface you choose for your repository has two main purposes. First, you allow the Spring Data repository infrastructure to find your interface and trigger the proxy creation so that you inject instances of the interface into clients. The second purpose is to pull in as much functionality as needed into the interface without having to declare extra methods.
The Spring Data core library ships with two base interfaces that expose a dedicated set of functionalities:
CrudRepository
- CRUD methodsPagingAndSortingRepository
- methods for pagination and sorting (extends CrudRepository
)The individual store modules (e.g. for JPA or MongoDB) expose store-specific extensions of these base interfaces to allow access to store-specific functionality like flushing or dedicated batching that take some store specifics into account. An example for this is deleteInBatch(…)
of JpaRepository
which is different from delete(…)
as it uses a query to delete the given entities which is more performant but comes with the side effect of not triggering the JPA-defined cascades (as the spec defines it).
We generally recommend not to use these base interfaces as they expose the underlying persistence technology to the clients and thus tighten the coupling between them and the repository. Plus, you get a bit away from the original definition of a repository which is basically "a collection of entities". So if you can, stay with PagingAndSortingRepository
.
The downside of directly depending on one of the provided base interfaces is two-fold. Both of them might be considered as theoretical but I think they're important to be aware of:
Page
or Pageable
in your code anyway. Spring Data is not any different from any other general purpose library like commons-lang or Guava. As long as it provides reasonable benefit, it's just fine.CrudRepository
, you expose a complete set of persistence method at once. This is probably fine in most circumstances as well but you might run into situations where you'd like to gain more fine-grained control over the methods expose, e.g. to create a ReadOnlyRepository
that doesn't include the save(…)
and delete(…)
methods of CrudRepository
.The solution to both of these downsides is to craft your own base repository interface or even a set of them. In a lot of applications I have seen something like this:
interface ApplicationRepository<T> extends PagingAndSortingRepository<T, Long> { }
interface ReadOnlyRepository<T> extends Repository<T, Long> {
// Al finder methods go here
}
The first repository interface is some general purpose base interface that actually only fixes point 1 but also ties the ID type to be Long
for consistency. The second interface usually has all the find…(…)
methods copied from CrudRepository
and PagingAndSortingRepository
but does not expose the manipulating ones. Read more on that approach in the reference documentation.
The repository abstraction allows you to pick the base repository totally driven by you architectural and functional needs. Use the ones provided out of the box if they suit, craft your own repository base interfaces if necessary. Stay away from the store specific repository interfaces unless unavoidable.
There are three types of allocation — static, automatic, and dynamic.
Static Allocation means, that the memory for your variables is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with static
defined inside functions.
Automatic memory allocation occurs for (non-static) variables defined inside functions, and is usually stored on the stack (though the C standard doesn't mandate that a stack is used). You do not have to reserve extra memory using them, but on the other hand, have also limited control over the lifetime of this memory. E.g: automatic variables in a function are only there until the function finishes.
void func() {
int i; /* `i` only exists during `func` */
}
Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don't free it, you'll run into memory leaks, which may cause your application to crash, since at some point of time, system cannot allocate more memory.
int* func() {
int* mem = malloc(1024);
return mem;
}
int* mem = func(); /* still accessible */
In the upper example, the allocated memory is still valid and accessible, even though the function terminated. When you are done with the memory, you have to free it:
free(mem);
I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.
In CSS:
textarea {
border-style: none;
border-color: Transparent;
overflow: auto;
}
I faced this problem as well but i could fix it by going to the folder /xampp/phpmyadmin/config.inc.php
Open config.inc.php, u will find (if no password) ['password']= '' or (if old password) ['password']= '123'
Change the password $cfg['Servers'][$i]['password'] = 'test' and u will be able to access phpmyadmin again :)
If using Newtonsoft.Json:
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
public static class Extensions
{
public static StringContent AsJson(this object o)
=> new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}
Example:
var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())
Maybe something like this:
<script>
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "path/to/jQuery";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
boolean Error = driver.getPageSource().contains("Your username or password was incorrect.");
if (Error == true)
{
System.out.print("Login unsuccessful");
}
else
{
System.out.print("Login successful");
}
Browser scrollbars don't work at all on iPhone/iPad. At work we are using custom JavaScript scrollbars like jScrollPane to provide a consistent cross-browser UI: http://jscrollpane.kelvinluck.com/
It works very well for me - you can make some really beautiful custom scrollbars that fit the design of your site.
The problem is caused by the fact that the Model
's toArray()
method ignores any accessors which do not directly relate to a column in the underlying table.
As Taylor Otwell mentioned here, "This is intentional and for performance reasons." However there is an easy way to achieve this:
class EventSession extends Eloquent {
protected $table = 'sessions';
protected $appends = array('availability');
public function getAvailabilityAttribute()
{
return $this->calculateAvailability();
}
}
Any attributes listed in the $appends property will automatically be included in the array or JSON form of the model, provided that you've added the appropriate accessor.
Old answer (for Laravel versions < 4.08):
The best solution that I've found is to override the toArray()
method and either explicity set the attribute:
class Book extends Eloquent {
protected $table = 'books';
public function toArray()
{
$array = parent::toArray();
$array['upper'] = $this->upper;
return $array;
}
public function getUpperAttribute()
{
return strtoupper($this->title);
}
}
or, if you have lots of custom accessors, loop through them all and apply them:
class Book extends Eloquent {
protected $table = 'books';
public function toArray()
{
$array = parent::toArray();
foreach ($this->getMutatedAttributes() as $key)
{
if ( ! array_key_exists($key, $array)) {
$array[$key] = $this->{$key};
}
}
return $array;
}
public function getUpperAttribute()
{
return strtoupper($this->title);
}
}
use this code
public List<Blog> removeDuplicates(List<Blog> list) {
// Set set1 = new LinkedHashSet(list);
Set set = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (((Blog) o1).get().equalsIgnoreCase(((Blog) o2).getId()) /*&&
((Blog)o1).getName().equalsIgnoreCase(((Blog)o2).getName())*/) {
return 0;
}
return 1;
}
});
set.addAll(list);
final List newList = new ArrayList(set);
return newList;
}
I think that the reason for this warning is config in Pycharm. You can uncheck the selection Method may be static in Editor->Inspection
As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.
I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (
The correct version, with the space before the bracket, would be
If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
start "\\filer\repo\lab\software\myapp\setup.exe"
pause
)
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
server {
index index.html index.htm;
server_name test.example.com;
location / {
root /web/test.example.com/www;
}
location /static {
root /web/test.example.com;
}
}
try this:
@System.Web.Optimization.Styles.Render("~/Content/css")
@System.Web.Optimization.Scripts.Render("~/bundles/modernizr")
It worked to me. I'm still learning, and I've not figured it out yet why it is happening
You should never need such a prefix. If such a prefix offers you any advantage, your coding style in general needs fixing, and it's not the prefix that's keeping your code from being clear. Typical bad variable names include "other" or "2". You do not fix that with requiring it to be mOther, you fix it by getting the developer to think about what that variable is doing there in the context of that function. Perhaps he meant remoteSide, or newValue, or secondTestListener or something in that scope.
It's an effective anachronism that's still propagated too far. Stop prefixing your variables and give them proper names whose clarity reflects how long they're used. Up to 5 lines you could call it "i" without confusion; beyond 50 lines you need a pretty long name.
It is worth noting that if you add things like connection strings into the app.config, that if you add items outside of the defined config sections, that it will not immediately complain, but when you try and access it, that you may then get the above errors.
Collapse all major sections and make sure there are no items outside the defined ones. Obvious, when you have actually spotted it.
Its simple:
Make your element hidden first like this:
<div id="hidden" style="display:none;">
Hi this is hidden
</div>
Then call your javascript:
<script type="text/javascript">
$(document).ready(function() {
$.fancybox("#hidden");
});
</script>
Check out the image below:
Another example:
<div id="example2" style="display:none;">
<img src="http://theinstitute.ieee.org/img/07tiProductsandServicesiStockphoto-1311258460873.jpg" />
</div>
<script type="text/javascript">
$(document).ready(function() {
$.fancybox("#example2");
});
</script>
It works for me.
public class Program
{
public static void main(String[] args) {
String str = "This is a string.\nThis is a long string.";
str = str.replaceAll("(\r\n|\n)", "<br />");
System.out.println(str);
}
}
Result:
This is a string.<br />This is a long string.
Your problem is somewhere else.
The simplest solution might be to limit the number of characters in the HTML itself. Rails has a truncate(string, length) helper, and I'm certain that whichever backend you're using provides something similar.
Due to the cross-browser issues you're already familiar with regarding the width of select boxes, this seems to me to be the most straightforward and least error-prone option.
<select>
<option value="1">One</option>
<option value="100">One hund...</option>
<select>
Using jQuery in 2016, to get click coordinates relative to the canvas, I do:
$(canvas).click(function(jqEvent) {
var coords = {
x: jqEvent.pageX - $(canvas).offset().left,
y: jqEvent.pageY - $(canvas).offset().top
};
});
This works since both canvas offset() and jqEvent.pageX/Y are relative to the document regardless of scroll position.
Note that if your canvas is scaled then these coordinates are not the same as canvas logical coordinates. To get those, you would also do:
var logicalCoords = {
x: coords.x * (canvas.width / $(canvas).width()),
y: coords.y * (canvas.height / $(canvas).height())
}
Swift 2.0 Compability
func listWithFilter () {
let fileManager = NSFileManager.defaultManager()
// We need just to get the documents folder url
let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
do {
// if you want to filter the directory contents you can do like this:
if let directoryUrls = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants) {
print(directoryUrls)
........
}
}
}
OR
func listFiles() -> [String] {
var theError = NSErrorPointer()
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if dirs != nil {
let dir = dirs![0]
do {
let fileList = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir)
return fileList as [String]
}catch {
}
}else{
let fileList = [""]
return fileList
}
let fileList = [""]
return fileList
}
It looks like you forgot to include the ngRoute module in your dependency for myApp.
In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.
'use strict';
angular.module('myApp', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);
Eclipse's JPA 2.0 support through Dali (which is included in "Eclipse IDE for JEE Developers") has its own metamodel generator integrated with Eclipse.
This should work on any JPA provider as the generated classes are standard.
Also see here.
Use AutoIt Script To Handle File Upload In Selenium Webdriver. It's working fine for the above scenario.
Runtime.getRuntime().exec("E:\\AutoIT\\FileUpload.exe");
Please use below link for further assistance: http://www.guru99.com/use-autoit-selenium.html
Amit, I have used one way to achieve this with less coding and more efficient way.
but it uses Linq.
I posted it here because maybe the answer helps other SO.
Below DAL code converts datatable object to List of YourViewModel and it's easy to understand.
public static class DAL
{
public static string connectionString = ConfigurationManager.ConnectionStrings["YourWebConfigConnection"].ConnectionString;
// function that creates a list of an object from the given data table
public static List<T> CreateListFromTable<T>(DataTable tbl) where T : new()
{
// define return list
List<T> lst = new List<T>();
// go through each row
foreach (DataRow r in tbl.Rows)
{
// add to the list
lst.Add(CreateItemFromRow<T>(r));
}
// return the list
return lst;
}
// function that creates an object from the given data row
public static T CreateItemFromRow<T>(DataRow row) where T : new()
{
// create a new object
T item = new T();
// set the item
SetItemFromRow(item, row);
// return
return item;
}
public static void SetItemFromRow<T>(T item, DataRow row) where T : new()
{
// go through each column
foreach (DataColumn c in row.Table.Columns)
{
// find the property for the column
PropertyInfo p = item.GetType().GetProperty(c.ColumnName);
// if exists, set the value
if (p != null && row[c] != DBNull.Value)
{
p.SetValue(item, row[c], null);
}
}
}
//call stored procedure to get data.
public static DataSet GetRecordWithExtendedTimeOut(string SPName, params SqlParameter[] SqlPrms)
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection con = new SqlConnection(connectionString);
try
{
cmd = new SqlCommand(SPName, con);
cmd.Parameters.AddRange(SqlPrms);
cmd.CommandTimeout = 240;
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(ds);
}
catch (Exception ex)
{
return ex;
}
return ds;
}
}
Now, The way to pass and call method is below.
DataSet ds = DAL.GetRecordWithExtendedTimeOut("ProcedureName");
List<YourViewModel> model = new List<YourViewModel>();
if (ds != null)
{
//Pass datatable from dataset to our DAL Method.
model = DAL.CreateListFromTable<YourViewModel>(ds.Tables[0]);
}
Till the date, for many of my applications, I found this as the best structure to get data.
Start your program as an administrator. The program can't rewrite your files cause your files are in a protected location on your hard drive.
Found these docu on the google docu pages:
In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns
edit
Using the example on the docu:
// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);
The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G
So you come to the range: C2:G8
If length
is undefined you can use:
function count(array){
var c = 0;
for(i in array) // in returns key, not object
if(array[i] != undefined)
c++;
return c;
}
var total = count(array);
Regarding the accepted answer, it is important to use toSerialize.GetType()
instead of typeof(T)
in XmlSerializer
constructor: if you use the first one the code covers all possible scenarios, while using the latter one fails sometimes.
Here is a link with some example code that motivate this statement, with XmlSerializer
throwing an Exception when typeof(T)
is used, because you pass an instance of a derived type to a method that calls SerializeObject<T>()
that is defined in the derived type's base class: http://ideone.com/1Z5J1. Note that Ideone uses Mono to execute code: the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.
For the sake of completeness I post the full code sample here for future reference, just in case Ideone (where I posted the code) becomes unavailable in the future:
using System;
using System.Xml.Serialization;
using System.IO;
public class Test
{
public static void Main()
{
Sub subInstance = new Sub();
Console.WriteLine(subInstance.TestMethod());
}
public class Super
{
public string TestMethod() {
return this.SerializeObject();
}
}
public class Sub : Super
{
}
}
public static class TestExt {
public static string SerializeObject<T>(this T toSerialize)
{
Console.WriteLine(typeof(T).Name); // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead
Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringWriter textWriter = new StringWriter();
// And now...this will throw and Exception!
// Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType());
// solves the problem
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
An alternative solution to floats is to use absolute positioning:
.title {
position: relative;
}
.title span:last-child {
position: absolute;
right: 6px; /* must be equal to parent's right padding */
}
See also the fiddle.
Dim x As Integer = 0
Dim y As Integer = 0
Dim k = 0
Dim l = 0
Dim bm As New Bitmap(p1.Image)
Dim om As New Bitmap(p1.Image.Width, p1.Image.Height)
Dim r, g, b As Byte
Do While x < bm.Width - 1
y = 0
l = 0
Do While y < bm.Height - 1
r = 255 - bm.GetPixel(x, y).R
g = 255 - bm.GetPixel(x, y).G
b = 255 - bm.GetPixel(x, y).B
om.SetPixel(k, l, Color.FromArgb(r, g, b))
y += 3
l += 1
Loop
x += 3
k += 1
Loop
p2.Image = om
First Option:
OPEN package.json and add "--port port-no" in "serve" section.
Just like below, I have done it.
{
"name": "app-name",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve --port 8090",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
}
Second Option: If You want through command prompt
npm run serve --port 8090
Use the utf8 module from npm to encode/decode the string.
Installation:
npm install utf8
In a browser:
<script src="utf8.js"></script>
In Node.js:
const utf8 = require('utf8');
API:
Encode:
utf8.encode(string)
Encodes any given JavaScript string (string) as UTF-8, and returns the UTF-8-encoded version of the string. It throws an error if the input string contains a non-scalar value, i.e. a lone surrogate. (If you need to be able to encode non-scalar values as well, use WTF-8 instead.)
// U+00A9 COPYRIGHT SIGN; see http://codepoints.net/U+00A9
utf8.encode('\xA9');
// ? '\xC2\xA9'
// U+10001 LINEAR B SYLLABLE B038 E; see http://codepoints.net/U+10001
utf8.encode('\uD800\uDC01');
// ? '\xF0\x90\x80\x81'
Decode:
utf8.decode(byteString)
Decodes any given UTF-8-encoded string (byteString) as UTF-8, and returns the UTF-8-decoded version of the string. It throws an error when malformed UTF-8 is detected. (If you need to be able to decode encoded non-scalar values as well, use WTF-8 instead.)
utf8.decode('\xC2\xA9');
// ? '\xA9'
utf8.decode('\xF0\x90\x80\x81');
// ? '\uD800\uDC01'
// ? U+10001 LINEAR B SYLLABLE B038 E
You simply need to do:
print 'lakjdfljsdf', # trailing comma
However in:
print 'lkajdlfjasd', 'ljkadfljasf'
There is implicit whitespace (ie ' '
).
You also have the option of:
import sys
sys.stdout.write('some data here without a new line')
After looking at sp_who, Oracle does not have that ability per se. Oracle has at least 8 processes running which run the db. Like RMON etc.
You can ask the DB which queries are running as that just a table query. Look at the V$ tables.
Quick Example:
SELECT sid,
opname,
sofar,
totalwork,
units,
elapsed_seconds,
time_remaining
FROM v$session_longops
WHERE sofar != totalwork;
>>> k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
>>> k = sorted(k)
>>> k
[[1, 2], [1, 2], [3], [4], [4], [5, 6, 2]]
>>> dedup = [k[i] for i in range(len(k)) if i == 0 or k[i] != k[i-1]]
>>> dedup
[[1, 2], [3], [4], [5, 6, 2]]
I don't know if it's necessarily faster, but you don't have to use to tuples and sets.
$('#loginBtn').click(function(e) {
e.preventDefault(); /// it should not have this code or else it wont continue
//....
});
You can't, with language primitives. As has been called out, the abc package provides this functionality in Python 2.6 and later, but there are no options for Python 2.5 and earlier. The abc
package is not a new feature of Python; instead, it adds functionality by adding explicit "does this class say it does this?" checks, with manually-implemented consistency checks to cause an error during initialization if such declarations are made falsely.
Python is a militantly dynamically-typed language. It does not specify language primitives to allow you to prevent a program from compiling because an object does not match type requirements; this can only be discovered at run time. If you require that a subclass implement a method, document that, and then just call the method in the blind hope that it will be there.
If it's there, fantastic, it simply works; this is called duck typing, and your object has quacked enough like a duck to satisfy the interface. This works just fine even if self
is the object you're calling such a method on, for the purposes of mandatory overrides due to base methods that need specific implementations of features (generic functions), because self
is a convention, not anything actually special.
The exception is in __init__
, because when your initializer is being called, the derived type's initializer hasn't, so it hasn't had the opportunity to staple its own methods onto the object yet.
If the method was't implemented, you'll get an AttributeError (if it's not there at all) or a TypeError (if something by that name is there but it's not a function or it didn't have that signature). It's up to you how you handle that- either call it programmer error and let it crash the program (and it "should" be obvious to a python developer what causes that kind of error there- an unmet duck interface), or catch and handle those exceptions when you discover that your object didn't support what you wish it did. Catching AttributeError and TypeError is important in a lot of situations, actually.
Scrum is just one of the many iterative and incremental agile software development methods. You can find here a very detailed description of the process.
In the SCRUM methodology, a Sprint is the basic unit of development. Each Sprint starts with a planning meeting, where the tasks for the sprint are identified and an estimated commitment for the sprint goal is made. A Sprint ends with a review or retrospective meeting where the progress is reviewed and lessons for the next sprint are identified. During each Sprint, the team creates finished portions of a Product.
In the Agile methods each iteration involves a team working through a full software development cycle, including planning, requirements analysis, design, coding, unit testing, and acceptance testing when a working product is demonstrated to stakeholders.
So if in a SCRUM Sprint you perform all the software development phases (from requirement analysis to acceptance testing), and in my opinion you should, you can say SCRUM Sprints correspond to AGILE Iterations.
I was receiving this error message, even though I had the max
settings set within the binding of my WCF service config file:
<basicHttpBinding>
<binding name="NewBinding1"
receiveTimeout="01:00:00"
sendTimeout="01:00:00"
maxBufferSize="2000000000"
maxReceivedMessageSize="2000000000">
<readerQuotas maxDepth="2000000000"
maxStringContentLength="2000000000"
maxArrayLength="2000000000"
maxBytesPerRead="2000000000"
maxNameTableCharCount="2000000000" />
</binding>
</basicHttpBinding>
It seemed as though these binding settings weren't being applied, thus the following error message:
IIS7 - (413) Request Entity Too Large when connecting to the service.
I realised that the name=""
attribute within the <service>
tag of the web.config
is not a free text field, as I thought it was. It is the fully qualified name of an implementation of a service contract as mentioned within this documentation page.
If that doesn't match, then the binding settings won't be applied!
<services>
<!-- The namespace appears in the 'name' attribute -->
<service name="Your.Namespace.ConcreteClassName">
<endpoint address="http://localhost/YourService.svc"
binding="basicHttpBinding" bindingConfiguration="NewBinding1"
contract="Your.Namespace.IConcreteClassName" />
</service>
</services>
I hope that saves someone some pain...
In the context of EF, marking a property as virtual allows EF to use lazy loading to load it. For lazy loading to work EF has to create a proxy object that overrides your virtual properties with an implementation that loads the referenced entity when it is first accessed. If you don't mark the property as virtual then lazy loading won't work with it.
The DBHelper class is what handles the opening and closing of sqlite databases as well sa creation and updating, and a decent article on how it all works is here. When I started android it was very useful (however I've been objective-c lately, and forgotten most of it to be any use.
interface
with a Singleton class, but a class's static methods (or e.g. a C# static class
) cannot.Yes! When IE9 is released in Jan 2011.
Let's say you want an even 15px on all four sides:
.myclass {
border-style: solid;
border-width: 2px;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
border-radius: 15px;
}
IE9 will use the default border-radius
, so just make sure you include that in all your styles calling a border radius. Then your site will be ready for IE9.
-moz-border-radius
is for Firefox, -webkit-border-radius
is for Safari and Chrome.
Furthermore: don't forget to declare your IE coding is ie9:
<meta http-equiv="X-UA-Compatible" content="IE=9" />
Some lazy developers have <meta http-equiv="X-UA-Compatible" content="IE=7" />
. If that tag exists, border-radius will never work in IE.
The easiest fix is to just float
the container. (eg. float: left;
) On another note, each id
should be unique, meaning you can't use the same id
twice in the same HTML
document. You should use classes instead, where you can use the same class
for multiple elements.
.container {
position: relative;
background: rgb(255, 100, 0);
margin: 0;
width: 40%;
height: 100px;
float: left;
}
You can use r libraries for 3 D plotting.
Steps are:
First create a data frame using data.frame() command.
Create a 3D plot by using scatterplot3D library.
Or You can also rotate your chart using rgl library by plot3d() command.
Alternately you can use plot3d() command from rcmdr library.
In MATLAB, you can use surf(), mesh() or surfl() command as per your requirement.
[http://in.mathworks.com/help/matlab/examples/creating-3-d-plots.html]
My issues was that I was running mvn compile from a child project directory instead of the parent project.
This looks far simpler:
git archive --remote=<repo_url> <branch> <path> | tar xvf -
~mypage.aspx?strID=x&strName=y&strDate=z
The below will print all the Nan columns in descending order.
df.isnull().sum().sort_values(ascending = False)
or
The below will print first 15 Nan columns in descending order.
df.isnull().sum().sort_values(ascending = False).head(15)
Best and simplest explanation I have seen on this topic - http://www.binaryintellect.net/articles/9db02aa1-c193-421e-94d0-926e440ed297.aspx
I got it working with only Route, and did not need RoutePrefix.
For example, in the controller
[HttpPost]
[Route("[action]")]
public IActionResult PostCustomer
([FromBody]CustomerOrder obj)
{
}
and
[HttpPost]
[Route("[action]")]
public IActionResult PostCustomerAndOrder
([FromBody]CustomerOrder obj)
{
}
Then, the function name goes in jquery as either -
options.url = "/api/customer/PostCustomer";
or
options.url = "/api/customer/PostCustomerAndOrder";
In Advance Tab -> scroll down and un-checked all options in advance security setting and try by checking one-by-one and finally app start running with one option TLS 1.1
that was the solution I got it.
You can use the adjacent sibling selector to achieve something similar, that might help.
.list-item.other-class + .list-item:not(.other-class)
Will effectively target the immediately following element after the last element with the class other-class
.
Read more here: https://css-tricks.com/almanac/selectors/a/adjacent-sibling/
It is easier to achieve it in SQL
var columnsList = dbContext.Database.SqlQuery<string>("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'SCHEMA_OF_YOUE_TABLE' AND TABLE_NAME = 'YOUR_TABLE_NAME'").ToList();
I have achieved this by using one nice example i have found here. I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.
You could use the GetSize function to get those information, cv.GetSize(im) would return a tuple with the width and height of the image. You can also use im.depth and img.nChan to get some more information.
And to resize an image, I would use a slightly different process, with another image instead of a matrix. It is better to try to work with the same type of data:
size = cv.GetSize(im)
thumbnail = cv.CreateImage( ( size[0] / 10, size[1] / 10), im.depth, im.nChannels)
cv.Resize(im, thumbnail)
Hope this helps ;)
Julien
One Line:
int pdfPageCount = System.IO.File.ReadAllText("example.pdf").Split(new string[] { "/Type /Page" }, StringSplitOptions.None).Count()-2;
Recommended: ITEXTSHARP
At our company, instead of asking a lot of SQL questions that anyone with a good memory can answer, we created a SQL Developers test. The test is designed to have the candidate put together a solid schema with normalization and RI considerations, check constraints etc. And then be able to create some queries to produce results sets we're looking for. They create all this against a brief design specification we give them. They are allowed to do this at home, and take as much time as they need (within reason).
Update: basic example available at https://github.com/speier/mvcassetshelper
We are using the following implementation to add JS and CSS files into the layout page.
View or PartialView:
@{
Html.Assets().Styles.Add("/Dashboard/Content/Dashboard.css");
Html.Assets().Scripts.Add("/Dashboard/Scripts/Dashboard.js");
}
Layout page:
<head>
@Html.Assets().Styles.Render()
</head>
<body>
...
@Html.Assets().Scripts.Render()
</body>
HtmlHelper extension:
public static class HtmlHelperExtensions
{
public static AssetsHelper Assets(this HtmlHelper htmlHelper)
{
return AssetsHelper.GetInstance(htmlHelper);
}
}
public class AssetsHelper
{
public static AssetsHelper GetInstance(HtmlHelper htmlHelper)
{
var instanceKey = "AssetsHelperInstance";
var context = htmlHelper.ViewContext.HttpContext;
if (context == null) return null;
var assetsHelper = (AssetsHelper)context.Items[instanceKey];
if (assetsHelper == null)
context.Items.Add(instanceKey, assetsHelper = new AssetsHelper());
return assetsHelper;
}
public ItemRegistrar Styles { get; private set; }
public ItemRegistrar Scripts { get; private set; }
public AssetsHelper()
{
Styles = new ItemRegistrar(ItemRegistrarFormatters.StyleFormat);
Scripts = new ItemRegistrar(ItemRegistrarFormatters.ScriptFormat);
}
}
public class ItemRegistrar
{
private readonly string _format;
private readonly IList<string> _items;
public ItemRegistrar(string format)
{
_format = format;
_items = new List<string>();
}
public ItemRegistrar Add(string url)
{
if (!_items.Contains(url))
_items.Add(url);
return this;
}
public IHtmlString Render()
{
var sb = new StringBuilder();
foreach (var item in _items)
{
var fmt = string.Format(_format, item);
sb.AppendLine(fmt);
}
return new HtmlString(sb.ToString());
}
}
public class ItemRegistrarFormatters
{
public const string StyleFormat = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";
public const string ScriptFormat = "<script src=\"{0}\" type=\"text/javascript\"></script>";
}
I use the current working directory ./
when building several apps off the same domain:
<base href="./">
On a side note, I use .htaccess
to assist with my routing on page reload:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.html [L]
Although building the URL or using tools is still possible, it is not needed anymore.
https://www.nuget.org/ currently has a download link named "Download package", that is available even if you don't have an account on the site.
(at the bottom of the right column).
Example of EntityFramework's detail page: https://www.nuget.org/packages/EntityFramework/: (Updated after comment of kwitee.)
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
~/.matplotlib
. ~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
If you have Node.js 4.4+, take a look at reqclient, it allows you to make calls and log the requests in cURL style, so you can easily check and reproduce the calls outside the application.
Returns Promise objects instead of pass simple callbacks, so you can handle the result in a more "fashion" way, chain the result easily, and handle errors in a standard way. Also removes a lot of boilerplate configurations on each request: base URL, time out, content type format, default headers, parameters and query binding in the URL, and basic cache features.
This is an example of how to initialize it, make a call and log the operation with curl style:
var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
baseUrl:"http://baseurl.com/api/", debugRequest:true, debugResponse:true});
client.post("client/orders", {"client": 1234, "ref_id": "A987"},{"x-token": "AFF01XX"});
This will log in the console...
[Requesting client/orders]-> -X POST http://baseurl.com/api/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json
And when the response is returned ...
[Response client/orders]<- Status 200 - {"orderId": 1320934}
This is an example of how to handle the response with the promise object:
client.get("reports/clients")
.then(function(response) {
// Do something with the result
}).catch(console.error); // In case of error ...
Of course, it can be installed with: npm install reqclient
.
I would also like to add something here that if you load desired form that contain tooltip controll before the program's run then tool tip control on that form will not work as described below...
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
objfrmmain = new Frm_Main();
Showtop();//this is procedure in program.cs to load an other form, so if that contain's tool tip control then it will not work
Application.Run(objfrmmain);
}
so I solved this problem by puting following code in Fram_main_load event procedure like this
private void Frm_Main_Load(object sender, EventArgs e)
{
Program.Showtop();
}
Just to save some of you time...
On my Galaxy S v.2.3.3 Shared Preferences are not stored in:/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
but are now located in: /dbdata/databases/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
I believe they changed this in 2.3
In CurrentGame
component you need to change initial state because you are trying use loop for participants
but this property is undefined
that's why you get error.,
getInitialState: function(){
return {
data: {
participants: []
}
};
},
also, as player
in .map
is Object
you should get properties from it
this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
// -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})
The API can't be loaded after the document has finished loading by default, you'll need to load it asynchronous.
modify the page with the map:
<div id="map_canvas" style="height: 354px; width:713px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script>
var directionsDisplay,
directionsService,
map;
function initialize() {
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
}
</script>
For more details take a look at: https://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function/14185834#14185834
You can set AWS_REGION environment.
assert(process.env.AWS_REGION, 'Missing AWS_REGION env (eg. ap-northeast-1)');
const aws = require('aws-sdk');
const lambda = new aws.Lambda();
You can pass the parameter to the setTimeout callback function as:
setTimeout(function, milliseconds, param1, param2, ...)
eg.
function myFunction() {
setTimeout(alertMsg, 3000, "Hello");
}
function alertMsg(message) {
alert(message)
}
db.<COLLECTION NAME>.find({ "<FIELD NAME>": { $exists: true, $ne: null } })
I use rank
:
rum <- read.table(textConnection("P1 P2 P3 T1 T2 T3 I1 I2
2 3 5 52 43 61 6 b
6 4 3 72 NA 59 1 a
1 5 6 55 48 60 6 f
2 4 4 65 64 58 2 b
1 5 6 55 48 60 6 c"), header = TRUE)
> rum[order(rum$I1, -rank(rum$I2), decreasing = TRUE), ]
P1 P2 P3 T1 T2 T3 I1 I2
1 2 3 5 52 43 61 6 b
5 1 5 6 55 48 60 6 c
3 1 5 6 55 48 60 6 f
4 2 4 4 65 64 58 2 b
2 6 4 3 72 NA 59 1 a
Use std::string::size
or std::string::length
(both are the same).
As you insist to use strlen
, you can:
int size = strlen( str.c_str() );
note the usage of std::string::c_str
, which returns const char*
.
BUT strlen
counts untill it hit \0
char and std::string
can store such chars. In other words, strlen
could sometimes lie for the size.
Changing the output path worked for me in Visual Studio 2015. This should help - Changing the Build Output directory
A functor is pretty much just a class which defines the operator(). That lets you create objects which "look like" a function:
// this is a functor
struct add_x {
add_x(int val) : x(val) {} // Constructor
int operator()(int y) const { return x + y; }
private:
int x;
};
// Now you can use it like this:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument
std::vector<int> in; // assume this contains a bunch of values)
std::vector<int> out(in.size());
// Pass a functor to std::transform, which calls the functor on every element
// in the input sequence, and stores the result to the output sequence
std::transform(in.begin(), in.end(), out.begin(), add_x(1));
assert(out[i] == in[i] + 1); // for all i
There are a couple of nice things about functors. One is that unlike regular functions, they can contain state. The above example creates a function which adds 42 to whatever you give it. But that value 42 is not hardcoded, it was specified as a constructor argument when we created our functor instance. I could create another adder, which added 27, just by calling the constructor with a different value. This makes them nicely customizable.
As the last lines show, you often pass functors as arguments to other functions such as std::transform or the other standard library algorithms. You could do the same with a regular function pointer except, as I said above, functors can be "customized" because they contain state, making them more flexible (If I wanted to use a function pointer, I'd have to write a function which added exactly 1 to its argument. The functor is general, and adds whatever you initialized it with), and they are also potentially more efficient. In the above example, the compiler knows exactly which function std::transform
should call. It should call add_x::operator()
. That means it can inline that function call. And that makes it just as efficient as if I had manually called the function on each value of the vector.
If I had passed a function pointer instead, the compiler couldn't immediately see which function it points to, so unless it performs some fairly complex global optimizations, it'd have to dereference the pointer at runtime, and then make the call.
Even if you are using IIS or apache, in my guess you are using static html page as a landing page, and by default the web server doesn't allow POST or GET verb on .html page, facebook calls your page via POST/GET verb
the solution would be to rename the page into .php or .aspx and you should be good to go :)
You are using aggregate
function which not getting the items to perform action , you must verify linq query is giving some result as below:
var maxOrderLevel =sdv.Any()? sdv.Max(s => s.nOrderLevel):0
In Oracle, you could do this:
create table D (
ID numeric(1),
CODE varchar(2),
constraint PK_D primary key (ID, CODE)
);
Dim MyString As String = "Hello World"
Dim YourString As String = "Hello World"
Console.WriteLine(String.Equals(MyString, YourString))
returns a bool True. This comparison is case-sensitive.
So in your example,
if String.Equals(string1, string2) and String.Equals(string3, string4) then
' do something
else
' do something else
end if
If you refer the official angular docs
https://angular.io/guide/attribute-directives
There are three kinds of directives in Angular:
As the Application grows we find difficulty in maintaining all these codes. For reusability purpose, we separate our logic in smart components and dumb components and we use directives (structural or attribute) to make changes in the DOM.
I would use virtualenv at your HOME directory.
$ sudo easy_install -U virtualenv
$ cd ~
$ virtualenv .
$ bin/pip ...
You could then also alter ~/.(login|profile|bash_profile)
, whichever is right for your shell to add ~/bin to your PATH and then that pip|python|easy_install
would be the one used by default.
Not sure what isn't working in your case, but the following code will put a formula into cell A1 that will retrieve the value in the cell G2.
strProjectName = "Sheet1"
Cells(1, 1).Formula = "=" & strProjectName & "!" & Cells(2, 7).Address
The workbook and worksheet that strProjectName
references must exist at the time that this formula is placed. Excel will immediately try to evaluate the formula. You might be able to stop that from happening by turning off automatic recalculation until the workbook does exist.
I might've over-engineered my own solution without realizing that Type.valueOf("enum string")
actually existed.
I guess it gives more granular control but I'm not sure it's really necessary.
public enum Type {
DEBIT,
CREDIT;
public static Map<String, Type> typeMapping = Maps.newHashMap();
static {
typeMapping.put(DEBIT.name(), DEBIT);
typeMapping.put(CREDIT.name(), CREDIT);
}
public static Type getType(String typeName) {
if (typeMapping.get(typeName) == null) {
throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
}
return typeMapping.get(typeName);
}
}
I guess you're exchanging IllegalArgumentException
for RuntimeException
(or whatever exception you wish to throw) which could potentially clean up code.
All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static
and I used the same STATIC_URL in my dev settings.py file.
This causes a silent failure in django/conf/urls/static.py.
The test elif not settings.DEBUG or '://' in prefix:
picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.
It would be thoughtful if Django spit out an error message stating you can't use a http(s)://
with DEBUG = True
I had to change STATIC_URL to be '/static/'
I have tried all the above answers and nothing worked for me, as there was a proxy password encoding issues.
This command worked:
git config --global http.proxy http://[email protected]:PortNumber
Do not enter the password in your command. It will dynamically ask for when you try to connect to any git repo.
To disable link to access another page on touch device:
if (control == false)
document.getElementById('id_link').setAttribute('href', '#');
else
document.getElementById('id_link').setAttribute('href', 'page/link.html');
end if;
Let maven generate a batch file to start your application. This is the simplest way to this.
You can use the appassembler-maven-plugin for such purposes.
You can also do
console.log("a = %o, b = %o", a, b);
where a and b are objects.
Here is a solution where you can add a gradient and change its colours using only CSS:
// JS is not required for the solution. It's used only for the interactive demo._x000D_
const svg = document.querySelector('svg');_x000D_
document.querySelector('#greenButton').addEventListener('click', () => svg.setAttribute('class', 'green'));_x000D_
document.querySelector('#redButton').addEventListener('click', () => svg.setAttribute('class', 'red'));
_x000D_
svg.green stop:nth-child(1) {_x000D_
stop-color: #60c50b;_x000D_
}_x000D_
svg.green stop:nth-child(2) {_x000D_
stop-color: #139a26;_x000D_
}_x000D_
_x000D_
svg.red stop:nth-child(1) {_x000D_
stop-color: #c84f31;_x000D_
}_x000D_
svg.red stop:nth-child(2) {_x000D_
stop-color: #dA3448;_x000D_
}
_x000D_
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
<linearGradient id="gradient">_x000D_
<stop offset="0%" />_x000D_
<stop offset="100%" />_x000D_
</linearGradient>_x000D_
<rect width="100" height="50" fill="url(#gradient)" />_x000D_
</svg>_x000D_
_x000D_
<br/>_x000D_
<button id="greenButton">Green</button>_x000D_
<button id="redButton">Red</button>
_x000D_
According to the documentation (emphasis mine):
Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
Something like:
function populate(selector) {
$(selector)
.append('<option value="foo">foo</option>')
.append('<option value="bar">bar</option>')
}
populate('#myform .myselect');
Or even:
$.fn.populate = function() {
$(this)
.append('<option value="foo">foo</option>')
.append('<option value="bar">bar</option>')
}
$('#myform .myselect').populate();
About losing your putty
: often the ps ... | awk/grep/perl/...
process gets matched, too! So the old school trick is like this
ps -ef | grep -i [n]ohup
That way the regex search doesn't match the regex search process!
In Eclipse, you don't need to change JAVA_HOME, you just need to change the run configuration for Maven to something above 1.6 (even if your project is on Java 6, Maven shouldn't be). Right-click the project, choose Maven Build or Run As > Run Configurations and set the correct JDK version.
This is working for me:
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->get();
If you want to do it from code behind, try this:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Message');", true);
profile name is not valid [SQLSTATE 42000] (Error 14607)
This happened to me after I copied job script from old SQL server to new SQL server. In SSMS, under Management, the Database Mail profile name was different in the new SQL Server. All I had to do was update the name in job script.
I Solved the issue simply by ensuring that I had the correct git SSH url without any trailing spaces:
[email protected]:USERNAME/REPOSITORY.git
You specify the named capture group string by passing it to the indexer of the Groups
property of a resulting Match
object.
Here is a small example:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
String sample = "hello-world-";
Regex regex = new Regex("-(?<test>[^-]*)-");
Match match = regex.Match(sample);
if (match.Success)
{
Console.WriteLine(match.Groups["test"].Value);
}
}
}
Hopefully this helps:
>>> seta = set('1234')
>>> listb = ['a','b','c']
>>> seta.union(listb)
set(['a', 'c', 'b', '1', '3', '2', '4'])
>>> seta
set(['1', '3', '2', '4'])
>>> seta = seta.union(listb)
>>> seta
set(['a', 'c', 'b', '1', '3', '2', '4'])
You can simply use the HTML onwheel attribute.
This option have no effects on scrolling over other elements of the page.
And add a listener for all inputs don't work in inputs dynamically created posteriorly.
Aditionaly, you can remove the input arrows with CSS.
input[type="number"]::-webkit-outer-spin-button, _x000D_
input[type="number"]::-webkit-inner-spin-button {_x000D_
-webkit-appearance: none;_x000D_
margin: 0;_x000D_
}_x000D_
input[type="number"] {_x000D_
-moz-appearance: textfield;_x000D_
}
_x000D_
<input type="number" onwheel="this.blur()" />
_x000D_
Assuming your ints are 0, 375, 668,5 and 6:
{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [
0,
375,
668,
5,
6
]
}
I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here http://json.org/
The most condensed version:
public String getNameFromURI(Uri uri) {
Cursor c = getContentResolver().query(uri, null, null, null, null);
c.moveToFirst();
return c.getString(c.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
According to React philosophy component can't change its props. they should be received from the parent and should be immutable. Only parent can change the props of its children.
nice explanation on state vs props
also, read this thread Why can't I update props in react.js?
Who needs sed
? Here is the bash
way:
cat test.txt | while read line; do echo -n "$line "; done
Use re.sub
directly, this allows you to specify a count
:
regex.sub('', url, 1)
(Note that the order of arguments is replacement
, original
not the opposite, as might be suspected.)
I was looking for an elegant way to do it where the bounds might be switched (ie. not sure which order the values are in).
This will only work on newer versions of C# where the ?: exists
bool ValueWithinBounds(float val, float bounds1, float bounds2)
{
return bounds1 >= bounds2 ?
val <= bounds1 && val >= bounds2 :
val <= bounds2 && val >= bounds1;
}
Obviously you could change the = signs in there for your purposes. Could get fancy with type casting too. I just needed a float return within bounds (or equal to)
Here is what worked for me in similar case.
After you finish writing into the Servlet
OutputStream
just call response.sendRedirect("yourPage.jsp");
. That would cause initiation of a new request from the browser, therefore avoid writing into the same output stream.
1. Installing OpenCV 2.4.3
First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\
.
Wait until all files get extracted. It will create a new directory C:\opencv
which
contains OpenCV header files, libraries, code samples, etc.
Now you need to add the directory C:\opencv\build\x86\vc10\bin
to your system PATH. This directory contains OpenCV DLLs required for running your code.
Open Control Panel → System → Advanced system settings → Advanced Tab → Environment variables...
On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin;
(3), then click Ok.
On some computers, you may need to restart your computer for the system to recognize the environment path variables.
This will completes the OpenCV 2.4.3 installation on your computer.
2. Create a new project and set up Visual C++
Open Visual C++ and select File → New → Project... → Visual C++ → Empty Project. Give a name for your project (e.g: cvtest
) and set the project location (e.g: c:\projects
).
Click Ok. Visual C++ will create an empty project.
Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest
and select Properties → VC++ Directories.
Select Include Directories to add a new entry and type C:\opencv\build\include
.
Click Ok to close the dialog.
Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib
.
Click Ok to close the dialog.
Back to the property dialog, select Linker → Input → Additional Dependencies to add new entries. On the popup dialog, type the files below:
opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib
Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).
Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.
NOTE:
These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:
opencv_core243.lib
opencv_imgproc243.lib
...
instead of:
opencv_core243d.lib
opencv_imgproc243d.lib
...
You've done setting up Visual C++, now is the time to write the real code. Right click your project and select Add → New Item... → Visual C++ → C++ File.
Name your file (e.g: loadimg.cpp
) and click Ok. Type the code below in the editor:
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat im = imread("c:/full/path/to/lena.jpg");
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
imshow("Image", im);
waitKey(0);
}
The code above will load c:\full\path\to\lena.jpg
and display the image. You can
use any image you like, just make sure the path to the image is correct.
Type F5 to compile the code, and it will display the image in a nice window.
And that is your first OpenCV program!
3. Where to go from here?
Now that your OpenCV environment is ready, what's next?
c:\opencv\samples\cpp
.If you use mongoose, you can just use(assuming you're using subdocuments and population):
Profile.findById profileId
.select 'friends'
.exec (err, profile) ->
if err or not profile
handleError err, profile, res
else
Status.find { profile: { $in: profile.friends } }, (err, statuses) ->
if err
handleErr err, statuses, res
else
res.json createJSON statuses
It retrieves Statuses
which belong to one of Profile
(profileId
) friends. Friends is array of references to other Profiles
. Profile
schema with friends
defined:
schema = new mongoose.Schema
# ...
friends: [
type: mongoose.Schema.Types.ObjectId
ref: 'Profile'
unique: true
index: true
]
Improving the answer https://stackoverflow.com/a/14720445/6654512 to work with Python3. That piece of code would sometimes generate numbers greater than 1 and matplotlib would throw an error.
for X,Y in data:
scatter(X, Y, c=numpy.random.random(3))
I was solving a similar task today in javascript.
I've settled on this getPerceivedLightness(rgb)
function for a HEX RGB color.
It deals with Helmholtz-Kohlrausch effect via Fairchild and Perrotta formula for luminance correction.
/**
* Converts RGB color to CIE 1931 XYZ color space.
* https://www.image-engineering.de/library/technotes/958-how-to-convert-between-srgb-and-ciexyz
* @param {string} hex
* @return {number[]}
*/
export function rgbToXyz(hex) {
const [r, g, b] = hexToRgb(hex).map(_ => _ / 255).map(sRGBtoLinearRGB)
const X = 0.4124 * r + 0.3576 * g + 0.1805 * b
const Y = 0.2126 * r + 0.7152 * g + 0.0722 * b
const Z = 0.0193 * r + 0.1192 * g + 0.9505 * b
// For some reason, X, Y and Z are multiplied by 100.
return [X, Y, Z].map(_ => _ * 100)
}
/**
* Undoes gamma-correction from an RGB-encoded color.
* https://en.wikipedia.org/wiki/SRGB#Specification_of_the_transformation
* https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
* @param {number}
* @return {number}
*/
function sRGBtoLinearRGB(color) {
// Send this function a decimal sRGB gamma encoded color value
// between 0.0 and 1.0, and it returns a linearized value.
if (color <= 0.04045) {
return color / 12.92
} else {
return Math.pow((color + 0.055) / 1.055, 2.4)
}
}
/**
* Converts hex color to RGB.
* https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
* @param {string} hex
* @return {number[]} [rgb]
*/
function hexToRgb(hex) {
const match = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
if (match) {
match.shift()
return match.map(_ => parseInt(_, 16))
}
}
/**
* Converts CIE 1931 XYZ colors to CIE L*a*b*.
* The conversion formula comes from <http://www.easyrgb.com/en/math.php>.
* https://github.com/cangoektas/xyz-to-lab/blob/master/src/index.js
* @param {number[]} color The CIE 1931 XYZ color to convert which refers to
* the D65/2° standard illuminant.
* @returns {number[]} The color in the CIE L*a*b* color space.
*/
// X, Y, Z of a "D65" light source.
// "D65" is a standard 6500K Daylight light source.
// https://en.wikipedia.org/wiki/Illuminant_D65
const D65 = [95.047, 100, 108.883]
export function xyzToLab([x, y, z]) {
[x, y, z] = [x, y, z].map((v, i) => {
v = v / D65[i]
return v > 0.008856 ? Math.pow(v, 1 / 3) : v * 7.787 + 16 / 116
})
const l = 116 * y - 16
const a = 500 * (x - y)
const b = 200 * (y - z)
return [l, a, b]
}
/**
* Converts Lab color space to Luminance-Chroma-Hue color space.
* http://www.brucelindbloom.com/index.html?Eqn_Lab_to_LCH.html
* @param {number[]}
* @return {number[]}
*/
export function labToLch([l, a, b]) {
const c = Math.sqrt(a * a + b * b)
const h = abToHue(a, b)
return [l, c, h]
}
/**
* Converts a and b of Lab color space to Hue of LCH color space.
* https://stackoverflow.com/questions/53733379/conversion-of-cielab-to-cielchab-not-yielding-correct-result
* @param {number} a
* @param {number} b
* @return {number}
*/
function abToHue(a, b) {
if (a >= 0 && b === 0) {
return 0
}
if (a < 0 && b === 0) {
return 180
}
if (a === 0 && b > 0) {
return 90
}
if (a === 0 && b < 0) {
return 270
}
let xBias
if (a > 0 && b > 0) {
xBias = 0
} else if (a < 0) {
xBias = 180
} else if (a > 0 && b < 0) {
xBias = 360
}
return radiansToDegrees(Math.atan(b / a)) + xBias
}
function radiansToDegrees(radians) {
return radians * (180 / Math.PI)
}
function degreesToRadians(degrees) {
return degrees * Math.PI / 180
}
/**
* Saturated colors appear brighter to human eye.
* That's called Helmholtz-Kohlrausch effect.
* Fairchild and Pirrotta came up with a formula to
* calculate a correction for that effect.
* "Color Quality of Semiconductor and Conventional Light Sources":
* https://books.google.ru/books?id=ptDJDQAAQBAJ&pg=PA45&lpg=PA45&dq=fairchild+pirrotta+correction&source=bl&ots=7gXR2MGJs7&sig=ACfU3U3uIHo0ZUdZB_Cz9F9NldKzBix0oQ&hl=ru&sa=X&ved=2ahUKEwi47LGivOvmAhUHEpoKHU_ICkIQ6AEwAXoECAkQAQ#v=onepage&q=fairchild%20pirrotta%20correction&f=false
* @return {number}
*/
function getLightnessUsingFairchildPirrottaCorrection([l, c, h]) {
const l_ = 2.5 - 0.025 * l
const g = 0.116 * Math.abs(Math.sin(degreesToRadians((h - 90) / 2))) + 0.085
return l + l_ * g * c
}
export function getPerceivedLightness(hex) {
return getLightnessUsingFairchildPirrottaCorrection(labToLch(xyzToLab(rgbToXyz(hex))))
}
If you store stylesheets/images in a folder so that multiple websites can use them, or you want to re-use the same files on another site on the same server, I have found that my browser/Apache does not allow me to go to any parent folder above the website root URL. This seems obvious for security reasons - one should not be able to browse around on the server any place other than the specified web folders.
Eg. does not work: www.mywebsite.com/../images
As a workaround, I use Symlinks:
Go to the directory of www.mywebsite.com Run the command ln -s ../images images
Now www.mywebsite.com/images will point to www.mywebsite.com/../images
For such companies as google, amazon etc, whose servers are running at max capacity in 24/7-mode, reducing traffic means real money - less hardware, less energy, less maintenance. Shifting CPU-usage from server to client pays off, and SPAs shine. The advantages overweight disadvantages by far. So, SPA or not SPA depends much on the use case.
Just for mentioning another, probably not so obvious (for Web-developers) use case for SPAs: I'm currently looking for a way to implement GUIs in embedded systems and browser-based architecture seems appealing to me. Traditionally there were not many possibilities for UIs in embedded systems - Java, Qt, wx, etc or propriety commercial frameworks. Some years ago Adobe tried to enter the market with flash but seems to be not so successful.
Nowadays, as "embedded systems" are as powerful as mainframes some years ago, a browser-based UI connected to the control unit via REST is a possible solution. The advantage is, the huge palette of tools for UI for no cost. (e.g. Qt require 20-30$ per sold unit on royalty fees plus 3000-4000$ per developer)
For such architecture SPA offers many advantages - e.g. more familiar development-approach for desktop-app developers, reduced server access (often in car-industry the UI and system muddles are separate hardware, where the system-part has an RT OS).
As the only client is the built-in browser, the mentioned disadvantages like JS-availability, server-side logging, security don't count any more.
Use a BinaryReader object to return a byte array from the stream like:
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
also for array you can use short annotattion:
$arr = [
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
]
];
echo json_encode($arr);
You shouldn't use ForEach
in that way. Read Lippert's “foreach” vs “ForEach”
If you want to be cruel with yourself (and the world), at least don't create useless List
employees.All(p => {
collection.AddRange(p.Departments);
p.Departments.All(u => { u.SomeProperty = null; return true; } );
return true;
});
Note that the result of the All
expression is a bool
value that we are discarding (we are using it only because it "cycles" all the elements)
I'll repeat. You shouldn't use ForEach
to change objects. LINQ should be used in a "functional" way (you can create new objects but you can't change old objects nor you can create side-effects). And what you are writing is creating so many useless List
only to gain two lines of code...
In case where multiple columns identify unique row (e.g relations table ) there you can use following
Use row id e.g. emp_dept(empid, deptid, startdate, enddate) suppose empid and deptid are unique and identify row in that case
select oed.empid, count(oed.empid)
from emp_dept oed
where exists ( select *
from emp_dept ied
where oed.rowid <> ied.rowid and
ied.empid = oed.empid and
ied.deptid = oed.deptid )
group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);
and if such table has primary key then use primary key instead of rowid, e.g id is pk then
select oed.empid, count(oed.empid)
from emp_dept oed
where exists ( select *
from emp_dept ied
where oed.id <> ied.id and
ied.empid = oed.empid and
ied.deptid = oed.deptid )
group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);
What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.
You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.
Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).
Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see EPAS.org
Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.
In summary then: it all depends on your region.
Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.
Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.
To replace a path within files (avoiding escape characters) you may use the following command:
sed -i 's@old_path@new_path@g'
The @ sign means that all of the special characters should be ignored in a following string.
Best way i use:
1- add link to your html:
<a id="linkDynamic" target="_blank" href="#"></a>
2- add JS function:
function OpenNewTab(href)
{
document.getElementById('linkDynamic').href = href;
document.getElementById('linkDynamic').click();
}
3- just call OpenNewTab function with the link you want
To prevent full size category images slowing page down, you can use smaller images with wp_get_attachment_image_src()
:
<?php
$thumbnail_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
// get the medium-sized image url
$image = wp_get_attachment_image_src( $thumbnail_id, 'medium' );
// Output in img tag
echo '<img src="' . $image[0] . '" alt="" />';
// Or as a background for a div
echo '<div class="image" style="background-image: url("' . $image[0] .'")"></div>';
?>
EDIT: Fixed variable name and missing quote
grep '^..' my_file
example
THIS
IS
THE
FILE
EOF_MYFILE
it gives as output only lines with at least 2 characters.
THIS
IS
THE
FILE
EOF_MYFILE
See also the results with grep '^' my_file
outputs
THIS
IS
THE
FILE
EOF_MYFILE
and also with grep '^.' my_file
outputs
THIS
IS
THE
FILE
EOF_MYFILE
The below is what I have used i the past to accomplish the need for a Scalar UDF in MS SQL:
IF OBJECT_ID('tempdb..##fn_Divide') IS NOT NULL DROP PROCEDURE ##fn_Divide
GO
CREATE PROCEDURE ##fn_Divide (@Numerator Real, @Denominator Real) AS
BEGIN
SELECT Division =
CASE WHEN @Denominator != 0 AND @Denominator is NOT NULL AND @Numerator != 0 AND @Numerator is NOT NULL THEN
@Numerator / @Denominator
ELSE
0
END
RETURN
END
GO
Exec ##fn_Divide 6,4
This approach which uses a global variable for the PROCEDURE allows you to make use of the function not only in your scripts, but also in your Dynamic SQL needs.
HTML Code:
<div id="welcomeDiv" style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />
Javascript:
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
}
See the Demo: http://jsfiddle.net/rathoreahsan/vzmnJ/
The whole point is to write implementation-independent code. unsigned char
is not guaranteed to be an 8-bit type. uint8_t
is (if available).
This is the answer.
<asp:TextBox id="yourtextBoxname" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
_x000D_
AutoCompleteType="Disabled"
If you still get the pre-filled boxes for example in the Firefox browser then its the browser's fault. You have to go
'Options' --> 'Security'(tab) --> Untick
'Remember password for sites and click on Saved Passwords button to delete any details that the browser has saved.
This should solve the problem
It happens when there is no runnable module for Android App in your project. Creating new project definitely solves this.
You can check this using Run > Edit Configurations > Adding Android App
. If there is not runnable Android App module then you can't see "AVD Manager" in the menu.
The Run as *Anything command saves you from logging out and logging in as the user for which you use the runas command for.
The reason programs ask for this elevated privilege started with Black Comb and the Panther folder. There is 0 access to the Kernel in windows unless through the Admin prompt and then it is only a virtual relation with the O/S kernel.
Hoorah!
Split on newlines (environment agnostic) and print regularly -- no need to worry about encoding or xss:
@if (!string.IsNullOrWhiteSpace(text))
{
var lines = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
<p>@line</p>
}
}
(remove empty entries is optional)
After this
Two things to do:
Project Settings > Project compiler output > Set it as "Project path(You actual project's path)”+”\out”.
Project Settings > Module > Path > Choose "Inherit project compile path""
If button ran is not active
You must reload IDEA
<button style="position: absolute; left: 20%; right: 20%; bottom: 5%;"> Button </button>
When you say
val map = scala.collection.mutable.Map
you are not creating a map instance, but instead aliasing the Map type.
map: collection.mutable.Map.type = scala.collection.mutable.Map$@fae93e
Try instead the following:
scala> val map = scala.collection.mutable.Map[String, Int]()
map: scala.collection.mutable.Map[String,Int] = Map()
scala> map("asdf") = 9
scala> map
res6: scala.collection.mutable.Map[String,Int] = Map((asdf,9))
Update May 2014
Google crawlers now executes javascript - you can use the Google Webmaster Tools to better understand how your sites are rendered by Google.
Original answer
If you want to optimize your app for search engines there is unfortunately no way around serving a pre-rendered version to the crawler. You can read more about Google's recommendations for ajax and javascript-heavy sites here.
If this is an option I'd recommend reading this article about how to do SEO for Angular with server-side rendering.
I’m not sure what the crawler does when it encounters custom tags.
The li
tag has a property called list-style-position
. This makes your bullets inside or outside the list. On default, it’s set to inside
. That makes your text wrap around it. If you set it to outside
, the text of your li
tags will be aligned.
The downside of that is that your bullets won't be aligned with the text outside the ul
. If you want to align it with the other text you can use a margin.
ul li {
/*
* We want the bullets outside of the list,
* so the text is aligned. Now the actual bullet
* is outside of the list’s container
*/
list-style-position: outside;
/*
* Because the bullet is outside of the list’s
* container, indent the list entirely
*/
margin-left: 1em;
}
Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement
em
’sul
elementFrom the comment by @ZhekaKozlov: ojdkbuild has OpenJDK builds (currently 8 and 11) for Windows (zip
and msi
).
"/tmp/mysql.sock" will be created automatically when you start the MySQL server. So remember to do that before starting the rails server.