glob2rx()
converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.
If you want to match "blue*"
where *
has the usual wildcard, not regular expression, meaning we use glob2rx()
to convert the wildcard pattern into a useful regular expression:
> glob2rx("blue*")
[1] "^blue"
The returned object is a regular expression.
Given your data:
x <- c('red','blue1','blue2', 'red2')
we can pattern match using grep()
or similar tools:
> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE TRUE TRUE FALSE
As for the selecting rows problem you posted
> a <- data.frame(x = c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
or via subset()
:
> with(a, subset(a, subset = grepl(grx, x)))
x
2 blue1
3 blue2
Hope that explains what grob2rx()
does and how to use it?
You can also use a pretty simple for
loop:
for f in `find . -not -name "*Music*"`
do
cp $f /target/dir
done
I tried all the different things mentioned here to get the index of the .
character in a filename that ends with .[0-9][0-9]*
, e.g. srcfile.1
, srcfile.12
, etc. Nothing worked. Finally, the following worked:
int dotIndex = inputfilename.lastIndexOf(".");
Weird! This is with java -version:
openjdk version "1.8.0_131"
OpenJDK Runtime Environment (build 1.8.0_131-8u131-b11-0ubuntu1.16.10.2-b11)
OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)
Also, the official Java doc page for regex
(from which there is a quote in one of the answers above) does not seem to specify how to look for the .
character. Because \.
, \\.
, and [.]
did not work for me, and I don't see any other options specified apart from these.
perl -lne 'print if((/abc/../mno/) && !(/abc/||/mno/))' your_file
The solution seems to be long accepted, but the solution could be improved, so if someone has a similar problem:
This is a classical application for multi-pattern-search-algorithms.
Java Pattern Search (with Matcher.find
) is not qualified for doing that. Searching for exactly one keyword is optimized in java, searching for an or-expression uses the regex non deterministic automaton which is backtracking on mismatches. In worse case each character of the text will be processed l times (where l is the sum of the pattern lengths).
Single pattern search is better, but not qualified, too. One will have to start the whole search for every keyword pattern. In worse case each character of the text will be processed p times where p is the number of patterns.
Multi pattern search will process each character of the text exactly once. Algorithms suitable for such a search would be Aho-Corasick, Wu-Manber, or Set Backwards Oracle Matching. These could be found in libraries like Stringsearchalgorithms or byteseek.
// example with StringSearchAlgorithms
AhoCorasick stringSearch = new AhoCorasick(asList("123woods", "woods"));
CharProvider text = new StringCharProvider("I will come and meet you at the woods 123woods and all the woods", 0);
StringFinder finder = stringSearch.createFinder(text);
List<StringMatch> all = finder.findAll();
#include <algorithm>
std::string s = "a_b_c";
size_t n = std::count(s.begin(), s.end(), '_');
It can also be done in some other manner
byte[] pass_byte = Encoding.ASCII.GetBytes("your input value");
and then print result. by using foreach
loop.
If you have any problems or are missing any packages you can simply right-click in your project and select "Manage NuGet Packages for Solution...". After clicking on this a screen will open where you see a menu bar saying "Restore":
Click on it and the required packages will be installed automatically.
I believe this is what you're looking for, this solved my problems.
A classic "or" would be |
. For example, ab|de
would match either side of the expression.
However, for something like your case you might want to use the ?
quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:
\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+
This pattern will match:
\d+
: One or more numbers.\s+
: One or more whitespaces.[A-Z\s]+
: One or more uppercase characters or space characters\s+
: One or more whitespaces.[A-Z][A-Za-z\s]+
: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.If you'd like a more static check, e.g. indeed only match ABC
and A ABC
, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):
\d (?:ABC|A ABC) Street
Or another alternative using a quantifier:
\d (?:A )?ABC Street
string sourceDateText = "31-08-2012";
DateTime sourceDate = DateTime.Parse(sourceDateText, "dd-MM-yyyy")
string formatted = sourceDate.ToString("yyyy-MM-dd");
You could also check if the required certificates are installed to make sure that it allows the dependencies to be downloaded.
Step :1)Remove the existing files using this command
find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch
Step : 2)Add .DS_Store in your .gitignore file
Step :3) Commit your changes in .gitignore git add .gitignore git commit -m "removed .DS_Store"
try using
@record.assign_attributes({ ... })
@record.save(validate: false)
works for me
Nowadays, Alpine images will boot directly into /bin/sh
by default, without having to specify a shell to execute:
$ sudo docker run -it --rm alpine
/ # echo $0
/bin/sh
This is since the alpine
image Dockerfiles now contain a CMD
command, that specifies the shell to execute when the container starts: CMD ["/bin/sh"]
.
In older Alpine image versions (pre-2017), the CMD command was not used, since Docker used to create an additional layer for CMD which caused the image size to increase. This is something that the Alpine image developers wanted to avoid. In recent Docker versions (1.10+), CMD no longer occupies a layer, and so it was added to alpine
images. Therefore, as long as CMD is not overridden, recent Alpine images will boot into /bin/sh
.
For reference, see the following commit to the official Alpine Dockerfiles by Glider Labs:
https://github.com/gliderlabs/docker-alpine/commit/ddc19dd95ceb3584ced58be0b8d7e9169d04c7a3#diff-db3dfdee92c17cf53a96578d4900cb5b
If you really mean small caps, then no, that is not possible – just as it isn’t possible to convert text to bold or italic in any text editor (as opposed to word processor). If you want to convert text to lowercase, create a visual block and press u
(or U
to convert to uppercase). Tilde (~
) in command mode reverses case of the character under the cursor.
If you want to see all text in Vim in small caps, you might want to look at the guifont
option, or type :set guifont=*
if your Vim flavour supports GUI font chooser.
The reason you aren't finding easy examples for how to do this in T-SQL is that it is generally considered bad practice to implement formatting logic in SQL code. RDBMS's simply are not designed for presentation. While it is possible to do some limited formatting, it is almost always better to let the application or user interface handle formatting of this type.
But if you must (and sometimes we must!) use T-SQL, cast your int to money and convert it to varchar, like this:
select convert(varchar,cast(1234567 as money),1)
If you don't want the trailing decimals, do this:
select replace(convert(varchar,cast(1234567 as money),1), '.00','')
Good luck!
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
Another way, go to layout -> your .xml file -> design view .Then go component tree and select layout you want to change color . In below component tree there is properties section .Select background in the properties section (In picture section 1). Then click section 2 in picture . Then Resources window will be open .From that select color menu .Then choose color you want .enter image description here
Well, when writing it out to file, you do know what class T is, so you can store that in dump
. Then, when reading it back in, you can dynamically call it using reflection.
public JSONObject dump() throws JSONException {
JSONObject result = new JSONObject();
JSONArray a = new JSONArray();
for(T i : items){
a.put(i.dump());
// inside this i.dump(), store "class-name"
}
result.put("items", a);
return result;
}
public void load(JSONObject obj) throws JSONException {
JSONArray arrayItems = obj.getJSONArray("items");
for (int i = 0; i < arrayItems.length(); i++) {
JSONObject item = arrayItems.getJSONObject(i);
String className = item.getString("class-name");
try {
Class<?> clazzy = Class.forName(className);
T newItem = (T) clazzy.newInstance();
newItem.load(obj);
items.add(newItem);
} catch (InstantiationException e) {
// whatever
} catch (IllegalAccessException e) {
// whatever
} catch (ClassNotFoundException e) {
// whatever
}
}
GO is like the end of a script.
You could have multiple CREATE TABLE statements, separated by GO. It's a way of isolating one part of the script from another, but submitting it all in one block.
BEGIN and END are just like { and } in C/++/#, Java, etc.
They bound a logical block of code. I tend to use BEGIN and END at the start and end of a stored procedure, but it's not strictly necessary there. Where it IS necessary is for loops, and IF statements, etc, where you need more then one step...
IF EXISTS (SELECT * FROM my_table WHERE id = @id)
BEGIN
INSERT INTO Log SELECT @id, 'deleted'
DELETE my_table WHERE id = @id
END
With the introduction of private
, static
, default
modifiers for interface methods in Java 8/9, things get more complicated and I tend to think that full declarations are more readable (needs Java 9 to compile):
public interface MyInterface {
//minimal
int CONST00 = 0;
void method00();
static void method01() {}
default void method02() {}
private static void method03() {}
private void method04() {}
//full
public static final int CONST10 = 0;
public abstract void method10();
public static void method11() {}
public default void method12() {}
private static void method13() {}
private void method14() {}
}
You miss the class declaration.
public class DerivativeQuiz{
public static void derivativeQuiz(String args[]){ ... }
}
You can append array of Data at the end of custom state:
const [vehicleData, setVehicleData] = React.useState<any[]>([]);
setVehicleData(old => [...old, ...newArrayData]);
For example, In below, you appear an example of axios:
useEffect(() => {
const fetchData = async () => {
const result = await axios(
{
url: `http://localhost:4000/api/vehicle?page=${page + 1}&pageSize=10`,
method: 'get',
}
);
setVehicleData(old => [...old, ...result.data.data]);
};
fetchData();
}, [page]);
Can also export functions from dll and import from the exe, it is more tricky at first but in the end is much easier than calling LoadLibrary/GetProcAddress. See MSDN.
When creating the project with the VS wizard there's a check box in the dll that let you export functions.
Then, in the exe application you only have to #include a header from the dll with the proper definitions, and add the dll project as a dependency to the exe application.
Check this other question if you want to investigate this point further Exporting functions from a DLL with dllexport.
Simple Try to make a function in javascript for dropdown collapse class.
Example:
JS:
$scope.toogleMyClass = function(){
//dropdown-element
$timeout(function(){
$scope.preLoader = false;
$(document).ready(function() {
$("#dropdown-element").toggleClass('show');
});
},100);
};
Hook this function to onClick
simple works for me.
To expand on @T.J.'s answer, if you're looking for simple months, rather than full calendar months, you could just check if d2's date is greater than or equal to than d1's. That is, if d2 is later in its month than d1 is in its month, then there is 1 more month. So you should be able to just do this:
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
// edit: increment months if d2 comes later in its month than d1 in its month
if (d2.getDate() >= d1.getDate())
months++
// end edit
return months <= 0 ? 0 : months;
}
monthDiff(
new Date(2008, 10, 4), // November 4th, 2008
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 16; 4 Nov – 4 Dec '08, 4 Dec '08 – 4 Dec '09, 4 Dec '09 – 4 March '10
This doesn't totally account for time issues (e.g. 3 March at 4:00pm and 3 April at 3:00pm), but it's more accurate and for just a couple lines of code.
delete C:\Users\username\.gradle\caches
folder.
%~dp0 expands to current directory path of the running batch file.
To get clear understanding, let's create a batch file in a directory.
C:\script\test.bat
with contents:
@echo off
echo %~dp0
When you run it from command prompt, you will see this result:
C:\script\
It is known HTTP headers problem with Internet Explorer. Try to edit your server's .htaccess
file (if you use Apache) and include the following rules:
# IE: force download of .xxx files
AddType application/octect-stream .xxx
<Files *.xxx>
ForceType application/octet-stream
Header Set Content-Disposition attachment
</Files>
Or just use this in your View(Razor page)
@item.ResgistrationhaseDate.ToString(string.Format("dd/MM/yyyy"))
I recommend that don't add date format in your model class
Note: all the examples here are using the OpenCV 2.X API.
In OpenCV 3.X, you need to use:
Ptr<SimpleBlobDetector> d = SimpleBlobDetector::create(params);
See also: the transition guide: http://docs.opencv.org/master/db/dfa/tutorial_transition_guide.html#tutorial_transition_hints_headers
http://www.roubaixinteractive.com/PlayGround/Binary_Conversion/The_Characters.asp it just looks here... (not HERE but it has a table).
There are 8 bits in a byte. One byte can be one symbol. One bit is either on or off.
This question has already been answered with very smart ways to fulfil the requirement but I am wondering why not take a step back and ask the basic question of why do we need a class with two constructors? If my class needs two constructors then probably the way I am designing my classes needs little more consideration to come up with a design that is cleaner and more testable.
We are trying to mix up how to instantiate a class with the actual class logic.
If a Student object is in a valid state, then does it matter if it was constructed from the row of a DB or data from a web form or a cli request?
Now to answer the question that that may arise here that if we don't add the logic of creating an object from db row, then how do we create an object from the db data, we can simply add another class, call it StudentMapper if you are comfortable with data mapper pattern, in some cases you can use StudentRepository, and if nothing fits your needs you can make a StudentFactory to handle all kinds of object construction tasks.
Bottomline is to keep persistence layer out of our head when we are working on the domain objects.
var o = {
r: 'some value',
t: 'some other value'
};
is functionally equivalent to
var o = new Object();
o.r = 'some value';
o.t = 'some other value';
select CONVERT(NVARCHAR, SYSDATETIME(), 106) AS [DD-MON-YYYY]
or else
select REPLACE(CONVERT(NVARCHAR,GETDATE(), 106), ' ', '-')
both works fine
When executable path has whitespace in system, call
#include<iostream>
using namespace std;
int main()
{
system("explorer C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe ");
system("pause");
return 0;
}
Make sure these references are included:
Then add the using statement
using System.Linq;
Java 6, now support TLS 1.2, check out below
http://www.oracle.com/technetwork/java/javase/overview-156328.html#R160_121
==
checks to see if they are actually the same object in memory (which confusingly sometimes is true, since they may both be from the pool), where as equals()
is overridden by java.lang.String
to check each character to ensure true equality. So therefore, equals()
is what you want.
tr
can be more concise for removing characters than sed
or awk
, especially when you want to remove different characters from a string.
Removing double quotes:
echo '"Hi"' | tr -d \"
# Produces Hi without quotes
Removing different kinds of brackets:
echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets
-d
stands for "delete".
mybytestring.encode(somecodec) is meaningful for these values of somecodec
:
I am not sure what decoding an already decoded unicode text is good for. Trying that with any encoding seems to always try to encode with the system's default encoding first.
Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:
char (*orderedIds)[ID_LEN+1]
= malloc(variableNumberOfElements * sizeof(*orderedIds));
// Clear-up
free(orderedIds);
A more cumbersome, but more general, solution, is to assign an array of pointers, and psuedo-initialising them to point at elements of a raw backing array:
char *raw = malloc(variableNumberOfElements * (ID_LEN + 1));
char **orderedIds = malloc(sizeof(*orderedIds) * variableNumberOfElements);
// Set each pointer to the start of its corresponding section of the raw buffer.
for (i = 0; i < variableNumberOfElements; i++)
{
orderedIds[i] = &raw[i * (ID_LEN+1)];
}
...
// Clear-up pointer array
free(orderedIds);
// Clear-up raw array
free(raw);
To extract the real part of a complex-valued expression z
, use the notation as __real__ z
.
Similarly, use __imag__
attribute on the z
to extract the imaginary part.
For example;
__complex__ float z;
float r;
float i;
r = __real__ z;
i = __imag__ z;
r is the real part of the complex number "z" i is the imaginary part of the complex number "z"
TL;DR
Java caches boxed Integer instances from -128
to 127
. Since you are using ==
to compare objects references instead of values, only cached objects will match. Either work with long
unboxed primitive values or use .equals()
to compare your Long
objects.
Long (pun intended) version
Why there is problem in comparing Long variable with value greater than 127? If the data type of above variable is primitive (long) then code work for all values.
Java caches Integer objects instances from the range -128 to 127. That said:
127
(cached), the same object instance will be pointed by all references. (N variables, 1 instance)128
(not cached), you will have an object instance pointed by every reference. (N variables, N instances)That's why this:
Long val1 = 127L;
Long val2 = 127L;
System.out.println(val1 == val2);
Long val3 = 128L;
Long val4 = 128L;
System.out.println(val3 == val4);
Outputs this:
true
false
For the 127L value, since both references (val1 and val2) point to the same object instance in memory (cached), it returns true
.
On the other hand, for the 128 value, since there is no instance for it cached in memory, a new one is created for any new assignments for boxed values, resulting in two different instances (pointed by val3 and val4) and returning false
on the comparison between them.
That happens solely because you are comparing two Long
object references, not long
primitive values, with the ==
operator. If it wasn't for this Cache mechanism, these comparisons would always fail, so the real problem here is comparing boxed values with ==
operator.
Changing these variables to primitive long
types will prevent this from happening, but in case you need to keep your code using Long
objects, you can safely make these comparisons with the following approaches:
System.out.println(val3.equals(val4)); // true
System.out.println(val3.longValue() == val4.longValue()); // true
System.out.println((long)val3 == (long)val4); // true
(Proper null checking is necessary, even for castings)
IMO, it's always a good idea to stick with .equals() methods when dealing with Object comparisons.
Reference links:
@echo off
color 0a
set /p language=
if %language% == DE (
goto LGDE
) else (
if %language% == EN (
goto LGEN
) else (
echo N/A
)
:LGDE
(code)
:LGEN
(code)
I don't think you need to change the MaxPermSize to 1024m. This works for me:
-startup
plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms256m
-Xmx1024m
-XX:PermSize=64m
-XX:MaxPermSize=128m
If the link should only change the location if the function run is successful, then do onclick="return runMyFunction();"
and in the function you would return true or false.
If you just want to run the function, and then let the anchor tag do its job, simply remove the return false
statement.
As a side note, you should probably use an event handler instead, as inline JS isn't a very optimal way of doing things.
Don’t Repeat Your CSS
a.abc, a.xyz{
margin-left:20px;
}
OR
a{
margin-left:20px;
}
Either [0-9]
or \d
1 should suffice if you only need a single digit. Append +
if you need more.
1 The semantics are slightly different as \d
potentially matches any decimal digit in any script out there that uses decimal digits.
Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b
prefix:
int foo = 0b1010;
If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
And then you can use it like this:
int foo = B(1010);
If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.
Proof:
The following code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
int main()
{
int foo = B(001100101);
printf("%d\n", foo);
return 0;
}
has been compiled using clang -o baz.S baz.c -Wall -O3 -S
, and it produced the following assembly:
.section __TEXT,__text,regular,pure_instructions
.globl _main
.align 4, 0x90
_main: ## @main
.cfi_startproc
## BB#0:
pushq %rbp
Ltmp2:
.cfi_def_cfa_offset 16
Ltmp3:
.cfi_offset %rbp, -16
movq %rsp, %rbp
Ltmp4:
.cfi_def_cfa_register %rbp
leaq L_.str1(%rip), %rdi
movl $101, %esi ## <= This line!
xorb %al, %al
callq _printf
xorl %eax, %eax
popq %rbp
ret
.cfi_endproc
.section __TEXT,__cstring,cstring_literals
L_.str1: ## @.str1
.asciz "%d\n"
.subsections_via_symbols
So clang
completely eliminated the call to the function, and replaced its return value with 101
. Neat, huh?
If you want your anchor to still appear to be clickable:
$("a").removeAttr("href").css("cursor","pointer");
And if you wanted to remove the href from only anchors with certain attributes (eg ones that just have a hash mark as the href - this can be useful in asp.net)
$("a[href='#']").removeAttr("href").css("cursor","pointer");
I haven't seen anyone mention the browser-image-compression
library. It's got a helper function perfect for this.
Usage: const orientation = await imageCompression.getExifOrientation(file)
Such a useful tool in many other ways too.
If you are looking for a specific length (such as a zipcode field):
$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
//make ajax request here after.
}
});
even shorter using the dot:
#!/bin/bash
. CONFIG_FILE
sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool
Check this Official Link
I'm not sure what's the point of all these answers that loop through parent elements and do all kinds of weird stuff.
The HTMLElement.getBoundingClientRect
method is designed to to handle actual screen position of any element. This includes scrolling, so stuff like scrollTop
is not needed:
(from MDN) The amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the bounding rectangle
The very simplest approach was already posted here. This is correct as long as no wild CSS rules are involved.
When image pixel width isn't matched by it's CSS width, you'll need to apply some ratio on pixel values:
/* Returns pixel coordinates according to the pixel that's under the mouse cursor**/
HTMLCanvasElement.prototype.relativeCoords = function(event) {
var x,y;
//This is the current screen rectangle of canvas
var rect = this.getBoundingClientRect();
var top = rect.top;
var bottom = rect.bottom;
var left = rect.left;
var right = rect.right;
//Recalculate mouse offsets to relative offsets
x = event.clientX - left;
y = event.clientY - top;
//Also recalculate offsets of canvas is stretched
var width = right - left;
//I use this to reduce number of calculations for images that have normal size
if(this.width!=width) {
var height = bottom - top;
//changes coordinates by ratio
x = x*(this.width/width);
y = y*(this.height/height);
}
//Return as an array
return [x,y];
}
As long as the canvas has no border, it works for stretched images (jsFiddle).
If the canvas has thick border, the things get little complicated. You'll literally need to subtract the border from the bounding rectangle. This can be done using .getComputedStyle. This answer describes the process.
The function then grows up a little:
/* Returns pixel coordinates according to the pixel that's under the mouse cursor**/
HTMLCanvasElement.prototype.relativeCoords = function(event) {
var x,y;
//This is the current screen rectangle of canvas
var rect = this.getBoundingClientRect();
var top = rect.top;
var bottom = rect.bottom;
var left = rect.left;
var right = rect.right;
//Subtract border size
// Get computed style
var styling=getComputedStyle(this,null);
// Turn the border widths in integers
var topBorder=parseInt(styling.getPropertyValue('border-top-width'),10);
var rightBorder=parseInt(styling.getPropertyValue('border-right-width'),10);
var bottomBorder=parseInt(styling.getPropertyValue('border-bottom-width'),10);
var leftBorder=parseInt(styling.getPropertyValue('border-left-width'),10);
//Subtract border from rectangle
left+=leftBorder;
right-=rightBorder;
top+=topBorder;
bottom-=bottomBorder;
//Proceed as usual
...
}
I can't think of anything that would confuse this final function. See yourself at JsFiddle.
If you don't like modifying the native prototype
s, just change the function and call it with (canvas, event)
(and replace any this
with canvas
).
I think the easiest way is to divide two integers and increase by one :
int r = list.Count() / 10;
r += (list.Count() % 10 == 0 ? 0 : 1);
No need of libraries or functions.
edited with the right code.
In CodeIgniter you can store your session value as single or also in array format as below:
If you want store any user’s data in session like userId, userName, userContact etc, then you should store in array:
<?php
$this->load->library('session');
$this->session->set_userdata(array(
'userId' => $user->userId,
'userName' => $user->userName,
'userContact ' => $user->userContact
));
?>
Get in details with Example Demo :
http://devgambit.com/how-to-store-and-get-session-value-in-codeigniter/
try this:
streetaddress.substring(0, streetaddress.indexOf(','));
Install opencv-python
(which is an unofficial pre-built OpenCV package for Python) by issuing the following command:
pip install opencv-python
For an updated answer see this SO question:
calling web service using VBA code in excel 2010
Both threads should be merged though.
ng-click return confirm 100% works
in html file call delete_plot() function
<i class="fa fa-trash delete-plot" ng-click="delete_plot()"></i>
Add this to your controller
$scope.delete_plot = function(){
check = confirm("Are you sure to delete this plot?")
if(check){
console.log("yes, OK pressed")
}else{
console.log("No, cancel pressed")
}
}
Simply by "unpacking" the list in the print function argument and using a newline (\n) as separator.
print(*lst, sep='\n')
lst = ['foo', 'bar', 'spam', 'egg']
print(*lst, sep='\n')
foo
bar
spam
egg
You can use the ??
test operator:
This checks if the attribute of the object is not null:
<#if object.attribute??></#if>
This checks if object or attribute is not null:
<#if (object.attribute)??></#if>
Source: FreeMarker Manual
Here are few steps that must be followed carefully
Create a folder named config inside C:\wamp\apps\phpmyadmin, the folder inside apps may have different name like phpmyadmin3.2.0.1
Return to your browser in phpmyadmin setup tab, and click New server.
Change the authentication type to ‘cookie’ and leave the username and password field empty but if you change the authentication type to ‘config’ enter the password for username root.
I have PHP 5.3.1 and Apache
When I add the extension=php_intl.dll
to php.ini and restart apache, it comes an alert that says "the requested operation has failed"
And this error on Event Monitor:
Faulting application name: httpd.exe, version: 2.2.14.0, time stamp: 0x4ac181d6
Faulting module name: php5ts.dll, version: 5.3.1.0, time stamp: 0x4b051b35
Exception code: 0xc0000005
The problem was some DLLs like icudt36.dll were missing (noticed with sysinternals ProcMon), I've downloaded php 5.3.1 zip version and extract all DLL's to PHP folder. That solved the problem.
There's no need to mess with your PYTHONPATH
or sys.path
here.
To properly use absolute imports in a package you should include the "root" packagename as well, e.g.:
from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2
Or you can use relative imports:
from .dirfoo1.foo1 import Foo1
from .dirfoo2.foo2 import Foo2
I found the answer here: Is it possible to pass query parameters via Django's {% url %} template tag?
Simply add them to the end:
<a href="{% url myview %}?office=foobar">
For Django 1.5+
<a href="{% url 'myview' %}?office=foobar">
[there is nothing else to improve but I'm getting a stupid error when I fix the code ticks]
To Find the problem label(s) in a large storyboard, follow my steps below.
Next, reveal your storyboard as source file.
Search. You should be able to tell what label it is from here quite easily by looking at the content.
Once you find the label the solution that worked for me was to set the "preferred width" to 0.
BTW, you can always quickly get the id of an interface item by selecting the item and looking under the identify inspector. Very handy.
For those of us using non-ISO standard date formats, like civilian vernacular 01/01/2001 (mm/dd/YYYY), including time in a 12hour date format with am/pm marks, the following function will return a valid Date object:
function convertDate(date) {
// # valid js Date and time object format (YYYY-MM-DDTHH:MM:SS)
var dateTimeParts = date.split(' ');
// # this assumes time format has NO SPACE between time and am/pm marks.
if (dateTimeParts[1].indexOf(' ') == -1 && dateTimeParts[2] === undefined) {
var theTime = dateTimeParts[1];
// # strip out all except numbers and colon
var ampm = theTime.replace(/[0-9:]/g, '');
// # strip out all except letters (for AM/PM)
var time = theTime.replace(/[[^a-zA-Z]/g, '');
if (ampm == 'pm') {
time = time.split(':');
// # if time is 12:00, don't add 12
if (time[0] == 12) {
time = parseInt(time[0]) + ':' + time[1] + ':00';
} else {
time = parseInt(time[0]) + 12 + ':' + time[1] + ':00';
}
} else { // if AM
time = time.split(':');
// # if AM is less than 10 o'clock, add leading zero
if (time[0] < 10) {
time = '0' + time[0] + ':' + time[1] + ':00';
} else {
time = time[0] + ':' + time[1] + ':00';
}
}
}
// # create a new date object from only the date part
var dateObj = new Date(dateTimeParts[0]);
// # add leading zero to date of the month if less than 10
var dayOfMonth = (dateObj.getDate() < 10 ? ("0" + dateObj.getDate()) : dateObj.getDate());
// # parse each date object part and put all parts together
var yearMoDay = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dayOfMonth;
// # finally combine re-formatted date and re-formatted time!
var date = new Date(yearMoDay + 'T' + time);
return date;
}
Usage:
date = convertDate('11/15/2016 2:00pm');
No, you can only get to the interior color of a cell by using a Macro. I am afraid. It's really easy to do (cell.interior.color) so unless you have a requirement that restricts you from using VBA, I say go for it.
You can use the --to-command
option to pipe files to an arbitrary script. Using this you can process the archive in a single pass (and without a temporary file). See also this question, and the manual.
Armed with the above information, you could try something like:
$ tar xf file.tar.gz --to-command "awk '/bar/ { print ENVIRON[\"TAR_FILENAME\"]; exit }'"
bfe2/.bferc
bfe2/CHANGELOG
bfe2/README.bferc
No, it needs three operands. That's why they're called ternary operators.
However, for what you have as your example, you can do this:
if(condition) x = true;
Although it's safer to have braces if you need to add more than one statement in the future:
if(condition) { x = true; }
Edit: Now that you mention the actual code in which your question applies to:
if(!defaults.slideshowWidth)
{ defaults.slideshowWidth = obj.find('img').width()+'px'; }
As long as strings can be viewed directly as a char array it's going to be really hard to convince me that std::string
represents strings as first class citizens in C++.
Besides, combining allocation and boundedness seems to be a bad idea to me anyways.
The answers here are all quite old.
In the HTML5 world, you should the use onpopstate
event.
window.onpopstate = function(event)
{
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
Or:
window.addEventListener('popstate', function(event)
{
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
});
The latter snippet allows multiple event handlers to exist, whereas the former will replace any existing handler which may cause hard-to-find bugs.
You can use .net application https://github.com/abhiyx/RedisSizeCalculator to calculate the size of redis key,
Please feel free to give your feedback for the same
Like it was saying previously - you can access any parameters by using injection container and use its parameter property.
"Symfony - Working with Container Service Definitions" is a good article about it.
Here is my best shot at it. I added another Div and made it red and changed you parent's height to 200px just to test it. The idea is the the child now becomes the grandchild and the parent becomes the grandparent. So the parent respects its parent. Hope you get my idea.
<html>
<body>
<div style="background-color: blue; padding: 10px; position: relative; height: 200px;">
<div style="background-color: red; position: relative; height: 100%;">
<div style="background-color: gray; position: absolute; left: 0px; right: 0px;bottom: 0px;">css sux</div>
</div>
</div>
</body>
</html>
Edit:
I think what you are trying to do can't be done. Absolute position means that you are going to give it co-ordinates it must honor. What if the parent has a padding of 5px. And you absolutely position the child at top: -5px; left: -5px. How is it suppose to honor the parent and you at the same time??
My solution
If you want it to honor the parent, don't absolutely position it then.
I know that this question was asked 8 years and 10 months ago but I want to present you my solution:
from multiprocessing import Pool
class Test:
def __init__(self):
self.main()
@staticmethod
def methodForMultiprocessing(x):
print(x*x)
def main(self):
if __name__ == "__main__":
p = Pool()
p.map(Test.methodForMultiprocessing, list(range(1, 11)))
p.close()
TestObject = Test()
You just need to make your class function into a static method. But it's also possible with a class method:
from multiprocessing import Pool
class Test:
def __init__(self):
self.main()
@classmethod
def methodForMultiprocessing(cls, x):
print(x*x)
def main(self):
if __name__ == "__main__":
p = Pool()
p.map(Test.methodForMultiprocessing, list(range(1, 11)))
p.close()
TestObject = Test()
Tested in Python 3.7.3
You can try in this way.
for(int a=5;a>0;a--){
int b=0;
for(b=0;b<a;b++){
System.out.print(" ");
}
for (int j=b;j<5;j++){
System.out.print(" $ ");
}
System.out.println("");
}
Out put
$
$ $
$ $ $
$ $ $ $
There's actually quite a bit of useful information added to debug allocations. This table is more complete:
http://www.nobugs.org/developer/win32/debug_crt_heap.html#table
Address Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments 0x00320FD8 -40 0x01090009 0x01090009 0x01090009 0x0109005A Win32 heap info 0x00320FDC -36 0x01090009 0x00180700 0x01090009 0x00180400 Win32 heap info 0x00320FE0 -32 0xBAADF00D 0x00320798 0xDDDDDDDD 0x00320448 Ptr to next CRT heap block (allocated earlier in time) 0x00320FE4 -28 0xBAADF00D 0x00000000 0xDDDDDDDD 0x00320448 Ptr to prev CRT heap block (allocated later in time) 0x00320FE8 -24 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Filename of malloc() call 0x00320FEC -20 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Line number of malloc() call 0x00320FF0 -16 0xBAADF00D 0x00000008 0xDDDDDDDD 0xFEEEFEEE Number of bytes to malloc() 0x00320FF4 -12 0xBAADF00D 0x00000001 0xDDDDDDDD 0xFEEEFEEE Type (0=Freed, 1=Normal, 2=CRT use, etc) 0x00320FF8 -8 0xBAADF00D 0x00000031 0xDDDDDDDD 0xFEEEFEEE Request #, increases from 0 0x00320FFC -4 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x00321000 +0 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321004 +4 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321008 +8 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x0032100C +12 0xBAADF00D 0xBAADF00D 0xDDDDDDDD 0xFEEEFEEE Win32 heap allocations are rounded up to 16 bytes 0x00321010 +16 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321014 +20 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321018 +24 0x00000010 0x00000010 0x00000010 0xFEEEFEEE Win32 heap bookkeeping 0x0032101C +28 0x00000000 0x00000000 0x00000000 0xFEEEFEEE Win32 heap bookkeeping 0x00321020 +32 0x00090051 0x00090051 0x00090051 0xFEEEFEEE Win32 heap bookkeeping 0x00321024 +36 0xFEEE0400 0xFEEE0400 0xFEEE0400 0xFEEEFEEE Win32 heap bookkeeping 0x00321028 +40 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping 0x0032102C +44 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping
I Think It Is Best!
And Use The Simple JS to make this work.
<script>
function privacypolicy(){
var privacypolicy1 = document.getElementById('privacypolicy');
var privacypolicy2 = ('display: inline;');
privacypolicy1.style= privacypolicy2;
}
function hideprivacypolicy(){
var privacypolicy1 = document.getElementById('privacypolicy');
var privacypolicy2 = ('display: none;');
privacypolicy1.style= privacypolicy2;
}
</script>
<style type="text/css">
.orthi-textlightbox-background{
background-color: rgba(30, 23, 23, 0.82);
font-family: siyam rupali;
position: fixed; top:0px;
bottom:0px;
right:0px;
width: 100%;
border: none;
margin:0;
padding:0;
overflow: hidden;
z-index:999999;
height: 100%;
}
.orthi-textlightbox-area {
background-color: #fff;
position: absolute;
width: 50%;
left: 300px;
top: 200px;
padding: 20px 10px;
border-radius: 6px;
}
.orthi-textlightbox-area-close{
font-weight: bold;
background-color:black;
color: white;
border-radius: 50%;
padding: 10px;
float: right;
border: 1px solid black;
box-shadow: 0 0 10px 0 rgba(33, 157, 216, 0.82);
margin-top:-30px;
margin-right:-30px;
cursor:pointer;
}
</style>
<button onclick="privacypolicy()">Show Content</button>
<div id="privacypolicy" class="orthi-textlightbox-background" style="display:none;">
<div class="orthi-textlightbox-area">
LOL<button class="orthi-textlightbox-area-close" onclick="hideprivacypolicy()">×</button>
</div>
</div>
Xml-to-json library has methods jsonToXml(json) and xmlToJson(xml).
solution is easy:
replace
mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
by
mask = ((50 < df['heart rate'] < 101) &
(140 < df['systolic blood pressure'] < 160) &
(90 < df['dyastolic blood pressure'] < 100) &
(35 < df['temperature'] < 39) &
(11 < df['respiratory rate'] < 19) &
(95 < df['pulse oximetry'] < 100)
, "excellent", "critical")
As provided in chosen explanation, git reset is good. But nowadays we often use sub-modules: repositories inside repositories. For example, you if you use ZF3 and jQuery in your project you most probably want them to be cloned from their original repositories. In such case git reset is not enough. We need to update submodules to that exact version that are defined in our repository:
git checkout master
git fetch origin master
git reset --hard origin/master
git pull
git submodule foreach git submodule update
git status
it is the same as you will come (cd) recursively to the working directory of each sub-module and will run:
git submodule update
And it's very different from
git checkout master
git pull
because sub-modules point not to branch but to the commit.
In that cases when you manually checkout some branch for 1 or more submodules you can run
git submodule foreach git pull
This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.
anaconda
. Latest version can be found hereanaconda-navigator
in terminalcreate
and then choose your python version in that. install
in that. Hope it helps!!
A solution without using "eval":
var setInnerHtml = function(elm, html) {
elm.innerHTML = html;
var scripts = elm.getElementsByTagName("script");
// If we don't clone the results then "scripts"
// will actually update live as we insert the new
// tags, and we'll get caught in an endless loop
var scriptsClone = [];
for (var i = 0; i < scripts.length; i++) {
scriptsClone.push(scripts[i]);
}
for (var i = 0; i < scriptsClone.length; i++) {
var currentScript = scriptsClone[i];
var s = document.createElement("script");
// Copy all the attributes from the original script
for (var j = 0; j < currentScript.attributes.length; j++) {
var a = currentScript.attributes[j];
s.setAttribute(a.name, a.value);
}
s.appendChild(document.createTextNode(currentScript.innerHTML));
currentScript.parentNode.replaceChild(s, currentScript);
}
}
This essentially clones the script tag and then replaces the blocked script tag with the newly generated one, thus allowing execution.
note you can only do this with Numbers and Strings
you could do...
var a, b, c; a = b = c = 0; //but why?
c++;
// c = 1, b = 0, a = 0;
If you would like to perform it dynamically try this:
using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Config;
using NUnit.Framework;
namespace ExampleConsoleApplication
{
enum DebugLevel : int
{
Fatal_Msgs = 0 ,
Fatal_Error_Msgs = 1 ,
Fatal_Error_Warn_Msgs = 2 ,
Fatal_Error_Warn_Info_Msgs = 3 ,
Fatal_Error_Warn_Info_Debug_Msgs = 4
}
class TestClass
{
private static readonly ILog logger = LogManager.GetLogger(typeof(TestClass));
static void Main ( string[] args )
{
TestClass objTestClass = new TestClass ();
Console.WriteLine ( " START " );
int shouldLog = 4; //CHANGE THIS FROM 0 TO 4 integer to check the functionality of the example
//0 -- prints only FATAL messages
//1 -- prints FATAL and ERROR messages
//2 -- prints FATAL , ERROR and WARN messages
//3 -- prints FATAL , ERROR , WARN and INFO messages
//4 -- prints FATAL , ERROR , WARN , INFO and DEBUG messages
string srtLogLevel = String.Empty;
switch (shouldLog)
{
case (int)DebugLevel.Fatal_Msgs :
srtLogLevel = "FATAL";
break;
case (int)DebugLevel.Fatal_Error_Msgs:
srtLogLevel = "ERROR";
break;
case (int)DebugLevel.Fatal_Error_Warn_Msgs :
srtLogLevel = "WARN";
break;
case (int)DebugLevel.Fatal_Error_Warn_Info_Msgs :
srtLogLevel = "INFO";
break;
case (int)DebugLevel.Fatal_Error_Warn_Info_Debug_Msgs :
srtLogLevel = "DEBUG" ;
break ;
default:
srtLogLevel = "FATAL";
break;
}
objTestClass.SetLogingLevel ( srtLogLevel );
objTestClass.LogSomething ();
Console.WriteLine ( " END HIT A KEY TO EXIT " );
Console.ReadLine ();
} //eof method
/// <summary>
/// Activates debug level
/// </summary>
/// <sourceurl>http://geekswithblogs.net/rakker/archive/2007/08/22/114900.aspx</sourceurl>
private void SetLogingLevel ( string strLogLevel )
{
string strChecker = "WARN_INFO_DEBUG_ERROR_FATAL" ;
if (String.IsNullOrEmpty ( strLogLevel ) == true || strChecker.Contains ( strLogLevel ) == false)
throw new Exception ( " The strLogLevel should be set to WARN , INFO , DEBUG ," );
log4net.Repository.ILoggerRepository[] repositories = log4net.LogManager.GetAllRepositories ();
//Configure all loggers to be at the debug level.
foreach (log4net.Repository.ILoggerRepository repository in repositories)
{
repository.Threshold = repository.LevelMap[ strLogLevel ];
log4net.Repository.Hierarchy.Hierarchy hier = (log4net.Repository.Hierarchy.Hierarchy)repository;
log4net.Core.ILogger[] loggers = hier.GetCurrentLoggers ();
foreach (log4net.Core.ILogger logger in loggers)
{
( (log4net.Repository.Hierarchy.Logger)logger ).Level = hier.LevelMap[ strLogLevel ];
}
}
//Configure the root logger.
log4net.Repository.Hierarchy.Hierarchy h = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository ();
log4net.Repository.Hierarchy.Logger rootLogger = h.Root;
rootLogger.Level = h.LevelMap[ strLogLevel ];
}
private void LogSomething ()
{
#region LoggerUsage
DOMConfigurator.Configure (); //tis configures the logger
logger.Debug ( "Here is a debug log." );
logger.Info ( "... and an Info log." );
logger.Warn ( "... and a warning." );
logger.Error ( "... and an error." );
logger.Fatal ( "... and a fatal error." );
#endregion LoggerUsage
}
} //eof class
} //eof namespace
The app config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="LogTest2.txt" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header] \r\n" />
<param name="Footer" value="[Footer] \r\n" />
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
</layout>
</appender>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="White" />
<backColor value="Red, HighIntensity" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.2.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=ysg;initial catalog=DBGA_DEV;integrated security=true;persist security info=True;" />
<commandText value="INSERT INTO [DBGA_DEV].[ga].[tb_Data_Log] ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout" value="%thread" />
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout" value="%level" />
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout" value="%logger" />
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout" value="%messag2e" />
</parameter>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="AdoNetAppender" />
<appender-ref ref="ColoredConsoleAppender" />
</root>
</log4net>
</configuration>
The references in the csproj file:
<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\Log4Net\log4net-1.2.10\bin\net\2.0\release\log4net.dll</HintPath>
</Reference>
<Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" />
I found 'running steps' (win32) software doing exactly what I was looking for: http://www.steppingsoftware.com/
You can load a bat file, place breakpoints / start stepping through it while seeing the output and environment variables.
The evaluation version only allows to step through 50 lines... Does anyone have a free alternative with similar functionality?
I think every edge has been considered twice and every node has been visited once, so the total time complexity should be O(2E+V).
In case someone is using Laravel and is getting this problem. I was getting this as well and the issue was in the order in which I was inserting the ids (i.e., the foreign keys) in the pivot table.
To be concrete, find below an example for a many to many relationship:
wordtokens <-> wordtoken_wordchunk <-> wordchunks
// wordtoken_wordchunk table
Schema::create('wordtoken_wordchunk', function(Blueprint $table) {
$table->integer('wordtoken_id')->unsigned();
$table->integer('wordchunk_id')->unsigned();
$table->foreign('wordtoken_id')->references('id')->on('word_tokens')->onDelete('cascade');
$table->foreign('wordchunk_id')->references('id')->on('wordchunks')->onDelete('cascade');
$table->primary(['wordtoken_id', 'wordchunk_id']);
});
// wordchunks table
Schema::create('wordchunks', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('text');
});
// wordtokens table
Schema::create('word_tokens', function (Blueprint $table) {
$table->increments('id');
$table->string('text');
});
Now my models look like follows:
class WordToken extends Model
{
public function wordchunks() {
return $this->belongsToMany('App\Wordchunk');
}
}
class Wordchunk extends Model
{
public function wordTokens() {
return $this->belongsToMany('App\WordToken', 'wordtoken_wordchunk', 'wordchunk_id', 'wordtoken_id');
}
}
I fixed the problem by exchanging the order of 'wordchunk_id' and 'wordtoken_id' in the Wordchunk model.
For code completion, this is how I persist the models:
private function persistChunks($chunks) {
foreach ($chunks as $chunk) {
$model = new Wordchunk();
$model->text = implode(' ', array_map(function($token) {return $token->text;}, $chunk));
$tokenIds = array_map(function($token) {return $token->id;}, $chunk);
$model->save();
$model->wordTokens()->attach($tokenIds);
}
}
captain_a is right that your app needs to be public with a developer email address. But if you are still getting the error then make sure that your website is using an SSL certificate.
For more detailed information and workarounds please checkout my answer at Facebook app is Public, but gives error "App not setup" when logging in
git pull origin master
will fetch all the changes from the remote's master branch and will merge it into your local.We generally don't use git pull origin/master.We can do the same thing by git merge origin/master
.It will merge all the changes from "cached copy" of origin's master branch into your local branch.In my case git pull origin/master
is throwing the error.
NSLog(@"%@",CGRectCreateDictionaryRepresentation(rect));
I change the line "pod 'Alamofire', '~> 4.0'" to "pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire', :commit => '3cc5b4e'" after that in terminal: "pod install --repo-update" and it works.
JSON has no functions as data types. You can only serialize strings, numbers, objects, arrays, and booleans (and null
)
You could create your own toJson
method, only passing the data that really has to be serialized:
Person.prototype.toJson = function() {
return JSON.stringify({age: this.age});
};
Similar for deserializing:
Person.fromJson = function(json) {
var data = JSON.parse(json); // Parsing the json string.
return new Person(data.age);
};
The usage would be:
var serialize = p1.toJson();
var _p1 = Person.fromJson(serialize);
alert("Is old: " + _p1.isOld());
To reduce the amount of work, you could consider to store all the data that needs to be serialized in a special "data" property for each Person
instance. For example:
function Person(age) {
this.data = {
age: age
};
this.isOld = function (){
return this.data.age > 60 ? true : false;
}
}
then serializing and deserializing is merely calling JSON.stringify(this.data)
and setting the data of an instance would be instance.data = JSON.parse(json)
.
This would keep the toJson
and fromJson
methods simple but you'd have to adjust your other functions.
Side note:
You should add the isOld
method to the prototype of the function:
Person.prototype.isOld = function() {}
Otherwise, every instance has it's own instance of that function which also increases memory.
You may try
$("#addRunner input").each(function(){ ... });
Inputs are no selectors, so you do not need the :
Haven't tested it with your code. Just a fast guess!
var visible = $(".media").visible();
You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();
You can access this by
Right click on instance (IE SQLServer2008)
Select "Properties"
Select "Security" option
Change "Server authentication" to "SQL Server and Windows Authentication mode"
Restart the SQLServer service
Right click on instance
Click "Restart"
Just for anyone else reading this: This worked for me on 2012 SQL Server too. Thanks
In my experience, using an event listener on scroll can create a lot of noise due to piping into that event stream, which can cause performance issues if you are executing a bulky handleScroll
function.
I often use the technique shown here in the highest rated answer, but I add debounce on top of it, usually about 100ms
yields good performance to UX ratio.
Here is an example using the top-rated answer with Lodash debounce added:
import debounce from 'lodash/debounce';
export default {
methods: {
handleScroll(event) {
// Any code to be executed when the window is scrolled
this.isUserScrolling = (window.scrollY > 0);
console.log('calling handleScroll');
}
},
created() {
this.handleDebouncedScroll = debounce(this.handleScroll, 100);
window.addEventListener('scroll', this.handleDebouncedScroll);
},
beforeDestroy() {
// I switched the example from `destroyed` to `beforeDestroy`
// to exercise your mind a bit. This lifecycle method works too.
window.removeEventListener('scroll', this.handleDebouncedScroll);
}
}
Try changing the value of 100
to 0
and 1000
so you can see the difference in how/when handleScroll
is called.
BONUS: You can also accomplish this in an even more concise and reuseable manner with a library like vue-scroll
. It is a great use case for you to learn about custom directives in Vue if you haven't seen those yet. Check out https://github.com/wangpin34/vue-scroll.
This is also a great tutorial by Sarah Drasner in the Vue docs: https://vuejs.org/v2/cookbook/creating-custom-scroll-directives.html
As mscdex said NPM comes with the nodejs msi installed file. I happened to just install the node js installer (standalone). To separately add NPM I followed following step
You can truncate the date
SELECT *
FROM Table1
WHERE trunc(field1) = to_Date('2012-01-01','YYY-MM-DD')
Look at the SQL Fiddle for more examples.
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)Beyond historical (good and already reported) reasons, there's is also a little problem with operators precedence: dot operator has higher priority than star operator, so if you have struct containing pointer to struct containing pointer to struct... These two are equivalent:
(*(*(*a).b).c).d
a->b->c->d
But the second is clearly more readable. Arrow operator has the highest priority (just as dot) and associates left to right. I think this is clearer than use dot operator both for pointers to struct and struct, because we know the type from the expression without have to look at the declaration, that could even be in another file.
On my machine a PID was not being shown from this command netstat -tulpn
for the in-use port (8080), so i could not kill it, killing the containers and restarting the computer did not work. So service docker restart
command restarted docker for me (ubuntu) and the port was no longer in use and i am a happy chap and off to lunch.
Personally, I do the following:
session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();
That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy
).
I know it is an old post, but I save it this way :
You can also see Local Modifications to see your revisions, very interesting feature. Also work with scripts.
A Distributed Storage System for Structured Data
Bigtable is a distributed storage system (built by Google) for managing structured data that is designed to scale to a very large size: petabytes of data across thousands of commodity servers.
Many projects at Google store data in Bigtable, including web indexing, Google Earth, and Google Finance. These applications place very different demands on Bigtable, both in terms of data size (from URLs to web pages to satellite imagery) and latency requirements (from backend bulk processing to real-time data serving).
Despite these varied demands, Bigtable has successfully provided a flexible, high-performance solution for all of these Google products.
Some features
Architecture
BigTable is not a relational database. It does not support joins nor does it support rich SQL-like queries. Each table is a multidimensional sparse map. Tables consist of rows and columns, and each cell has a time stamp. There can be multiple versions of a cell with different time stamps. The time stamp allows for operations such as "select 'n' versions of this Web page" or "delete cells that are older than a specific date/time."
In order to manage the huge tables, Bigtable splits tables at row boundaries and saves them as tablets. A tablet is around 200 MB, and each machine saves about 100 tablets. This setup allows tablets from a single table to be spread among many servers. It also allows for fine-grained load balancing. If one table is receiving many queries, it can shed other tablets or move the busy table to another machine that is not so busy. Also, if a machine goes down, a tablet may be spread across many other servers so that the performance impact on any given machine is minimal.
Tables are stored as immutable SSTables and a tail of logs (one log per machine). When a machine runs out of system memory, it compresses some tablets using Google proprietary compression techniques (BMDiff and Zippy). Minor compactions involve only a few tablets, while major compactions involve the whole table system and recover hard-disk space.
The locations of Bigtable tablets are stored in cells. The lookup of any particular tablet is handled by a three-tiered system. The clients get a point to a META0 table, of which there is only one. The META0 table keeps track of many META1 tablets that contain the locations of the tablets being looked up. Both META0 and META1 make heavy use of pre-fetching and caching to minimize bottlenecks in the system.
Implementation
BigTable is built on Google File System (GFS), which is used as a backing store for log and data files. GFS provides reliable storage for SSTables, a Google-proprietary file format used to persist table data.
Another service that BigTable makes heavy use of is Chubby, a highly-available, reliable distributed lock service. Chubby allows clients to take a lock, possibly associating it with some metadata, which it can renew by sending keep alive messages back to Chubby. The locks are stored in a filesystem-like hierarchical naming structure.
There are three primary server types of interest in the Bigtable system:
Example from Google's research paper:
A slice of an example table that stores Web pages. The row name is a reversed URL. The contents column family contains the page contents, and the anchor column family contains the text of any anchors that reference the page. CNN's home page is referenced by both the Sports Illustrated and the MY-look home pages, so the row contains columns named
anchor:cnnsi.com
andanchor:my.look.ca
. Each anchor cell has one version; the contents column has three versions, at timestampst3
,t5
, andt6
.
API
Typical operations to BigTable are creation and deletion of tables and column families, writing data and deleting columns from a row. BigTable provides this functions to application developers in an API. Transactions are supported at the row level, but not across several row keys.
Here is the link to the PDF of the research paper.
And here you can find a video showing Google's Jeff Dean in a lecture at the University of Washington, discussing the Bigtable content storage system used in Google's backend.
In Java, once you have the reference of the button:
Button button = (Button) findviewById(R.id.button);
To enable/disable the button, you can use either:
button.setEnabled(false);
button.setEnabled(true);
Or:
button.setClickable(false);
button.setClickable(true);
Since you want to disable the button from the beginning, you can use button.setEnabled(false); in the onCreate method. Otherwise, from XML, you can directly use:
android:clickable = "false"
So:
<Button
android:id="@+id/button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/button_text"
android:clickable = "false" />
Because python checks in the directories in sequential order starting at the first directory in sys.path
list, till it find the .py
file it was looking for.
Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.
So, most probably, you had a .py
file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).
Also, a thing to note about ImportError
s , lets say the import error says -
ImportError: No module named main
- it doesn't mean the main.py
is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py
or some other file.
Example -
My directory structure looks like -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
Now From testmain.py
, I call from shared import phtest
, it works fine.
Now lets say I introduce a shared.py in test
directory` , example -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
- shared.py
Now when I try to do from shared import phtest
from testmain.py
, I will get the error -
ImportError: cannot import name 'phtest'
As you can see above, the file that is causing the issue is shared.py
, not phtest.py
.
I found that this can be done rather simple using the ".values" method, which also gives named fields:
result_list = list(my_queryset.values('first_named_field', 'second_named_field'))
return HttpResponse(json.dumps(result_list))
"list" must be used to get data as iterable, since the "value queryset" type is only a dict if picked up as an iterable.
Documentation: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#values
Execute the workbench.action.reloadWindow
command.
There are some ways to do so:
Open the command palette (Ctrl + Shift + P) and execute the command:
>Reload Window
Define a keybinding for the command (for example CTRL+F5) in keybindings.json
:
[
{
"key": "ctrl+f5",
"command": "workbench.action.reloadWindow",
"when": "editorTextFocus"
}
]
@keithwyland answer is great. Here's a SCSS mixin:
@mixin font-awesome($content){
font-family: FontAwesome;
font-weight: normal;
font-style: normal;
display: inline-block;
text-decoration: inherit;
content: $content;
}
Usage:
@include font-awesome("\f054");
In 9.4.4 using the #>>
operator works for me:
select to_json('test'::text) #>> '{}';
To use with a table column:
select jsoncol #>> '{}' from mytable;
Yes, that's possible - you can use INSERT ... ON DUPLICATE KEY UPDATE.
Using your example:
INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12)
ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);
The whole creating and dispatching events works, but since you are using the onchange
attribute, your life can be a little simpler:
http://jsfiddle.net/xwywvd1a/3/
var selEl = document.getElementById("sel");
selEl.options[1].selected = true;
selEl.onchange();
If you use the browser's event API (addEventListener, IE's AttachEvent, etc), then you will need to create and dispatch events as others have pointed out already.
Consider using System.Windows.Forms.Timer
instead of System.Threading.Timer
for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.
In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.
When you want to pass new information to your application, you need to use POST form. In Razor you can use the following
View Code:
@* By default BeginForm use FormMethod.Post *@
@using(Html.BeginForm("Update")){
@Html.Hidden("id", Model.Id)
@Html.Hidden("productid", Model.ProductId)
@Html.TextBox("qty", Model.Quantity)
@Html.TextBox("unitrate", Model.UnitRate)
<input type="submit" value="Update" />
}
Controller's actions
[HttpGet]
public ActionResult Update(){
//[...] retrive your record object
return View(objRecord);
}
[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)
{
if (ModelState.IsValid){
int _records = UpdatePrice(id,productid,qty,unitrate);
if (_records > 0){ {
return RedirectToAction("Index1", "Shopping");
}else{
ModelState.AddModelError("","Can Not Update");
}
}
return View("Index1");
}
Note that alternatively, if you want to use @Html.TextBoxFor(model => model.Quantity)
you can either have an input with the name (respectecting case) "Quantity"
or you can change your POST Update() to receive an object parameter, that would be the same type as your strictly typed view. Here's an example:
Model
public class Record {
public string Id { get; set; }
public string ProductId { get; set; }
public string Quantity { get; set; }
public decimal UnitRate { get; set; }
}
View
@using(Html.BeginForm("Update")){
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.ProductId)
@Html.TextBoxFor(model=> model.Quantity)
@Html.TextBoxFor(model => model.UnitRate)
<input type="submit" value="Update" />
}
Post Action
[HttpPost]
public ActionResult Update(Record rec){ //Alternatively you can also use FormCollection object as well
if(TryValidateModel(rec)){
//update code
}
return View("Index1");
}
I also had this problem in my system, but after looking inside the project I saw the XML structure of the .classpath file in the project path was incorrect. After amending that file the problem was solved.
Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
continue;
continue;
key word would start the next iteration upon invocation
For Example
for(int i= 0 ; i < 5; i++){
if(i==2){
continue;
}
System.out.print(i);
}
This will print
0134
See
You can provide a file-like object to the stdin
argument of subprocess.call()
.
The documentation for the Popen
object applies here.
To capture the output, you should instead use subprocess.check_output()
, which takes similar arguments. From the documentation:
>>> subprocess.check_output(
... "ls non_existent_file; exit 0",
... stderr=subprocess.STDOUT,
... shell=True)
'ls: non_existent_file: No such file or directory\n'
Use driver.find_elements_by_xpath and matches regex matching function for the case insensitive search of the element by its text.
driver.find_elements_by_xpath("//*[matches(.,'My Button', 'i')]")
.
(dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess
files, then they are probably in the root folder for the website.
If you are using a command line (terminal) to access, then they will only show up if you use:
ls -a
If you are using a GUI application, look for a setting to "show hidden files" or something similar.
If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):
cd /
find . -name ".htaccess"
This will list out any files it finds with that name.
Try margin: 0 auto
, the div will need a fixed with.
It should be implemented as a free, non-friend functions, especially if, like most things these days, the output is mainly used for diagnostics and logging. Add const accessors for all the things that need to go into the output, and then have the outputter just call those and do formatting.
I've actually taken to collecting all of these ostream output free functions in an "ostreamhelpers" header and implementation file, it keeps that secondary functionality far away from the real purpose of the classes.
While this question is premised by not caring about the data, sometimes maintenance of the data is essential.
If so, I wrote a list of steps on how to recover from Entity Framework nightmare when the database already has tables with the same name here: How to recover from Entity Framework nightmare - database already has tables with the same name
Apparently... a moderator saw fit to delete my post so I'll paste it here:
How to recover from Entity Framework nightmare - database already has tables with the same name
Description: If you're like us when your team is new to EF, you'll end up in a state where you either can't create a new local database or you can't apply updates to your production database. You want to get back to a clean EF environment and then stick to basics, but you can't. If you get it working for production, you can't create a local db, and if you get it working for local, your production server gets out of sync. And finally, you don't want to delete any production server data.
Symptom: Can't run Update-Database because it's trying to run the creation script and the database already has tables with the same name.
Error Message: System.Data.SqlClient.SqlException (0x80131904): There is already an object named '' in the database.
Problem Background: EF understands where the current database is at compared to where the code is at based on a table in the database called dbo.__MigrationHistory. When it looks at the Migration Scripts, it tries to reconsile where it was last at with the scripts. If it can't, it just tries to apply them in order. This means, it goes back to the initial creation script and if you look at the very first part in the UP command, it'll be the CreeateTable for the table that the error was occurring on.
To understand this in more detail, I'd recommend watching both videos referenced here: https://msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx
Solution: What we need to do is to trick EF into thinking that the current database is up to date while not applying these CreateTable commands. At the same time, we still want those commands to exist so we can create new local databases.
Step 1: Production DB clean First, make a backup of your production db. In SSMS, Right-Click on the database, Select "Tasks > Export Data-tier application..." and follow the prompts. Open your production database and delete/drop the dbo.__MigrationHistory table.
Step 2: Local environment clean Open your migrations folder and delete it. I'm assuming you can get this all back from git if necessary.
Step 3: Recreate Initial In the Package Manager, run "Enable-Migrations" (EF will prompt you to use -ContextTypeName if you have multiple contexts). Run "Add-Migration Initial -verbose". This will Create the initial script to create the database from scratch based on the current code. If you had any seed operations in the previous Configuration.cs, then copy that across.
Step 4: Trick EF At this point, if we ran Update-Database, we'd be getting the original error. So, we need to trick EF into thinking that it's up to date, without running these commands. So, go into the Up method in the Initial migration you just created and comment it all out.
Step 5: Update-Database With no code to execute on the Up process, EF will create the dbo.__MigrationHistory table with the correct entry to say that it ran this script correctly. Go and check it out if you like. Now, uncomment that code and save. You can run Update-Database again if you want to check that EF thinks its up to date. It won't run the Up step with all of the CreateTable commands because it thinks it's already done this.
Step 6: Confirm EF is ACTUALLY up to date If you had code that hadn't yet had migrations applied to it, this is what I did...
Run "Add-Migration MissingMigrations" This will create practically an empty script. Because the code was there already, there was actually the correct commands to create these tables in the initial migration script, so I just cut the CreateTable and equivalent drop commands into the Up and Down methods.
Now, run Update-Database again and watch it execute your new migration script, creating the appropriate tables in the database.
Step 7: Re-confirm and commit. Build, test, run. Ensure that everything is running then commit the changes.
Step 8: Let the rest of your team know how to proceed. When the next person updates, EF won't know what hit it given that the scripts it had run before don't exist. But, assuming that local databases can be blown away and re-created, this is all good. They will need to drop their local database and add create it from EF again. If they had local changes and pending migrations, I'd recommend they create their DB again on master, switch to their feature branch and re-create those migration scripts from scratch.
Here is the crisp answer:
public String sendSMS(String phone, String token) {
WebClient webClient = WebClient.create(smsServiceUrl);
SMSRequest smsRequest = new SMSRequest();
smsRequest.setMessage(token);
smsRequest.setPhoneNo(phone);
smsRequest.setTokenId(smsServiceTokenId);
Mono<String> response = webClient.post()
.uri(smsServiceEndpoint)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body(Mono.just(smsRequest), SMSRequest.class)
.retrieve().bodyToMono(String.class);
String deliveryResponse = response.block();
if (deliveryResponse.equalsIgnoreCase("success")) {
return deliveryResponse;
}
return null;
}
Not putting a submit button could do. Just put a script to the input (type=button) or add eventListener if you want it to submit the data in the form.
Rather use this
<input type="button">
than using this
<input type="submit">
You can use std::find
to get an iterator to a value:
#include <algorithm>
std::vector<int>::iterator position = std::find(myVector.begin(), myVector.end(), 8);
if (position != myVector.end()) // == myVector.end() means the element was not found
myVector.erase(position);
Perhaps this will help? The definition of the primary key column should be exactly the same as the foreign key column.
BenAlabaster showed a practical way of doing a variable switch, but the try-catch clause is not needed. This code is enough.
static void Swap<T>(ref T x, ref T y)
{
T t = y;
y = x;
x = t;
}
The usage is the same as he shown:
float startAngle = 159.9F
float stopAngle = 355.87F
Swap(ref startAngle, ref stopAngle);
You could also use an extension method:
static class SwapExtension
{
public static T Swap<T>(this T x, ref T y)
{
T t = y;
y = x;
return t;
}
}
Use it like this:
float startAngle = 159.9F;
float stopAngle = 355.87F;
startAngle = startAngle.Swap(ref stopAngle);
Both ways uses a temporary variable in the method, but you don't need the temporary variable where you do the swapping.
It turns out that lstlisting
is able to format code nicely, but requires a lot of tweaking.
Wikibooks has a good example for the parameters you can tweak.
If I were you I would use conditional compilation or feature detection.
Here's another alternative:
<!--[if lt IE 9]><!-->
<script>
var LTEIE8 = true;
</script>
<!--<![endif]-->
I just had the same problem, what I did, I arranged the library order in sequence, for example there were java.lang.NullPointerException and javacard.lang.NullPointerException. I made the first one as default library and if you needed to use the other you can explicitly specify the full qualified class name.
Hibernate does not allow for specifying time zones by annotation or any other means. If you use Calendar instead of date, you can implement a workaround using HIbernate property AccessType and implementing the mapping yourself. The more advanced solution is to implement a custom UserType to map your Date or Calendar. Both solutions are explained in my blog post here: http://www.joobik.com/2010/11/mapping-dates-and-time-zones-with.html
Use this to obtain only the filename.
Path.GetFileName(files[0]);
A part of your question is relevant to me as I just came across it.
A third-party provider is providing a REST service that is used by multiple clients. It's a straight-forward REST called with query parameters that returns a well-formed JSON. I have tested it with PHP and Java where it worked as expected.
My client uses Oracle Service Bus as a gateway between his application server and the Internet. When I made the OSB service, it crashed with an Invalid message format
error. Turned out that the content-type
being returned was text/html
. OSB treats responses as per this header; converting between text, XML and JSON. In this case, the response was JSON but the header didn't say so. Contacting the provider, I got the reply: "We're not going to change it as it doesn't effect anyone else".
The Content-Type
header specifies what the content should be, not what it actually is. That is to say, in your consuming program, it's up to you to check or ignore it and process the content in any manner. Another example, you can return GIF data but specify the content type as JSON, then go ahead and ignore the header and read the image data. This won't hurt your program, but may hurt others.
Moral of the story: Play nice.
I think excessive uses of global variables with static keyword will also leads to memory leakage at some point of instance in the applica
Just for fun, consider the different question one would get with a very literal interpretation of the OP's description: "Write a query to print the list of names of students who have scored the maximum mark in each subject."
Those who've answered here have written queries to list a student if he or she scored the maximum mark in any one subject, but not necessarily in all subjects. Since the question posed by the OP does not ask for subject names in the output, this is a plausible interpretation.
To list the names of students (if any) who have scored the maximum mark in all subjects (excluding subjects with no marks, since arguably there is then no maximum mark then), I think this works, using column names from Michael's SQL Fiddle, which I've adapted here.
select StudentName
from Student
where not exists (
select * from Subject
where exists (
select * from Mark as M1
where M1.SubjectID = Subject.SubjectID
and M1.StudentID <> Student.StudentID
and not exists (
select * from Mark as M2
where M2.StudentID = Student.StudentID
and M2.SubjectID = M1.SubjectID
and M2.MarkRate >= M1.MarkRate
)
)
)
In other words, select a student X's name if there is no subject in which someone's mark for that subject is not matched or exceeded by some mark belonging to X for the same subject. (This query returns a student's name if the student has received more than one mark in a subject, so long as one of those marks is the highest for the subject.)
Try Following
Update A a, B b, SET a.column1=b.column1 where b.id=1
EDITED:- Update more than one column
Update A a, B b, SET a.column1=b.column1, a.column2=b.column2 where b.id=1
The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward moment.js.
Borrowing from this answer, you could do something like this without moment.js:
controller
var app1 = angular.module('app1',[]);
app1.controller('ctrl',['$scope',function($scope){
var toUTCDate = function(date){
var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return _utc;
};
var millisToUTCDate = function(millis){
return toUTCDate(new Date(millis));
};
$scope.toUTCDate = toUTCDate;
$scope.millisToUTCDate = millisToUTCDate;
}]);
template
<html ng-app="app1">
<head>
<script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ctrl">
<div>
utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
</div>
<div>
local {{1400167800 | date:'dd-M-yyyy H:mm'}}
</div>
</div>
</body>
</html>
here's plunker to play with it
Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.
You can use this
 
or  
It works on Visual Studio
In Java 1.8 This code snippet perfectly working to read CSV files
POM.xml
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-sql_2.10 -->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.10</artifactId>
<version>2.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.scala-lang/scala-library -->
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.8</version>
</dependency>
<dependency>
<groupId>com.databricks</groupId>
<artifactId>spark-csv_2.10</artifactId>
<version>1.4.0</version>
</dependency>
Java
SparkConf conf = new SparkConf().setAppName("JavaWordCount").setMaster("local");
// create Spark Context
SparkContext context = new SparkContext(conf);
// create spark Session
SparkSession sparkSession = new SparkSession(context);
Dataset<Row> df = sparkSession.read().format("com.databricks.spark.csv").option("header", true).option("inferSchema", true).load("hdfs://localhost:9000/usr/local/hadoop_data/loan_100.csv");
//("hdfs://localhost:9000/usr/local/hadoop_data/loan_100.csv");
System.out.println("========== Print Schema ============");
df.printSchema();
System.out.println("========== Print Data ==============");
df.show();
System.out.println("========== Print title ==============");
df.select("title").show();
If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:
while true; do foo; sleep 2; done
By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.
$ while true
> do
> echo "hello"
> sleep 2
> done
hello
hello
hello
^C
$ <arrow up> while true; do echo "hello"; sleep 2; done
As another person just mentioned, it's a base64 encoded string. In the past, I've used this website to decode it:
If you use package names, it won't work with folders containing dots (Error: Could not find or load main class
). Even though it compiles and creates the jar file successfully.
Instead it requires a complete folder hierarchy.
Fails:
com.example.mypackage/
Main.java
Works:
com/
example/
mypackage/
Main.java
To compile in Linux:
javac `find com/ -name '*.java'` \
&& jar cfe app.jar com.example.mypackage.Main `find com/ -name '*.class'`
I had a very close issue but in my case, it was Identifier 'e' has already been declared
.
In my case caused because of using try {} catch (e) { var e = ... }
where letter e
is generated via minifier (uglifier).
So better solution could be use catch(ex){}
(ex
as an Excemption
)
Hope somebody who searched with the similar question could find this question helpful.
Using the default works, but so does:
urls[url] = urls.get(url, 0) + 1
using .get
, you can get a default return if it doesn't exist. By default it's None, but in the case I sent you, it would be 0.
Or Simply Do this Stuff:
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
else
return false;
}
}
This worked for me:
<string name="text_with_bullet">Text with a \u2022</string>
if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {
PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}
This could be one of possible solutions, so 'or' is || not !!
I have solved this issue by extending the textview and drawing a border manually. I even added so you can select if a border is dotted or dashed.
public class BorderedTextView extends TextView {
private Paint paint = new Paint();
public static final int BORDER_TOP = 0x00000001;
public static final int BORDER_RIGHT = 0x00000002;
public static final int BORDER_BOTTOM = 0x00000004;
public static final int BORDER_LEFT = 0x00000008;
private Border[] borders;
public BorderedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public BorderedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BorderedTextView(Context context) {
super(context);
init();
}
private void init(){
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.BLACK);
paint.setStrokeWidth(4);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(borders == null) return;
for(Border border : borders){
paint.setColor(border.getColor());
paint.setStrokeWidth(border.getWidth());
if(border.getStyle() == BORDER_TOP){
canvas.drawLine(0, 0, getWidth(), 0, paint);
} else
if(border.getStyle() == BORDER_RIGHT){
canvas.drawLine(getWidth(), 0, getWidth(), getHeight(), paint);
} else
if(border.getStyle() == BORDER_BOTTOM){
canvas.drawLine(0, getHeight(), getWidth(), getHeight(), paint);
} else
if(border.getStyle() == BORDER_LEFT){
canvas.drawLine(0, 0, 0, getHeight(), paint);
}
}
}
public Border[] getBorders() {
return borders;
}
public void setBorders(Border[] borders) {
this.borders = borders;
}
}
And the border class:
public class Border {
private int orientation;
private int width;
private int color = Color.BLACK;
private int style;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public int getStyle() {
return style;
}
public void setStyle(int style) {
this.style = style;
}
public int getOrientation() {
return orientation;
}
public void setOrientation(int orientation) {
this.orientation = orientation;
}
public Border(int Style) {
this.style = Style;
}
}
Hope this helps someone :)
I've found Waldo!
How I've done it
First, I'm filtering out all colours that aren't red
waldo = Import["http://www.findwaldo.com/fankit/graphics/IntlManOfLiterature/Scenes/DepartmentStore.jpg"];
red = Fold[ImageSubtract, #[[1]], Rest[#]] &@ColorSeparate[waldo];
Next, I'm calculating the correlation of this image with a simple black and white pattern to find the red and white transitions in the shirt.
corr = ImageCorrelate[red,
Image@Join[ConstantArray[1, {2, 4}], ConstantArray[0, {2, 4}]],
NormalizedSquaredEuclideanDistance];
I use Binarize
to pick out the pixels in the image with a sufficiently high correlation and draw white circle around them to emphasize them using Dilation
pos = Dilation[ColorNegate[Binarize[corr, .12]], DiskMatrix[30]];
I had to play around a little with the level. If the level is too high, too many false positives are picked out.
Finally I'm combining this result with the original image to get the result above
found = ImageMultiply[waldo, ImageAdd[ColorConvert[pos, "GrayLevel"], .5]]
0755
= User:rwx
Group:r-x
World:r-x
0750
= User:rwx
Group:r-x
World:---
(i.e. World: no access)
r = read
w = write
x = execute (traverse for directories)
First of all, you should install SignalR.Host.Self on the server application and SignalR.Client on your client application by nuget :
PM> Install-Package SignalR.Hosting.Self -Version 0.5.2
PM> Install-Package Microsoft.AspNet.SignalR.Client
Then add the following code to your projects ;)
(run the projects as administrator)
Server console app:
using System;
using SignalR.Hubs;
namespace SignalR.Hosting.Self.Samples {
class Program {
static void Main(string[] args) {
string url = "http://127.0.0.1:8088/";
var server = new Server(url);
// Map the default hub url (/signalr)
server.MapHubs();
// Start the server
server.Start();
Console.WriteLine("Server running on {0}", url);
// Keep going until somebody hits 'x'
while (true) {
ConsoleKeyInfo ki = Console.ReadKey(true);
if (ki.Key == ConsoleKey.X) {
break;
}
}
}
[HubName("CustomHub")]
public class MyHub : Hub {
public string Send(string message) {
return message;
}
public void DoSomething(string param) {
Clients.addMessage(param);
}
}
}
}
Client console app:
using System;
using SignalR.Client.Hubs;
namespace SignalRConsoleApp {
internal class Program {
private static void Main(string[] args) {
//Set connection
var connection = new HubConnection("http://127.0.0.1:8088/");
//Make proxy to hub based on hub name on server
var myHub = connection.CreateHubProxy("CustomHub");
//Start connection
connection.Start().ContinueWith(task => {
if (task.IsFaulted) {
Console.WriteLine("There was an error opening the connection:{0}",
task.Exception.GetBaseException());
} else {
Console.WriteLine("Connected");
}
}).Wait();
myHub.Invoke<string>("Send", "HELLO World ").ContinueWith(task => {
if (task.IsFaulted) {
Console.WriteLine("There was an error calling send: {0}",
task.Exception.GetBaseException());
} else {
Console.WriteLine(task.Result);
}
});
myHub.On<string>("addMessage", param => {
Console.WriteLine(param);
});
myHub.Invoke<string>("DoSomething", "I'm doing something!!!").Wait();
Console.Read();
connection.Stop();
}
}
}
You could use the ternary operator:
return string.IsNullOrEmpty(strTestString) ? "0" : strTestString
FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;
I hope that I am understing your question correctly, but you can do this very quickly with Linq. I'm assuming that universally you will always have an Id property. Just create an interface to ensure this.
If how you identify an object to be the same changes from class to class, I would recommend passing in a delegate that returns true if the two objects have the same persistent id.
Here is how to do it in Linq:
List<Employee> listA = new List<Employee>();
List<Employee> listB = new List<Employee>();
listA.Add(new Employee() { Id = 1, Name = "Bill" });
listA.Add(new Employee() { Id = 2, Name = "Ted" });
listB.Add(new Employee() { Id = 1, Name = "Bill Sr." });
listB.Add(new Employee() { Id = 3, Name = "Jim" });
var identicalQuery = from employeeA in listA
join employeeB in listB on employeeA.Id equals employeeB.Id
select new { EmployeeA = employeeA, EmployeeB = employeeB };
foreach (var queryResult in identicalQuery)
{
Console.WriteLine(queryResult.EmployeeA.Name);
Console.WriteLine(queryResult.EmployeeB.Name);
}
An alternative answer is to use a Base64 encoded command switch:
powershell -EncodedCommand "QwA6AFwAUAByAG8AZwByAGEAbQAgAEYAaQBsAGUAcwBcAEkASQBTAFwATQBpAGMAcgBvAHMAbwBmAHQAIABXAGUAYgAgAEQAZQBwAGwAbwB5AFwAbQBzAGQAZQBwAGwAbwB5AC4AZQB4AGUAIAAtAHYAZQByAGIAOgBzAHkAbgBjACAALQBzAG8AdQByAGMAZQA6AGQAYgBmAHUAbABsAHMAcQBsAD0AIgBEAGEAdABhACAAUwBvAHUAcgBjAGUAPQBtAHkAcwBvAHUAcgBjAGUAOwBJAG4AdABlAGcAcgBhAHQAZQBkACAAUwBlAGMAdQByAGkAdAB5AD0AZgBhAGwAcwBlADsAVQBzAGUAcgAgAEkARAA9AHMAYQA7AFAAdwBkAD0AcwBhAHAAYQBzAHMAIQA7AEQAYQB0AGEAYgBhAHMAZQA9AG0AeQBkAGIAOwAiACAALQBkAGUAcwB0ADoAZABiAGYAdQBsAGwAcwBxAGwAPQAiAEQAYQB0AGEAIABTAG8AdQByAGMAZQA9AC4AXABtAHkAZABlAHMAdABzAG8AdQByAGMAZQA7AEkAbgB0AGUAZwByAGEAdABlAGQAIABTAGUAYwB1AHIAaQB0AHkAPQBmAGEAbABzAGUAOwBVAHMAZQByACAASQBEAD0AcwBhADsAUAB3AGQAPQBzAGEAcABhAHMAcwAhADsARABhAHQAYQBiAGEAcwBlAD0AbQB5AGQAYgA7ACIALABjAG8AbQBwAHUAdABlAHIAbgBhAG0AZQA9ADEAMAAuADEAMAAuADEAMAAuADEAMAAsAHUAcwBlAHIAbgBhAG0AZQA9AGEAZABtAGkAbgBpAHMAdAByAGEAdABvAHIALABwAGEAcwBzAHcAbwByAGQAPQBhAGQAbQBpAG4AcABhAHMAcwAiAA=="
When decoded, you'll see it's the OP's original snippet with all arguments and double quotes preserved.
powershell.exe -EncodedCommand
Accepts a base-64-encoded string version of a command. Use this parameter
to submit commands to Windows PowerShell that require complex quotation
marks or curly braces.
The original command:
C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"
It turns into this when encoded as Base64:
QwA6AFwAUAByAG8AZwByAGEAbQAgAEYAaQBsAGUAcwBcAEkASQBTAFwATQBpAGMAcgBvAHMAbwBmAHQAIABXAGUAYgAgAEQAZQBwAGwAbwB5AFwAbQBzAGQAZQBwAGwAbwB5AC4AZQB4AGUAIAAtAHYAZQByAGIAOgBzAHkAbgBjACAALQBzAG8AdQByAGMAZQA6AGQAYgBmAHUAbABsAHMAcQBsAD0AIgBEAGEAdABhACAAUwBvAHUAcgBjAGUAPQBtAHkAcwBvAHUAcgBjAGUAOwBJAG4AdABlAGcAcgBhAHQAZQBkACAAUwBlAGMAdQByAGkAdAB5AD0AZgBhAGwAcwBlADsAVQBzAGUAcgAgAEkARAA9AHMAYQA7AFAAdwBkAD0AcwBhAHAAYQBzAHMAIQA7AEQAYQB0AGEAYgBhAHMAZQA9AG0AeQBkAGIAOwAiACAALQBkAGUAcwB0ADoAZABiAGYAdQBsAGwAcwBxAGwAPQAiAEQAYQB0AGEAIABTAG8AdQByAGMAZQA9AC4AXABtAHkAZABlAHMAdABzAG8AdQByAGMAZQA7AEkAbgB0AGUAZwByAGEAdABlAGQAIABTAGUAYwB1AHIAaQB0AHkAPQBmAGEAbABzAGUAOwBVAHMAZQByACAASQBEAD0AcwBhADsAUAB3AGQAPQBzAGEAcABhAHMAcwAhADsARABhAHQAYQBiAGEAcwBlAD0AbQB5AGQAYgA7ACIALABjAG8AbQBwAHUAdABlAHIAbgBhAG0AZQA9ADEAMAAuADEAMAAuADEAMAAuADEAMAAsAHUAcwBlAHIAbgBhAG0AZQA9AGEAZABtAGkAbgBpAHMAdAByAGEAdABvAHIALABwAGEAcwBzAHcAbwByAGQAPQBhAGQAbQBpAG4AcABhAHMAcwAiAA==
and here is how to replicate at home:
$command = 'C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
$encodedCommand
# The clip below copies the base64 string to your clipboard for right click and paste.
$encodedCommand | Clip
Combining the answers of worldofjr and Alix Axel into one small function that will handle most use-cases:
function get_url_hostname($url) {
$parse = parse_url($url);
return str_ireplace('www.', '', $parse['host']);
}
get_url_hostname('http://www.google.com/example/path/file.html'); // google.com
You mentioned you are using a CER certificate.
According to the Postman page on certificates.
Choose your client certificate file in the CRT file field. Currently, we only support the CRT format. Support for other formats (like PFX) will come soon.
The name of the extension CER, CRT doesn't make the certificate that type of certificate but, these are the excepted extensions names.
CER is an X.509 certificate in binary form, DER encoded.
CRT is a binary X.509 certificate, encapsulated in text (base-64) encoding.
You can use OpenSSL to change a CER file into a CRT file. I have not had good luck with it but it looks like this.
openssl x509 -inform PEM -in certificate.cer -out certificate.crt
or
openssl x509 -inform DER -in certificate.cer -out certificate.crt
For me the scrollTop way did not work, but I found other:
element.style.display = 'none';
setTimeout(function() { element.style.display = 'block' }, 100);
Did not check the minimum time for reliable css rendering though, 100ms might be overkill.
I prefer Serializable
= no boilerplate code. For passing data to other Fragments or Activities the speed difference to a Parcelable
does not matter.
I would also always provide a helper method for a Fragment
or Activity
, this way you always know, what data has to be passed. Here an example for your ListMusicFragment
:
private static final String EXTRA_MUSIC_LIST = "music_list";
public static ListMusicFragment createInstance(List<Music> music) {
ListMusicFragment fragment = new ListMusicFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(EXTRA_MUSIC_LIST, music);
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(...) {
...
Bundle bundle = intent.getArguments();
List<Music> musicList = (List<Music>)bundle.getSerializable(EXTRA_MUSIC_LIST);
...
}
OK, nevermind.. I found the trick:
scales: {
yAxes: [
{
gridLines: {
lineWidth: 0
}
}
]
}
Add this function to the script
function myFunction() {
var btn = document.getElementById("myButton");
if (btn.value == "Open Curtain") {
btn.value = "Close Curtain";
btn.innerHTML = "Close Curtain";
}
else {
btn.value = "Open Curtain";
btn.innerHTML = "Open Curtain";
}
}
and edit the button
<button onclick="myFunction()" id="myButton" value="Open Curtain">Open Curtain</button>
Please note instead of
public TomcatEmbeddedServletContainerFactory tomcatFactory()
I had to use the following method signature
public EmbeddedServletContainerFactory embeddedServletContainerFactory()
If you want to kill the Sticky Service,the following command NOT WORKING:
adb shell am force-stop <PACKAGE>
adb shell kill <PID>
The following command is WORKING:
adb shell pm disable <PACKAGE>
If you want to restart the app,you must run command below first:
adb shell pm enable <PACKAGE>
If the variable table
contains invalid characters (like a space) you should add square brackets around the variable.
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo.[" + table + "]";
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input
I came upon this thread today and after having tried out this solution from Mark Rushakoff
from time import sleep
import sys
for i in range(21):
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i))
sys.stdout.flush()
sleep(0.25)
I can say that this works fine on W7-64 with python 3.4.3 64-bit but only in the native console. However when using the built-in console of spyder 3.0.0dev, the line breaks are still/again present. As this took me some time to figure out, I'd like to report this observation here.
In IntelliJ IDEA 2016.1.1:
Thanks to DroidT, I made this:
I realize that if the Fragment does not execute onCreateView(), its view is not instantiated. So, if the fragment on back stack did not create its views, I save the last stored state, otherwise I build my own bundle with the data I want to save/restore.
1) Extend this class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
public abstract class StatefulFragment extends Fragment {
private Bundle savedState;
private boolean saved;
private static final String _FRAGMENT_STATE = "FRAGMENT_STATE";
@Override
public void onSaveInstanceState(Bundle state) {
if (getView() == null) {
state.putBundle(_FRAGMENT_STATE, savedState);
} else {
Bundle bundle = saved ? savedState : getStateToSave();
state.putBundle(_FRAGMENT_STATE, bundle);
}
saved = false;
super.onSaveInstanceState(state);
}
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
if (state != null) {
savedState = state.getBundle(_FRAGMENT_STATE);
}
}
@Override
public void onDestroyView() {
savedState = getStateToSave();
saved = true;
super.onDestroyView();
}
protected Bundle getSavedState() {
return savedState;
}
protected abstract boolean hasSavedState();
protected abstract Bundle getStateToSave();
}
2) In your Fragment, you must have this:
@Override
protected boolean hasSavedState() {
Bundle state = getSavedState();
if (state == null) {
return false;
}
//restore your data here
return true;
}
3) For example, you can call hasSavedState in onActivityCreated:
@Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
if (hasSavedState()) {
return;
}
//your code here
}
Stringstream with a simple preproccessor macro using a lambda function seems nice:
#include <sstream>
#define make_string(args) []{std::stringstream ss; ss << args; return ss;}()
and then
auto str = make_string("hello" << " there" << 10 << '$');
"the origin is at the top-left of the screen and the Y-Coordinate increases going down, while the X-Coordinate increases to the right like normal. I guess my question becomes, do I have to convert the screen coordinates to Cartesian coordinates before applying the above formula?"
If you were calculating the angle using Cartesian coordinates, and both points were in quadrant 1 (where x>0 and y>0), the situation would be identical to screen pixel coordinates (except for the upside-down-Y thing. If you negate Y to get it right-side up, it becomes quadrant 4...). Converting screen pixel coordinates to Cartesian doesnt really change the angle.
If you're using Reactive forms you can listen for changes to the select control like so..
this.form.get('mySelectControl').valueChanges.subscribe(value => { ... do stuff ... })
To add bold, italic and underline, just add the following to the font argument:
font=("Arial", 8, 'normal', 'bold', 'italic', 'underline')
You can call the super class's constructor like this
class A(object):
def __init__(self, number):
print "parent", number
class B(A):
def __init__(self):
super(B, self).__init__(5)
b = B()
NOTE:
This will work only when the parent class inherits object
If you are looking for the solution in Android Studio :
Added additional improvements to surajits answer:
using System;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Data.SqlClient;
namespace MyNamespace
{
public partial class RunSqlScript : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var connectionString = @"your-connection-string";
var pathToScriptFile = Server.MapPath("~/sql-scripts/") + "sql-script.sql";
var sqlScript = File.ReadAllText(pathToScriptFile);
using (var connection = new SqlConnection(connectionString))
{
var server = new Server(new ServerConnection(connection));
server.ConnectionContext.ExecuteNonQuery(sqlScript);
}
}
}
}
Also, I had to add the following references to my project:
C:\Program Files\Microsoft SQL Server\120\SDK\Assemblies\Microsoft.SqlServer.ConnectionInfo.dll
C:\Program Files\Microsoft SQL Server\120\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
I have no idea if those are the right dll:s to use since there are several folders in C:\Program Files\Microsoft SQL Server but in my application these two work.
Let's start from keeping in mind that data is stored as bytes; Unicode is a character set where characters are mapped to code points (unique integers), and we need something to translate these code points data into bytes. That's where UTF-8 comes in so called encoding – simple!
After reading some email-lists and other forums i found that the trick seems to add som unique data to the intent.
like this:
Intent notificationIntent = new Intent(Main.this, Main.class);
notificationIntent.putExtra("sport_id", "sport"+id);
notificationIntent.putExtra("game_url", "gameURL"+id);
notificationIntent.setData((Uri.parse("foobar://"+SystemClock.elapsedRealtime())));
I dont understand why this needs to be done, It got something to do with the intent cant be identified only by its extras...
You can apply multiple conditions in xpath using and, or
//input[@class='_2zrpKA _1dBPDZ' and @type='text']
//input[@class='_2zrpKA _1dBPDZ' or @type='text']
I had the same problem , first I couldn't find those dlls
in the list of .NET components
. but later I figured it out that the solution is :
1- first I changed target framework
from .NET framework 4 client profile
to .NET framework 4
.
2- then scroll down the list of .NET components
, pass first list of system.web.
.. , scroll down , and find the second list of system.web.
.. at the bottom , they're there .
I hope this could help others
If you want to check if your -vm eclipse.ini
option worked correctly you can use this to see under what JVM the IDE itself runs: menu Help > About Eclipse > Installation Details > Configuration tab. Locate the line that says: java.runtime.version=...
.
Quite a lot of answers but still: why not simpler?
An es5 version of getting the value would be:
function value(obj, keys) {
if (obj === undefined) return obj;
if (keys.length === 1 && obj.hasOwnProperty(keys[0])) return obj[keys[0]];
return value(obj[keys.shift()], keys);
}
if (value(test, ['level1', 'level2', 'level3'])) {
// do something
}
you could also use it with value(config, ['applet', i, 'height']) || 42
Credits to CMS for his ES6 solution that gave me this idea.
That is the release version of RHEL, or at least the release of RHEL from which the package supplying /etc/redhat-release was installed. A file like that is probably the closest you can come; you could also look at /etc/lsb-release.
It is theoretically possible to have packages installed from a mix of versions (e.g. upgrading part of the system to 5.5 while leaving other parts at 5.4), so if you depend on the versions of specific components you will need to check for those individually.
With the render
method potentially deprecating the returned value, the recommended approach is now to attach a callback ref to the root element. Like this:
ReactDOM.render( <Hello name="World" ref={(element) => {window.helloComponent = element}}/>, document.getElementById('container'));
which we can then access using window.helloComponent, and any of its methods can be accessed with window.helloComponent.METHOD.
Here's a full example:
var onButtonClick = function() {_x000D_
window.helloComponent.alertMessage();_x000D_
}_x000D_
_x000D_
class Hello extends React.Component {_x000D_
alertMessage() {_x000D_
alert(this.props.name);_x000D_
}_x000D_
_x000D_
render() {_x000D_
return React.createElement("div", null, "Hello ", this.props.name);_x000D_
}_x000D_
};_x000D_
_x000D_
ReactDOM.render( <Hello name="World" ref={(element) => {window.helloComponent = element}}/>, document.getElementById('container'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>_x000D_
<button onclick="onButtonClick()">Click me!</button>
_x000D_
If you are using SQL Server 2005 or above use this:
SELECT *
FROM (
SELECT ID,
Email,
ProductName,
ProductModel,
ROW_NUMBER() OVER(PARTITION BY Email ORDER BY ID DESC) rn
FROM Products
) a
WHERE rn = 1
EDIT: Example using a where clause:
SELECT *
FROM (
SELECT ID,
Email,
ProductName,
ProductModel,
ROW_NUMBER() OVER(PARTITION BY Email ORDER BY ID DESC) rn
FROM Products
WHERE ProductModel = 2
AND ProductName LIKE 'CYBER%'
) a
WHERE rn = 1
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.
Thanks - this helped me to understand better ansd solve a problem I had. The JQuery provided to get the text of selectedItem did NOT wwork for me I changed it to
$(function () {
$("#SelectedVender").on("change", function () {
$("#SelectedvendorText").val($(**"#SelectedVender option:selected"**).text());
});
});
The variable $token
is not being retrieved from the session when it's in there
The easiest way to solve is the to recognize that in javascript dates are just numbers. It starts 0
or 'Wed Dec 31 1969 18:00:00 GMT-0600 (CST)
. Every 1
represents a millisecond. You can add or subtract milliseconds by getting the value and instantiating a new date using that value. You can manage it pretty easy with that mind.
const minutesToAdjust = 10;
const millisecondsPerMinute = 60000;
const originalDate = new Date('11/20/2017 10:00 AM');
const modifiedDate1 = new Date(originalDate.valueOf() - (minutesToAdjust * millisecondsPerMinute));
const modifiedDate2 = new Date(originalDate.valueOf() + (minutesToAdjust * millisecondsPerMinute));
console.log(originalDate); // Mon Nov 20 2017 10:00:00 GMT-0600 (CST)
console.log(modifiedDate1); // Mon Nov 20 2017 09:50:00 GMT-0600 (CST)
console.log(modifiedDate2); // Mon Nov 20 2017 10:10:00 GMT-0600 (CST)
Here's a dplyr
solution:
library(dplyr)
# find max for each column
summarise_each(ozone, funs(max(., na.rm=TRUE)))
# sort by Solar.R, descending
arrange(ozone, desc(Solar.R))
UPDATE: summarise_each()
has been deprecated in favour of a more featureful family of functions: mutate_all()
, mutate_at()
, mutate_if()
, summarise_all()
, summarise_at()
, summarise_if()
Here is how you could do:
# find max for each column
ozone %>%
summarise_if(is.numeric, funs(max(., na.rm=TRUE)))%>%
arrange(Ozone)
or
ozone %>%
summarise_at(vars(1:6), funs(max(., na.rm=TRUE)))%>%
arrange(Ozone)
I had a similar error message "Fragment MyFragment not attached to Context" in Xamarine Android.
this error messege getting because of this resource calling
button.Text = Resources.GetString(Resource.String.please_wait)
I did fix that by using in Xamarine Android.
if (Context != null && IsAdded){
button.Text = Resources.GetString(Resource.String.please_wait);
}
You can also define a class for the bullets you want to show, so in the CSS:
ul {list-style:none; list-style-type:none; list-style-image:none;}
And in the HTML you just define which lists to show:
<ul style="list-style:disc;">
Or you alternatively define a CSS class:
.show-list {list-style:disc;}
Then apply it to the list you want to show:
<ul class="show-list">
All other lists won't show the bullets...
Table structure...very basic:
create table tabla(ID int, Stuff varchar (50));
insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');
Query:
SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla
Or, try this:
SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla
Working on SQLServer 2008
Bootstrap 2.x
You could create a new CSS class such as:
.img-center {margin:0 auto;}
And then, add this to each IMG:
<img src="images/2.png" class="img-responsive img-center">
OR, just override the .img-responsive
if you're going to center all images..
.img-responsive {margin:0 auto;}
Demo: http://bootply.com/86123
Bootstrap 3.x
EDIT - With the release of Bootstrap 3.0.1, the center-block
class can now be used without any additional CSS..
<img src="images/2.png" class="img-responsive center-block">
Bootstrap 4
In Bootstrap 4, the mx-auto
class (auto x-axis margins) can be used to center images that are display:block
. However, img is display:inline
by default so text-center
can be used on the parent.
<div class="container">
<div class="row">
<div class="col-12">
<img class="mx-auto d-block" src="//placehold.it/200">
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<img src="//placehold.it/200">
</div>
</div>
</div>
Yes, you should use docstrings to make your classes and functions more friendly to other programmers:
More: http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
Some editors allow you to see docstrings while typing, so it really makes work easier.
while ((line = stringReader.ReadLine()) != null)
{
// split the lines
for (int c = 0; c < line.Length; c++)
{
line = line.Replace("\\", "");
lineBreakOne = line.Substring(1, c - 2);
lineBreakTwo = line.Substring(c + 2, line.Length - 2);
}
}
If you want to store your output into your desktop, follow the below command using post command in git bash.It worked for me.
curl https://localhost:8080 --request POST --header "Content-Type: application/json" -o "C:\Desktop\test.txt"
I had a similar issue as you, although I was trying to use start
to open Chrome and using the file path. I used only start chrome.exe
and it opened just fine. You may want to try to do the same with exe file. Using the file path may be unnecessary.
Here are some examples (using the file name you gave in a comment on another answer):
Instead of C:\Program^ Files\temp.exe
you can try temp.exe
.
Instead of start C:\Program^ Files\temp.exe
you can try start
temp.exe
As you say, this can mean that your IP address has been blocked. I'd make sure that you specify the key parameter on the query string for the Geocoding API request.
https://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=Placename&key=XXxxxXXxXxxxxXXxx
Also make sure that if you've set up IP Address Restrictions within the Developer Console, you've allowed the correct IP address, just click the project within the list and you'll see the allowed IPs.
If you're still running into issues, you might want to look into printing out the values of the status
and error_message
elements from the response from Google, you'll see something like this:
REQUEST_DENIED - This IP, site or mobile application is not authorized to use this API key. Request received from IP address 123.4.5.678, with empty referer
If it doesn't mention an IP address restriction, it may well give you enough information about the problem to Google a fix.