Although there is no need to close the file manually but it is good idea to do so if the scope of the file variable is bigger:
ifstream infile(szFilePath);
for (string line = ""; getline(infile, line); )
{
//do something with the line
}
if(infile.is_open())
infile.close();
Use CASE
:
SELECT
TABEL1.Id,
CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
THEN 'TRUE'
ELSE 'FALSE'
END AS NewFiled
FROM TABLE1
If TABLE2.ID
is Unique or a Primary Key, you could also use this:
SELECT
TABEL1.Id,
CASE WHEN TABLE2.ID IS NOT NULL
THEN 'TRUE'
ELSE 'FALSE'
END AS NewFiled
FROM TABLE1
LEFT JOIN Table2
ON TABLE2.ID = TABLE1.ID
Nothing of the above worked for me. But those lines solved the same problem on my WordPress site:
RewriteEngine On
RewriteCond %{HTTP:HTTPS} !on
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Try this one
Open Visual Studio Code and press Command + Shift + P or F1 then type Shell
in command palette now you are able to find this option like Shell Command : Install code in PATH
from suggested list in command palette. Select that options.
That's it.
Now open your terminal type.
$ code .
This is what I use. I make no pretense that it's far less "efficient" than the simpler solutions above. What it does do is provide a much clearer exception message than "ArrayIndexOutOfBounds" when an invalid ordinal value is used in the solution above.
It utilizes the fact that EnumSet javadoc specifies the iterator returns elements in their natural order. There's an assert if that's not correct.
The JUnit4 Test demonstrates how it's used.
/**
* convert ordinal to Enum
* @param clzz may not be null
* @param ordinal
* @return e with e.ordinal( ) == ordinal
* @throws IllegalArgumentException if ordinal out of range
*/
public static <E extends Enum<E> > E lookupEnum(Class<E> clzz, int ordinal) {
EnumSet<E> set = EnumSet.allOf(clzz);
if (ordinal < set.size()) {
Iterator<E> iter = set.iterator();
for (int i = 0; i < ordinal; i++) {
iter.next();
}
E rval = iter.next();
assert(rval.ordinal() == ordinal);
return rval;
}
throw new IllegalArgumentException("Invalid value " + ordinal + " for " + clzz.getName( ) + ", must be < " + set.size());
}
@Test
public void lookupTest( ) {
java.util.concurrent.TimeUnit tu = lookupEnum(TimeUnit.class, 3);
System.out.println(tu);
}
Lets make it as simple if you don't want to hardcode the value of year and month and you want to take the value from current date and time:
Date d = new Date();
String myDate = new SimpleDateFormat("dd/MM/yyyy").format(d);
int iDayFromDate = Integer.parseInt(myDate.substring(0, 2));
int iMonthFromDate = Integer.parseInt(myDate.substring(3, 5));
int iYearfromDate = Integer.parseInt(myDate.substring(6, 10));
YearMonth CurrentYear = YearMonth.of(iYearfromDate, iMonthFromDate);
int lengthOfCurrentMonth = CurrentYear.lengthOfMonth();
System.out.println("Total number of days in current month is " + lengthOfCurrentMonth );
Removing parameters from injectable constructor() method solved it for my case.
I like this answer:
cat > FILE.txt <<EOF
info code info
...
EOF
but would suggest cat >> FILE.txt << EOF
if you want just add something to the end of the file without wiping out what is already exists
Like this:
cat >> FILE.txt <<EOF
info code info
...
EOF
1. Run Android SDK Manager and install the latest SDK and Android Support Libarary. The version of SDK and Android Support Libarary should be the same! 23 in my case. Another variants will give you the errors.
2. Change SDK version of your IDEA project to the last one you installed in previous step. (ps. you may not use Maven).
3. Add new Module from existing sourse to your IDEA project.
4. Add AppCompat project. !!! Should be under the last SDK too! (ps. Say "Yes" anywhere in process of this step)
5. Open settings of your main Project Module and add to it next 3 dependecies:
5.1. Module Dependency. Chose android-support-v7-appcompat
5.2. 2 pc. Library Dependencies. Add android-sdk\extras\android\support\v7\appcompat\libs\android-support-v4.jar and android-support-v4\android-support-v7-appcompat.jar
6. Very important!!!
Add theme with prefix @style (not another!).
1. Run Android SDK Manager and install the latest SDK and Android Support Libarary. The version of SDK and Android Support Libarary should be the same! 23 in my case. Another variants will give you the errors.
2. Add next to build.gradle
dependencies {
compile 'com.android.support:appcompat-v7:23.0.1'
}
P.S. If you are new in Android developing, I strongly recomend you move to Android Studio & Gradle right now - you will get the simplest way of managing your android app.
Manoj Govindan's answer is correct but I saw that comment:
Run it from the terminal.
And got to thinking about why this is so not obvious to windows users and realized it's because CMD.EXE is such a poor excuse for a shell that it should start with:
Windows command interpreter copyright 1999 Microsoft
Mein Gott!! Whatever you do, don't use this!!
C:>
Which leads me to point at https://stackoverflow.com/questions/913912/bash-shell-for-windows
Disclaimer: This is intended for those supporting a continuous integration workflow that require an automated process. If you don't, please use Xcode as described in Javier's answer.
This worked for me to set ENABLE_BITCODE = NO
via the command line:
find . -name *project.pbxproj | xargs sed -i -e 's/\(GCC_VERSION = "";\)/\1\ ENABLE_BITCODE = NO;/g'
Note that this is likely to be unstable across Xcode versions. It was tested with Xcode 7.0.1 and as part of a Cordova 4.0 project.
I recently discovered an interesting trick that allows to "Split String With String As Delimiter", so I couldn't resist the temptation to post it here as a new answer. Note that "obviously the question wasn't accurate. Firstly, both string1 and string2 can contain spaces. Secondly, both string1 and string2 can contain ampersands ('&')". This method correctly works with the new specifications (posted as a comment below Stephan's answer).
@echo off
setlocal
set "str=string1&with spaces by string2&with spaces.txt"
set "string1=%str: by =" & set "string2=%"
set "string2=%string2:.txt=%"
echo "%string1%"
echo "%string2%"
For further details on the split method, see this post.
This is a known issue with Swift 4.2 and Xcode 10. I found an article here that fixed it for me: https://github.com/Yummypets/YPImagePicker/issues/236
In short, go to your projects build settings, and add a user defined setting named SWIFT_ENABLE_BATCH_MODE and set its value to NO.
Previously, I tried each of the methods suggested here (rebuild, exit Xcode, clean and rebuild, purge Derived Data files). None of them worked.
Once I added the user define build setting per the article, Swift then told me the true error. In my case, it was a missing }, but it could be any number of problems.
Root Cause #1 - The Delimiter Problem
Sql injection is possible because we use quotation marks to delimit strings and also to be parts of strings, making it impossible to interpret them sometimes. If we had delimiters that could not be used in string data, sql injection never would have happened. Solving the delimiter problem eliminates the sql injection problem. Structure queries do that.
Root Cause #2 - Human Nature, People are Crafty and Some Crafty People Are Malicious And All People Make Mistakes
The other root cause of sql injection is human nature. People, including programmers, make mistakes. When you make a mistake on a structured query, it does not make your system vulnerable to sql injection. If you are not using structured queries, mistakes can generate sql injection vulnerability.
How Structured Queries Resolve the Root Causes of SQL Injection
Structured Queries Solve The Delimiter Problem, by by putting sql commands in one statement and putting the data in a separate programming statement. Programming statements create the separation needed.
Structured queries help prevent human error from creating critical security holes. With regard to humans making mistakes, sql injection cannot happen when structure queries are used. There are ways of preventing sql injection that don't involve structured queries, but normal human error in that approaches usually leads to at least some exposure to sql injection. Structured Queries are fail safe from sql injection. You can make all the mistakes in the world, almost, with structured queries, same as any other programming, but none that you can make can be turned into a ssstem taken over by sql injection. That is why people like to say this is the right way to prevent sql injection.
So, there you have it, the causes of sql injection and the nature structured queries that makes them impossible when they are used.
IntelliJ 14 (Ubuntu):
See: how-do-i-turn-on-line-numbers-permanently-in-intellij-14
Permanently:
File > Settings > Editor > General > Appearance > show line numbers
For current Editor:
View > Active Editor > Show Line Numbers
I came across the same problem. I properly installed the MYSQL Workbench 6.x, but faced the connection as below:
I did a bit R&D on this and found that MySQL service in service.msc is not present. To achieve this I created a new connection in MySQL Workbench then manually configured the MySQL Database Server in "System Profile" (see the below picture).
You also need to install MySQL Database Server and set a configuration file path for my.ini
. Now at last test the connection (make sure MySQL service is running in services.msc).
Have you tried somethig like this?
.showme{display: none;}
.showhim:hover .showme{display : block;}
.hideme{display:block;}
.showhim:hover .hideme{display:none;}
<div class="showhim">HOVER ME
<div class="showme">hai</div>
<div class="hideme">bye</div>
</div>
I dont know any reason why it shouldn't be possible.
Another way ..
<img ng-src="{{!video.playing ? 'img/icons/play-rounded-button-outline.svg' : 'img/icons/pause-thin-rounded-button.svg'}}" />
Your local branch likely has modifications to it you want to discard. To do this, you'll need to use git reset
to reset the branch head to the last spot that you diverged from the upstream repo's branch. Use git branch -v
to find the sha1 id of the upstream branch, and reset your branch it it using git reset SHA1ID
. Then you should be able to do a git checkout
to discard the changes it left in your directory.
Note: always do this on a backed-up repo. That way you can assure you're self it worked right. Or if it didn't, you have a backup to revert to.
Just to add one case to unutbu's list.
One of the biggest practical differences for me of numpy ndarrays compared to numpy matrices or matrix languages like matlab, is that the dimension is not preserved in reduce operations. Matrices are always 2d, while the mean of an array, for example, has one dimension less.
For example demean rows of a matrix or array:
with matrix
>>> m = np.mat([[1,2],[2,3]])
>>> m
matrix([[1, 2],
[2, 3]])
>>> mm = m.mean(1)
>>> mm
matrix([[ 1.5],
[ 2.5]])
>>> mm.shape
(2, 1)
>>> m - mm
matrix([[-0.5, 0.5],
[-0.5, 0.5]])
with array
>>> a = np.array([[1,2],[2,3]])
>>> a
array([[1, 2],
[2, 3]])
>>> am = a.mean(1)
>>> am.shape
(2,)
>>> am
array([ 1.5, 2.5])
>>> a - am #wrong
array([[-0.5, -0.5],
[ 0.5, 0.5]])
>>> a - am[:, np.newaxis] #right
array([[-0.5, 0.5],
[-0.5, 0.5]])
I also think that mixing arrays and matrices gives rise to many "happy" debugging hours. However, scipy.sparse matrices are always matrices in terms of operators like multiplication.
I made some big lists. One is a list and one is a numpy array.
import numpy as np
import random
arrayv=np.random.randint(0,10,(100000000,1))
listv=[]
for i in range(0,100000000):
listv.append(random.randint(0,9))
Using jupyter notebook's %%time function I can compare the speed of various things.
2 seconds:
%%time
listv.index(max(listv))
54.6 seconds:
%%time
listv.index(max(arrayv))
6.71 seconds:
%%time
np.argmax(listv)
103 ms:
%%time
np.argmax(arrayv)
numpy's arrays are crazy fast.
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
How about using a Browser plugin that gives you an overview of ANY html page. I have tried the following:
They both work pretty well for IPython Notebooks. I was reluctant to use the previous solutions as they seem a bit unstable and ended up using these extensions.
Use a setter for the ViewChild:
private contentPlaceholder: ElementRef;
@ViewChild('contentPlaceholder') set content(content: ElementRef) {
if(content) { // initially setter gets called with undefined
this.contentPlaceholder = content;
}
}
The setter is called with an element reference once *ngIf
becomes true
.
Note, for Angular 8 you have to make sure to set { static: false }
, which is a default setting in other Angular versions:
@ViewChild('contentPlaceholder', { static: false })
Note: if contentPlaceholder is a component you can change ElementRef to your component Class:
private contentPlaceholder: MyCustomComponent;
@ViewChild('contentPlaceholder') set content(content: MyCustomComponent) {
if(content) { // initially setter gets called with undefined
this.contentPlaceholder = content;
}
}
You can resolve this in several ways:
g++
in stead of gcc
: g++ -g -o MatSim MatSim.cpp
-lstdc++
: gcc -g -o MatSim MatSim.cpp -lstdc++
<string.h>
by <string>
This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.
With the release of Docker 19.03, you can skip creating the container and even building an image. There's an option with BuildKit based builds to change the output destination. You can use this to write the results of the build to your local directory rather than into an image. E.g. here's a build of a go binary:
$ ls
Dockerfile go.mod main.go
$ cat Dockerfile
FROM golang:1.12-alpine as dev
RUN apk add --no-cache git ca-certificates
RUN adduser -D appuser
WORKDIR /src
COPY . /src/
CMD CGO_ENABLED=0 go build -o app . && ./app
FROM dev as build
RUN CGO_ENABLED=0 go build -o app .
USER appuser
CMD [ "./app" ]
FROM scratch as release
COPY --from=build /etc/passwd /etc/group /etc/
COPY --from=build /src/app /app
USER appuser
CMD [ "/app" ]
FROM scratch as artifact
COPY --from=build /src/app /app
FROM release
From the above Dockerfile, I'm building the artifact
stage that only includes the files I want to export. And the newly introduced --output
flag lets me write those to a local directory instead of an image. This needs to be performed with the BuildKit engine that ships with 19.03:
$ DOCKER_BUILDKIT=1 docker build --target artifact --output type=local,dest=. .
[+] Building 43.5s (12/12) FINISHED
=> [internal] load build definition from Dockerfile 0.7s
=> => transferring dockerfile: 572B 0.0s
=> [internal] load .dockerignore 0.5s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/golang:1.12-alpine 0.9s
=> [dev 1/5] FROM docker.io/library/golang:1.12-alpine@sha256:50deab916cce57a792cd88af3479d127a9ec571692a1a9c22109532c0d0499a0 22.5s
=> => resolve docker.io/library/golang:1.12-alpine@sha256:50deab916cce57a792cd88af3479d127a9ec571692a1a9c22109532c0d0499a0 0.0s
=> => sha256:1ec62c064901392a6722bb47a377c01a381f4482b1ce094b6d28682b6b6279fd 155B / 155B 0.3s
=> => sha256:50deab916cce57a792cd88af3479d127a9ec571692a1a9c22109532c0d0499a0 1.65kB / 1.65kB 0.0s
=> => sha256:2ecd820bec717ec5a8cdc2a1ae04887ed9b46c996f515abc481cac43a12628da 1.36kB / 1.36kB 0.0s
=> => sha256:6a17089e5a3afc489e5b6c118cd46eda66b2d5361f309d8d4b0dcac268a47b13 3.81kB / 3.81kB 0.0s
=> => sha256:89d9c30c1d48bac627e5c6cb0d1ed1eec28e7dbdfbcc04712e4c79c0f83faf17 2.79MB / 2.79MB 0.6s
=> => sha256:8ef94372a977c02d425f12c8cbda5416e372b7a869a6c2b20342c589dba3eae5 301.72kB / 301.72kB 0.4s
=> => sha256:025f14a3d97f92c07a07446e7ea8933b86068d00da9e252cf3277e9347b6fe69 125.33MB / 125.33MB 13.7s
=> => sha256:7047deb9704134ff71c99791be3f6474bb45bc3971dde9257ef9186d7cb156db 125B / 125B 0.8s
=> => extracting sha256:89d9c30c1d48bac627e5c6cb0d1ed1eec28e7dbdfbcc04712e4c79c0f83faf17 0.2s
=> => extracting sha256:8ef94372a977c02d425f12c8cbda5416e372b7a869a6c2b20342c589dba3eae5 0.1s
=> => extracting sha256:1ec62c064901392a6722bb47a377c01a381f4482b1ce094b6d28682b6b6279fd 0.0s
=> => extracting sha256:025f14a3d97f92c07a07446e7ea8933b86068d00da9e252cf3277e9347b6fe69 5.2s
=> => extracting sha256:7047deb9704134ff71c99791be3f6474bb45bc3971dde9257ef9186d7cb156db 0.0s
=> [internal] load build context 0.3s
=> => transferring context: 2.11kB 0.0s
=> [dev 2/5] RUN apk add --no-cache git ca-certificates 3.8s
=> [dev 3/5] RUN adduser -D appuser 1.7s
=> [dev 4/5] WORKDIR /src 0.5s
=> [dev 5/5] COPY . /src/ 0.4s
=> [build 1/1] RUN CGO_ENABLED=0 go build -o app . 11.6s
=> [artifact 1/1] COPY --from=build /src/app /app 0.5s
=> exporting to client 0.1s
=> => copying files 10.00MB 0.1s
After the build was complete the app
binary was exported:
$ ls
Dockerfile app go.mod main.go
$ ./app
Ready to receive requests on port 8080
Docker has other options to the --output
flag documented in their upstream BuildKit repo: https://github.com/moby/buildkit#output
Try this:
constructor( public router: Router,) {
this.route.params.subscribe(params => this._onRouteGetParams(params));
}
this.router.navigate(['otherRoute']);
I'm actually using an extension for it and controlling if it is ios 11 or not.
extension UIView {
var safeTopAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.topAnchor
}
return self.topAnchor
}
var safeLeftAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *){
return self.safeAreaLayoutGuide.leftAnchor
}
return self.leftAnchor
}
var safeRightAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *){
return self.safeAreaLayoutGuide.rightAnchor
}
return self.rightAnchor
}
var safeBottomAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.bottomAnchor
}
return self.bottomAnchor
}
}
Here's a quick way to get what is happening:
When you did the following:
name? : string
You were saying to TypeScript it was optional. Nevertheless, when you did:
let name1 : string = person.name; //<<<Error here
You did not leave it a choice. You needed to have a Union on it reflecting the undefined type:
let name1 : string | undefined = person.name; //<<<No error here
Using your answer, I was able to sketch out the following which is basically, an Interface, a Class and an Object. I find this approach simpler, never mind if you don't.
// Interface
interface iPerson {
fname? : string,
age? : number,
gender? : string,
occupation? : string,
get_person?: any
}
// Class Object
class Person implements iPerson {
fname? : string;
age? : number;
gender? : string;
occupation? : string;
get_person?: any = function () {
return this.fname;
}
}
// Object literal
const person1 : Person = {
fname : 'Steve',
age : 8,
gender : 'Male',
occupation : 'IT'
}
const p_name: string | undefined = person1.fname;
// Object instance
const person2: Person = new Person();
person2.fname = 'Steve';
person2.age = 8;
person2.gender = 'Male';
person2.occupation = 'IT';
// Accessing the object literal (person1) and instance (person2)
console.log('person1 : ', p_name);
console.log('person2 : ', person2.get_person());
Try deleting your ASO files.
ASO files are cached compiled versions of your class files. Although the IDE is a lot better at letting go of old caches when changes are made, sometimes you have to manually delete them. To delete ASO files: Control>Delete ASO Files.
This is also the cause of the "I-am-not-seeing-my-changes-so-let-me-add-a-trace-now-everything-works" bug that was introduced in CS3.
when you return some thing, the code exits out of the loop with what ever you are returning.so, in your code, in the first iteration, name is "one"
. so, as soon as it reaches return new Text(name)
, code exits the loop with return new Text("one")
. so, try to print it or use asynchronous returns.
Without hitting db we can fetch all months name.
WITH CTE_Sample1 AS
(
Select 0 as MonthNumber
UNION ALL
select MonthNumber+1 FROM CTE_Sample1
WHERE MonthNumber+1<12
)
Select DateName( month , DateAdd( month , MonthNumber ,0 ) ) from CTE_Sample1
I wrote this code:
word = input("enter: ")
word = ''.join(word.split())`
for x in range(len(word)):
if list(word)[x] == ((list(word)[len(word)-x-1])):
if x+1 == len(word):
print("its pali")
and it works. it gets the word, then removes the spaces and turns it into a list then it tests if the first letter is equal to the last and if the 2nd is equal to 2nd last and so on.
then the 'if x+1 == len(word)' means that since x starts at 0 it becomes 1 and then for every next .. blah blah blah it works so it works.
In spring3.2, new solution is introduced by: http://static.springsource.org/spring/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBean.html , the below is my example:
<mvc:annotation-driven>
?<mvc:message-converters>
??<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
???<property name="objectMapper">
????<bean
class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
?????<property name="featuresToEnable">
??????<array>
???????<util:constant static-field="com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES" />
??????</array>
?????</property>
????</bean>
???</property>
??</bean>
?</mvc:message-converters>
</mvc:annotation-driven>
You can see all the version of a module with npm view
.
eg: To list all versions of bootstrap including beta.
npm view bootstrap versions
But if the version list is very big it will truncate. An --json
option will print all version including beta versions as well.
npm view bootstrap versions --json
If you want to list only the stable versions not the beta then use singular version
npm view bootstrap@* versions
Or
npm view bootstrap@* versions --json
And, if you want to see only latest version then here you go.
npm view bootstrap version
match
returns an array.
The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:
var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);
Regex Email Pattern:
^(?:[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+\\.)*[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!\\.)){0,61}[a-zA-Z0-9]?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\\[(?:(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\]))$
Following is one liner for accepted answer ... (for one line lovers ..)
def search_dict(my_dict,searchFor):
s_val = [[ k if searchFor in v else None for v in my_dict[k]] for k in my_dict]
return s_val
When you added the file to the resources, you should select its Access Modifiers as public than you can make something like following.
byte[] clistAsByteArray = Properties.Resources.CLIST01;
CLIST01 is the name of the embedded file.
Actually you can go to the resources.Designer.cs and see what is the name of the getter.
Try to use (focusout) instead of (blur)
In git
stash is a storage area where current changed files can be moved.
stash
area is useful when you want to pull some changes from git
repository and detected some changes in some mutual files available in git
repo.
git stash apply //apply the changes without removing stored files from stash area.
git stash pop // apply the changes as well as remove stored files from stash area.
Note :-
git apply
only apply the changes from stash area whilegit pop
apply as well as remove change fromstash
area.
I usually start with the following when styling definition lists as tables:
dt,
dd{
/* Override browser defaults */
display: inline;
margin: 0;
}
dt {
clear:left;
float:left;
line-height:1; /* Adjust this value as you see fit */
width:33%; /* 1/3 the width of the parent. Adjust this value as you see fit */
}
dd {
clear:right;
float: right;
line-height:1; /* Adjust this value as you see fit */
width:67%; /* 2/3 the width of the parent. Adjust this value as you see fit */
}
Many people set their cookie path to /. That will cause every favicon request to send a copy of the sites cookies, at least in chrome. Addressing your favicon to your cookieless domain should correct this.
<link rel="icon" href="https://cookieless.MySite.com/favicon.ico" type="image/x-icon" />
Depending on how much traffic you get, this may be the most practical reason for adding the link.
Info on setting up a cookieless domain:
New solution with ES6
Default object
object = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
Another object
object = {'id': 5};
Object assign ES6
resultObject = {...obj, ...newobj};
Result
[{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}];
Maybe this is a little bit late but I found a web site which gives social media account details by know email addreess. It is https://www.fullcontact.com
You can use Person Api there and get the info.
This is a type of get : https://api.fullcontact.com/v2/person.xml?email=someone@****&apiKey=********
Also there is xml or json choice.
Require all granted seemed a bit to far for me. Looking at the documentation I used: Require ip 192.168
to allow all internal access.
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Require local
Require ip 192.168
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
Here's a cool ASP.NET Web control called Multi-Select List Field at http://www.xnodesystems.com/. It's capable of:
(1) Multi-select; (2) Auto-complete; (3) Validation.
tessdata_dir_config = r'--tessdata-dir "/usr/local/Cellar/tesseract/4.1.1/share/tessdata"'
pytesseract.image_to_string(imgCrop,lang='eng',config=tessdata_dir_config)
It seems that the latest function for this in windows 7 is robocopy.
Usage example:
robocopy <source> <destination> /e /xf <file to exclude> <another file>
/e copies subdirectories including empty ones, /xf excludes certain files from being copied.
More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx
It is as simple as string[:2]
. A function can be easily written to do it, if you need.
Even this, is as simple as
def first2(s):
return s[:2]
string.translate with table=None works fine.
>>> name = "Barack (of Washington)"
>>> name = name.translate(None, "(){}<>")
>>> print name
Barack of Washington
You can click the dropdown near the run button on toolbar,
Now press ok,
all you need to do is now select your configuration from the dropdown and press run button. It will take some time. Your unsigned apk is now located in
Project\app\build\outputs\apk
I had the same problem: Eclipse couldn't find (g++) and (gcc) in PATH even they were accessible from command-line. I was also sure they are pointed by PATH correctly.
I have just deleted the (.metadata) folder from Eclipse's Workspace as a mean to reset it and this worked for me.
You can do it by MXBeans
public class Check {
public static void main(String[] args) {
MemoryMXBean memBean = ManagementFactory.getMemoryMXBean() ;
MemoryUsage heapMemoryUsage = memBean.getHeapMemoryUsage();
System.out.println(heapMemoryUsage.getMax()); // max memory allowed for jvm -Xmx flag (-1 if isn't specified)
System.out.println(heapMemoryUsage.getCommitted()); // given memory to JVM by OS ( may fail to reach getMax, if there isn't more memory)
System.out.println(heapMemoryUsage.getUsed()); // used now by your heap
System.out.println(heapMemoryUsage.getInit()); // -Xms flag
// |------------------ max ------------------------| allowed to be occupied by you from OS (less than xmX due to empty survival space)
// |------------------ committed -------| | now taken from OS
// |------------------ used --| | used by your heap
}
}
But remember it is equivalent to Runtime.getRuntime()
(took depicted schema from here)
memoryMxBean.getHeapMemoryUsage().getUsed() <=> runtime.totalMemory() - runtime.freeMemory()
memoryMxBean.getHeapMemoryUsage().getCommitted() <=> runtime.totalMemory()
memoryMxBean.getHeapMemoryUsage().getMax() <=> runtime.maxMemory()
from javaDoc
init - represents the initial amount of memory (in bytes) that the Java virtual machine requests from the operating system for memory management during startup. The Java virtual machine may request additional memory from the operating system and may also release memory to the system over time. The value of init may be undefined.
used - represents the amount of memory currently used (in bytes).
committed - represents the amount of memory (in bytes) that is guaranteed to be available for use by the Java virtual machine. The amount of committed memory may change over time (increase or decrease). The Java virtual machine may release memory to the system and committed could be less than init. committed will always be greater than or equal to used.
max - represents the maximum amount of memory (in bytes) that can be used for memory management. Its value may be undefined. The maximum amount of memory may change over time if defined. The amount of used and committed memory will always be less than or equal to max if max is defined. A memory allocation may fail if it attempts to increase the used memory such that used > committed even if used <= max would still be true (for example, when the system is low on virtual memory).
+----------------------------------------------+
+//////////////// | +
+//////////////// | +
+----------------------------------------------+
|--------|
init
|---------------|
used
|---------------------------|
committed
|----------------------------------------------|
max
As additional note, maxMemory is less than -Xmx because there is necessity at least in one empty survival space, which can't be used for heap allocation.
also it is worth to to take a look at here and especially here
Not necessary to use \restylefloat
and destroys other options, like caption placement. just use [H]
or [!h]
after \begin{table}
.
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
You can use setColumnWidth()
if you want to expand your cell more.
you can try this, but you must be sure the type of values for each Column
List<MyClass> result = myDataTable.AsEnumerable().Select(x=> new MyClass(){
Property1 = (string)x.Field<string>("ColumnName1"),
Property2 = (int)x.Field<int>("ColumnName2"),
Property3 = (bool)x.Field<bool>("ColumnName3"),
});
Not to be horribly pedantic, but if you are internationalising the code it might be more useful to have the facility to get the short date for a given culture, e.g.:-
using System.Globalization;
using System.Threading;
...
var currentCulture = Thread.CurrentThread.CurrentCulture;
try {
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-us");
string shortDateString = DateTime.Now.ToShortDateString();
// Do something with shortDateString...
} finally {
Thread.CurrentThread.CurrentCulture = currentCulture;
}
Though clearly the "m/dd/yyyy" approach is considerably neater!!
Another option is to create a file in the $_SERVER['DOCUMENT_ROOT']
directory with the definition of your absolute path.
For example, if your $_SERVER['DOCUMENT_ROOT']
directory is
C:\wamp\www\
create a file (i.e. my_paths.php
) containing this
<?php if(!defined('MY_ABS_PATH')) define('MY_ABS_PATH',$_SERVER['DOCUMENT_ROOT'].'MyProyect/')
Now you only need to include in every file inside your MyProyect folder this file (my_paths.php
), so you can user MY_ABS_PATH
as an absolute path for MyProject.
The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:
DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '
SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT name
FROM sysobjects
WHERE xtype = 'PK'
AND parent_obj = OBJECT_ID('Student')))
EXEC (@SQL)
For anyone else who runs into this, I had this in my hosts file:
127.0.0.1 localhost
127.0.0.1 customname
and I needed it to be this:
127.0.0.1 localhost
127.0.0.1 localhost customname
Christoph's answer is perfect. Sometimes however you may want to go more classes up than one. In this case you could try the @at-root
and #{}
css features which would enable two root classes to sit next to each other using &
.
This wouldn't work (due to the nothing before &
rule):
container {_x000D_
background:red;_x000D_
color:white;_x000D_
_x000D_
.desc& {_x000D_
background: blue;_x000D_
}_x000D_
_x000D_
.hello {_x000D_
padding-left:50px;_x000D_
}_x000D_
}
_x000D_
But this would (using @at-root plus #{&}
):
container {_x000D_
background:red;_x000D_
color:white;_x000D_
_x000D_
@at-root .desc#{&} {_x000D_
background: blue;_x000D_
}_x000D_
_x000D_
.hello {_x000D_
padding-left:50px;_x000D_
}_x000D_
}
_x000D_
<form onsubmit="alert('submit');return false;">
<input name="username">
<input name="password" type="password">
<button onclick="if(document.activeElement === this){alert('button 1');}else{default_submit.click();}return false;">button 1</button>
<button onclick="if(document.activeElement === this){alert('button 2');}else{default_submit.click();}return false;">button 2</button>
<input id="default_submit" type="submit">
</form>
if you press enter from text input, then the button will not focused, then we ignore this click and click the default submit instead, but if you click the button by mouse, it will be focused, then we apply this click
As far as I've been able to find out, there is no simple way to do it. The easiest way is to not actually convert the class file into an executable, but to wrap an executable launcher around the class file. That is, create an executable file (perhaps an OS-based, executable scripting file) which simply invokes the Java class through the command line.
If you want to actually have a program that does it, you should look into some of the automated installers out there.
Here is a way I've found:
[code]
import java.io.*;
import java.util.jar.*;
class OnlyExt implements FilenameFilter{
String ext;
public OnlyExt(String ext){
this.ext="." + ext;
}
@Override
public boolean accept(File dir,String name){
return name.endsWith(ext);
}
}
public class ExeCreator {
public static int buffer = 10240;
protected void create(File exefile, File[] listFiles) {
try {
byte b[] = new byte[buffer];
FileOutputStream fout = new FileOutputStream(exefile);
JarOutputStream out = new JarOutputStream(fout, new Manifest());
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i] == null || !listFiles[i].exists()|| listFiles[i].isDirectory())
System.out.println("Adding " + listFiles[i].getName());
JarEntry addFiles = new JarEntry(listFiles[i].getName());
addFiles.setTime(listFiles[i].lastModified());
out.putNextEntry(addFiles);
FileInputStream fin = new FileInputStream(listFiles[i]);
while (true) {
int len = fin.read(b, 0, b.length);
if (len <= 0)
break;
out.write(b, 0, len);
}
fin.close();
}
out.close();
fout.close();
System.out.println("Jar File is created successfully.");
} catch (Exception ex) {}
}
public static void main(String[]args){
ExeCreator exe=new ExeCreator();
FilenameFilter ff = new OnlyExt("class");
File folder = new File("./examples");
File[] files = folder.listFiles(ff);
File file=new File("examples.exe");
exe.create(file, files);
}
}
[/code]`
To get any sort of file path use this (taken from https://github.com/iPaulPro/aFileChooser)
package com.yourpackage;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.File;
import java.io.FileFilter;
import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.List;
/**
* @author Peli
* @author paulburke (ipaulpro)
* @version 2013-12-11
*/
public class FileUtils {
private FileUtils() {
} //private constructor to enforce Singleton pattern
/**
* TAG for log messages.
*/
static final String TAG = "FileUtils";
private static final boolean DEBUG = true; // Set to true to enable logging
public static final String MIME_TYPE_AUDIO = "audio/*";
public static final String MIME_TYPE_TEXT = "text/*";
public static final String MIME_TYPE_IMAGE = "image/*";
public static final String MIME_TYPE_VIDEO = "video/*";
public static final String MIME_TYPE_APP = "application/*";
public static final String HIDDEN_PREFIX = ".";
/**
* Gets the extension of a file name, like ".png" or ".jpg".
*
* @param uri
* @return Extension including the dot("."); "" if there is no extension;
* null if uri was null.
*/
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}
/**
* @return Whether the URI is a local one.
*/
public static boolean isLocal(String url) {
if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) {
return true;
}
return false;
}
/**
* @return True if Uri is a MediaStore Uri.
* @author paulburke
*/
public static boolean isMediaUri(Uri uri) {
return "media".equalsIgnoreCase(uri.getAuthority());
}
/**
* Convert File into Uri.
*
* @param file
* @return uri
*/
public static Uri getUri(File file) {
if (file != null) {
return Uri.fromFile(file);
}
return null;
}
/**
* Returns the path only (without file name).
*
* @param file
* @return
*/
public static File getPathWithoutFilename(File file) {
if (file != null) {
if (file.isDirectory()) {
// no file to be split off. Return everything
return file;
} else {
String filename = file.getName();
String filepath = file.getAbsolutePath();
// Construct path without file name.
String pathwithoutname = filepath.substring(0,
filepath.length() - filename.length());
if (pathwithoutname.endsWith("/")) {
pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);
}
return new File(pathwithoutname);
}
}
return null;
}
/**
* @return The MIME type for the given file.
*/
public static String getMimeType(File file) {
String extension = getExtension(file.getName());
if (extension.length() > 0)
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
return "application/octet-stream";
}
/**
* @return The MIME type for the give Uri.
*/
public static String getMimeType(Context context, Uri uri) {
File file = new File(getPath(context, uri));
return getMimeType(file);
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is {@link LocalStorageProvider}.
* @author paulburke
*/
public static boolean isLocalStorageDocument(Uri uri) {
return LocalStorageProvider.AUTHORITY.equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
* @author paulburke
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
* @author paulburke
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
* @author paulburke
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
* @author paulburke
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* Get a file path from a Uri. This will quickGet the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.<br>
* <br>
* Callers should check whether the path is local before assuming it
* represents a local file.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
* @see #isLocal(String)
* @see #getFile(Context, Uri)
*/
public static String getPath(final Context context, final Uri uri) {
if (DEBUG)
Log.d(TAG + " File -",
"Authority: " + uri.getAuthority() +
", Fragment: " + uri.getFragment() +
", Port: " + uri.getPort() +
", Query: " + uri.getQuery() +
", Scheme: " + uri.getScheme() +
", Host: " + uri.getHost() +
", Segments: " + uri.getPathSegments().toString()
);
// DocumentProvider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
// LocalStorageProvider
if (isLocalStorageDocument(uri)) {
// The path is the id
return DocumentsContract.getDocumentId(uri);
}
// ExternalStorageProvider
else if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
// if ("primary".equalsIgnoreCase(type)) {
// return Environment.getExternalStorageDirectory() + "/" + split[1];
// }
return Environment.getExternalStorageDirectory() + "/" + split[1];
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
try {
final String id = DocumentsContract.getDocumentId(uri);
Log.d(TAG, "getPath: id= " + id);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}catch (Exception e){
e.printStackTrace();
List<String> segments = uri.getPathSegments();
if(segments.size() > 1) {
String rawPath = segments.get(1);
if(!rawPath.startsWith("/")){
return rawPath.substring(rawPath.indexOf("/"));
}else {
return rawPath;
}
}
}
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Convert Uri into File, if possible.
*
* @return file A local file that the Uri was pointing to, or null if the
* Uri is unsupported or pointed to a remote resource.
* @author paulburke
* @see #getPath(Context, Uri)
*/
public static File getFile(Context context, Uri uri) {
if (uri != null) {
String path = getPath(context, uri);
if (path != null && isLocal(path)) {
return new File(path);
}
}
return null;
}
/**
* Get the file size in a human-readable string.
*
* @param size
* @return
* @author paulburke
*/
public static String getReadableFileSize(int size) {
final int BYTES_IN_KILOBYTES = 1024;
final DecimalFormat dec = new DecimalFormat("###.#");
final String KILOBYTES = " KB";
final String MEGABYTES = " MB";
final String GIGABYTES = " GB";
float fileSize = 0;
String suffix = KILOBYTES;
if (size > BYTES_IN_KILOBYTES) {
fileSize = size / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
suffix = GIGABYTES;
} else {
suffix = MEGABYTES;
}
}
}
return String.valueOf(dec.format(fileSize) + suffix);
}
/**
* Attempt to retrieve the thumbnail of given File from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param file
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, File file) {
return getThumbnail(context, getUri(file), getMimeType(file));
}
/**
* Attempt to retrieve the thumbnail of given Uri from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param uri
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, Uri uri) {
return getThumbnail(context, uri, getMimeType(context, uri));
}
/**
* Attempt to retrieve the thumbnail of given Uri from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param uri
* @param mimeType
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) {
if (DEBUG)
Log.d(TAG, "Attempting to quickGet thumbnail");
if (!isMediaUri(uri)) {
Log.e(TAG, "You can only retrieve thumbnails for images and videos.");
return null;
}
Bitmap bm = null;
if (uri != null) {
final ContentResolver resolver = context.getContentResolver();
Cursor cursor = null;
try {
cursor = resolver.query(uri, null, null, null, null);
if (cursor.moveToFirst()) {
final int id = cursor.getInt(0);
if (DEBUG)
Log.d(TAG, "Got thumb ID: " + id);
if (mimeType.contains("video")) {
bm = MediaStore.Video.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Video.Thumbnails.MINI_KIND,
null);
} else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) {
bm = MediaStore.Images.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Images.Thumbnails.MINI_KIND,
null);
}
}
} catch (Exception e) {
if (DEBUG)
Log.e(TAG, "getThumbnail", e);
} finally {
if (cursor != null)
cursor.close();
}
}
return bm;
}
/**
* File and folder comparator. TODO Expose sorting option method
*
* @author paulburke
*/
public static Comparator<File> sComparator = new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
// Sort alphabetically by lower case, which is much cleaner
return f1.getName().toLowerCase().compareTo(
f2.getName().toLowerCase());
}
};
/**
* File (not directories) filter.
*
* @author paulburke
*/
public static FileFilter sFileFilter = new FileFilter() {
@Override
public boolean accept(File file) {
final String fileName = file.getName();
// Return files only (not directories) and skip hidden files
return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX);
}
};
/**
* Folder (directories) filter.
*
* @author paulburke
*/
public static FileFilter sDirFilter = new FileFilter() {
@Override
public boolean accept(File file) {
final String fileName = file.getName();
// Return directories only and skip hidden directories
return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX);
}
};
/**
* Get the Intent for selecting content to be used in an Intent Chooser.
*
* @return The intent for opening a file with Intent.createChooser()
* @author paulburke
*/
public static Intent createGetContentIntent() {
// Implicitly allow the user to select a particular kind of data
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// The MIME data type filter
intent.setType("*/*");
// Only return URIs that can be opened with ContentResolver
intent.addCategory(Intent.CATEGORY_OPENABLE);
return intent;
}
}
Just want to add my take here, as the other answers do provide reasonable explanations, but not ones that fully satisfy me.
Optional parameters are syntactic sugar for compile-time injection of the default value at the call site. This doesn't have anything to do with interfaces/implementations, and it can be seen as purely a side-effect of methods with optional parameters. So, when you call the method,
public void TestMethod(bool value = false) { /*...*/ }
like SomeClass.TestMethod()
, it is actually SomeClass.TestMethod(false)
. If you call this method on an interface, from static type-checking, the method signature has the optional parameter. If you call this method on a deriving class's instance that doesn't have the optional parameter, from static type-checking, the method signature does not have the optional parameter, and must be called with full arguments.
Due to how optional parameters are implemented, this is the natural design result.
Here are some real-world examples of the types of relationships:
A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.
To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).
For example:
CREATE TABLE Gov(
GID number(6) PRIMARY KEY,
Name varchar2(25),
Address varchar2(30),
TermBegin date,
TermEnd date
);
CREATE TABLE State(
SID number(3) PRIMARY KEY,
StateName varchar2(15),
Population number(10),
SGID Number(4) REFERENCES Gov(GID),
CONSTRAINT GOV_SDID UNIQUE (SGID)
);
INSERT INTO gov(GID, Name, Address, TermBegin)
values(110, 'Bob', '123 Any St', '1-Jan-2009');
INSERT INTO STATE values(111, 'Virginia', 2000000, 110);
A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.
To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).
For example:
CREATE TABLE Vendor(
VendorNumber number(4) PRIMARY KEY,
Name varchar2(20),
Address varchar2(20),
City varchar2(15),
Street varchar2(2),
ZipCode varchar2(10),
Contact varchar2(16),
PhoneNumber varchar2(12),
Status varchar2(8),
StampDate date
);
CREATE TABLE Inventory(
Item varchar2(6) PRIMARY KEY,
Description varchar2(30),
CurrentQuantity number(4) NOT NULL,
VendorNumber number(2) REFERENCES Vendor(VendorNumber),
ReorderQuantity number(3) NOT NULL
);
A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.
To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.
CREATE TABLE Class(
ClassID varchar2(10) PRIMARY KEY,
Title varchar2(30),
Instructor varchar2(30),
Day varchar2(15),
Time varchar2(10)
);
CREATE TABLE Student(
StudentID varchar2(15) PRIMARY KEY,
Name varchar2(35),
Major varchar2(35),
ClassYear varchar2(10),
Status varchar2(10)
);
CREATE TABLE ClassStudentRelation(
StudentID varchar2(15) NOT NULL,
ClassID varchar2(14) NOT NULL,
FOREIGN KEY (StudentID) REFERENCES Student(StudentID),
FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
UNIQUE (StudentID, ClassID)
);
If the problem is not solved by above answer, check whether the Windows SDK version is 10.0.15063.0.
Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0
After this rebuild the solution.
I've seen that problem when I'm writing to a filesystem which doesn't (properly) handle times -- I think SMB shares or FAT or something.
What is your target filesystem?
Instead of switch statements, consider using tables of strings indexed by a small value.
const char * const ones[20] = {"zero", "one", "two", ..., "nineteen"};
const char * const tens[10] = {"", "ten", "twenty", ..., "ninety"};
Now break the problem into small pieces. Write a function that can output a single-digit number. Then write a function that can handle a two-digit number (which will probably use the previous function). Continue building up the functions as necessary.
Create a list of test cases with expected output, and write code to call your functions and check the output, so that, as you fix problems for the more complicated cases, you can be sure that the simpler cases continue to work.
You can delay your code using setTimeout
to execute after click
function changeLink(){
setTimeout(function() {
var link = document.getElementById("mylink");
link.setAttribute('href', "http://facebook.com");
document.getElementById("mylink").innerHTML = "facebook";
}, 100);
}
Direct link to awk version : http://www.shelldorado.com/scripts/cmds/urlencode
I used it for years and it works like a charm
:
##########################################################################
# Title : urlencode - encode URL data
# Author : Heiner Steven ([email protected])
# Date : 2000-03-15
# Requires : awk
# Categories : File Conversion, WWW, CGI
# SCCS-Id. : @(#) urlencode 1.4 06/10/29
##########################################################################
# Description
# Encode data according to
# RFC 1738: "Uniform Resource Locators (URL)" and
# RFC 1866: "Hypertext Markup Language - 2.0" (HTML)
#
# This encoding is used i.e. for the MIME type
# "application/x-www-form-urlencoded"
#
# Notes
# o The default behaviour is not to encode the line endings. This
# may not be what was intended, because the result will be
# multiple lines of output (which cannot be used in an URL or a
# HTTP "POST" request). If the desired output should be one
# line, use the "-l" option.
#
# o The "-l" option assumes, that the end-of-line is denoted by
# the character LF (ASCII 10). This is not true for Windows or
# Mac systems, where the end of a line is denoted by the two
# characters CR LF (ASCII 13 10).
# We use this for symmetry; data processed in the following way:
# cat | urlencode -l | urldecode -l
# should (and will) result in the original data
#
# o Large lines (or binary files) will break many AWK
# implementations. If you get the message
# awk: record `...' too long
# record number xxx
# consider using GNU AWK (gawk).
#
# o urlencode will always terminate it's output with an EOL
# character
#
# Thanks to Stefan Brozinski for pointing out a bug related to non-standard
# locales.
#
# See also
# urldecode
##########################################################################
PN=`basename "$0"` # Program name
VER='1.4'
: ${AWK=awk}
Usage () {
echo >&2 "$PN - encode URL data, $VER
usage: $PN [-l] [file ...]
-l: encode line endings (result will be one line of output)
The default is to encode each input line on its own."
exit 1
}
Msg () {
for MsgLine
do echo "$PN: $MsgLine" >&2
done
}
Fatal () { Msg "$@"; exit 1; }
set -- `getopt hl "$@" 2>/dev/null` || Usage
[ $# -lt 1 ] && Usage # "getopt" detected an error
EncodeEOL=no
while [ $# -gt 0 ]
do
case "$1" in
-l) EncodeEOL=yes;;
--) shift; break;;
-h) Usage;;
-*) Usage;;
*) break;; # First file name
esac
shift
done
LANG=C export LANG
$AWK '
BEGIN {
# We assume an awk implementation that is just plain dumb.
# We will convert an character to its ASCII value with the
# table ord[], and produce two-digit hexadecimal output
# without the printf("%02X") feature.
EOL = "%0A" # "end of line" string (encoded)
split ("1 2 3 4 5 6 7 8 9 A B C D E F", hextab, " ")
hextab [0] = 0
for ( i=1; i<=255; ++i ) ord [ sprintf ("%c", i) "" ] = i + 0
if ("'"$EncodeEOL"'" == "yes") EncodeEOL = 1; else EncodeEOL = 0
}
{
encoded = ""
for ( i=1; i<=length ($0); ++i ) {
c = substr ($0, i, 1)
if ( c ~ /[a-zA-Z0-9.-]/ ) {
encoded = encoded c # safe character
} else if ( c == " " ) {
encoded = encoded "+" # special handling
} else {
# unsafe character, encode it as a two-digit hex-number
lo = ord [c] % 16
hi = int (ord [c] / 16);
encoded = encoded "%" hextab [hi] hextab [lo]
}
}
if ( EncodeEOL ) {
printf ("%s", encoded EOL)
} else {
print encoded
}
}
END {
#if ( EncodeEOL ) print ""
}
' "$@"
Well, maven is not supposed to be good in doing fine granular tasks, it is not a scripting language like bash or ant, it is rather declarative - you say - i need a war, or an ear, and you get it. However if you need to customize how the war or ear should look like inside, you have a problem. It is just not procedural like ant, but declarative. This have some pros in the beginning, and could have a lot of cons at the end.
I guess the initial concept was to have fine plugins, that "just work" but the reality is different if you do non-standard stuff.
If you however put enough effort in your poms and few custom plugins, you'll get a much better build environment as with ant for example (depends on you project of course, but it gets more and more true for bigger projects).
First, you need to understand the difference between window
and document
. The window
object is a top level client side object. There is nothing above the window
object. JavaScript is an object orientated language. You start with an object and apply methods to its properties or the properties of its object groups. For example, the document
object is an object of the window
object. To change the document
's background color, you'd set the document
's bgcolor
property.
window.document.bgcolor = "red"
To answer your question, There is no difference in the end result between window
and document
scrollTop
. Both will give the same output.
In general use document
mainly to register events and use window
to do things like scroll
, scrollTop
, and resize
.
Here's what I use for integers:
Math.ceil(parseFloat(val)) === val
Short, nice :) Works all the time. This is what David Flanagan suggests if I'm not mistaken.
By default, variables created within a script are only available to the current shell; child processes (sub-shells) will not have access to values that have been set or modified. Allowing child processes to see the values, requires use of the export command.
Do .libPaths()
, close every R runing, check in the first directory, remove the zoo
package restart R and install
zoo
again. Of course you need to have sufficient rights.
For everyone that has Android problems in the string.xml, use \'\' instead of single quote.
I was running into this error on my mac and found that I needed to upgrade from mysql 32bit to mysql 64 bit to get this error to go away. I was running OSX 10.6 on an intel macbook pro with ruby 1.9.2 and rails3.0.0
I also needed to install xcode in order to get unix utilities like "make" that are required to compile the gem.
once this was done I was able to run gem install mysql and gem install mysql2 without error.
In your view, you have to cast it back to the original type. Without the cast, it's just an object.
<td>@((ViewBag.data as ICollection<Person>).First().FirstName)</td>
ViewBag is a C# 4 dynamic type. Entities returned from it are also dynamic unless cast. However, extension methods like .First() and all the other Linq ones do not work with dynamics.
Edit - to address the comment:
If you want to display the whole list, it's as simple as this:
<ul>
@foreach (var person in ViewBag.data)
{
<li>@person.FirstName</li>
}
</ul>
Extension methods like .First() won't work, but this will.
Just to point out that there is an approach using functions from the tidyverse
, which I find more readable than gsub
:
a %>% stringr::str_remove(pattern = ".*_")
If a website's directory does NOT have an "index...." file, AND .htaccess has NOT been used to block access to the directory itself, then Apache will create an "index of" page for that directory. You can save that page, and its icons, using "Save page as..." along with the "Web page, complete" option (Firefox example). If you own the website, temporarily rename any "index...." file, and reference the directory locally. Then restore your "index...." file.
To supplement Thomas's answer, the Application
class also has the DispatcherUnhandledException
event that you can handle.
Sort and Lock Table is the only solution I have seen which does work on other browsers than IE. (although this "locked column css" might do the trick as well). Required code block below.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script type="text/javascript" src="/js/lib/dummy.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
/* Scrollable Content Height */
.scrollContent {
height:100px;
overflow-x:hidden;
overflow-y:auto;
}
.scrollContent tr {
height: auto;
white-space: nowrap;
}
/* Prevent Mozilla scrollbar from hiding right-most cell content */
.scrollContent tr td:last-child {
padding-right: 20px;
}
/* Fixed Header Height */
.fixedHeader tr {
position: relative;
height: auto;
}
/* Put border around entire table */
div.TableContainer {
border: 1px solid #7DA87D;
}
/* Table Header formatting */
.headerFormat {
background-color: white;
color: #FFFFFF;
margin: 3px;
padding: 1px;
white-space: nowrap;
font-family: Helvetica;
font-size: 16px;
text-decoration: none;
font-weight: bold;
}
.headerFormat tr td {
border: 1px solid #000000;
background-color: #7DA87D;
}
/* Table Body (Scrollable Content) formatting */
.bodyFormat tr td {
color: #000000;
margin: 3px;
padding: 1px;
border: 0px none;
font-family: Helvetica;
font-size: 12px;
}
/* Use to set different color for alternating rows */
.alternateRow {
background-color: #E0F1E0;
}
/* Styles used for SORTING */
.point {
cursor:pointer;
}
td.sortedColumn {
background-color: #E0F1E0;
}
tr.alternateRow td.sortedColumn {
background-color: #c5e5c5;
}
.total {
background-color: #FED362;
color: #000000;
white-space: nowrap;
font-size: 12px;
text-decoration: none;
}
</style>
<title></title>
<script type='text/javascript'>//<![CDATA[
/* This script and many more are available free online at
The JavaScript Source :: http://www.javascriptsource.com
Created by: Stan Slaughter :: http://www.stansight.com/ */
/* ======================================================
Generic Table Sort
Basic Concept: A table can be sorted by clicking on the title of any
column in the table, toggling between ascending and descending sorts.
Assumptions:
* The first row of the table contains column titles that are "clicked"
to sort the table
* The images 'desc.gif','asc.gif','none.gif','sorting.gif' exist
* The img tag is in each column of the the title row to represent the
sort graphic.
* The CSS classes 'alternateRow' and 'sortedColumn' exist so we can
have alternating colors for each row and a highlight the sorted
column. Something like the <style> definition below, but with the
background colors set to whatever you want.
<style>
tr.alternateRow {
background-color: #E0F1E0;
}
td.sortedColumn {
background-color: #E0F1E0;
}
tr.alternateRow td.sortedColumn {
background-color: #c5e5c5;
}
</style>
====================================================== */
function sortTable(td_element,ignoreLastLines) {
// If the optional ignoreLastLines parameter (number of lines *not* to sort at end of table)
// was not passed then make it 0
ignoreLastLines = (typeof(ignoreLastLines)=='undefined') ? 0 : ignoreLastLines;
var sortImages =['data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUz4IVcZDleixQIQjA1pFFZx2FVRklZvOWUl8LsVgBeFLyE8TLgDZYESISwvAAA1QvjAQwBADs=','data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUw4CVeDzOeFwCgIhFBBDtY1sAmtIIWFV0VJweNRhkZeoeDpWIQNSYBgSAgWYgQLGwIADs=','data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7','http://web.archive.org/web/20150906203819im_/http://www.javascriptsource.com/miscellaneous/sorting.gif'];
// Get the image used in the first row of the current column
var sortColImage = td_element.getElementsByTagName('img')[0];
// If current image is 'asc.gif' or 'none.gif' (elements 1 and 2 of sortImages array) then this will
// be a descending sort else it will be ascending - get new sort image icon and set sort order flag
var sortAscending = false;
var newSortColImage = "";
if (sortColImage.getAttribute('src').indexOf(sortImages[1])>-1 ||
sortColImage.getAttribute('src').indexOf(sortImages[2])>-1) {
newSortColImage = sortImages[0];
sortAscending = false;
} else {
newSortColImage = sortImages[1];
sortAscending = true;
}
// Assign "SORTING" image icon (element 3 of sortImages array)) to current column title
// (will replace with newSortColImage when sort completes)
sortColImage.setAttribute('src',sortImages[3]);
// Find which column was clicked by getting it's column position
var indexCol = td_element.cellIndex;
// Get the table element from the td element that was passed as a parameter to this function
var table_element = td_element.parentNode;
while (table_element.nodeName != "TABLE") {
table_element = table_element.parentNode;
}
// Get all "tr" elements from the table and assign then to the Array "tr_elements"
var tr_elements = table_element.getElementsByTagName('tr');
// Get all the images used in the first row then set them to 'none.gif'
// (element 2 or sortImages array) except for the current column (all ready been changed)
var allImg = tr_elements[0].getElementsByTagName('img');
for(var i=0;i<allImg.length;i++){
if(allImg[i]!=sortColImage){allImg[i].setAttribute('src',sortImages[2])}
}
// Some explantion of the basic concept of the following code before we
// actually start. Essentially we are going to copy the current columns information
// into an array to be sorted. We'll sort the column array then go back and use the information
// we saved about the original row positions to re-order the entire table.
// We are never really sorting more than a columns worth of data, which should keep the sorting fast.
// Create a new array for holding row information
var clonedRows = new Array()
// Create a new array to store just the selected column values, not the whole row
var originalCol = new Array();
// Now loop through all the data row elements
// NOTE: Starting at row 1 because row 0 contains the column titles
for (var i=1; i<tr_elements.length - ignoreLastLines; i++) {
// "Clone" the tr element i.e. save a copy all of its attributes and values
clonedRows[i]=tr_elements[i].cloneNode(true);
// Text value of the selected column on this row
var valueCol = getTextValue(tr_elements[i].cells[indexCol]);
// Format text value for sorting depending on its type, ie Date, Currency, number, etc..
valueCol = FormatForType(valueCol);
// Assign the column value AND the row number it was originally on in the table
originalCol[i]=[valueCol,tr_elements[i].rowIndex];
}
// Get rid of element "0" from this array. A value was never assigned to it because the first row
// in the table just contained the column titles, which we did not bother to assign.
originalCol.shift();
// Sort the column array returning the value of a sort into a new array
sortCol = originalCol.sort(sortCompare);
// If it was supposed to be an Ascending sort then reverse the order
if (sortAscending) { sortCol.reverse(); }
// Now take the values from the sorted column array and use that information to re-arrange
// the order of the tr_elements in the table
for (var i=1; i < tr_elements.length - ignoreLastLines; i++) {
var old_row = sortCol[i-1][1];
var new_row = i;
tr_elements[i].parentNode.replaceChild(clonedRows[old_row],tr_elements[new_row]);
}
// Format the table, making the rows alternating colors and highlight the sorted column
makePretty(table_element,indexCol,ignoreLastLines);
// Assign correct sort image icon to current column title
sortColImage.setAttribute('src',newSortColImage);
}
// Function used by the sort routine to compare the current value in the array with the next one
function sortCompare (currValue, nextValue) {
// Since the elements of this array are actually arrays themselves, just sort
// on the first element which contiains the value, not the second which contains
// the original row position
if ( currValue[0] == nextValue[0] ) return 0;
if ( currValue[0] < nextValue[0] ) return -1;
if ( currValue[0] > nextValue[0] ) return 1;
}
//-----------------------------------------------------------------------------
// Functions to get and compare values during a sort.
//-----------------------------------------------------------------------------
// This code is necessary for browsers that don't reflect the DOM constants
// (like IE).
if (document.ELEMENT_NODE == null) {
document.ELEMENT_NODE = 1;
document.TEXT_NODE = 3;
}
function getTextValue(el) {
var i;
var s;
// Find and concatenate the values of all text nodes contained within the
// element.
s = "";
for (i = 0; i < el.childNodes.length; i++)
if (el.childNodes[i].nodeType == document.TEXT_NODE)
s += el.childNodes[i].nodeValue;
else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&
el.childNodes[i].tagName == "BR")
s += " ";
else
// Use recursion to get text within sub-elements.
s += getTextValue(el.childNodes[i]);
return normalizeString(s);
}
// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");
function normalizeString(s) {
s = s.replace(whtSpMult, " "); // Collapse any multiple whites space.
s = s.replace(whtSpEnds, ""); // Remove leading or trailing white space.
return s;
}
// Function used to modify values to make then sortable depending on the type of information
function FormatForType(itm) {
var sortValue = itm.toLowerCase();
// If the item matches a date pattern (MM/DD/YYYY or MM/DD/YY or M/DD/YYYY)
if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/) ||
itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/) ||
itm.match(/^\d[\/-]\d\d[\/-]\d\d\d\d$/) ) {
// Convert date to YYYYMMDD format for sort comparison purposes
// y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
var yr = -1;
if (itm.length == 10) {
sortValue = itm.substr(6,4)+itm.substr(0,2)+itm.substr(3,2);
} else if (itm.length == 9) {
sortValue = itm.substr(5,4)+"0" + itm.substr(0,1)+itm.substr(2,2);
} else {
yr = itm.substr(6,2);
if (parseInt(yr) < 50) {
yr = '20'+yr;
} else {
yr = '19'+yr;
}
sortValue = yr+itm.substr(3,2)+itm.substr(0,2);
}
}
// If the item matches a Percent patten (contains a percent sign)
if (itm.match(/%/)) {
// Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
sortValue = itm.replace(/[^0-9.-]/g,'');
sortValue = parseFloat(sortValue);
}
// If item starts with a "(" and ends with a ")" then remove them and put a negative sign in front
if (itm.substr(0,1) == "(" & itm.substr(itm.length - 1,1) == ")") {
itm = "-" + itm.substr(1,itm.length - 2);
}
// If the item matches a currency pattern (starts with a dollar or negative dollar sign)
if (itm.match(/^[£$]|(^-)/)) {
// Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
sortValue = itm.replace(/[^0-9.-]/g,'');
if (isNaN(sortValue)) {
sortValue = 0;
} else {
sortValue = parseFloat(sortValue);
}
}
// If the item matches a numeric pattern
if (itm.match(/(\d*,\d*$)|(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/)) {
// Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
sortValue = itm.replace(/[^0-9.-]/g,'');
// sortValue = sortValue.replace(/,/g,'');
if (isNaN(sortValue)) {
sortValue = 0;
} else {
sortValue = parseFloat(sortValue);
}
}
return sortValue;
}
//-----------------------------------------------------------------------------
// Functions to update the table appearance after a sort.
//-----------------------------------------------------------------------------
// Style class names.
var rowClsNm = "alternateRow";
var colClsNm = "sortedColumn";
// Regular expressions for setting class names.
var rowTest = new RegExp(rowClsNm, "gi");
var colTest = new RegExp(colClsNm, "gi");
function makePretty(tblEl, col, ignoreLastLines) {
var i, j;
var rowEl, cellEl;
// Set style classes on each row to alternate their appearance.
for (i = 1; i < tblEl.rows.length - ignoreLastLines; i++) {
rowEl = tblEl.rows[i];
rowEl.className = rowEl.className.replace(rowTest, "");
if (i % 2 != 0)
rowEl.className += " " + rowClsNm;
rowEl.className = normalizeString(rowEl.className);
// Set style classes on each column (other than the name column) to
// highlight the one that was sorted.
for (j = 0; j < tblEl.rows[i].cells.length; j++) {
cellEl = rowEl.cells[j];
cellEl.className = cellEl.className.replace(colTest, "");
if (j == col)
cellEl.className += " " + colClsNm;
cellEl.className = normalizeString(cellEl.className);
}
}
}
// END Generic Table sort.
// =================================================
// Function to scroll to top before sorting to fix an IE bug
// Which repositions the header off the top of the screen
// if you try to sort while scrolled to bottom.
function GoTop() {
document.getElementById('TableContainer').scrollTop = 0;
}
//]]>
</script>
</head>
<body>
<table cellpadding="0" cellspacing="0" border="0">
<tr><td>
<div id="TableContainer" class="TableContainer" style="height:230px;">
<table class="scrollTable">
<thead class="fixedHeader headerFormat">
<tr>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort"><b>NAME</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Amt</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Lvl</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Rank</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Position</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Date</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
</tr>
</thead>
<tbody class="scrollContent bodyFormat" style="height:200px;">
<tr class="alternateRow">
<td>Maha</td>
<td align="right">$19,923.19</td>
<td align="right">100</td>
<td align="right">100</td>
<td>Owner</td>
<td align="right">01/02/2001</td>
</tr>
<tr>
<td>Thrawl</td>
<td align="right">$9,550</td>
<td align="right">159</td>
<td align="right">100%</td>
<td>Co-Owner</td>
<td align="right">11/07/2003</td>
</tr>
<tr class="alternateRow">
<td>Marhanen</td>
<td align="right">$223.04</td>
<td align="right">83</td>
<td align="right">99%</td>
<td>Banker</td>
<td align="right">06/27/2006</td>
</tr>
<tr>
<td>Peter</td>
<td align="right">$121</td>
<td align="right">567</td>
<td align="right">23423%</td>
<td>FishHead</td>
<td align="right">06/06/2006</td>
</tr>
<tr class="alternateRow">
<td>Jones</td>
<td align="right">$15</td>
<td align="right">11</td>
<td align="right">15%</td>
<td>Bubba</td>
<td align="right">10/27/2005</td>
</tr>
<tr>
<td>Supa-De-Dupa</td>
<td align="right">$145</td>
<td align="right">91</td>
<td align="right">32%</td>
<td>momma</td>
<td align="right">12/15/1996</td>
</tr>
<tr class="alternateRow">
<td>ClickClock</td>
<td align="right">$1,213</td>
<td align="right">23</td>
<td align="right">1%</td>
<td>Dada</td>
<td align="right">1/30/1998</td>
</tr>
<tr>
<td>Mrs. Robinson</td>
<td align="right">$99</td>
<td align="right">99</td>
<td align="right">99%</td>
<td>Wife</td>
<td align="right">07/04/1963</td>
</tr>
<tr class="alternateRow">
<td>Maha</td>
<td align="right">$19,923.19</td>
<td align="right">100</td>
<td align="right">100%</td>
<td>Owner</td>
<td align="right">01/02/2001</td>
</tr>
<tr>
<td>Thrawl</td>
<td align="right">$9,550</td>
<td align="right">159</td>
<td align="right">100%</td>
<td>Co-Owner</td>
<td align="right">11/07/2003</td>
</tr>
<tr class="alternateRow">
<td>Marhanen</td>
<td align="right">$223.04</td>
<td align="right">83</td>
<td align="right">59%</td>
<td>Banker</td>
<td align="right">06/27/2006</td>
</tr>
<tr>
<td>Peter</td>
<td align="right">$121</td>
<td align="right">567</td>
<td align="right">534.23%</td>
<td>FishHead</td>
<td align="right">06/06/2006</td>
</tr>
<tr class="alternateRow">
<td>Jones</td>
<td align="right">$15</td>
<td align="right">11</td>
<td align="right">15%</td>
<td>Bubba</td>
<td align="right">10/27/2005</td>
</tr>
<tr>
<td>Supa-De-Dupa</td>
<td align="right">$145</td>
<td align="right">91</td>
<td align="right">42%</td>
<td>momma</td>
<td align="right">12/15/1996</td>
</tr>
<tr class="alternateRow">
<td>ClickClock</td>
<td align="right">$1,213</td>
<td align="right">23</td>
<td align="right">2%</td>
<td>Dada</td>
<td align="right">1/30/1998</td>
</tr>
<tr>
<td>Mrs. Robinson</td>
<td align="right">$99</td>
<td align="right">99</td>
<td align="right">(-10.42%)</td>
<td>Wife</td>
<td align="right">07/04/1963</td>
</tr>
<tr class="alternateRow">
<td>Maha</td>
<td align="right">-$19,923.19</td>
<td align="right">100</td>
<td align="right">(-10.01%)</td>
<td>Owner</td>
<td align="right">01/02/2001</td>
</tr>
<tr>
<td>Thrawl</td>
<td align="right">$9,550</td>
<td align="right">159</td>
<td align="right">-10.20%</td>
<td>Co-Owner</td>
<td align="right">11/07/2003</td>
</tr>
<tr class="total">
<td><strong>TOTAL</strong>:</td>
<td align="right"><strong>999999</strong></td>
<td align="right"><strong>9999999</strong></td>
<td align="right"><strong>99</strong></td>
<td > </td>
<td align="right"> </td>
</tr>
</tbody>
</table>
</div>
</td></tr>
</table>
</body>
</html>
"foobar".gsub(/(o+)/){|s|s+'ball'}
#=> "fooballbar"
Some excellent answers but these answers did not solve my issue.
As soon as a folder permission issue arises: "Permission Denied" the code fails. This is what I used to get around the "Permission Denied" issue:
private int counter = 0;
private string[] MyDirectories = Directory.GetDirectories("C:\\");
private void ScanButton_Click(object sender, EventArgs e)
{
Thread MonitorSpeech = new Thread(() => ScanFiles());
MonitorSpeech.Start();
}
private void ScanFiles()
{
string CurrentDirectory = string.Empty;
while (counter < MyDirectories.Length)
{
try
{
GetDirectories();
CurrentDirectory = MyDirectories[counter++];
}
catch
{
if (!this.IsDisposed)
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + CurrentDirectory); });
}
}
}
}
private void GetDirectories()
{
foreach (string directory in MyDirectories)
{
GetFiles(directory);
}
}
private void GetFiles(string directory)
{
try
{
foreach (string file in Directory.GetFiles(directory, "*"))
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(file); });
}
}
catch
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + directory); });
}
}
Hope this helps others.
The solutions posted here did not work well for me, so I did a mixture of the ones of this question and the following question: Is it possible to create multi-level ordered list in HTML?
/* Numbered lists like 1, 1.1, 2.2.1... */
ol li {display:block;} /* hide original list counter */
ol > li:first-child {counter-reset: item;} /* reset counter */
ol > li {counter-increment: item; position: relative;} /* increment counter */
ol > li:before {content:counters(item, ".") ". "; position: absolute; margin-right: 100%; right: 10px;} /* print counter */
Result:
Note: the screenshot, if you wish to see the source code or whatever is from this post: http://estiloasertivo.blogspot.com.es/2014/08/introduccion-running-lean-y-lean.html
This command works for me. It does its work recursively
find . -name "node_modules" -type d -prune -exec rm -rf '{}' +
. - current folder
"node_modules" - folder name
check up blur()
:
$('#textarea').blur()
source: http://api.jquery.com/blur/
Put the h1
and h2
in a container with an id of container
then:
#container {
display: flex;
justify-content: space-beteen;
}
Using the highlighted/checked answer above worked for me... here's a little insight. I cheated a little on getting the URL, but basically I'm defining the URL in the Javascript, and then setting it via the jquery answer from above:
<select id="select" onChange="window.location.href=this.value">
<option value="">Select a task </option>
<option value="http://127.0.0.1:5000/choose_form/1">Task 1</option>
<option value="http://127.0.0.1:5000/choose_form/2">Task 2</option>
<option value="http://127.0.0.1:5000/choose_form/3">Task 3</option>
<option value="http://127.0.0.1:5000/choose_form/4">Task 4</option>
<option value="http://127.0.0.1:5000/choose_form/5">Task 5</option>
<option value="http://127.0.0.1:5000/choose_form/6">Task 6</option>
<option value="http://127.0.0.1:5000/choose_form/7">Task 7</option>
<option value="http://127.0.0.1:5000/choose_form/8">Task 8</option>
</select>
<script>
var pathArray = window.location.pathname.split( '/' );
var selectedItem = "http://127.0.0.1:5000/" + pathArray[1] + "/" + pathArray[2];
var trimmedItem = selectedItem.trim();
$("#select").val(trimmedItem);
</script>
The old #top
can do the trick
document.location.href = "#top";
Works fine in FF, IE and Chrome
Override the onBackPressed method and do nothing if you meant to handle the back button on the device.
@Override
public void onBackPressed() {
if (shouldAllowBack()) {
super.onBackPressed();
} else {
doSomething();
}
}
For MinGW this worked for me:
Properties
C/C++ General
- Paths and Symbols
- Includes
- GNU C++
- Include directories
Add...
Variables...
MINGW_HOME
and click OK
Apply
and OK
You should now see several MinGW paths in Includes in your project explorer.
The errors may not disappear instantly, you may need to refresh/build your project.
If you are using Cygwin, there could be an equivalent variable present.
Manually changing XML and/or settings is very dangerous in eclipse unless you know exactly what you're doing. In the other case you might end up finding your complete project is screwed. Taking a backup is very recommended!
How to do it just using Eclipse?
That did it for me. And Eclipse is configured correctly. Hope it'll work for you too.
In my case (Mac OS X), the problem was the file's break type. Try this:
1.- Open the .pem file with TextWrangler
2.- At Bottom of app, verify if the Break Type is "Windows(CRLF)".
As mainframer said, you can use grep, but i would use exit status for testing, try this:
#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"
echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found
if [ $? = 1 ]
then
echo "$anotherstring was not found"
fi
it should be enough to mark your aspect method like this:
@After("@annotation(com.marcot.CommitTransaction)")
public void after() {
have a look at this for a step by step guide on this.
To cast a double to an int and have it be rounded to the nearest integer (i.e. unlike the typical (int)(1.8)
and (int)(1.2)
, which will both "round down" towards 0 and return 1
), simply add 0.5 to the double
that you will typecast to an int
.
For example, if we have
double a = 1.2;
double b = 1.8;
Then the following typecasting expressions for x and y and will return the rounded-down values (x = 1
and y = 1
):
int x = (int)(a); // This equals (int)(1.2) --> 1
int y = (int)(b); // This equals (int)(1.8) --> 1
But by adding 0.5 to each, we will obtain the rounded-to-closest-integer result that we may desire in some cases (x = 1
and y = 2
):
int x = (int)(a + 0.5); // This equals (int)(1.8) --> 1
int y = (int)(b + 0.5); // This equals (int)(2.3) --> 2
As a small note, this method also allows you to control the threshold at which the double
is rounded up or down upon (int)
typecasting.
(int)(a + 0.8);
to typecast. This will only round up to (int)a + 1
whenever the decimal values are greater than or equal to 0.2. That is, by adding 0.8 to the double
immediately before typecasting, 10.15 and 10.03 will be rounded down to 10 upon (int)
typecasting, but 10.23 and 10.7 will be rounded up to 11.
I copied model code from w3school bootstrap model and added following css. This code provides beautiful animation. You can try it.
.modal.fade .modal-dialog {
-webkit-transform: scale(0.1);
-moz-transform: scale(0.1);
-ms-transform: scale(0.1);
transform: scale(0.1);
top: 300px;
opacity: 0;
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
transition: all 0.3s;
}
.modal.fade.in .modal-dialog {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
transform: scale(1);
-webkit-transform: translate3d(0, -300px, 0);
transform: translate3d(0, -300px, 0);
opacity: 1;
}
var str = "This-is-a-news-item-";
while (str.contains("-")) {
str = str.replace("-", ' ');
}
alert(str);
I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.
Try this one:
onsubmit="return f(this.'yourfieldname'.value);"
I hope this will help you.
One sub and two functions. The sub builds your path and use the functions to check if the path exists and create if not. If the full path exists already, it will just pass on by. This will work on PC, but you will have to check what needs to be modified to work on Mac as well.
'requires reference to Microsoft Scripting Runtime
Sub MakeFolder()
Dim strComp As String, strPart As String, strPath As String
strComp = Range("A1") ' assumes company name in A1
strPart = CleanName(Range("C1")) ' assumes part in C1
strPath = "C:\Images\"
If Not FolderExists(strPath & strComp) Then
'company doesn't exist, so create full path
FolderCreate strPath & strComp & "\" & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strComp & "\" & strPart) Then
FolderCreate strPath & strComp & "\" & strPart
End If
End If
End Sub
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim fso As New FileSystemObject
If Functions.FolderExists(path) Then
Exit Function
Else
On Error GoTo DeadInTheWater
fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
Exit Function
End If
DeadInTheWater:
MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
FolderCreate = False
Exit Function
End Function
Function FolderExists(ByVal path As String) As Boolean
FolderExists = False
Dim fso As New FileSystemObject
If fso.FolderExists(path) Then FolderExists = True
End Function
Function CleanName(strName as String) as String
'will clean part # name so it can be made into valid folder name
'may need to add more lines to get rid of other characters
CleanName = Replace(strName, "/","")
CleanName = Replace(CleanName, "*","")
etc...
End Function
If you want to get the real path of java web application such as Spring (Servlet), you can get it from Servlet Context object that comes with your HttpServletRequest.
@GetMapping("/")
public String index(ModelMap m, HttpServletRequest request) {
String realPath = request.getServletContext().getRealPath("/");
System.out.println(realPath);
return "index";
}
fill_parent
will make the width or height of the element to be as
large as the parent element, in other words, the container.
wrap_content
will make the width or height be as large as needed to
contain the elements within it.
I prefer to avoid using Ajax.BeginForm
helper and do an Ajax call with JQuery. In my experience it is easier to maintain code written like this. So below are the details:
Models
public class ManagePeopleModel
{
public List<PersonModel> People { get; set; }
... any other properties
}
public class PersonModel
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
... any other properties
}
Parent View
This view contains the following things:
@model ManagePeopleModel
<h1>Manage People</h1>
@using(var table = Html.Bootstrap().Begin(new Table()))
{
foreach(var person in Model.People)
{
<tr>
<td>@person.Id</td>
<td>@Person.Name</td>
<td>@person.Age</td>
<td>@html.Bootstrap().Button().Text("Edit Person").Data(new { @id = person.Id }).Class("btn-trigger-modal")</td>
</tr>
}
}
@using (var m = Html.Bootstrap().Begin(new Modal().Id("modal-person")))
{
}
@section Scripts
{
<script type="text/javascript">
// Handle "Edit Person" button click.
// This will make an ajax call, get information for person,
// put it all in the modal and display it
$(document).on('click', '.btn-trigger-modal', function(){
var personId = $(this).data('id');
$.ajax({
url: '/[WhateverControllerName]/GetPersonInfo',
type: 'GET',
data: { id: personId },
success: function(data){
var m = $('#modal-person');
m.find('.modal-content').html(data);
m.modal('show');
}
});
});
// Handle submitting of new information for Person.
// This will attempt to save new info
// If save was successful, it will close the Modal and reload page to see updated info
// Otherwise it will only reload contents of the Modal
$(document).on('click', '#btn-person-submit', function() {
var self = $(this);
$.ajax({
url: '/[WhateverControllerName]/UpdatePersonInfo',
type: 'POST',
data: self.closest('form').serialize(),
success: function(data) {
if(data.success == true) {
$('#modal-person').modal('hide');
location.reload(false)
} else {
$('#modal-person').html(data);
}
}
});
});
</script>
}
Partial View
This view contains a modal that will be populated with information about person.
@model PersonModel
@{
// get modal helper
var modal = Html.Bootstrap().Misc().GetBuilderFor(new Modal());
}
@modal.Header("Edit Person")
@using (var f = Html.Bootstrap.Begin(new Form()))
{
using (modal.BeginBody())
{
@Html.HiddenFor(x => x.Id)
@f.ControlGroup().TextBoxFor(x => x.Name)
@f.ControlGroup().TextBoxFor(x => x.Age)
}
using (modal.BeginFooter())
{
// if needed, add here @Html.Bootstrap().ValidationSummary()
@:@Html.Bootstrap().Button().Text("Save").Id("btn-person-submit")
@Html.Bootstrap().Button().Text("Close").Data(new { dismiss = "modal" })
}
}
Controller Actions
public ActionResult GetPersonInfo(int id)
{
var model = db.GetPerson(id); // get your person however you need
return PartialView("[Partial View Name]", model)
}
public ActionResult UpdatePersonInfo(PersonModel model)
{
if(ModelState.IsValid)
{
db.UpdatePerson(model); // update person however you need
return Json(new { success = true });
}
// else
return PartialView("[Partial View Name]", model);
}
This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.
Here is my code in the view
@Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));
Now you can use this in the JavaScript file as:
var url = $("#RedirectTo").val();
location.href = url;
It worked like a charm fro me. I hope it helps you too.
A simple way to find actionbar height is from Activity onPrepareOptionMenu
method.
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
....
int actionBarHeight = getActionBar().getHeight());
.....
}
"How do I do that? I explored PHPMyAdmin, and I can't find a "change engine" functionality."
In direct response to this part of your question, you can issue an ALTER TABLE tbl engine=InnoDB;
and it'll recreate the table in the proper engine.
I had through the same situation. I solved using two Promise.All().
I think was really good solution, so I published it on npm: https://www.npmjs.com/package/promise-foreach
I think your code will be something like this
var promiseForeach = require('promise-foreach')
var jsonItems = [];
promiseForeach.each(jsonItems,
[function (jsonItems){
return new Promise(function(resolve, reject){
if(jsonItems.type === 'file'){
jsonItems.getFile().then(function(file){ //or promise.all?
resolve(file.getSize())
})
}
})
}],
function (result, current) {
return {
type: current.type,
size: jsonItems.result[0]
}
},
function (err, newList) {
if (err) {
console.error(err)
return;
}
console.log('new jsonItems : ', newList)
})
Sure you can with reflection. Here is the code to grab the properties off of a given type.
var info = typeof(SomeType).GetProperties();
If you can give more info on what you're comparing about the properties we can get together a basic diffing algorithmn. This code for intstance will diff on names
public bool AreDifferent(Type t1, Type t2) {
var list1 = t1.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
var list2 = t2.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
return list1.SequenceEqual(list2);
}
The following is an example of how you might write and read a pickle file. Note that if you keep appending pickle data to the file, you will need to continue reading from the file until you find what you want or an exception is generated by reaching the end of the file. That is what the last function does.
import os
import pickle
PICKLE_FILE = 'pickle.dat'
def main():
# append data to the pickle file
add_to_pickle(PICKLE_FILE, 123)
add_to_pickle(PICKLE_FILE, 'Hello')
add_to_pickle(PICKLE_FILE, None)
add_to_pickle(PICKLE_FILE, b'World')
add_to_pickle(PICKLE_FILE, 456.789)
# load & show all stored objects
for item in read_from_pickle(PICKLE_FILE):
print(repr(item))
os.remove(PICKLE_FILE)
def add_to_pickle(path, item):
with open(path, 'ab') as file:
pickle.dump(item, file, pickle.HIGHEST_PROTOCOL)
def read_from_pickle(path):
with open(path, 'rb') as file:
try:
while True:
yield pickle.load(file)
except EOFError:
pass
if __name__ == '__main__':
main()
DECLARE @theDate DATETIME
SET @theDate = '2010-01-01'
Then change your query to use this logic:
AND
(
tblWO.OrderDate > DATEADD(MILLISECOND, -1, @theDate)
AND tblWO.OrderDate < DATEADD(DAY, 1, @theDate)
)
CREATE PROCEDURE [dbo].[sp_Myforeach_Date]
-- Add the parameters for the stored procedure here
@SatrtDate as DateTime,
@EndDate as dateTime,
@DatePart as varchar(2),
@OutPutFormat as int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
Declare @DateList Table
(Date varchar(50))
WHILE @SatrtDate<= @EndDate
BEGIN
INSERT @DateList (Date) values(Convert(varchar,@SatrtDate,@OutPutFormat))
IF Upper(@DatePart)='DD'
SET @SatrtDate= DateAdd(dd,1,@SatrtDate)
IF Upper(@DatePart)='MM'
SET @SatrtDate= DateAdd(mm,1,@SatrtDate)
IF Upper(@DatePart)='YY'
SET @SatrtDate= DateAdd(yy,1,@SatrtDate)
END
SELECT * FROM @DateList
END
Just put this Code and call the SP in This way
exec sp_Myforeach_Date @SatrtDate='03 Jan 2010',@EndDate='03 Mar 2010',@DatePart='dd',@OutPutFormat=106
I was searching for similar solution. The replies here and the Tutorial on top is informative. I studied posts/blogs referred here to build mine successful. I am posting complete CMakeLists.txt worked for me. I guess, this would be helpful as a basic template for beginners.
"CMakeLists.txt"
cmake_minimum_required(VERSION 3.10.2)
# Target Project
project (ClientProgram)
# Begin: Including Sources and Headers
include_directories(include)
file (GLOB SOURCES "src/*.c")
# End: Including Sources and Headers
# Begin: Generate executables
add_executable (ClientProgram ${SOURCES})
# End: Generate executables
# This Project Depends on External Project(s)
include (ExternalProject)
# Begin: External Third Party Library
set (libTLS ThirdPartyTlsLibrary)
ExternalProject_Add (${libTLS}
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
# Begin: Download Archive from Web Server
URL http://myproject.com/MyLibrary.tgz
URL_HASH SHA1=<expected_sha1sum_of_above_tgz_file>
DOWNLOAD_NO_PROGRESS ON
# End: Download Archive from Web Server
# Begin: Download Source from GIT Repository
# GIT_REPOSITORY https://github.com/<project>.git
# GIT_TAG <Refer github.com releases -> Tags>
# GIT_SHALLOW ON
# End: Download Source from GIT Repository
# Begin: CMAKE Comamnd Argiments
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
CMAKE_ARGS -DUSE_SHARED_LIBRARY:BOOL=ON
# End: CMAKE Comamnd Argiments
)
# The above ExternalProject_Add(...) construct wil take care of \
# 1. Downloading sources
# 2. Building Object files
# 3. Install under DCMAKE_INSTALL_PREFIX Directory
# Acquire Installation Directory of
ExternalProject_Get_Property (${libTLS} install_dir)
# Begin: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# Include PATH that has headers required by Target Project
include_directories (${install_dir}/include)
# Import librarues from External Project required by Target Project
add_library (lmytls SHARED IMPORTED)
set_target_properties (lmytls PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmytls.so)
add_library (lmyxdot509 SHARED IMPORTED)
set_target_properties(lmyxdot509 PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmyxdot509.so)
# End: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# End: External Third Party Library
# Begin: Target Project depends on Third Party Component
add_dependencies(ClientProgram ${libTLS})
# End: Target Project depends on Third Party Component
# Refer libraries added above used by Target Project
target_link_libraries (ClientProgram lmytls lmyxdot509)
It is SO ridiculous that this is not super-easy... let alone next to impossible. Hands up, I defer to Apple/Spotlight...
mdfind 'kMDItemContentType=public.unix-executable'
At least it works!
You should escape the quotes like this:
curl -i -X POST -d '{\"screencast\":{\"subject\":\"tools\"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
I would expect either:
// Makes sure item is at newIndex after the operation
T item = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, item);
... or:
// Makes sure relative ordering of newIndex is preserved after the operation,
// meaning that the item may actually be inserted at newIndex - 1
T item = list[oldIndex];
list.RemoveAt(oldIndex);
newIndex = (newIndex > oldIndex ? newIndex - 1, newIndex)
list.Insert(newIndex, item);
... would do the trick, but I don't have VS on this machine to check.
I dont believe you can without cropping them, I mean you could make the divs the same height by using jquery however this will not make the images the same size.
You could take a look at using Masonry which will make this look decent.
You could do this with partial application, although using named variables definitely leads to more readable code. John Resig wrote a blog article in 2008 about how to do it in JavaScript: http://ejohn.org/blog/partial-functions-in-javascript/
Function.prototype.partial = function(){
var fn = this, args = Array.prototype.slice.call(arguments);
return function(){
var arg = 0;
for ( var i = 0; i < args.length && arg < arguments.length; i++ )
if ( args[i] === undefined )
args[i] = arguments[arg++];
return fn.apply(this, args);
};
};
It would probably be possible to apply the same principle in Ruby (except for the prototypal inheritance).
It's worth understanding what those error messages mean - needs merge
and error: you need to resolve your current index first
indicate that a merge failed, and that there are conflicts in those files. If you've decided that whatever merge you were trying to do was a bad idea after all, you can put things back to normal with:
git reset --merge
However, otherwise you should resolve those merge conflicts, as described in the git manual.
Once you've dealt with that by either technique you should be able to checkout the 9-sign-in-out
branch. The problem with just renaming your 9-sign-in-out
to master
, as suggested in wRAR's answer is that if you've shared your previous master branch with anyone, this will create problems for them, since if the history of the two branches diverged, you'll be publishing rewritten history.
Essentially what you want to do is to merge your topic branch 9-sign-in-out
into master
but exactly keep the versions of the files in the topic branch. You could do this with the following steps:
# Switch to the topic branch:
git checkout 9-sign-in-out
# Create a merge commit, which looks as if it's merging in from master, but is
# actually discarding everything from the master branch and keeping everything
# from 9-sign-in-out:
git merge -s ours master
# Switch back to the master branch:
git checkout master
# Merge the topic branch into master - this should now be a fast-forward
# that leaves you with master exactly as 9-sign-in-out was:
git merge 9-sign-in-out
In your project parent directory, run:
git submodule update --init
Or if you have recursive submodules run:
git submodule update --init --recursive
Sometimes this still doesn't work, because somehow you have local changes in the local submodule directory while the submodule is being updated.
Most of the time the local change might not be the one you want to commit. It can happen due to a file deletion in your submodule, etc. If so, do a reset in your local submodule directory and in your project parent directory, run again:
git submodule update --init --recursive
answer = True
myvar = "the answer is " + str(answer)
or
myvar = "the answer is %s" % answer
Replace
new Timestamp();
with
new java.util.Date()
because there is no default constructor for Timestamp
, or you can do it with the method:
new Timestamp(System.currentTimeMillis());
I put this function in a util file in one of the apps in my project:
import logging
import re
from django.db import connection
logger = logging.getLogger(__name__)
def sql_logger():
logger.debug('TOTAL QUERIES: ' + str(len(connection.queries)))
logger.debug('TOTAL TIME: ' + str(sum([float(q['time']) for q in connection.queries])))
logger.debug('INDIVIDUAL QUERIES:')
for i, query in enumerate(connection.queries):
sql = re.split(r'(SELECT|FROM|WHERE|GROUP BY|ORDER BY|INNER JOIN|LIMIT)', query['sql'])
if not sql[0]: sql = sql[1:]
sql = [(' ' if i % 2 else '') + x for i, x in enumerate(sql)]
logger.debug('\n### {} ({} seconds)\n\n{};\n'.format(i, query['time'], '\n'.join(sql)))
Then, when needed, I just import it and call it from whatever context (usually a view) is necessary, e.g.:
# ... other imports
from .utils import sql_logger
class IngredientListApiView(generics.ListAPIView):
# ... class variables and such
# Main function that gets called when view is accessed
def list(self, request, *args, **kwargs):
response = super(IngredientListApiView, self).list(request, *args, **kwargs)
# Call our function
sql_logger()
return response
It's nice to do this outside the template because then if you have API views (usually Django Rest Framework), it's applicable there too.
As mentioned above, if your data contains tab characters, commas, or newlines in your data then it's going to be very hard to export and import it with CSV. Values will overflow out of the fields and you will get errors. This problem is even worse if any of your long fields contain multi-line text with newline characters in them.
My method in these cases is to use the BCP command-line utility to export the data from SQL server, then use LOAD DATA INFILE .. INTO TABLE command in MySQL to read the data file back in. BCP is one of the oldest SQL Server command line utilities (dating back to the birth of SQL server - v6.5) but it is still around and still one of the easiest and most reliable ways to get data out.
To use this technique you need to create each destination table with the same or equivalent schema in MySQL. I do that by right clicking the Database in SQL enterprise manager, then Tasks->Generate Scripts... and create a SQL script for all the tables. You must then convert the script to MySQL compatible SQL by hand (definitely the worst part of the job) and finally run the CREATE TABLE commands on the MySQL database so you have matching tables to the SQL server versions column-wise, empty and ready for data.
Then, export the data from the MS-SQL side as follows.
bcp DatabaseName..TableName out TableName.dat -q -c -T -S ServerName -r \0 -t !\t!
(If you're using SQL Server Express, use a -S value like so: -S "ComputerName\SQLExpress")
That will create a file named TableName.dat, with fields delimited by ![tab]! and rows delimited by \0 NUL characters.
Now copy the .dat files into /tmp on the MySQL server and load on the MySQL side like so:
LOAD DATA INFILE '/tmp/TableName.dat' INTO TABLE TableName FIELDS TERMINATED BY '!\t!' LINES TERMINATED BY '\0';
Don't forget that the tables (TableName in this example) must be created already on the MySQL side.
This procedure is painfully manual when it comes to converting the SQL schema over, however it works for even the most difficult of data and because it uses flat files you never need to persuade SQL Server to talk to MySQL, or vice versa.
Use:
subA.tick_params(labelsize=6)
ReducedForm
is a type, so you cannot say
ReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;
You can only use the .
operator on an instance:
ReducedForm rf;
rf.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;
PHPMailer handles errors nicely, also a good script to use for sending mail via SMTP...
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
you should just be able to call it by typing in the file name. You may have to call ./a.exe as the current directory is usually not on the path for security reasons.
I'd recommend that you take a look at jQuery.
jQuery way:
$("html").addClass("myClass");
select * from person where DATE(dob) between '2011-01-01' and '2011-01-31'
Surprisingly such conversions are solutions to many problems in MySQL.
You may also need to enable ReferralChasing on the DirectorySearcher - http://msdn.microsoft.com/en-us/library/ms180884(VS.80).aspx.
This works like a clock for me:
methods: {
hasHistory () { return window.history.length > 2 }
}
Then, in the template:
<button
type="button"
@click="hasHistory()
? $router.go(-1)
: $router.push('/')" class="my-5 btn btn-outline-success">«
Back
</button>
Well, there are multiple ways you can include dynamic javascript, I use this one for many of the projects.
var script = document.createElement("script")
script.type = "text/javascript";
//Chrome,Firefox, Opera, Safari 3+
script.onload = function(){
console.log("Script is loaded");
};
script.src = "file1.js";
document.getElementsByTagName("head")[0].appendChild(script);
You can call create a universal function which can help you to load as many javascript files as needed. There is a full tutorial about this here.
To save hours of coding time, use a jquery plug-in already optimized for embedded video iframes.
I spent a couple days trying to integrate Vimeo's moogaloop API with jquery tools unsuccessfully. See this list for a handful of easier options.
Most modern languages are in varying degree both imperative and functional but to better understand functional programming, it will be best to take an example of pure functional language like Haskell in contrast of imperative code in not so functional language like java/C#. I believe it is always easy to explain by example, so below is one.
Functional programming: calculate factorial of n i.e n! i.e n x (n-1) x (n-2) x ...x 2 X 1
-- | Haskell comment goes like
-- | below 2 lines is code to calculate factorial and 3rd is it's execution
factorial 0 = 1
factorial n = n * factorial (n - 1)
factorial 3
-- | for brevity let's call factorial as f; And x => y shows order execution left to right
-- | above executes as := f(3) as 3 x f(2) => f(2) as 2 x f(1) => f(1) as 1 x f(0) => f(0) as 1
-- | 3 x (2 x (1 x (1)) = 6
Notice that Haskel allows function overloading to the level of argument value. Now below is example of imperative code in increasing degree of imperativeness:
//somewhat functional way
function factorial(n) {
if(n < 1) {
return 1;
}
return n * factorial(n-1);
}
factorial(3);
//somewhat more imperative way
function imperativeFactor(n) {
int f = 1;
for(int i = 1; i <= n; i++) {
f = f * i;
}
return f;
}
This read can be a good reference to understand that how imperative code focus more on how part, state of machine (i in for loop), order of execution, flow control.
The later example can be seen as java/C# lang code roughly and first part as limitation of the language itself in contrast of Haskell to overload the function by value (zero) and hence can be said it is not purist functional language, on the other hand you can say it support functional prog. to some extent.
Disclosure: none of the above code is tested/executed but hopefully should be good enough to convey the concept; also I would appreciate comments for any such correction :)
From Activity#showDialog(int)
:
This method is deprecated.
Use the newDialogFragment
class withFragmentManager
instead; this is also available on older platforms through the Android compatibility package.
Maven version 3.2.1 added this feature, you can use the -pl
switch (shortcut for --projects
list) with !
or -
(source) to exclude certain submodules.
mvn -pl '!submodule-to-exclude' install
mvn -pl -submodule-to-exclude install
Be careful in bash the character ! is a special character, so you either have to single quote it (like I did) or escape it with the backslash character.
The syntax to exclude multiple module is the same as the inclusion
mvn -pl '!submodule1,!submodule2' install
mvn -pl -submodule1,-submodule2 install
EDIT Windows does not seem to like the single quotes, but it is necessary in bash ; in Windows, use double quotes (thanks @awilkinson)
mvn -pl "!submodule1,!submodule2" install
The best solution (from 2019-2021) I found is that:
function YouTubeGetID(url){
url = url.split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
return (url[2] !== undefined) ? url[2].split(/[^0-9a-z_\-]/i)[0] : url[0];
}
I found it here.
/*
* Tested URLs:
var url = 'http://youtube.googleapis.com/v/4e_kz79tjb8?version=3';
url = 'https://www.youtube.com/watch?feature=g-vrec&v=Y1xs_xPb46M';
url = 'http://www.youtube.com/watch?feature=player_embedded&v=Ab25nviakcw#';
url = 'http://youtu.be/Ab25nviakcw';
url = 'http://www.youtube.com/watch?v=Ab25nviakcw';
url = '<iframe width="420" height="315" src="http://www.youtube.com/embed/Ab25nviakcw" frameborder="0" allowfullscreen></iframe>';
url = '<object width="420" height="315"><param name="movie" value="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&hl=en_US" type="application/x-shockwave-flash" width="420" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>';
url = 'http://i1.ytimg.com/vi/Ab25nviakcw/default.jpg';
url = 'https://www.youtube.com/watch?v=BGL22PTIOAM&feature=g-all-xit';
url = 'BGL22PTIOAM';
*/
you can use the tool bar setNavigationIcon method. Android Doc
mToolBar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handleOnBackPress();
}
});
class App extends React.Component {_x000D_
_x000D_
buttonClick(){_x000D_
console.log("came here")_x000D_
_x000D_
}_x000D_
_x000D_
subComponent() {_x000D_
return (<div>Hello World</div>);_x000D_
}_x000D_
_x000D_
render() {_x000D_
return ( _x000D_
<div className="patient-container">_x000D_
<button onClick={this.buttonClick.bind(this)}>Click me</button>_x000D_
{this.subComponent()}_x000D_
</div>_x000D_
)_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App/>, document.getElementById('app'));
_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="app"></div>
_x000D_
it depends on your need, u can use either this.renderIcon()
or bind this.renderIcon.bind(this)
UPDATE
This is how you call a method outside the render.
buttonClick(){
console.log("came here")
}
render() {
return (
<div className="patient-container">
<button onClick={this.buttonClick.bind(this)}>Click me</button>
</div>
);
}
The recommended way is to write a separate component and import it.
We can read properties file in spring boot using 3 way
1. Read value from application.properties Using @Value
map key as
public class EmailService {
@Value("${email.username}")
private String username;
}
2. Read value from application.properties Using @ConfigurationProperties
In this we will map prefix of key using ConfigurationProperties and key name is same as field of class
@Component
@ConfigurationProperties("email")
public class EmailConfig {
private String username;
}
3. Read application.properties Using using Environment object
public class EmailController {
@Autowired
private Environment env;
@GetMapping("/sendmail")
public void sendMail(){
System.out.println("reading value from application properties file using Environment ");
System.out.println("username ="+ env.getProperty("email.username"));
System.out.println("pwd ="+ env.getProperty("email.pwd"));
}
Reference : how to read value from application.properties in spring boot
Regarding your code: It's slightly hard to read... If you want to try to view it all in a php array format, just print_r it. This might help:
<?php
$a =
array(
'languages' =>
array (
76 =>
array ( 'id' => '76', 'tag' => 'Deutsch', ), ), 'targets' =>
array ( 81 =>
array ( 'id' => '81', 'tag' => 'Deutschland', ), ), 'tags' =>
array ( 7866 =>
array ( 'id' => '7866', 'tag' => 'automobile', ), 17800 =>
array ( 'id' => '17800', 'tag' => 'seat leon', ), 17801 =>
array ( 'id' => '17801', 'tag' => 'seat leon cupra', ), ),
'inactiveTags' =>
array ( 195 =>
array ( 'id' => '195', 'tag' => 'auto', ), 17804 =>
array ( 'id' => '17804', 'tag' => 'coupès', ), 17805 =>
array ( 'id' => '17805', 'tag' => 'fahrdynamik', ), 901 =>
array ( 'id' => '901', 'tag' => 'fahrzeuge', ), 17802 =>
array ( 'id' => '17802', 'tag' => 'günstige neuwagen', ), 1991 =>
array ( 'id' => '1991', 'tag' => 'motorsport', ), 2154 =>
array ( 'id' => '2154', 'tag' => 'neuwagen', ), 10660 =>
array ( 'id' => '10660', 'tag' => 'seat', ), 17803 =>
array ( 'id' => '17803', 'tag' => 'sportliche ausstrahlung', ), 74 =>
array ( 'id' => '74', 'tag' => 'web 2.0', ), ), 'categories' =>
array ( 16082 =>
array ( 'id' => '16082', 'tag' => 'Auto & Motorrad', ), 51 =>
array ( 'id' => '51', 'tag' => 'Blogosphäre', ), 66 =>
array ( 'id' => '66', 'tag' => 'Neues & Trends', ), 68 =>
array ( 'id' => '68', 'tag' => 'Privat', ), ), );
printarr($a);
printarr($a['languages'][76]['tag']);
parintarr($a['targets'][81]['id']);
function printarr($in){
echo "\n";
print_r($in);
echo "\n";
}
//run in php command line php path/to/file.php to test, switching otu the print_r.
In a terminal put these:
cd C:\Program Files (x86)\Google\Chrome\Application
chrome.exe --disable-web-security --user-data-dir="c:/chromedev"
Reading and printing the content of a text file (.txt)
in Python3
Consider this as the content of text file with the name world.txt
:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!
First we will open this file by doing this:
file= open("world.txt", 'r')
Now we will get the content of file in a variable using .read()
like this:
content_of_file= file.read()
Finally we will just print the content_of_file
variable using print
command.
print(content_of_file)
Output:
Hello World! This is an example of Content of the Text file we are about to read and print using python!
From your screenshot it appears you have ReSharper installed.
Depending on the key binding options you chose when you installed it, some of your standard shortcuts may now be redirected to ReSharper commands. It's worth checking, for example Ctrl+E, C is used by R# for the code cleanup dialog.
Old post but as you said "why is it not using the correct certificate" I would like to offer an way to find out which SSL certificate is used for SMTP (see here) which required openssl:
openssl s_client -connect exchange01.int.contoso.com:25 -starttls smtp
This will outline the used SSL certificate for the SMTP service. Based on what you see here you can replace the wrong certificate (like you already did) with a correct one (or trust the certificate manually).
You can use strstream
. It's formally deprecated, but it's still a great tool if you need to work with C strings, i think.
char result[100]; // max size 100
std::ostrstream s(result, sizeof result - 1);
s << one << two << std::ends;
result[99] = '\0';
This will write one
and then two
into the stream, and append a terminating \0
using std::ends
. In case both strings could end up writing exactly 99
characters - so no space would be left writing \0
- we write one manually at the last position.
I know this is old, but I'm gonna chime in anyway because it may be useful to someone. If you can still see the file in Finder, then click on the file in your project and delete it, selecting "remove references" and not "move to trash".
Once the reference is removed, drag and drop the file from finder into your project again and it should sort itself out.
The res
argument in the http.get()
callback is not the body, but rather an http.ClientResponse object. You need to assemble the body:
var url = 'http://graph.facebook.com/517267866/?fields=picture';
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var fbResponse = JSON.parse(body);
console.log("Got a response: ", fbResponse.picture);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});
All variables are cached so the loop and keyup event doesn't have to create a jQuery object everytime it runs.
var $input = $('input:text'),
$register = $('#register');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
Check working example at http://jsfiddle.net/DKNhx/3/
Maybe this can help
string input = "hello123world";
bool isDigitPresent = input.Any(c => char.IsDigit(c));
answer from msdn.
Just open a command shell and type (saying your port is 123456):
netstat -a -n -o | find "123456"
You will see everything you need.
The headers are:
Proto Local Address Foreign Address State PID
TCP 0.0.0.0:37 0.0.0.0:0 LISTENING 1111
This is as mentioned here.
There are different points of view. One is they are the same. But in practice, we need to differentiate formal parameters (declarations in the method's header) and actual parameters (values passed at the point of invocation). While phrases "formal parameter" and "actual parameter" are common, "formal argument" and "actual argument" are not used. This is because "argument" is used mainly to denote "actual parameter". As a result, some people insist that "parameter" can denote only "formal parameter".
final String url = "some/url";
instead of:
final JSONObject jsonBody = "{\"type\":\"example\"}";
you can use:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("type", "my type");
} catch (JSONException e) {
e.printStackTrace();
}
new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });
Making a Toast inside Fragment
Toast.makeText(getActivity(), "Your Text Here!", Toast.LENGTH_SHORT).show();
OR
Activity activityObj = this.getActivity();
Toast.makeText(activityObj, "Your Text Here!", Toast.LENGTH_SHORT).show();
OR
Toast.makeText(this, "Your Text Here!", Toast.LENGTH_SHORT).show();
Use -A and -B switches (mean lines-after and lines-before):
grep -A 1 -B 1 FAILED file.txt
public static String getRandomString(int length)
{
String randomStr = UUID.randomUUID().toString();
while(randomStr.length() < length) {
randomStr += UUID.randomUUID().toString();
}
return randomStr.substring(0, length);
}
To convert any JSON to array, use the below code:
const usersJson: any[] = Array.of(res.json());
you should also be able to use groovy and do what textfinder did
marking a build as un-stable with groovy post-build plugin
if(manager.logContains("Could not login to FTP server")) {
manager.addWarningBadge("FTP Login Failure")
manager.createSummary("warning.gif").appendText("<h1>Failed to login to remote FTP Server!</h1>", false, false, false, "red")
manager.buildUnstable()
}
Also see Groovy Postbuild Plugin
insert into table1(id1) select (max(id1)+1) from table1;
Adding this to my .vimrc works for me. Just make sure you don't have anything else conflicting..
autocmd VimEnter * :syn match space /\s/
autocmd VimEnter * :hi space ctermbg=lightgray ctermfg=black guibg=lightgray guifg=black
You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable
.
Main you have to consider three thing while binding the datasource of a dropdown.
you can use following code to bind a dropdownlist to a datasource as a datatable
:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
DropDownList1.DataTextField = "QUIZ_Name";
DropDownList1.DataValueField = "QUIZ_ID"
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true"
you can use SelectedIndexChanged
event to write your code.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strQUIZ_ID=DropDownList1.SelectedValue;
string strQUIZ_Name=DropDownList1.SelectedItem.Text;
// Your code..............
}
I would like to give you also the idea to disable an <option>
with a given defined value (not innerhtml
). I recommend to it with jQuery
to get the simplest way. See my sample below.
HTML
Status:
<div id="option">
<select class="status">
<option value="hand" selected>Hand</option>
<option value="simple">Typed</option>
<option value="printed">Printed</option>
</select>
</div>
Javascript
The idea here is how to disable Printed
option when current Status
is Hand
var status = $('#option').find('.status');//to get current the selected value
var op = status.find('option');//to get the elements for disable attribute
(status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;
You may see how it works here:
Try this
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />
if you want 0 or 1 "description" elements, Or
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />
if you want 0 to infinity number of "description" elements.
It seems to work fine in Google Chrome. Which browser are you using? Here the proof http://jsfiddle.net/CN8XL/
Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value
. You have to wrap in the input in a <form>
tag like with the proper name
attribute, like shown below:
<form name="FormName">
<input type="hidden" name="checkyear" id="checkyear" value="">
</form>
Have you considered using the jQuery Library? Here are the docs for .val()
function.
If a value contains a comma, a newline character or a double quote, then the string must be enclosed in double quotes. E.g: "Newline char in this field \n".
You can use below online tool to escape "" and , operators. https://www.freeformatter.com/csv-escape.html#ad-output
Java 8 now allows implementation of methods inside an interface itself with default scope (and static only).
If you are using latest versions of Angular (2/5/6) :
In your component.ts
//x.component.ts
prefs = false;
hidePrefs(){
this.prefs = true;
}
Try adding this at the end of your code:
import matplotlib.pyplot as plt
plt.title('add title here')
A better solution:
if type(value) == str:
# Ignore errors even if the string is not proper UTF-8 or has
# broken marker bytes.
# Python built-in function unicode() can do this.
value = unicode(value, "utf-8", errors="ignore")
else:
# Assume the value object has proper __unicode__() method
value = unicode(value)
If you would like to read more about why:
http://docs.plone.org/manage/troubleshooting/unicode.html#id1
Change appBase
in server.xml
If you want to keep both previous webapps and a new one, you can use another Host instance with another port defined in tomcat.
As previously mentioned - in case of a project, Makefile
or otherwise, this is a project configuration issue, where you'll likely need to specify other flags too.
But what about one-off programs, where you would normally just write g++ file.cpp && ./a.out
?
Well, I would much like to have some #pragma
to turn in on at source level, or maybe a default extension - say .cxx
or .C11
or whatever, trigger it by default. But as of today, there is no such feature.
But, as you probably are working in a manual environment (i.e. shell), you can just have an alias in you .bashrc
(or whatever):
alias g++11="g++ -std=c++0x"
or, for newer G++ (and when you want to feel "real C++11")
alias g++11="g++ -std=c++11"
You can even alias to g++
itself, if you hate C++03 that much ;)
The traditonal 4 bit hex is pretty direct. Hex String to Integer (Assuming value is stored in field called FHexString) :
CONVERT(BIGINT,CONVERT(varbinary(4),
(SELECT master.dbo.fn_cdc_hexstrtobin(
LEFT(FMEID_ESN,8)
))
))
Integer to Hex String (Assuming value is stored in field called FInteger):
(SELECT master.dbo.fn_varbintohexstr(CONVERT(varbinary,CONVERT(int,
FInteger
))))
Important to note is that when you begin to use bit sizes that cause register sharing, especially on an intel machine, your High and Low and Left and Rights in the registers will be swapped due to the little endian nature of Intel. For example, when using a varbinary(3), we're talking about a 6 character Hex. In this case, your bits are paired as the following indexes from right to left "54,32,10". In an intel system, you would expect "76,54,32,10". Since you are only using 6 of the 8, you need to remember to do the swaps yourself. "76,54" will qualify as your left and "32,10" will qualify as your right. The comma separates your high and low. Intel swaps the high and lows, then the left and rights. So to do a conversion...sigh, you got to swap them yourselves for example, the following converts the first 6 of an 8 character hex:
(SELECT master.dbo.fn_replvarbintoint(
CONVERT(varbinary(3),(SELECT master.dbo.fn_cdc_hexstrtobin(
--intel processors, registers are switched, so reverse them
----second half
RIGHT(FHex8,2)+ --0,1 (0 indexed)
LEFT(RIGHT(FHex8,4),2)+ -- 2,3 (oindex)
--first half
LEFT(RIGHT(FHex8,6),2) --4,5
)))
))
It's a bit complicated, so I would try to keep my conversions to 8 character hex's (varbinary(4)).
In summary, this should answer your question. Comprehensively.
I had the same question. While there are good answers here I decided to create a table-valued function. With a table (or scalar) valued function you don't have to change your stored proc. I simply did a select from the table-valued function. Note that the parameter (MyParameter is optional).
CREATE FUNCTION [dbo].[MyDateFunction]
(@MyParameter varchar(max))
RETURNS TABLE
AS
RETURN
(
--- Query your table or view or whatever and select the results.
SELECT DateValue FROM MyTable WHERE ID = @MyParameter;
)
To assign to your variable you simply can do something like:
Declare @MyDate datetime;
SET @MyDate = (SELECT DateValue FROM MyDateFunction(@MyParameter));
You can also use a scalar valued function:
CREATE FUNCTION TestDateFunction()
RETURNS datetime
BEGIN
RETURN (SELECT GetDate());
END
Then you can simply do
Declare @MyDate datetime;
SET @MyDate = (Select dbo.TestDateFunction());
SELECT @MyDate;
There is the wget
command or the curl
.
You can now use the file you downloaded with wget. Or you can handle a stream with curl.
Resources :
This resource(broken link) is also worth considering - some very tidy code that uses GD. However, I modified their final code snippet to create this function which meets the OPs requirements...
function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
$target_dir = "your-uploaded-images-folder/";
$target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
$image = new SimpleImage();
$image->load($_FILES[$html_element_name]['tmp_name']);
$image->resize($new_img_width, $new_img_height);
$image->save($target_file);
return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user
}
You will also need to include this PHP file...
<?php
/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/
class SimpleImage {
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
?>
Javascript arrays have a length property. Use it like this:
st.itemb.length
<?php
$browser_ver = get_browser(null,true);
//echo $browser_ver['browser'];
if($browser_ver['browser'] == 'IE') {
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pdf print test</title>
<style>
html { height:100%; }
</style>
<script>
function printIt(id) {
var pdf = document.getElementById("samplePDF");
pdf.click();
pdf.setActive();
pdf.focus();
pdf.print();
}
</script>
</head>
<body style="margin:0; height:100%;">
<embed id="samplePDF" type="application/pdf" src="/pdfs/2010/dash_fdm350.pdf" width="100%" height="100%" />
<button onClick="printIt('samplePDF')">Print</button>
</body>
</html>
<?php
} else {
?>
<HTML>
<script Language="javascript">
function printfile(id) {
window.frames[id].focus();
window.frames[id].print();
}
</script>
<BODY marginheight="0" marginwidth="0">
<iframe src="/pdfs/2010/dash_fdm350.pdf" id="objAdobePrint" name="objAdobePrint" height="95%" width="100%" frameborder=0></iframe><br>
<input type="button" value="Print" onclick="javascript:printfile('objAdobePrint');">
</BODY>
</HTML>
<?php
}
?>
This article suggests the following properties of the browser's navigator object:
navigator.language
(Netscape - Browser Localization)navigator.browserLanguage
(IE-Specific - Browser Localized Language)navigator.systemLanguage
(IE-Specific - Windows OS - Localized Language)navigator.userLanguage
Roll these into a javascript function and you should be able to guess the right language, in most circumstances. Be sure to degrade gracefully, so have a div containing your language choice links, so that if there is no javascript or the method doesn't work, the user can still decide. If it does work, just hide the div.
The only problem with doing this on the client side is that either you serve up all the languages to the client, or you have to wait until the script has run and detected the language before requesting the right version. Perhaps serving up the most popular language version as a default would irritate the fewest people.
Edit: I'd second Ivan's cookie suggestion, but make sure the user can always change the language later; not everyone prefers the language their browser defaults to.
I am using the following code in such cases:
obj, created = Model.objects.get_or_create(id=some_id)
if not created:
resp= "It was created"
else:
resp= "OK"
obj.save()
Use the title
attribute while alt
is important for SEO stuff.
Manzur Alahi is right! I'm trying to learn Rider by JetBrains and I had the same error when I was trying to use dotnet-ef migrations add ...
in Cmd, PowerShell, etc. but when I used Visual Studio IDE I didn't have problem.
I fixed the error with:
dotnet ef migrations add InitialMigration --project "Domain.Entities" --startup-project "WebApi"
and this to update the database
dotnet ef database update --project "Domain.Entities" --startup-project "WebApi"
just like Manzur Alahi said.
In Swift:
func pathForResource( name: String?,
ofType ext: String?,
inDirectory subpath: String?) -> String? {
// **name:** Name of Hmtl
// **ofType ext:** extension for type of file. In this case "html"
// **inDirectory subpath:** the folder where are the file.
// In this case the file is in root folder
let path = NSBundle.mainBundle().pathForResource( "dados",
ofType: "html",
inDirectory: "root")
var requestURL = NSURL(string:path!)
var request = NSURLRequest(URL:requestURL)
webView.loadRequest(request)
}
This will do:
/^(apple|banana)$/
to exclude from captured strings (e.g. $1
,$2
):
(?:apple|banana)
The way to do this is by using background-size so in your case:
background-size: 50% 50%;
or
You can set the width and the height of the elements to percentages as well
On newer versions of spark (2.0+)
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
import org.apache.spark.sql._
import org.apache.spark.sql.types._
val spark = SparkSession
.builder()
.getOrCreate()
import spark.implicits._
val dfSchema = Seq("col1", "col2", "col3")
rdd.toDF(dfSchema: _*)
select * from information_schema.TRIGGERS;
To represent a unicode string as a string of bytes is known as encoding. Use u'...'.encode(encoding)
.
Example:
>>> u'æøå'.encode('utf8') '\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5' >>> u'æøå'.encode('latin1') '\xc3\xa6\xc3\xb8\xc3\xa5' >>> u'æøå'.encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
You typically encode a unicode string whenever you need to use it for IO, for instance transfer it over the network, or save it to a disk file.
To convert a string of bytes to a unicode string is known as decoding. Use unicode('...', encoding)
or '...'.decode(encoding).
Example:
>>> u'æøå' u'\xc3\xa6\xc3\xb8\xc3\xa5' # the interpreter prints the unicode object like so >>> unicode('\xc3\xa6\xc3\xb8\xc3\xa5', 'latin1') u'\xc3\xa6\xc3\xb8\xc3\xa5' >>> '\xc3\xa6\xc3\xb8\xc3\xa5'.decode('latin1') u'\xc3\xa6\xc3\xb8\xc3\xa5'
You typically decode a string of bytes whenever you receive string data from the network or from a disk file.
I believe there are some changes in unicode handling in python 3, so the above is probably not correct for python 3.
Some good links:
Use wwtd (what would travis do) ruby gem to run tests on your local machine roughly as they would run on travis.
It will recreate the build matrix and run each configuration, great to sanity check setup before pushing.
gem i wwtd
wwtd
It is possible to send Emails without using any heavy libraries I have included my example here.
lightweight SMTP Email sender for PHP
https://github.com/jerryurenaa/EZMAIL
Tested in both environments production and development.
and most importantly emails will not go to spam unless your IP is blacklisted by the server.
cheers.
I use the version of NCover that comes with TestDriven.NET. It will allow you to easily right-click on your unit test class library, and hit Test With→Coverage, and it will pull up the report.
try if install lampp
sudo chown www-data:www-data -R /opt/lampp/phpmyadmin/*
sudo chown www-data:www-data -R /opt/lampp/phpmyadmin
or if install phpmyadmin
sudo chown www-data:www-data -R /etc/phpmyadmin/*
sudo chown www-data:www-data -R /etc/phpmyadmin
The style that you give the "g" element will apply the child elements, not the "g" element itself.
Add a rectangle element and position around the group you wish to style.
See: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g
EDIT: updated wording and added fiddle in comments.