In HTML file you can add ngIf for you pattern like this
<div class="form-control-feedback" *ngIf="Mobile.errors && (Mobile.dirty || Mobile.touched)">
<p *ngIf="Mobile.errors.pattern" class="text-danger">Number Only</p>
</div>
In .ts file you can add the Validators pattern - "^[0-9]*$"
this.Mobile = new FormControl('', [
Validators.required,
Validators.pattern("^[0-9]*$"),
Validators.minLength(8),
]);
subscribe() -Invokes an execution of an Observable and registers Observer handlers for notifications it will emit. -Observable- representation of any set of values over any amount of time.
In navigateExtra we can pass only some specific name as argument otherwise it showing error like below: For Ex- Here I want to pass customer key in router navigate and I pass like this-
this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});
but it showing some error like below:
Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'
.
Solution: we have to write like this:
this.Router.navigate(['componentname'],{state: {customerkey:response.key}});
Check out this plunkr.
When you're binding to variables, you need to use the brackets. Also, you use the hashtag when you want to get references to elements in your html, not for declaring variables inside of templates like that.
<md-button-toggle *ngFor="let indicador of indicadores; let first = first;" [value]="indicador.id" [checked]="first">
...
Edit: Thanks to Christopher Moore: Angular exposes the following local variables:
index
first
last
even
odd
We had this problem years ago before I had joined and had in place a solution that used local storage for user and environment information. Angular 1.0 days to be exact. We were formerly dynamically creating a js file at runtime that would then place the generated api urls into a global variable. We're a little more OOP driven these days and don't use local storage for anything.
I created a better solution for both determining environment and api url creation.
How does this differ?
The app will not load unless the config.json file is loaded. It uses factory functions to create a higher degree of SOC. I could encapsulate this into a service, but I never saw any reason when the only similarity between the different sections of the file are that they exist together in the file. Having a factory function allows me to pass the function directly into a module if it's capable of accepting a function. Last, I have an easier time setting up InjectionTokens when factory functions are available to utilize.
Downsides?
You're out of luck using this setup (and most of the other answers) if the module you want to configure doesn't allow a factory function to be passed into either forRoot() or forChild(), and there's no other way to configure the package by using a factory function.
Instructions
-- This is where my solution starts to really differ --
{}
or any
when you know you can specify something more concrete-- and/or --
-- main.ts
I check window["environment"] is not populated before creating an event listener to allow the possiblilty of a solution where window["environment"] is populated by some other means before the code in main.ts ever executes.
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { configurationSubject } from './app/utils/environment-resolver';
var configurationLoadedEvent = document.createEvent('Event');
configurationLoadedEvent.initEvent('config-set', true, true);
fetch("../../assets/config.json")
.then(result => { return result.json(); })
.then(data => {
window["environment"] = data;
document.dispatchEvent(configurationLoadedEvent);
}, error => window.location.reload());
/*
angular-cli only loads the first thing it finds it needs a dependency under /app in main.ts when under local scope.
Make AppModule the first dependency it needs and the rest are done for ya. Event listeners are
ran at a higher level of scope bypassing the behavior of not loading AppModule when the
configurationSubject is referenced before calling platformBrowserDynamic().bootstrapModule(AppModule)
example: this will not work because configurationSubject is the first dependency the compiler realizes that lives under
app and will ONLY load that dependency, making AppModule an empty object.
if(window["environment"])
{
if (window["environment"].production) {
enableProdMode();
}
configurationSubject.next(window["environment"]);
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
}
*/
if(!window["environment"]) {
document.addEventListener('config-set', function(e){
if (window["environment"].production) {
enableProdMode();
}
configurationSubject.next(window["environment"]);
window["environment"] = undefined;
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
});
}
--- environment-resolvers.ts
I assign a value to the BehaviorSubject using window["environment"] for redundancy. You could devise a solution where your config is preloaded already and window["environment"] is already populated by the time any of your Angular's app code is ran, including the code in main.ts
import { BehaviorSubject } from "rxjs";
import { IConfig } from "../config.interface";
const config = <IConfig>Object.assign({}, window["environment"]);
export const configurationSubject = new BehaviorSubject<IConfig>(config);
export function resolveEnvironment() {
const env = configurationSubject.getValue().environment;
let resolvedEnvironment = "";
switch (env) {
// case statements for determining whether this is dev, test, stage, or prod
}
return resolvedEnvironment;
}
export function resolveNgxLoggerConfig() {
return configurationSubject.getValue().logging;
}
-- app.module.ts - Stripped down for easier understanding
Fun fact! Older versions of NGXLogger required you to pass in an object into LoggerModule.forRoot(). In fact, the LoggerModule still does! NGXLogger kindly exposes LoggerConfig which you can override allowing you to use a factory function for setup.
import { resolveEnvironment, resolveNgxLoggerConfig, resolveSomethingElse } from './environment-resolvers';
import { LoggerConfig } from 'ngx-logger';
@NgModule({
modules: [
SomeModule.forRoot(resolveSomethingElse)
],
providers:[
{
provide: ENVIRONMENT,
useFactory: resolveEnvironment
},
{
provide: LoggerConfig,
useFactory: resolveNgxLoggerConfig
}
]
})
export class AppModule
Addendum
How did I solve the creation of my API urls?
I wanted to be able to understand what each url did via a comment and wanted typechecking since that's TypeScript's greatest strength compared to javascript (IMO). I also wanted to create an experience for other devs to add new endpoints, and apis that was as seamless as possible.
I created a class that takes in the environment (dev, test, stage, prod, "", and etc) and passed this value to a series of classes[1-N] whose job is to create the base url for each API collection. Each ApiCollection is responsible for creating the base url for each collection of APIs. Could be our own APIs, a vendor's APIs, or even an external link. That class will pass the created base url into each subsequent api it contains. Read the code below to see a bare bones example. Once setup, it's very simple for another dev to add another endpoint to an Api class without having to touch anything else.
TLDR; basic OOP principles and lazy getters for memory optimization
@Injectable({
providedIn: 'root'
})
export class ApiConfig {
public apis: Apis;
constructor(@Inject(ENVIRONMENT) private environment: string) {
this.apis = new Apis(environment);
}
}
export class Apis {
readonly microservices: MicroserviceApiCollection;
constructor(environment: string) {
this.microservices = new MicroserviceApiCollection(environment);
}
}
export abstract class ApiCollection {
protected domain: any;
constructor(environment: string) {
const domain = this.resolveDomain(environment);
Object.defineProperty(ApiCollection.prototype, 'domain', {
get() {
Object.defineProperty(this, 'domain', { value: domain });
return this.domain;
},
configurable: true
});
}
}
export class MicroserviceApiCollection extends ApiCollection {
public member: MemberApi;
constructor(environment) {
super(environment);
this.member = new MemberApi(this.domain);
}
resolveDomain(environment: string): string {
return `https://subdomain${environment}.actualdomain.com/`;
}
}
export class Api {
readonly base: any;
constructor(baseUrl: string) {
Object.defineProperty(this, 'base', {
get() {
Object.defineProperty(this, 'base',
{ value: baseUrl, configurable: true});
return this.base;
},
enumerable: false,
configurable: true
});
}
attachProperty(name: string, value: any, enumerable?: boolean) {
Object.defineProperty(this, name,
{ value, writable: false, configurable: true, enumerable: enumerable || true });
}
}
export class MemberApi extends Api {
/**
* This comment will show up when referencing this.apiConfig.apis.microservices.member.memberInfo
*/
get MemberInfo() {
this.attachProperty("MemberInfo", `${this.base}basic-info`);
return this.MemberInfo;
}
constructor(baseUrl: string) {
super(baseUrl + "member/api/");
}
}
There are two additional ways to do it apart from the two methods mentioned in @PradeepJain's answer.
I would suggest not to use this approach and to fall back to this only as a last resort if you are not using [(ngModel)]
directive and also not using data binding via [value]
. Read this for more info.
app.component.html
<div>
<input type="text" #searchInput placeholder="Search...">
<button (click)="clearSearchInput()">Clear</button>
</div>
app.component.ts
export class App {
@ViewChild('searchInput') searchInput: ElementRef;
clearSearchInput(){
this.searchInput.nativeElement.value = '';
}
}
app.component.html
<form [formGroup]="form">
<div *ngIf="first.invalid"> Name is too short. </div>
<input formControlName="first" placeholder="First name">
<input formControlName="last" placeholder="Last name">
<button type="submit">Submit</button>
</form>
<button (click)="setValue()">Set preset value</button>
<button (click)="clearInputMethod1()">Clear Input Method 1</button>
<button (click)="clearInputMethod2()">Clear Input Method 2</button>
app.component.ts
export class AppComponent {
form = new FormGroup({
first: new FormControl('Nancy', Validators.minLength(2)),
last: new FormControl('Drew'),
});
get first(): any { return this.form.get('first'); }
get last(): any { return this.form.get('last'); }
clearInputMethod1() { this.first.reset(); this.last.reset(); }
clearInputMethod2() { this.form.setValue({first: '', last: ''}); }
setValue() { this.form.setValue({first: 'Nancy', last: 'Drew'}); }
}
Try it out on stackblitz Clearing input in a FormGroup
That's how I've done it in angular2 (it is similar to that plunkered solution) In your HTML file:
<div id="print-section">
// your html stuff that you want to print
</div>
<button (click)="print()">print</button>
and in your TS file :
print(): void {
let printContents, popupWin;
printContents = document.getElementById('print-section').innerHTML;
popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Print tab</title>
<style>
//........Customized style.......
</style>
</head>
<body onload="window.print();window.close()">${printContents}</body>
</html>`
);
popupWin.document.close();
}
You can also shortcut the path and use merely ngx-print library for less inconsistent coding (mixing JS and TS) and more out-of-the-box controllable and secured printing cases.
Shubham's answer explains very well. This answer is addition to it as per to avoid some pitfalls and refactoring to a more readable syntax
Pitfall : There is common misconception in rendering array of objects especially if there is an update or delete action performed on data. Use case would be like deleting an item from table row. Sometimes when row which is expected to be deleted, does not get deleted and instead other row gets deleted.
To avoid this, use key
prop in root element which is looped over in JSX tree of .map()
. Also adding React's Fragment
will avoid adding another element in between of ul
and li
when rendered via calling method.
state = {
userData: [
{ id: '1', name: 'Joe', user_type: 'Developer' },
{ id: '2', name: 'Hill', user_type: 'Designer' }
]
};
deleteUser = id => {
// delete operation to remove item
};
renderItems = () => {
const data = this.state.userData;
const mapRows = data.map((item, index) => (
<Fragment key={item.id}>
<li>
{/* Passing unique value to 'key' prop, eases process for virtual DOM to remove specific element and update HTML tree */}
<span>Name : {item.name}</span>
<span>User Type: {item.user_type}</span>
<button onClick={() => this.deleteUser(item.id)}>
Delete User
</button>
</li>
</Fragment>
));
return mapRows;
};
render() {
return <ul>{this.renderItems()}</ul>;
}
Important : Decision to use which value should we pass to key
prop also matters as common way is to use index
parameter provided by .map()
.
TLDR; But there's a drawback to it and avoid it as much as possible and use any unique id
from data which is being iterated such as item.id
. There's a good article on this - https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class
myObj:any = {
doSomething: function () { console.log('doing something'); return 'doing something'; },
};
myArray:any;
constructor() { }
ngOnInit() {
this.myArray = [this.myObj];
}
You can use it in template html file as following:
<div>test-1: {{ myObj?.doSomething()}}</div>
<div>test-2: {{ myArray[0].doSomething()}}</div>
<div>test-3: {{ myArray[2]?.doSomething()}}</div>
To apply min/max validation
on a number
you will need to create a Custom Validator
Validators class currently only have a few validators, namely
Validator: Here is toned down version of my number Validator, you can improve it as you like
static number(prms = {}): ValidatorFn {
return (control: FormControl): {[key: string]: any} => {
if(isPresent(Validators.required(control))) {
return null;
}
let val: number = control.value;
if(isNaN(val) || /\D/.test(val.toString())) {
return {"number": true};
} else if(!isNaN(prms.min) && !isNaN(prms.max)) {
return val < prms.min || val > prms.max ? {"number": true} : null;
} else if(!isNaN(prms.min)) {
return val < prms.min ? {"number": true} : null;
} else if(!isNaN(prms.max)) {
return val > prms.max ? {"number": true} : null;
} else {
return null;
}
};
}
Usage:
// check for valid number
var numberControl = new FormControl("", [Validators.required, CustomValidators.number()])
// check for valid number and min value
var numberControl = new FormControl("", CustomValidators.number({min: 0}))
// check for valid number and max value
var numberControl = new FormControl("", CustomValidators.number({max: 20}))
// check for valid number and value range ie: [0-20]
var numberControl = new FormControl("", CustomValidators.number({min: 0, max: 20}))
A simplified version, I had a similar issue to this when using the Google Maps JS SDK.
My solution was to extract the div
and ViewChild
into it's own child component which when used in the parent component was able to be hid/displayed using an *ngIf
.
Before
HomePageComponent
Template
<div *ngIf="showMap">
<div #map id="map" class="map-container"></div>
</div>
HomePageComponent
Component
@ViewChild('map') public mapElement: ElementRef;
public ionViewDidLoad() {
this.loadMap();
});
private loadMap() {
const latLng = new google.maps.LatLng(-1234, 4567);
const mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
public toggleMap() {
this.showMap = !this.showMap;
}
After
MapComponent
Template
<div>
<div #map id="map" class="map-container"></div>
</div>
MapComponent
Component
@ViewChild('map') public mapElement: ElementRef;
public ngOnInit() {
this.loadMap();
});
private loadMap() {
const latLng = new google.maps.LatLng(-1234, 4567);
const mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
HomePageComponent
Template
<map *ngIf="showMap"></map>
HomePageComponent
Component
public toggleMap() {
this.showMap = !this.showMap;
}
For some reason in Angular 6 simply importing the FormsModule did not fix my issue. What finally fixed my issue was by adding
import { CommonModule } from '@angular/common';
@NgModule({
imports: [CommonModule],
})
export class MyClass{
}
I had this error when I had specified fromGroupName instead of formArrayName.
Make sure you correctly specify if it is a form array or form group.
<div formGroupName="formInfo"/>
<div formArrayName="formInfo"/>
This is a few months late but I thought I'd provide my solution based on this here tutorial. The gist of it is that it's a lot easier to manage once you change the way you approach forms.
First, use ReactiveFormsModule
instead of or in addition to the normal FormsModule
. With reactive forms you create your forms in your components/services and then plug them into your page instead of your page generating the form itself. It's a bit more code but it's a lot more testable, a lot more flexible, and as far as I can tell the best way to make a lot of non-trivial forms.
The end result will look a little like this, conceptually:
You have one base FormGroup
with whatever FormControl
instances you need for the entirety of the form. For example, as in the tutorial I linked to, lets say you want a form where a user can input their name once and then any number of addresses. All of the one-time field inputs would be in this base form group.
Inside that FormGroup
instance there will be one or more FormArray
instances. A FormArray
is basically a way to group multiple controls together and iterate over them. You can also put multiple FormGroup
instances in your array and use those as essentially "mini-forms" nested within your larger form.
By nesting multiple FormGroup
and/or FormControl
instances within a dynamic FormArray
, you can control validity and manage the form as one, big, reactive piece made up of several dynamic parts. For example, if you want to check if every single input is valid before allowing the user to submit, the validity of one sub-form will "bubble up" to the top-level form and the entire form becomes invalid, making it easy to manage dynamic inputs.
As a FormArray
is, essentially, a wrapper around an array interface but for form pieces, you can push, pop, insert, and remove controls at any time without recreating the form or doing complex interactions.
In case the tutorial I linked to goes down, here some sample code you can implement yourself (my examples use TypeScript) that illustrate the basic ideas:
Base Component code:
import { Component, Input, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'my-form-component',
templateUrl: './my-form.component.html'
})
export class MyFormComponent implements OnInit {
@Input() inputArray: ArrayType[];
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
let newForm = this.fb.group({
appearsOnce: ['InitialValue', [Validators.required, Validators.maxLength(25)]],
formArray: this.fb.array([])
});
const arrayControl = <FormArray>newForm.controls['formArray'];
this.inputArray.forEach(item => {
let newGroup = this.fb.group({
itemPropertyOne: ['InitialValue', [Validators.required]],
itemPropertyTwo: ['InitialValue', [Validators.minLength(5), Validators.maxLength(20)]]
});
arrayControl.push(newGroup);
});
this.myForm = newForm;
}
addInput(): void {
const arrayControl = <FormArray>this.myForm.controls['formArray'];
let newGroup = this.fb.group({
/* Fill this in identically to the one in ngOnInit */
});
arrayControl.push(newGroup);
}
delInput(index: number): void {
const arrayControl = <FormArray>this.myForm.controls['formArray'];
arrayControl.removeAt(index);
}
onSubmit(): void {
console.log(this.myForm.value);
// Your form value is outputted as a JavaScript object.
// Parse it as JSON or take the values necessary to use as you like
}
}
Sub-Component Code: (one for each new input field, to keep things clean)
import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'my-form-sub-component',
templateUrl: './my-form-sub-component.html'
})
export class MyFormSubComponent {
@Input() myForm: FormGroup; // This component is passed a FormGroup from the base component template
}
Base Component HTML
<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
<label>Appears Once:</label>
<input type="text" formControlName="appearsOnce" />
<div formArrayName="formArray">
<div *ngFor="let control of myForm.controls['formArray'].controls; let i = index">
<button type="button" (click)="delInput(i)">Delete</button>
<my-form-sub-component [myForm]="myForm.controls.formArray.controls[i]"></my-form-sub-component>
</div>
</div>
<button type="button" (click)="addInput()">Add</button>
<button type="submit" [disabled]="!myForm.valid">Save</button>
</form>
Sub-Component HTML
<div [formGroup]="form">
<label>Property One: </label>
<input type="text" formControlName="propertyOne"/>
<label >Property Two: </label>
<input type="number" formControlName="propertyTwo"/>
</div>
In the above code I basically have a component that represents the base of the form and then each sub-component manages its own FormGroup
instance within the FormArray
situated inside the base FormGroup
. The base template passes along the sub-group to the sub-component and then you can handle validation for the entire form dynamically.
Also, this makes it trivial to re-order component by strategically inserting and removing them from the form. It works with (seemingly) any number of inputs as they don't conflict with names (a big downside of template-driven forms as far as I'm aware) and you still retain pretty much automatic validation. The only "downside" of this approach is, besides writing a little more code, you do have to relearn how forms work. However, this will open up possibilities for much larger and more dynamic forms as you go on.
If you have any questions or want to point out some errors, go ahead. I just typed up the above code based on something I did myself this past week with the names changed and other misc. properties left out, but it should be straightforward. The only major difference between the above code and my own is that I moved all of the form-building to a separate service that's called from the component so it's a bit less messy.
This works for me.
<select formControlName="preferredBankAccountId" class="form-control" value="">
<option value="">Please select</option>
<option *ngFor="let item of societyAccountDtos" [value]="item.societyAccountId" >{{item.nickName}}</option>
</select>
Not sure this is valid or not, correct me if it's wrong.
Correct me if this should not be like this.
In html:
<input (keypress)="onlyNumber(event)"/>
In Component:
onlyNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
Alternative Solution:
This answer of Thierry Templier is an alternative way to get around the problem.
After some questions with Thierry Templier, I came to the following working example that meets my expectations as an alternative to inheritance limitation mentioned in this question:
1 - Create custom decorator:
export function CustomComponent(annotation: any) {
return function (target: Function) {
var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
var parentAnnotation = parentAnnotations[0];
Object.keys(parentAnnotation).forEach(key => {
if (isPresent(parentAnnotation[key])) {
// verify is annotation typeof function
if(typeof annotation[key] === 'function'){
annotation[key] = annotation[key].call(this, parentAnnotation[key]);
}else if(
// force override in annotation base
!isPresent(annotation[key])
){
annotation[key] = parentAnnotation[key];
}
}
});
var metadata = new Component(annotation);
Reflect.defineMetadata('annotations', [ metadata ], target);
}
}
2 - Base Component with @Component decorator:
@Component({
// create seletor base for test override property
selector: 'master',
template: `
<div>Test</div>
`
})
export class AbstractComponent {
}
3 - Sub component with @CustomComponent decorator:
@CustomComponent({
// override property annotation
//selector: 'sub',
selector: (parentSelector) => { return parentSelector + 'sub'}
})
export class SubComponent extends AbstractComponent {
constructor() {
}
}
You need to leverage the @ViewChild
decorator to reference the child component from the parent one by injection:
import { Component, ViewChild } from 'angular2/core';
(...)
@Component({
selector: 'my-app',
template: `
<h1>My First Angular 2 App</h1>
<child></child>
<button (click)="submit()">Submit</button>
`,
directives:[App]
})
export class AppComponent {
@ViewChild(Child) child:Child;
(...)
someOtherMethod() {
this.searchBar.someMethod();
}
}
Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.
You can notice that the @Query
parameter decorator could also be used:
export class AppComponent {
constructor(@Query(Child) children:QueryList<Child>) {
this.childcmp = children.first();
}
(...)
}
Tested on Angular 11. I need an extra object 'typeSelected'. Pay attention I'm not using [(ngValue)] as other answers do :
HTML
<mat-select formControlName="type" [(value)]="typeSelected" [compareWith]="typeComparation">
<mat-option *ngFor="let myType of allSurveysTypes" [value]="myType">
{{myType.title}}
</mat-option>
</mat-select>
CODE
// declaration
typeSelected: SurveyType;
...
// assigning variable 'type' of object 'survey' to 'typeSelected'
this.typeSelected = survey?.type;
...
// function to compare SurveyType objects
typeComparation = ( option, value ) => {
if (option && value) {
return option.id === value.id;
}
}
You can find more information about the date pipe here, such as formats.
If you want to use it in your component, you can simply do
pipe = new DatePipe('en-US'); // Use your own locale
Now, you can simply use its transform method, which will be
const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');
There's a real nice library that does this among other nice pipes. It's called ngx-pipes.
For example, keys pipe returns keys for an object, and values pipe returns values for an object:
keys pipe
<div *ngFor="let key of {foo: 1, bar: 2} | keys">{{key}}</div>
<!-- Output: 'foo' and 'bar -->
values pipe
<div *ngFor="let value of {foo: 1, bar: 2} | values">{{value}}</div>
<!-- Output: 1 and 2 -->
No need to create your own custom pipe :)
The other answers are correct but you can omit the [attr.data-index]
altogether and just use
<ul>
<li *ngFor="let item of items; let i = index">{{i + 1}}</li>
</ul
I ran into this issue today. I found an solution on GitHub that does not require going to a later version of the beta.
Add the following script to your html:
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
This resolved the problem for me. For more details, you can follow the github issue here: https://github.com/angular/angular/issues/7144
import { HttpClientModule } from '@angular/common/http';
The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below
http.get('friends.json').subscribe(result => this.result =result);
Now as from angular2 beta 8 we can use *ngIf
and *ngFor
on same component see here.
Alternate:
Sometimes we can't use HTML tags inside another like in tr
, th
(table
) or in li
(ul
). We cannot use another HTML tag but we have to perform some action in same situation so we can HTML5 feature tag <template>
in this way.
<template ngFor #abc [ngForOf]="someArray">
code here....
</template>
<template [ngIf]="show">
code here....
</template>
For more information about structural directives in angular2 see here.
For angular 5+
version. Putting version helps as angular makes lot of changes.
ngOnInit() {
this.myForm = formBuilder.group({
firstName: 'Thomas',
lastName: 'Mann'
})
this.formControlValueChanged() // Note if you are doing an edit/fetching data from an observer this must be called only after your form is properly initialized otherwise you will get error.
}
formControlValueChanged(): void {
this.myForm.valueChanges.subscribe(value => {
console.log('value changed', value)
})
}
Copying the answer from Chris:
Got it working:
import {AfterViewInit} from 'angular2/core';
export class HomeCmp implements AfterViewInit {
ngAfterViewInit() {
//Copy in all the js code from the script.js. Typescript will complain but it works just fine
}
This is not valid TypeScript code. You can not have method invocations in the body of a class.
// INVALID CODE
export class AppComponent {
public n: number = 1;
setTimeout(function() {
n = n + 10;
}, 1000);
}
Instead move the setTimeout
call to the constructor
of the class. Additionally, use the arrow function =>
to gain access to this
.
export class AppComponent {
public n: number = 1;
constructor() {
setTimeout(() => {
this.n = this.n + 10;
}, 1000);
}
}
In TypeScript, you can only refer to class properties or methods via this
. That's why the arrow function =>
is important.
Update:
Separate the event and property bindings:
<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
console.log(newValue);
this.selectedItem = newValue; // don't forget to update the model here
// ... do other stuff here ...
}
You could also use
<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">
and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.
Old answer, before they fixed a bug in beta.1:
Create a local template variable and attach a (change)
event:
<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">
See also How can I get new selection in "select" in Angular 2?
You just have to update your message in the right lifecycle hook, in this case is ngAfterContentChecked
instead of ngAfterViewInit
, because in ngAfterViewInit a check for the variable message has been started but is not yet ended.
see: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#afterview
so the code will be just:
import { Component } from 'angular2/core'
@Component({
selector: 'my-app',
template: `<div>I'm {{message}} </div>`,
})
export class App {
message: string = 'loading :(';
ngAfterContentChecked() {
this.message = 'all done loading :)'
}
}
see the working demo on Plunker.
Check project configuration. Linker->System->SubSystem should be Windows.
Using AngularJS
1.6.9+
There is one more incident, it also happen when you declare variable name different of module name.
var indexPageApp = angular.module('indexApp', []);
to get rid of this error,
Error: [$injector:nomod] Module 'indexPageApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
change the module name similar to var declared name or vice versa -
var indexPageApp = angular.module('indexPageApp', []);
Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945
Also, the Angular docs now have a cookbook example that uses a Subject.
Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.
Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.
nav.service.ts
import {EventEmitter} from 'angular2/core';
export class NavService {
navchange: EventEmitter<number> = new EventEmitter();
constructor() {}
emitNavChangeEvent(number) {
this.navchange.emit(number);
}
getNavChangeEmitter() {
return this.navchange;
}
}
components.ts
import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';
@Component({
selector: 'obs-comp',
template: `obs component, item: {{item}}`
})
export class ObservingComponent {
item: number = 0;
subscription: any;
constructor(private navService:NavService) {}
ngOnInit() {
this.subscription = this.navService.getNavChangeEmitter()
.subscribe(item => this.selectedNavItem(item));
}
selectedNavItem(item: number) {
this.item = item;
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
@Component({
selector: 'my-nav',
template:`
<div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
<div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
`,
})
export class Navigation {
item = 1;
constructor(private navService:NavService) {}
selectedNavItem(item: number) {
console.log('selected nav item ' + item);
this.navService.emitNavChangeEvent(item);
}
}
As answered above, the right answer is to compile everything with VS2015, but for interest the following is my analysis of the problem.
This symbol does not appear to be defined in any static library provided by Microsoft as part of VS2015, which is rather peculiar since all others are. To discover why, we need to look at the declaration of that function and, more importantly, how it's used.
Here's a snippet from the Visual Studio 2008 headers:
_CRTIMP FILE * __cdecl __iob_func(void);
#define stdin (&__iob_func()[0])
#define stdout (&__iob_func()[1])
#define stderr (&__iob_func()[2])
So we can see that the job of the function is to return the start of an array of FILE objects (not handles, the "FILE *" is the handle, FILE is the underlying opaque data structure storing the important state goodies). The users of this function are the three macros stdin, stdout and stderr which are used for various fscanf, fprintf style calls.
Now let's take a look at how Visual Studio 2015 defines the same things:
_ACRTIMP_ALT FILE* __cdecl __acrt_iob_func(unsigned);
#define stdin (__acrt_iob_func(0))
#define stdout (__acrt_iob_func(1))
#define stderr (__acrt_iob_func(2))
So the approach has changed for the replacement function to now return the file handle rather than the address of the array of file objects, and the macros have changed to simply call the function passing in an identifying number.
So why can't they/we provide a compatible API? There are two key rules which Microsoft can't contravene in terms of their original implementation via __iob_func:
Any change in either of the above would mean existing compiled code linked against that would go badly wrong if that API is called.
Let's take a look at how FILE was/is defined.
First the VS2008 FILE definition:
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
And now the VS2015 FILE definition:
typedef struct _iobuf
{
void* _Placeholder;
} FILE;
So there is the crux of it: the structure has changed shape. Existing compiled code referring to __iob_func relies upon the fact that the data returned is both an array that can be indexed and that in that array the elements are the same distance apart.
The possible solutions mentioned in the answers above along these lines would not work (if called) for a few reasons:
FILE _iob[] = {*stdin, *stdout, *stderr};
extern "C" FILE * __cdecl __iob_func(void)
{
return _iob;
}
The FILE array _iob would be compiled with VS2015 and so it would be laid out as a block of structures containing a void*. Assuming 32-bit alignment, these elements would be 4 bytes apart. So _iob[0] is at offset 0, _iob[1] is at offset 4 and _iob[2] is at offset 8. The calling code will instead expect FILE to be much longer, aligned at 32 bytes on my system, and so it will take the address of the returned array and add 0 bytes to get to element zero (that one is okay), but for _iob[1] it will deduce that it needs to add 32 bytes and for _iob[2] it will deduce that it needs to add 64-bytes (because that's how it looked in the VS2008 headers). And indeed the disassembled code for VS2008 demonstrates this.
A secondary issue with the above solution is that it copies the content of the FILE structure (*stdin), not the FILE * handle. So any VS2008 code would be looking at a different underlying structure to VS2015. This might work if the structure only contained pointers, but that's a big risk. In any case the first issue renders this irrelevant.
The only hack I've been able to dream up is one in which __iob_func walks the call stack to work out which actual file handle they are looking for (based on the offset added to the returned address) and returns a computed value such that it gives the right answer. This is every bit as insane as it sounds, but the prototype for x86 only (not x64) is listed below for your amusement. It worked okay in my experiments, but your mileage may vary - not recommended for production use!
#include <windows.h>
#include <stdio.h>
#include <dbghelp.h>
/* #define LOG */
#if defined(_M_IX86)
#define GET_CURRENT_CONTEXT(c, contextFlags) \
do { \
c.ContextFlags = contextFlags; \
__asm call x \
__asm x: pop eax \
__asm mov c.Eip, eax \
__asm mov c.Ebp, ebp \
__asm mov c.Esp, esp \
} while(0);
#else
/* This should work for 64-bit apps, but doesn't */
#define GET_CURRENT_CONTEXT(c, contextFlags) \
do { \
c.ContextFlags = contextFlags; \
RtlCaptureContext(&c); \
} while(0);
#endif
FILE * __cdecl __iob_func(void)
{
CONTEXT c = { 0 };
STACKFRAME64 s = { 0 };
DWORD imageType;
HANDLE hThread = GetCurrentThread();
HANDLE hProcess = GetCurrentProcess();
GET_CURRENT_CONTEXT(c, CONTEXT_FULL);
#ifdef _M_IX86
imageType = IMAGE_FILE_MACHINE_I386;
s.AddrPC.Offset = c.Eip;
s.AddrPC.Mode = AddrModeFlat;
s.AddrFrame.Offset = c.Ebp;
s.AddrFrame.Mode = AddrModeFlat;
s.AddrStack.Offset = c.Esp;
s.AddrStack.Mode = AddrModeFlat;
#elif _M_X64
imageType = IMAGE_FILE_MACHINE_AMD64;
s.AddrPC.Offset = c.Rip;
s.AddrPC.Mode = AddrModeFlat;
s.AddrFrame.Offset = c.Rsp;
s.AddrFrame.Mode = AddrModeFlat;
s.AddrStack.Offset = c.Rsp;
s.AddrStack.Mode = AddrModeFlat;
#elif _M_IA64
imageType = IMAGE_FILE_MACHINE_IA64;
s.AddrPC.Offset = c.StIIP;
s.AddrPC.Mode = AddrModeFlat;
s.AddrFrame.Offset = c.IntSp;
s.AddrFrame.Mode = AddrModeFlat;
s.AddrBStore.Offset = c.RsBSP;
s.AddrBStore.Mode = AddrModeFlat;
s.AddrStack.Offset = c.IntSp;
s.AddrStack.Mode = AddrModeFlat;
#else
#error "Platform not supported!"
#endif
if (!StackWalk64(imageType, hProcess, hThread, &s, &c, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL))
{
#ifdef LOG
printf("Error: 0x%08X (Address: %p)\n", GetLastError(), (LPVOID)s.AddrPC.Offset);
#endif
return NULL;
}
if (s.AddrReturn.Offset == 0)
{
return NULL;
}
{
unsigned char const * assembly = (unsigned char const *)(s.AddrReturn.Offset);
#ifdef LOG
printf("Code bytes proceeding call to __iob_func: %p: %02X,%02X,%02X\n", assembly, *assembly, *(assembly + 1), *(assembly + 2));
#endif
if (*assembly == 0x83 && *(assembly + 1) == 0xC0 && (*(assembly + 2) == 0x20 || *(assembly + 2) == 0x40))
{
if (*(assembly + 2) == 32)
{
return (FILE*)((unsigned char *)stdout - 32);
}
if (*(assembly + 2) == 64)
{
return (FILE*)((unsigned char *)stderr - 64);
}
}
else
{
return stdin;
}
}
return NULL;
}
There is a function called shift()
.
It will remove the first element of your array.
There is some good documentation and examples.
IE.Document.getElementById("dgTime").getElementsByTagName("a")(0).Click
EDIT: to loop through the collection (items should appear in the same order as they are in the source document)
Dim links, link
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
'For Each loop
For Each link in links
link.Click
Next link
'For Next loop
Dim n, i
n = links.length
For i = 0 to n-1 Step 2
links(i).click
Next I
If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.
Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Package version are very important.
I found some stable combination that works on my Windows10 64 bit machine:
pip install numpy-1.12.0+mkl-cp36-cp36m-win64.whl
pip install scipy-0.18.1-cp36-cp36m-win64.whl
pip install matplotlib-2.0.0-cp36-cp36m-win64.whl
When you want to create interval store promise to variable:
var p = $interval(function() { ... },1000);
And when you want to stop / clear the interval simply use:
$interval.cancel(p);
I've got the same issue, my model is binding from another form, I've added ng-change
and ng-model
and it still doesn't work:
<input type="hidden" id="pdf-url" class="form-control" ng-model="pdfUrl"/>
<ng-dropzone
dropzone="dropzone"
dropzone-config="dropzoneButtonCfg"
model="pdfUrl">
</ng-dropzone>
An input #pdf-url
gets data from dropzone (two ways binding), however, ng-change
doesn't work in this case. $scope.$watch
is a solution for me:
$scope.$watch('pdfUrl', function updatePdfUrl(newPdfUrl, oldPdfUrl) {
if (newPdfUrl !== oldPdfUrl) {
// It's updated - Do something you want here.
}
});
Hope this help.
A simple fix for this is to install the Google Cast extension. If you don't have a Chromecast, or don't want to use the extension, no problem; just don't use the extension.
I edited your plunker to include ABOS's solution.
<body ng-controller="MainCtrl">
<ul ng-repeat='item in items'>
<li ng-if='item.color'>The color is {{item.color}}</li>
<li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
</ul>
</body>
Update: After several attempts, it looks like this may have been fixed in latest Chrome builds (per Paul Irish's comment below). That would suggest we will see this fixed in stable Chrome June-July 2016. Let's see ...
This is a known bug with the official Chromecast JavaScript library. Instead of failing silently, it dumps these error messages in all non-Chrome browsers as well as Chrome browsers where the Chromecast extension isn't present.
The Chromecast team have indicated they won't fix this bug.
If you are a developer shipping with this library, you can't do anything about it according to Chromecast team. You can only inform users to ignore the errors. (I believe Chromecast team is not entirely correct as the library could, at the least, avoid requesting the extension scipt if the browser is not Chrome. And I suspect it could be possible to suppress the error even if it is Chrome, but haven't tried anything.)
If you are a user annoyed by these console messages, you can switch to Chrome if not using it already. Within Chrome, either:
Update [Nov 13, 2014]: The problem has now been acknowledged by Google. A member of the Chromecast team seems to suggest the issue will be bypassed by a change the team is currently working on.
Update 2 [Feb 17, 2015]: The team claim there's nothing they can do to remove the error logs as it's a standard Chrome network error and they are still working on a long-term fix. Public comments on the bug tracker were closed with that update.
Update 3 [Dec 4, 2015]: This has finally been fixed! In the end, Chrome team simply added some code to block out this specific error. Hopefully some combination of devtools and extensions API will be improved in the future to make it possible to fix this kind of problem without patching the browser. Chrome Canary already has the patch, so it should roll out to all users around mid-January. Additionally, the team has confirmed the issue no longer affects other browsers as the SDK was updated to only activate if it's in Chrome.
Update 4 (April 30): Nope, not yet anyway. Thankfully Google's developer relations team are more aware than certain other stakeholders how badly this has affected developer experience. More whitelist updates have recently been made to clobber these log messages. Current status at top of the post.
Steps to change the default date format of ng-model
For different date formats check the jqueryui datepicker date format values here for example I have used dd/mm/yy
Create angularjs directive
angular.module('app', ['ui.bootstrap']).directive('dt', function () {
return {
restrict: 'EAC',
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
ngModel.$parsers.push(function (viewValue) {
return dateFilter(viewValue, 'dd/mm/yy');
});
}
}
});
Write dateFilter function
function dateFilter(val,format) {
return $.datepicker.formatDate(format,val);
}
In html page write the ng-modal attribute
<input type="text" class="form-control" date-type="string" uib-datepicker-popup="{{format}}" ng-model="src.pTO_DATE" is-open="popup2.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" show-button-bar="false" show-weeks="false" dt />
Update: Disabling the href works better in the link function return. Code below has been updated.
aDisabled
naturally executes before ngClick
because directives are sorted in alphabetical order. When aDisabled
is renamed to tagDisabled
, the directive does not work.
To "disable" the "a" tag, I'd want the following things:
href
links not to be followed when clickedngClick
events not to fire when clickeddisabled
classThis directive does this by mimicking the ngDisabled directive. Based on the value of a-disabled
directive, all of the above features are toggled.
myApp.directive('aDisabled', function() {
return {
compile: function(tElement, tAttrs, transclude) {
//Disable ngClick
tAttrs["ngClick"] = "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")";
//return a link function
return function (scope, iElement, iAttrs) {
//Toggle "disabled" to class when aDisabled becomes true
scope.$watch(iAttrs["aDisabled"], function(newValue) {
if (newValue !== undefined) {
iElement.toggleClass("disabled", newValue);
}
});
//Disable href on click
iElement.on("click", function(e) {
if (scope.$eval(iAttrs["aDisabled"])) {
e.preventDefault();
}
});
};
}
};
});
Here is a css style that might indicate a disabled tag:
a.disabled {
color: #AAAAAA;
cursor: default;
pointer-events: none;
text-decoration: none;
}
replace:true
is DeprecatedFrom the Docs:
replace
([DEPRECATED!], will be removed in next major release - i.e. v2.0)specify what the template should replace. Defaults to
false
.
true
- the template will replace the directive's element.false
- the template will replace the contents of the directive's element.
-- AngularJS Comprehensive Directive API
From GitHub:
Caitp-- It's deprecated because there are known, very silly problems with
replace: true
, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".
Note:
replace: true
is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.
transclude: element
in the replace template root can have unexpected effectsFor more information, see
You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:
var app = angular.module("ap",[]);_x000D_
_x000D_
app.controller("con",function($scope){_x000D_
$scope.class = "red";_x000D_
$scope.changeClass = function(){_x000D_
if ($scope.class === "red")_x000D_
$scope.class = "blue";_x000D_
else_x000D_
$scope.class = "red";_x000D_
};_x000D_
});
_x000D_
.red{_x000D_
color:red;_x000D_
}_x000D_
_x000D_
.blue{_x000D_
color:blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<body ng-app="ap" ng-controller="con">_x000D_
<div ng-class="class">{{class}}</div>_x000D_
<button ng-click="changeClass()">Change Class</button> _x000D_
</body>
_x000D_
Here is the example working on jsFiddle
item.date = $filter('date')(item.date, "dd/MM/yyyy"); // for conversion to string
http://docs.angularjs.org/api/ng.filter:date
But if you are using HTML5 type="date" then the ISO format yyyy-MM-dd MUST be used.
item.dateAsString = $filter('date')(item.date, "yyyy-MM-dd"); // for type="date" binding
<input type="date" ng-model="item.dateAsString" value="{{ item.dateAsString }}" pattern="dd/MM/YYYY"/>
http://www.w3.org/TR/html-markup/input.date.html
NOTE: use of pattern="" with type="date" looks non-standard, but it appears to work in the expected way in Chrome 31.
Nothing wrong with the other answers, but I use the following technique when passing functions in a directive attribute.
Leave off the parenthesis when including the directive in your html:
<my-directive callback="someFunction" />
Then "unwrap" the function in your directive's link or controller. here is an example:
app.directive("myDirective", function() {
return {
restrict: "E",
scope: {
callback: "&"
},
template: "<div ng-click='callback(data)'></div>", // call function this way...
link: function(scope, element, attrs) {
// unwrap the function
scope.callback = scope.callback();
scope.data = "data from somewhere";
element.bind("click",function() {
scope.$apply(function() {
callback(data); // ...or this way
});
});
}
}
}]);
The "unwrapping" step allows the function to be called using a more natural syntax. It also ensures that the directive works properly even when nested within other directives that may pass the function. If you did not do the unwrapping, then if you have a scenario like this:
<outer-directive callback="someFunction" >
<middle-directive callback="callback" >
<inner-directive callback="callback" />
</middle-directive>
</outer-directive>
Then you would end up with something like this in your inner-directive:
callback()()()(data);
Which would fail in other nesting scenarios.
I adapted this technique from an excellent article by Dan Wahlin at http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-3-isolate-scope-and-function-parameters
I added the unwrapping step to make calling the function more natural and to solve for the nesting issue which I had encountered in a project.
It turned out I was using .c files with .cpp files. Renaming .c to .cpp solved my problem.
I needed to execute an directive AFTER loading several templates so I created this directive:
utilModule.directive('utPreload',_x000D_
['$templateRequest', '$templateCache', '$q', '$compile', '$rootScope',_x000D_
function($templateRequest, $templateCache, $q, $compile, $rootScope) {_x000D_
'use strict';_x000D_
var link = function(scope, element) {_x000D_
scope.$watch('done', function(done) {_x000D_
if(done === true) {_x000D_
var html = "";_x000D_
if(scope.slvAppend === true) {_x000D_
scope.urls.forEach(function(url) {_x000D_
html += $templateCache.get(url);_x000D_
});_x000D_
}_x000D_
html += scope.slvHtml;_x000D_
element.append($compile(html)($rootScope));_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
var controller = function($scope) {_x000D_
$scope.done = false;_x000D_
$scope.html = "";_x000D_
$scope.urls = $scope.slvTemplate.split(',');_x000D_
var promises = [];_x000D_
$scope.urls.forEach(function(url) {_x000D_
promises.add($templateRequest(url));_x000D_
});_x000D_
$q.all(promises).then(_x000D_
function() { // SUCCESS_x000D_
$scope.done = true;_x000D_
}, function() { // FAIL_x000D_
throw new Error('preload failed.');_x000D_
}_x000D_
);_x000D_
};_x000D_
_x000D_
return {_x000D_
restrict: 'A',_x000D_
scope: {_x000D_
utTemplate: '=', // the templates to load (comma separated)_x000D_
utAppend: '=', // boolean: append templates to DOM after load?_x000D_
utHtml: '=' // the html to append and compile after templates have been loaded_x000D_
},_x000D_
link: link,_x000D_
controller: controller_x000D_
};_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
_x000D_
<div class="container-fluid"_x000D_
ut-preload_x000D_
ut-append="true"_x000D_
ut-template="'html/one.html,html/two.html'"_x000D_
ut-html="'<my-directive></my-directive>'">_x000D_
_x000D_
</div>
_x000D_
Since it's in bootstrap 3, the site will be using jQuery. So the solution could also be the following, instead of trying to play with complex CSS:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="css/bootstrap.min.css" rel="stylesheet" />
<style>
.my-footer {
border-radius : 0px;
margin : 0px; /* pesky margin below .navbar */
position : absolute;
width : 100%;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<!-- Content of any length -->
asdfasdfasdfasdfs <br />
asdfasdfasdfasdfs <br />
asdfasdfasdfasdfs <br />
</div>
</div>
<div class="navbar navbar-inverse my-footer">
<div class="container-fluid">
<div class="row">
<p class="navbar-text">My footer content goes here...</p>
</div>
</div>
</div>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var $docH = $(document).height();
// The document height will grow as the content on the page grows.
$('.my-footer').css({
/*
The default height of .navbar is 50px with a 1px border,
change this 52 if you change the height of your footer.
*/
top: ($docH - 52) + 'px'
});
});
</script>
</body>
</html>
A different take on it, hope it helps.
Kind regards.
You are trying to link objects compiled by different versions of the compiler. That's not supported in modern versions of VS, at least not if you are using the C++ standard library. Different versions of the standard library are binary incompatible and so you need all the inputs to the linker to be compiled with the same version. Make sure you re-compile all the objects that are to be linked.
The compiler error names the objects involved so the information the the question already has the answer you are looking for. Specifically it seems that the static library that you are linking needs to be re-compiled.
So the solution is to recompile Projectname1.lib with VS2012.
Your define following in router.js
$stateProvider.state('users', {
url: '/users',
controller: 'UsersCtrl',
params: {
obj: null
}
})
Your controller need add $stateParams.
function UserCtrl($stateParams) {
console.log($stateParams);
}
You can send an object by parameter as follows.
$state.go('users', {obj:yourObj});
You probably want to have LI rather than the UL have the background-color:
.selected li {
background-color: red;
}
Then you want to have a dynamic class for the UL:
<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">
Now you need to update the $scope.selected when clicking the row:
$scope.setSelected = function() {
console.log("show", arguments, this);
this.selected = 'selected';
}
and then un-select the previously highlighted row:
$scope.setSelected = function() {
// console.log("show", arguments, this);
if ($scope.lastSelected) {
$scope.lastSelected.selected = '';
}
this.selected = 'selected';
$scope.lastSelected = this;
}
Working solution:
NullPointerException with JSP can also happen if:
A getter returns a non-public inner class.
This code will fail if you remove Getters's access modifier or make it private or protected.
JAVA:
package com.myPackage;
public class MyClass{
//: Must be public or you will get:
//: org.apache.jasper.JasperException:
//: java.lang.NullPointerException
public class Getters{
public String
myProperty(){ return(my_property); }
};;
//: JSP EL can only access functions:
private Getters _get;
public Getters get(){ return _get; }
private String
my_property;
public MyClass(String my_property){
super();
this.my_property = my_property;
_get = new Getters();
};;
};;
JSP
<%@ taglib uri ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
MyClass inst = new MyClass("[PROP_VALUE]");
pageContext.setAttribute("my_inst", inst );
%><html lang="en"><body>
${ my_inst.get().myProperty() }
</body></html>
A complete solution to the validate form with angularjs.
HTML is as follows.
<div ng-app="areaApp" ng-controller="addCtrler">
<form class="form-horizontal" name="fareainfo">
<div class="form-group">
<label for="input-areaname" class="col-sm-2 control-label">Area Name : </label>
<div class="col-sm-4">
<input type="text" class="form-control" name="name" id="input-areaname" ng-model="Area.Name" placeholder="" required>
<span class="text-danger" ng-show="(fareainfo.$submitted || fareainfo.name.$dirty) && fareainfo.name.$error.required"> Field is required</span>
</div>
</div>
<div class="col-sm-12">
<button type="button" class="btn btn-primary pull-right" ng-click="submitAreaInfo()">Submit</button>
</div>
</form>
</div>
AngularJS App and Controller is as follows
var areaApp = angular.module('areaApp', []);
areaApp.controller('addCtrler', function ($scope) {
$scope.submitAreaInfo = function () {
if ($scope.fareainfo.$valid) {
//after Form is Valid
} else {
$scope.fareainfo.$setSubmitted();
}
};
});
ng-app="areaApp" ng-controller="addCtrler"
Defines the angular app and controller
ng-show="(fareainfo.$submitted || fareainfo.name.$dirty) && fareainfo.name.$error.required"
Above condition ensure that whenever a user first sees the form there's no any validation error on the screen and after a user does changes to the form it ensure that validation message show on the screen. .name. is the name attribute of the input element.
$scope.fareainfo.$valid
Above code, segment check whether the form is valid whenever a user submits the form.
$scope.fareainfo.$setSubmitted();
Above code, segment ensures that all validation messages are displayed on the screen whenever a user submits the form without doing anything.
So, the trick here is to use absolute positioning calc
like this:
top: calc(50% - XYpx);
left: calc(50% - XYpx);
where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.
I'm a bit late to the party, but I have my own directive that looks like it'll fit your case (You can adapt it yourself). It's a modification of the ng-repeat directive that's specifically built for list re-ordering via DnD. I built it as I don't like JQuery UI (preference for less libraries than anything else) also I wanted mine to work on touch screens too ;).
Code is here: http://codepen.io/SimeonC/pen/AJIyC
Blog post is here: http://sdevgame.wordpress.com/2013/08/27/angularjs-drag-n-drop-re-order-in-ngrepeat/
You can use id with a message or without. Without message the default message will show.
Directive
app.directive('ngConfirmMessage', [function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('click', function (e) {
var message = attrs.ngConfirmMessage || "Are you sure ?";
if (!confirm(message)) {
e.stopImmediatePropagation();
}
});
}
}
}]);
Controller
$scope.sayHello = function(){
alert("hello")
}
HTML
With a message
<span ng-click="sayHello()" ng-confirm-message="Do you want to say Hello ?" >Say Hello!</span>
Without a messsage
<span ng-click="sayHello()" ng-confirm-message>Say Hello!</span>
The issue here is that ng-repeat
creates its own scope, so when you do selected=$index
it creates a new a selected
property in that scope rather than altering the existing one. To fix this you have two options:
Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:
$scope.selected = {value: 0};
<a ng-click="selected.value = $index">A{{$index}}</a>
or
Use the $parent
variable to access the correct property. Though less recommended as it increases coupling between scopes
<a ng-click="$parent.selected = $index">A{{$index}}</a>
That means that the definition of your function is not present in your program. You forgot to add that one.cpp
to your program.
What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp
to the project.
In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp
is missing.
When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.
In Visual Studio:
Properties ->
Advanced ->
Entry Point ->
write just the name of the function you want the program to begin running from, case sensitive, without any brackets and command line arguments.
Here is my global function for showing the form error messages.
function show_validation_erros(form_error_object) {
angular.forEach(form_error_object, function (objArrayFields, errorName) {
angular.forEach(objArrayFields, function (objArrayField, key) {
objArrayField.$setDirty();
});
});
};
And in my any controllers,
if ($scope.form_add_sale.$invalid) {
$scope.global.show_validation_erros($scope.form_add_sale.$error);
}
There is another way to pristine form that is by sending form into the controller. For example:-
In view:-
<form name="myForm" ng-submit="addUser(myForm)" novalidate>
<input type="text" ng-mode="user.name"/>
<span style="color:red" ng-show="myForm.name.$dirty && myForm.name.$invalid">
<span ng-show="myForm.name.$error.required">Name is required.</span>
</span>
<button ng-disabled="myForm.$invalid">Add User</button>
</form>
In Controller:-
$scope.addUser = function(myForm) {
myForm.$setPristine();
};
ng-model
and ng-checked
directives should not be used togetherFrom the Docs:
ngChecked
Sets the checked attribute on the element, if the expression inside
ngChecked
is truthy.Note that this directive should not be used together with
ngModel
, as this can lead to unexpected behavior.
Instead set the desired initial value from the controller:
<input type="checkbox" name="test" ng-model="testModel['item1']" ?n?g?-?c?h?e?c?k?e?d?=?"?t?r?u?e?"? />
Testing<br />
<input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2<br />
<input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3<br />
<input type="button" ng-click="submit()" value="Submit" />
$scope.testModel = { item1: true };
You can call more of 1 function filters in the same ng-repeat filter
<article data-ng-repeat="result in results | filter:search() | filter:filterFn()" class="result">
Angular syntax is to use the : operator to perform the equivalent of an if modifier
<div ng-class="{ 'clearfix' : (row % 2) == 0 }">
Add clearfix class to even rows. Nonetheless, expression could be anything we can have in normal if condition and it should evaluate to either true or false.
The AngularJS Bootstrap website hasn't been updated with the latest documentation. About 3 months ago pkozlowski-opensource authored a change to separate out $modal from $dialog commit is below:
https://github.com/angular-ui/bootstrap/commit/d7a48523e437b0a94615350a59be1588dbdd86bd
In that commit he added new documentation for $modal, which can be found below:
Hope this helps!
I think it's a better way to bind on the service itself instead of the attributes on it.
Here's why:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<body ng-app="BindToService">
<div ng-controller="BindToServiceCtrl as ctrl">
ArrService.arrOne: <span ng-repeat="v in ArrService.arrOne">{{v}}</span>
<br />
ArrService.arrTwo: <span ng-repeat="v in ArrService.arrTwo">{{v}}</span>
<br />
<br />
<!-- This is empty since $scope.arrOne never changes -->
arrOne: <span ng-repeat="v in arrOne">{{v}}</span>
<br />
<!-- This is not empty since $scope.arrTwo === ArrService.arrTwo -->
<!-- Both of them point the memory space modified by the `push` function below -->
arrTwo: <span ng-repeat="v in arrTwo">{{v}}</span>
</div>
<script type="text/javascript">
var app = angular.module("BindToService", []);
app.controller("BindToServiceCtrl", function ($scope, ArrService) {
$scope.ArrService = ArrService;
$scope.arrOne = ArrService.arrOne;
$scope.arrTwo = ArrService.arrTwo;
});
app.service("ArrService", function ($interval) {
var that = this,
i = 0;
this.arrOne = [];
that.arrTwo = [];
$interval(function () {
// This will change arrOne (the pointer).
// However, $scope.arrOne is still same as the original arrOne.
that.arrOne = that.arrOne.concat([i]);
// This line changes the memory block pointed by arrTwo.
// And arrTwo (the pointer) itself never changes.
that.arrTwo.push(i);
i += 1;
}, 1000);
});
</script>
</body>
You can play it on this plunker.
By using ng-focus you can achieve your goal. you need to provide ng-focus in your input field. And while writing your ng-show derivatives you have to write a logic not equal too. Like the below code:
<input type="text" class="form-control" name="inputPhone" ng-model="demo.phoneNumber" required ng-focus>
<div ng-show="demoForm.inputPhone.$dirty && demoForm.inputPhone.$invalid && !demoForm.inputPhone.$focused"></div>
You can't put variable definitions in header files, as these will then be a part of all source file you include the header into.
The #pragma once
is just to protect against multiple inclusions in the same source file, not against multiple inclusions in multiple source files.
You could declare the variables as extern
in the header file, and then define them in a single source file. Or you could declare the variables as const
in the header file and then the compiler and linker will manage it.
I've modified your plunker to get it working via angular-xeditable:
http://plnkr.co/edit/xUDrOS?p=preview
It is common solution for inline editing - you creale hyperlinks with editable-text
directive
that toggles into <input type="text">
tag:
<a href="#" editable-text="bday.name" ng-click="myform.$show()" e-placeholder="Name">
{{bday.name || 'empty'}}
</a>
For date I used editable-date
directive that toggles into html5 <input type="date">
.
I do recomend doing it in 2 filles (.h .cpp)
But if u lazy just add inline
before the function
So it will look something like this
inline void functionX()
{ }
more about inline functions:
The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of executable instruction etc) then, compiler can ignore the “inline” request and treat the function as normal function.
more info here
Replace [True | False (default)]
Effect
1. Replace the directive element.
Dependency:
1. When replace: true, the template or templateUrl must be required.
Way more elegant solution than $parent.$index
is using ng-init
:
<ul ng-repeat="section in sections" ng-init="sectionIndex = $index">
<li class="section_title {{section.active}}" >
{{section.name}}
</li>
<ul>
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(sectionIndex)" ng-repeat="tutorial in section.tutorials">
{{tutorial.name}}
</li>
</ul>
</ul>
Just to document:
The callback argument previousRoute
is having a property called $route
which is much similar to the $route
service.
Unfortunately currentRoute
argument, is not having much information about the current route.
To overcome this i have tried some thing like this.
$routeProvider.
when('/', {
controller:...,
templateUrl:'...',
routeName:"Home"
}).
when('/menu', {
controller:...,
templateUrl:'...',
routeName:"Site Menu"
})
Please note that in the above routes config a custom property called routeName
is added.
app.run(function($rootScope, $route){
//Bind the `$routeChangeSuccess` event on the rootScope, so that we dont need to
//bind in induvidual controllers.
$rootScope.$on('$routeChangeSuccess', function(currentRoute, previousRoute) {
//This will give the custom property that we have defined while configuring the routes.
console.log($route.current.routeName)
})
})
For command line (i.e. - makefile) users only:
You (like me) probably "tuned" your makefile to #1, above, via something like this:
MS_SDK_BASE_DOS := C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A
ENV_SET := LIB="$(MS_SDK_BASE_DOS)\Lib\x64"
But, now, you need to change that tuning to #2, above, like this:
MS_SDK_BASE_DOS := C:\Program Files\Microsoft SDKs\Windows\v7.1
(Don't miss the "v7.0A" to "v7.1" change, as well.)
HTML has an attribute autofocus
.
<input type="text" name="fname" autofocus>
(This is already answered in comments, but since it lacks an actual answer, I'm writing this.)
This problem arises in newer versions of Visual C++ (the older versions usually just silently linked the program and it would crash and burn at run time.) It means that some of the libraries you are linking with your program (or even some of the source files inside your program itself) are using different versions of the CRT (the C RunTime library.)
To correct this error, you need to go into your Project Properties
(and/or those of the libraries you are using,) then into C/C++
, then Code Generation
, and check the value of Runtime Library
; this should be exactly the same for all the files and libraries you are linking together. (The rules are a little more relaxed for linking with DLLs, but I'm not going to go into the "why" and into more details here.)
There are currently four options for this setting:
Your particular problem seems to stem from you linking a library built with "Multithreaded Debug" (i.e. static multithreaded debug CRT) against a program that is being built using the "Multithreaded Debug DLL" setting (i.e. dynamic multithreaded debug CRT.) You should change this setting either in the library, or in your program. For now, I suggest changing this in your program.
Note that since Visual Studio projects use different sets of project settings for debug and release builds (and 32/64-bit builds) you should make sure the settings match in all of these project configurations.
For (some) more information, you can see these (linked from a comment above):
UPDATE: (This is in response to a comment that asks for the reason that this much care must be taken.)
If two pieces of code that we are linking together are themselves linking against and using the standard library, then the standard library must be the same for both of them, unless great care is taken about how our two code pieces interact and pass around data. Generally, I would say that for almost all situations just use the exact same version of the standard library runtime (regarding debug/release, threads, and obviously the version of Visual C++, among other things like iterator debugging, etc.)
The most important part of the problem is this: having the same idea about the size of objects on either side of a function call.
Consider for example that the above two pieces of code are called A
and B
. A is compiled against one version of the standard library, and B against another. In A's view, some random object that a standard function returns to it (e.g. a block of memory or an iterator or a FILE
object or whatever) has some specific size and layout (remember that structure layout is determined and fixed at compile time in C/C++.) For any of several reasons, B's idea of the size/layout of the same objects is different (it can be because of additional debug information, natural evolution of data structures over time, etc.)
Now, if A calls the standard library and gets an object back, then passes that object to B, and B touches that object in any way, chances are that B will mess that object up (e.g. write the wrong field, or past the end of it, etc.)
The above isn't the only kind of problems that can happen. Internal global or static objects in the standard library can cause problems too. And there are more obscure classes of problems as well.
All this gets weirder in some aspects when using DLLs (dynamic runtime library) instead of libs (static runtime library.)
This situation can apply to any library used by two pieces of code that work together, but the standard library gets used by most (if not almost all) programs, and that increases the chances of clash.
What I've described is obviously a watered down and simplified version of the actual mess that awaits you if you mix library versions. I hope that it gives you an idea of why you shouldn't do it!
My answer to this quesiton.
Modify file C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\vcvarsqueryregistry.bat
The content of :GetWin10SdkDir
From
@REM ---------------------------------------------------------------------------
:GetWin10SdkDir
@call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE > nul 2>&1
@if errorlevel 1 exit /B 1
@exit /B 0
to
@REM ---------------------------------------------------------------------------
:GetWin10SdkDir
@call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE > nul 2>&1
@if errorlevel 1 exit /B 1
@setlocal enableDelayedExpansion
set HostArch=x86
if "%PROCESSOR_ARCHITECTURE%"=="AMD64" ( set "HostArch=x64" )
if "%PROCESSOR_ARCHITECTURE%"=="EM64T" ( set "HostArch=x64" )
if "%PROCESSOR_ARCHITECTURE%"=="ARM64" ( set "HostArch=arm64" )
if "%PROCESSOR_ARCHITECTURE%"=="arm" ( set "HostArch=arm" )
@endlocal & set PATH=%WindowsSdkDir%bin\%WindowsSDKVersion%%HostArch%;%PATH%
@exit /B 0
Modify this single place will enable the support for all Windows 10 sdk along with all build target of visual studio, including
They are all working.
This is a little late answer, but I found this awesome post about NgModelController
, which I think is exactly what you were looking for.
TL;DR - you can use require: 'ngModel'
and then add NgModelController
to your linking function:
link: function(scope, iElement, iAttrs, ngModelCtrl) {
//TODO
}
This way, no hacks needed - you are using Angular's built-in ng-model
2>LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc120-mt-sgd-1_55.lib
In my case, bootstrap/bjam was not available (libraries were precompiled and committed to SCM) on old inherited project. Libraries did not have VC or BOOST versioning in their filenames eg: libboost_regex-mt-sgd.lib
, however Processed /DEFAULTLIB:libboost_regex-vc120-mt-sgd-1_55.lib
was somehow triggered automatically.
Fixed by manually adding the non-versioned filename to:
<AdditionalDependencies>$(DK_BOOST)\lib64\libboost_regex-mt-sgd.lib</AdditionalDependencies>
and blacklisting the ...vc120-mt-sgd-1_55.lib
in
<IgnoreSpecificDefaultLibraries>libboost_regex-vc120-mt-sgd-1_55.lib</IgnoreSpecificDefaultLibraries>
Easier CSS solution independent from select2
//HTML
<select id="" class="input-xlg">
</select>
<input type="text" id="" name="" value="" class="input-lg" />
//CSS
.input-xxsm {
width: 40px!important; //for 2 digits
}
.input-xsm {
width: 60px!important; //for 4 digits
}
.input-sm {
width: 100px!important; //for short options
}
.input-md {
width: 160px!important; //for medium long options
}
.input-lg {
width: 220px!important; //for long options
}
.input-xlg {
width: 300px!important; //for very long options
}
.input-xxlg {
width: 100%!important; //100% of parent
}
Because it is asynchronous, the $scope
is getting the data before the ajax call is complete.
You could use $q
in your service to create promise
and give it back to
controller, and controller obtain the result within then()
call against promise
.
In your service,
app.factory('myService', function($http, $q) {
var deffered = $q.defer();
var data = [];
var myService = {};
myService.async = function() {
$http.get('test.json')
.success(function (d) {
data = d;
console.log(d);
deffered.resolve();
});
return deffered.promise;
};
myService.data = function() { return data; };
return myService;
});
Then, in your controller:
app.controller('MainCtrl', function( myService,$scope) {
myService.async().then(function() {
$scope.data = myService.data();
});
});
I am using Visual Studio 2010.
This happened to me when I installed .NET 4.5. Uninstall of .NET 4.5 and install of .NET 4.0 helped me and error messages disappeared.
well, I actually just saved and closed the project and restarted VS Express 2013 in windows 8 and that sorted my problem.
I had the problem before, but it was solved. The main problem was that I mistakenly spell the int main() function. Instead of writing int main() I wrote int mian()....Cheers !
Reinstalling CMake worked for me. The new copy of CMake figured out that it should use Visual Studio 11 instead of 10.
The linker tells you that you have the variable k
defined multiple times. Indeed, you have a definition in A.cpp and another in B.cpp. Both compilation units produce a corresponding object file that the linker uses to create your program. The problem is that in your case the linker does not know whic definition of k
to use. In C++ you can have only one defintion of the same construct (variable, type, function).
To fix it, you will have to decide what your goal is
k
, you can use an anonymous namespace in both .cpp files, then refer to k
as you are doing now:.
namespace {
int k;
}
k
s to something else, thus avoiding the duplicate defintion.k
and use that in both .cpp files, you need to declare in one as extern int k;
, and leave it as it is in the other. This will tell the linker to use the one definition (the unchanged version) in both cases -- extern
implies that the variable is defined in another compilation unit.Yet another possible problem (that I just scratched my head about for some time):
If you define your functions as inline
, they—of course!—have to be defined in the header (or an inline file), not a cpp.
In my case, they were in an inline file, but only because they were a platform specific implementation, and a cpp included this corresponding inl file… instead of a header. Yeah, s**t happens.
I thought I'd leave this here, too, maybe someone else runs into the same issue and finds it here.
You could also do it more concisely using
driver.find_element_by_id("some_id").size != 0
you need to put it after wp_head(); Because that loads your jQuery and you need to load jQuery first and then your js
You can get the best of both worlds. It is possible to use ExternalProject
to download the gtest source and then use add_subdirectory()
to add it to your build. This has the following advantages:
Used in the normal way, ExternalProject won't do the download and unpacking at configure time (i.e. when CMake is run), but you can get it to do so with just a little bit of work. I've written a blog post on how to do this which also includes a generalised implementation which works for any external project which uses CMake as its build system, not just gtest. You can find them here:
Update: This approach is now also part of the googletest documentation.
I managed to get rid of this error (in my case using Ogre3D + Bullet) by changing the dependency libraries to the debug versions in Project Properties -> Linker -> Input -> Additional Dependencies (VC10).
I changed BulletCollision.lib to BulletCollision_debug.lib (for debug configuration) and it compiled.
Well it seems that you are missing a reference to some library. I had the similar error solved it by adding a reference to the #pragma comment(lib, "windowscodecs.lib")
The easiest way is to create your GridView with some data source in ASP and call that data source in Row_Deletinng Event. For example if you have SqlDataSource1 as your GridView data source, your Row_Deleting event would be:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int ID = int.Parse(GridView1.Rows[e.RowIndex].FindControl("ID").toString());
string delete_command = "DELETE FROM your_table WHERE ID = " + ID;
SqlDataSource1.DeleteCommand = delete_command;
}
Try with below code.
Like GridView in LinkButton, Label, HtmlAnchor and HtmlInputControl.
<asp:GridView ID="mainGrid" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-hover tablesorter"
OnRowDataBound="mainGrid_RowDataBound" EmptyDataText="No Data Found.">
<Columns>
<asp:TemplateField HeaderText="HeaderName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label runat="server" ID="lblName" Text=' <%# Eval("LabelName") %>'></asp:Label>
<asp:LinkButton ID="btnLink" runat="server">ButtonName</asp:LinkButton>
<a href="javascript:void(0);" id="btnAnchor" runat="server">ButtonName</a>
<input type="hidden" runat="server" id="hdnBtnInput" value='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Handling RowDataBound event,
protected void mainGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblName = (Label)e.Row.FindControl("lblName");
LinkButton btnLink = (LinkButton)e.Row.FindControl("btnLink");
HtmlAnchor btnAnchor = (HtmlAnchor)e.Row.FindControl("btnAnchor");
HtmlInputControl hdnBtnInput = (HtmlInputControl)e.Row.FindControl("hdnBtnInput");
}
}
Try using:
@ECHO off
ECHO Hello World!
START /MAX D:\SA\pro\hello.txt
If you are using CMake, you can also get this error when you set SET(GUI_TYPE WIN32)
on a console application.
I had a similar problem in that I was getting LINK1181
errors on the .OBJ
file that was part of the project itself (and there were only 2 .cxx files in the entire project).
Initially I had setup the project to generate an .EXE
in Visual Studio, and then in the
Property Pages -> Configuration Properties -> General -> Project Defaults -> Configuration Type
, I changed the .EXE to .DLL. Suspecting that somehow Visual Studio 2008 was getting confused, I recreated the entire solution from scratch using .DLL mode right from the start. Problem went away after that. I imagine if you manually picked your way through the .vcproj and other related files you could figure out how to fix things without starting from scratch (but my program consisted of two .cpp files so it was easier to start over).
I can't see a new-line after that last brace.
As you know: "If a source file that is not empty does not end in a new-line character, ... the behavior is undefined".
The reason is that the compiler has to actually see the definition in order to be able to drop it in in place of the call.
Remember that C and C++ use a very simplistic compilation model, where the compiler always only sees one translation unit at a time. (This fails for export, which is the main reason only one vendor actually implemented it.)
if you have _tmain
function in your projects you need to include <tchar.h>.
Mine is that if you set MASM listing file option some extra selection, it will give you this error.
Just use
Enable Assembler Generated Code Listing Yes/Sg
Assembled Code Listing $(ProjectName).lst
it is fine.
But any extra you have issue.
This happened to me today because I had added a library directory while still in x86 mode, and accidently removed the inherited directories, making them hardcoded instead. Then after switching to x64, my VC++ Directories still read:
"...;$(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);"
instead of the _x64.
import base64
coded_string = '''Q5YACgA...'''
base64.b64decode(coded_string)
worked for me. At the risk of pasting an offensively-long result, I got:
>>> base64.b64decode(coded_string)
2: 'C\x96\x00\n\x00\x00\x00\x00C\x96\x00\x1b\x00\x00\x00\x00C\x96\x00-\x00\x00\x00\x00C\x96\x00?\x00\x00\x00\x00C\x96\x07M\x00\x00\x00\x00C\x96\x07_\x00\x00\x00\x00C\x96\x07p\x00\x00\x00\x00C\x96\x07\x82\x00\x00\x00\x00C\x96\x07\x94\x00\x00\x00\x00C\x96\x07\xa6Cq\xf0\x7fC\x96\x07\xb8DJ\x81\xc7C\x96\x07\xcaD\xa5\x9dtC\x96\x07\xdcD\xb6\x97\x11C\x96\x07\xeeD\x8b\x8flC\x96\x07\xffD\x03\xd4\xaaC\x96\x08\x11B\x05&\xdcC\x96\x08#\x00\x00\x00\x00C\x96\x085C\x0c\xc9\xb7C\x96\x08GCy\xc0\xebC\x96\x08YC\x81\xa4xC\x96\x08kC\x0f@\x9bC\x96\x08}\x00\x00\x00\x00C\x96\x08\x8e\x00\x00\x00\x00C\x96\x08\xa0\x00\x00\x00\x00C\x96\x08\xb2\x00\x00\x00\x00C\x96\x86\xf9\x00\x00\x00\x00C\x96\x87\x0b\x00\x00\x00\x00C\x96\x87\x1d\x00\x00\x00\x00C\x96\x87/\x00\x00\x00\x00C\x96\x87AA\x0b\xe7PC\x96\x87SCI\xf5gC\x96\x87eC\xd4J\xeaC\x96\x87wD\r\x17EC\x96\x87\x89D\x00F6C\x96\x87\x9bC\x9cg\xdeC\x96\x87\xadB\xd56\x0cC\x96\x87\xbf\x00\x00\x00\x00C\x96\x87\xd1\x00\x00\x00\x00C\x96\x87\xe3\x00\x00\x00\x00C\x96\x87\xf5\x00\x00\x00\x00C\x9cY}\x00\x00\x00\x00C\x9cY\x90\x00\x00\x00\x00C\x9cY\xa4\x00\x00\x00\x00C\x9cY\xb7\x00\x00\x00\x00C\x9cY\xcbC\x1f\xbd\xa3C\x9cY\xdeCCz{C\x9cY\xf1CD\x02\xa7C\x9cZ\x05C+\x9d\x97C\x9cZ\x18C\x03R\xe3C\x9cZ,\x00\x00\x00\x00C\x9cZ?
[stuff omitted as it exceeded SO's body length limits]
\xbb\x00\x00\x00\x00D\xc5!7\x00\x00\x00\x00D\xc5!\xb2\x00\x00\x00\x00D\xc7\x14x\x00\x00\x00\x00D\xc7\x14\xf6\x00\x00\x00\x00D\xc7\x15t\x00\x00\x00\x00D\xc7\x15\xf2\x00\x00\x00\x00D\xc7\x16pC5\x9f\xf9D\xc7\x16\xeeC[\xb5\xf5D\xc7\x17lCG\x1b;D\xc7\x17\xeaB\xe3\x0b\xa6D\xc7\x18h\x00\x00\x00\x00D\xc7\x18\xe6\x00\x00\x00\x00D\xc7\x19d\x00\x00\x00\x00D\xc7\x19\xe2\x00\x00\x00\x00D\xc7\xfe\xb4\x00\x00\x00\x00D\xc7\xff3\x00\x00\x00\x00D\xc7\xff\xb2\x00\x00\x00\x00D\xc8\x001\x00\x00\x00\x00'
What problem are you having, specifically?
Also, linear congruential PRNGs tend to produce more randomness on the higher bits that on the lower bits, so to cap the result don't use modulo, but instead use something like:
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
(This one is from "Numerical Recipes in C", ch.7)
There are 4 versions of the CRT link libraries present in vc\lib:
Look at the linker options, Project + Properties, Linker, Command Line. Note how these libraries are not mentioned here. The linker automatically figures out what /M switch was used by the compiler and which .lib should be linked through a #pragma comment directive. Kinda important, you'd get horrible link errors and hard to diagnose runtime errors if there was a mismatch between the /M option and the .lib you link with.
You'll see the error message you quoted when the linker is told both to link to msvcrt.lib and libcmt.lib. Which will happen if you link code that was compiled with /MT with code that was linked with /MD. There can be only one version of the CRT.
/NODEFAULTLIB tells the linker to ignore the #pragma comment directive that was generated from the /MT compiled code. This might work, although a slew of other linker errors is not uncommon. Things like errno, which is a extern int in the static CRT version but macro-ed to a function in the DLL version. Many others like that.
Well, fix this problem the Right Way, find the .obj or .lib file that you are linking that was compiled with the wrong /M option. If you have no clue then you could find it by grepping the .obj/.lib files for "/MT"
Btw: the Windows executables (like version.dll) have their own CRT version to get their job done. It is located in c:\windows\system32, you cannot reliably use it for your own programs, its CRT headers are not available anywhere. The CRT DLL used by your program has a different name (like msvcrt90.dll).
In my case it appears it was because I had "copied settings" from a 32-bit to a new configuration (64 bit) and it hadn't updated the libraries. Odd.
1>MSVCRTD.lib(ti_inst.obj) : fatal error LNK1112: module machine type ‘X86’ conflicts with target machine type ‘x64’
this meant “your properties -> VC++ Directories -> Library Directories” is pointing to a directory that has 32 bit libs built in it. Fix somehow!
In my case http://social.msdn.microsoft.com/Forums/ar/vcgeneral/thread/c747cd6f-32be-4159-b9d3-d2e33d2bab55
ref: http://betterlogic.com/roger/2012/02/visual-studio-2010-express-64-bit-woe
If you VS solution contains several projects, select all of them in the right pane, and press "properties". Then go to C++ -> Code Generation and chose one Run Time library option for all of them
As to @Marc's answer, I don't think VC uses the path from the OS. Did you add the path to VC's library paths. I usually add the DLLs to the project and copy if newer on the build and that works very well for me.
Ink-Jet is right. More specifically, an .o (.obj) -- or object file is a single source file compiled in to machine code (I'm not sure if the "machine code" is the same or similar to an executable machine code). Ultimately, it's an intermediate between an executable program and plain-text source file.
The linker uses the o files to assemble the file executable.
Wikipedia may have more detailed information. I'm not sure how much info you'd like or need.
Well, it is cool that nobody found the solution for now, but it looks like I have something for you. The bad news is that the dialog grabs focus in any case even if no inputs and links are inside. I use the dialog as a tooltip and definitely need focus stay in the original element. Here is my solution:
use option [autoOpen: false]
$toolTip.dialog("widget").css("visibility", "hidden");
$toolTip.dialog("open");
$toolTip.dialog("widget").css("visibility", "visible");
While the dialog invisible, the focus is not set anywhere and stay in the original place. It works for tooltips with just a plain text, but not tested for more functional dialogs where it may be important to have dialog visible on opening moment. Probably will work fine in any case.
I understand that the original post was just to avoid getting focus on the first element, but you can easily decide where the focus should be after the dialog is opened (after my code).
Tested in IE, FF and Chrome.
Hopefully this will help somebody.
(For the record and before the thread disappears on the msdn forums) You can't disable the warning (at least under VS2010) because it is on the list of the warnings that can't be disabled (so /wd4099 will not work), but what you can do instead is patch link.exe (usually C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\link.exe) to remove it from said list . Sounds like a jackhammer, i know. It works though.
For instance, if you want to remove the warning for 4099, open link.exe with an hex editor, goto line 15A0 which reads 03 10 (little endian for 4099) and replace it with FF 00 (which does not exist.)
Out of experience, I think the correct maximum z-index
is 2147483638.
I hit the same problem with "Visual Studio 2013".
LNK1104: cannot open file 'debug\****.exe
It resolved after closing and re-starting Visual studio.
I found other methods to check if a point is inside a polygon (here). I tested two of them only (is_inside_sm and is_inside_postgis) and the results were the same as the other methods.
Thanks to @epifanio, I parallelized the codes and compared them with @epifanio and @user3274748 (ray_tracing_numpy) methods. Note that both methods had a bug so I fixed them as shown in their codes below.
One more thing that I found is that the code provided for creating a polygon does not generate a closed path np.linspace(0,2*np.pi,lenpoly)[:-1]
. As a result, the codes provided in above GitHub repository may not work properly. So It's better to create a closed path (first and last points should be the same).
Codes
Method 1: parallelpointinpolygon
from numba import jit, njit
import numba
import numpy as np
@jit(nopython=True)
def pointinpolygon(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in numba.prange(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
D = np.empty(len(points), dtype=numba.boolean)
for i in numba.prange(0, len(D)): #<-- Fixed here, must start from zero
D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
return D
Method 2: ray_tracing_numpy_numba
@jit(nopython=True)
def ray_tracing_numpy_numba(points,poly):
x,y = points[:,0], points[:,1]
n = len(poly)
inside = np.zeros(len(x),np.bool_)
p2x = 0.0
p2y = 0.0
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
idx = np.nonzero((y > min(p1y,p2y)) & (y <= max(p1y,p2y)) & (x <= max(p1x,p2x)))[0]
if len(idx): # <-- Fixed here. If idx is null skip comparisons below.
if p1y != p2y:
xints = (y[idx]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x:
inside[idx] = ~inside[idx]
else:
idxx = idx[x[idx] <= xints]
inside[idxx] = ~inside[idxx]
p1x,p1y = p2x,p2y
return inside
Method 3: Matplotlib contains_points
path = mpltPath.Path(polygon,closed=True) # <-- Very important to mention that the path
# is closed (default is false)
Method 4: is_inside_sm (got it from here)
@jit(nopython=True)
def is_inside_sm(polygon, point):
length = len(polygon)-1
dy2 = point[1] - polygon[0][1]
intersections = 0
ii = 0
jj = 1
while ii<length:
dy = dy2
dy2 = point[1] - polygon[jj][1]
# consider only lines which are not completely above/bellow/right from the point
if dy*dy2 <= 0.0 and (point[0] >= polygon[ii][0] or point[0] >= polygon[jj][0]):
# non-horizontal line
if dy<0 or dy2<0:
F = dy*(polygon[jj][0] - polygon[ii][0])/(dy-dy2) + polygon[ii][0]
if point[0] > F: # if line is left from the point - the ray moving towards left, will intersect it
intersections += 1
elif point[0] == F: # point on line
return 2
# point on upper peak (dy2=dx2=0) or horizontal line (dy=dy2=0 and dx*dx2<=0)
elif dy2==0 and (point[0]==polygon[jj][0] or (dy==0 and (point[0]-polygon[ii][0])*(point[0]-polygon[jj][0])<=0)):
return 2
ii = jj
jj += 1
#print 'intersections =', intersections
return intersections & 1
@njit(parallel=True)
def is_inside_sm_parallel(points, polygon):
ln = len(points)
D = np.empty(ln, dtype=numba.boolean)
for i in numba.prange(ln):
D[i] = is_inside_sm(polygon,points[i])
return D
Method 5: is_inside_postgis (got it from here)
@jit(nopython=True)
def is_inside_postgis(polygon, point):
length = len(polygon)
intersections = 0
dx2 = point[0] - polygon[0][0]
dy2 = point[1] - polygon[0][1]
ii = 0
jj = 1
while jj<length:
dx = dx2
dy = dy2
dx2 = point[0] - polygon[jj][0]
dy2 = point[1] - polygon[jj][1]
F =(dx-dx2)*dy - dx*(dy-dy2);
if 0.0==F and dx*dx2<=0 and dy*dy2<=0:
return 2;
if (dy>=0 and dy2<0) or (dy2>=0 and dy<0):
if F > 0:
intersections += 1
elif F < 0:
intersections -= 1
ii = jj
jj += 1
#print 'intersections =', intersections
return intersections != 0
@njit(parallel=True)
def is_inside_postgis_parallel(points, polygon):
ln = len(points)
D = np.empty(ln, dtype=numba.boolean)
for i in numba.prange(ln):
D[i] = is_inside_postgis(polygon,points[i])
return D
Timing for 10 million points:
parallelpointinpolygon Elapsed time: 4.0122294425964355
Matplotlib contains_points Elapsed time: 14.117807388305664
ray_tracing_numpy_numba Elapsed time: 7.908452272415161
sm_parallel Elapsed time: 0.7710440158843994
is_inside_postgis_parallel Elapsed time: 2.131121873855591
Here is the code.
import matplotlib.pyplot as plt
import matplotlib.path as mpltPath
from time import time
import numpy as np
np.random.seed(2)
time_parallelpointinpolygon=[]
time_mpltPath=[]
time_ray_tracing_numpy_numba=[]
time_is_inside_sm_parallel=[]
time_is_inside_postgis_parallel=[]
n_points=[]
for i in range(1, 10000002, 1000000):
n_points.append(i)
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)]
polygon = np.array(polygon)
N = i
points = np.random.uniform(-1.5, 1.5, size=(N, 2))
#Method 1
start_time = time()
inside1=parallelpointinpolygon(points, polygon)
time_parallelpointinpolygon.append(time()-start_time)
# Method 2
start_time = time()
path = mpltPath.Path(polygon,closed=True)
inside2 = path.contains_points(points)
time_mpltPath.append(time()-start_time)
# Method 3
start_time = time()
inside3=ray_tracing_numpy_numba(points,polygon)
time_ray_tracing_numpy_numba.append(time()-start_time)
# Method 4
start_time = time()
inside4=is_inside_sm_parallel(points,polygon)
time_is_inside_sm_parallel.append(time()-start_time)
# Method 5
start_time = time()
inside5=is_inside_postgis_parallel(points,polygon)
time_is_inside_postgis_parallel.append(time()-start_time)
plt.plot(n_points,time_parallelpointinpolygon,label='parallelpointinpolygon')
plt.plot(n_points,time_mpltPath,label='mpltPath')
plt.plot(n_points,time_ray_tracing_numpy_numba,label='ray_tracing_numpy_numba')
plt.plot(n_points,time_is_inside_sm_parallel,label='is_inside_sm_parallel')
plt.plot(n_points,time_is_inside_postgis_parallel,label='is_inside_postgis_parallel')
plt.xlabel("N points")
plt.ylabel("time (sec)")
plt.legend(loc = 'best')
plt.show()
CONCLUSION
The fastest algorithms are:
1- is_inside_sm_parallel
2- is_inside_postgis_parallel
3- parallelpointinpolygon (@epifanio)
What do you thing about this approach?
with open(filename) as data:
datalines = (line.rstrip('\r\n') for line in data)
for line in datalines:
...do something awesome...
Generator expression avoids loading whole file into memory and with
ensures closing the file
add this in web.config file
<configuration>
<appSettings>
<add key="ConnectionString" value="Your connection string which contains database id and password"/>
</appSettings>
</configuration>
.cs file
public ConnectionObjects()
{
string connectionstring= ConfigurationManager.AppSettings["ConnectionString"].ToString();
}
Hope this helps.
For anyone else struggling with this: Qwertie's comment worked well for me.
<Border Width="1" Margin="2" Background="#8888"/>
This creates a vertical seperator which you can talior to suit your needs.
You've missed the id out before the NOT; it needs to be specified.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
I would go for the second, the token system.
Did you know about ember-auth or ember-simple-auth? They both use the token based system, like ember-simple-auth states:
A lightweight and unobtrusive library for implementing token based authentication in Ember.js applications. http://ember-simple-auth.simplabs.com
They have session management, and are easy to plug into existing projects too.
There is also an Ember App Kit example version of ember-simple-auth: Working example of ember-app-kit using ember-simple-auth for OAuth2 authentication.
There is also another option. Adobe Acrobat Pro is also able to display the internal tree structure of the PDF.
On top Adobe Acrobat Pro can also display the internal structure of the Document Fonts in the PDF most of other "PDF tree structure viewer" don't have this otion
==
takes precedence over in
, so you're actually testing word == True
.
>>> w = 'ab c'
>>> ' ' in w == True
1: False
>>> (' ' in w) == True
2: True
But you don't need == True
at all. if
requires [something that evalutes to True or False] and ' ' in word
will evalute to true or false. So, if ' ' in word: ...
is just fine:
>>> ' ' in w
3: True
doesnt directly answer your question. But helpful for those who want to start something after some time.
Future.delayed(Duration(seconds: 1), () {
print('yo hey');
});
HTML
alone does not support this. You need to use some JS
.
And also consider nowadays people use popup blocker in browsers.
<a href="javascript:window.open('document.aspx','mypopuptitle','width=600,height=400')">open popup</a>
I know its 2 months but yeah
replace your code
Private TextView err;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enviar_mensaje);
err = (TextView)findViewById(R.id.texto);
err.setText("Escriba su mensaje y luego seleccione el canal.");
}
A global Mutex is not only to ensure to have only one instance of an application. I personally prefer using Microsoft.VisualBasic to ensure single instance application like described in What is the correct way to create a single-instance WPF application? (Dale Ragan answer)... I found that's easier to pass arguments received on new application startup to the initial single instance application.
But regarding some previous code in this thread, I would prefer to not create a Mutex each time I want to have a lock on it. It could be fine for a single instance application but in other usage it appears to me has overkill.
That's why I suggest this implementation instead:
Usage:
static MutexGlobal _globalMutex = null;
static MutexGlobal GlobalMutexAccessEMTP
{
get
{
if (_globalMutex == null)
{
_globalMutex = new MutexGlobal();
}
return _globalMutex;
}
}
using (GlobalMutexAccessEMTP.GetAwaiter())
{
...
}
Mutex Global Wrapper:
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
namespace HQ.Util.General.Threading
{
public class MutexGlobal : IDisposable
{
// ************************************************************************
public string Name { get; private set; }
internal Mutex Mutex { get; private set; }
public int DefaultTimeOut { get; set; }
public Func<int, bool> FuncTimeOutRetry { get; set; }
// ************************************************************************
public static MutexGlobal GetApplicationMutex(int defaultTimeOut = Timeout.Infinite)
{
return new MutexGlobal(defaultTimeOut, ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value);
}
// ************************************************************************
public MutexGlobal(int defaultTimeOut = Timeout.Infinite, string specificName = null)
{
try
{
if (string.IsNullOrEmpty(specificName))
{
Name = Guid.NewGuid().ToString();
}
else
{
Name = specificName;
}
Name = string.Format("Global\\{{{0}}}", Name);
DefaultTimeOut = defaultTimeOut;
FuncTimeOutRetry = DefaultFuncTimeOutRetry;
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
Mutex = new Mutex(false, Name, out bool createdNew, securitySettings);
if (Mutex == null)
{
throw new Exception($"Unable to create mutex: {Name}");
}
}
catch (Exception ex)
{
Log.Log.Instance.AddEntry(Log.LogType.LogException, $"Unable to create Mutex: {Name}", ex);
throw;
}
}
// ************************************************************************
/// <summary>
///
/// </summary>
/// <param name="timeOut"></param>
/// <returns></returns>
public MutexGlobalAwaiter GetAwaiter(int timeOut)
{
return new MutexGlobalAwaiter(this, timeOut);
}
// ************************************************************************
/// <summary>
///
/// </summary>
/// <param name="timeOut"></param>
/// <returns></returns>
public MutexGlobalAwaiter GetAwaiter()
{
return new MutexGlobalAwaiter(this, DefaultTimeOut);
}
// ************************************************************************
/// <summary>
/// This method could either throw any user specific exception or return
/// true to retry. Otherwise, retruning false will let the thread continue
/// and you should verify the state of MutexGlobalAwaiter.HasTimedOut to
/// take proper action depending on timeout or not.
/// </summary>
/// <param name="timeOutUsed"></param>
/// <returns></returns>
private bool DefaultFuncTimeOutRetry(int timeOutUsed)
{
// throw new TimeoutException($"Mutex {Name} timed out {timeOutUsed}.");
Log.Log.Instance.AddEntry(Log.LogType.LogWarning, $"Mutex {Name} timeout: {timeOutUsed}.");
return true; // retry
}
// ************************************************************************
public void Dispose()
{
if (Mutex != null)
{
Mutex.ReleaseMutex();
Mutex.Close();
}
}
// ************************************************************************
}
}
Awaiter
using System;
namespace HQ.Util.General.Threading
{
public class MutexGlobalAwaiter : IDisposable
{
MutexGlobal _mutexGlobal = null;
public bool HasTimedOut { get; set; } = false;
internal MutexGlobalAwaiter(MutexGlobal mutexEx, int timeOut)
{
_mutexGlobal = mutexEx;
do
{
HasTimedOut = !_mutexGlobal.Mutex.WaitOne(timeOut, false);
if (! HasTimedOut) // Signal received
{
return;
}
} while (_mutexGlobal.FuncTimeOutRetry(timeOut));
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_mutexGlobal.Mutex.ReleaseMutex();
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~MutexExAwaiter()
// {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}
Solve the issue by following steps.
Uninstalled softwares Vscode and git and reinstalled the same. Changed the git repository clone url from ssh to https.
Thanks jbaliuka for the suggestion. I opened the registry editor (by typing regedit in cmd) and going to HKEY_CLASSES_ROOT > jarfile > shell > open > command, then opening (Default) and changing the value from
"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*
to
"C:\Program Files\Java\jre7\bin\java.exe" -jar "%1" %*
(I just removed the w in javaw.exe.) After that you have to right click a jar -> open with -> choose default program -> navigate to your java folder and open \jre7\bin\java.exe (or any other java.exe file in you java folder). If it doesn't work, try switching to javaw.exe, open a jar file with it, then switch back.
I don't know anything about editing the registry except that it's dangerous, so you might wanna back it up before doing this (in the top bar, File>Export).
To complement Jakub's answer, if you have access to the remote git server in ssh, you can go into the git remote directory and set:
user@remote$ git config receive.denyNonFastforwards false
Then go back to your local repo, try again to do your commit with --force
:
user@local$ git push origin +master:master --force
And finally revert the server's setting in the original protected state:
user@remote$ git config receive.denyNonFastforwards true
It is not necessary to change java as a String parameter. You have to change the c code to receive a String without a pointer and in its code:
Bool DmgrGetVersion (String szVersion);
Char NewszVersion [200];
Strcpy (NewszVersion, szVersion.t_str ());
.t_str () applies to builder c ++ 2010
There are several methods.
If you want just the consolidated string value returned, this is a good quick and easy approach
DECLARE @combinedString VARCHAR(MAX)
SELECT @combinedString = COALESCE(@combinedString + ', ', '') + stringvalue
FROM jira.customfieldValue
WHERE customfield = 12534
AND ISSUE = 19602
SELECT @combinedString as StringValue
Which will return your combined string.
You can also try one of the XML methods e.g.
SELECT DISTINCT Issue, Customfield, StringValues
FROM Jira.customfieldvalue v1
CROSS APPLY ( SELECT StringValues + ','
FROM jira.customfieldvalue v2
WHERE v2.Customfield = v1.Customfield
AND v2.Issue = v1.issue
ORDER BY ID
FOR XML PATH('') ) D ( StringValues )
WHERE customfield = 12534
AND ISSUE = 19602
May be join two ..
folder, to get parent of the parent folder?
path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))
If it ain't broke - fix it till it is...just kidding :)
But seriously BackgroundWorker is probably very similar to what you already have, had you started with it from the beginning maybe you would have saved some time - but at this point I don't see the need. Unless something isn't working, or you think your current code is hard to understand, then I would stick with what you have.
<html>
<head>
<title>Print</title>
<script type="text/javascript">
window.print();
document.margin='none';
</script>
</head>
<body>
<p>hello</p>
<p>hi</p>
</body>
</html>
//place it in a script file or in the script tag.
This will remove all the margins and you won't be able to see the headers and footers.
I found that selecting a clob
column in CTE caused this explosion. ie
with cte as (
select
mytable1.myIntCol,
mytable2.myClobCol
from mytable1
join mytable2 on ...
)
select myIntCol, myClobCol
from cte
where ...
presumably because oracle can't handle a clob in a temporary table.
Because my values were longer than 4K, I couldn't use to_char()
.
My work around was to select it from the final select
, ie
with cte as (
select
mytable1.myIntCol
from mytable1
)
select myIntCol, myClobCol
from cte
join mytable2 on ...
where ...
Too bad if this causes a performance problem.
hibernate-types has a utility method to log jpql and criteria queries. More details can be found in the autors's blog post. Here is an example using jpql:
Query jpql = entityManager.createQuery("""
select
YEAR(p.createdOn) as year,
count(p) as postCount
from
Post p
group by
YEAR(p.createdOn)
""", Tuple.class
);
String sql = SQLExtractor.from(jpql);
sql
variable has the following value:
SELECT
extract(YEAR FROM sqlextract0_.created_on) AS col_0_0_,
count(sqlextract0_.id) AS col_1_0_
FROM
post p
GROUP BY
extract(YEAR FROM p.created_on)
It can be copy-pasted into the db console as is.
A little anecdote to illustrate the use of array_key_exists
.
// A programmer walked through the parking lot in search of his car
// When he neared it, he reached for his pocket to grab his array of keys
$keyChain = array(
'office-door' => unlockOffice(),
'home-key' => unlockSmallApartment(),
'wifes-mercedes' => unusedKeyAfterDivorce(),
'safety-deposit-box' => uselessKeyForEmptyBox(),
'rusto-old-car' => unlockOldBarrel(),
);
// He tried and tried but couldn't find the right key for his car
// And so he wondered if he had the right key with him.
// To determine this he used array_key_exists
if (array_key_exists('rusty-old-car', $keyChain)) {
print('Its on the chain.');
}
Even if both work, I would use the latter.
location
is an object, and assigning a string to an object doesn't bode well for readability or maintenance.
If you are using Table.query
property:
from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()
If you are using session.query()
method (as stated in miniwark's answer):
from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()
Hopefully this helps:-
If you run a script/module from anywhere you'll be able to access the __file__
variable which is a module variable representing the location of the script.
On the other hand, if you're using the interpreter you don't have access to that variable, where you'll get a name NameError
and os.getcwd()
will give you the incorrect directory if you're running the file from somewhere else.
This solution should give you what you're looking for in all cases:
from inspect import getsourcefile
from os.path import abspath
abspath(getsourcefile(lambda:0))
I haven't thoroughly tested it but it solved my problem.
Update pandas 0.17.0
@7stud's answer for the newest pandas version would require to just call
s.plot(
kind='bar',
color=my_colors,
)
instead of
pd.Series.plot(
s,
kind='bar',
color=my_colors,
)
The plotting functions have become members of the Series, DataFrame objects and in fact calling pd.Series.plot
with a color
argument gives an error
I do a lot of logging where the timestamps are float64 and use this function to get the timestamps as string:
func dateFormat(layout string, d float64) string{
intTime := int64(d)
t := time.Unix(intTime, 0)
if layout == "" {
layout = "2006-01-02 15:04:05"
}
return t.Format(layout)
}
I had a similar question to solve in a Udacity´s problems. Instead of a built-in function i coded:
def list_mean(n):
summing = float(sum(n))
count = float(len(n))
if n == []:
return False
return float(summing/count)
Much more longer than usual but for a beginner its quite challenging.
A better way to debug the code is, by using module clrprint
It prints a color full output only when pass parameter debug=True
from clrprint import *
clrprint('ERROR:', information,clr=['r','y'], debug=True)
Your requirements are all over the place, but this is the solution to my understanding of them:
To group by Reference property:
var refGroupQuery = (from m in context.Measurements
group m by m.Reference into refGroup
select refGroup);
Now you say you want to limit results by "most recent numOfEntries" - I take this to mean you want to limit the returned Measurements... in that case:
var limitedQuery = from g in refGroupQuery
select new
{
Reference = g.Key,
RecentMeasurements = g.OrderByDescending( p => p.CreationTime ).Take( numOfEntries )
}
To order groups by first Measurement creation time (note you should order the measurements; if you want the earliest CreationTime value, substitue "g.SomeProperty" with "g.CreationTime"):
var refGroupsOrderedByFirstCreationTimeQuery = limitedQuery.OrderBy( lq => lq.RecentMeasurements.OrderBy( g => g.SomeProperty ).First().CreationTime );
To order groups by average CreationTime, use the Ticks property of the DateTime struct:
var refGroupsOrderedByAvgCreationTimeQuery = limitedQuery.OrderBy( lq => lq.RecentMeasurements.Average( g => g.CreationTime.Ticks ) );
Simply go to the directory where the troubling file is, type touch *
without quotes in the console, and you should be good.
There is also a GUI tool that allows visual JKS creation and certificates importing.
http://portecle.sourceforge.net/
Portecle is a user friendly GUI application for creating, managing and examining keystores, keys, certificates, certificate requests, certificate revocation lists and more.
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
Similar to @sirthomas's answer, JSON.NET also respects the EmitDefaultValue
property on DataMemberAttribute
:
[DataMember(Name="property_name", EmitDefaultValue=false)]
This may be desirable if you are already using [DataContract]
and [DataMember]
in your model type and don't want to add JSON.NET-specific attributes.
Create an IBOutlet of NSLayoutConstraint of yourView and update the constant value accordingly the condition specifies.
//Connect them from Interface
@IBOutlet viewHeight: NSLayoutConstraint!
@IBOutlet view: UIView!
private func updateViewHeight(height:Int){
guard let aView = view, aViewHeight = viewHeight else{
return
}
aViewHeight.constant = height
aView.layoutIfNeeded()
}
Use the Key
keyword in your select will work, like below.
product.Select(m => new {Key m.CategoryId, Key m.CategoryName}).Distinct();
I realize this is bringing up an old thread but figured it might help some people. I generally code in VB.NET when working with .NET so Key
may translate differently into C#.
Create an anchor:
<a name="anchor" id="anchor"></a>
then link to it:
<a href="http://server/page.html#anchor">Link text</a>
If you look at the documentation for str.split
:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
In other words, if you're trying to figure out what to pass to split
to get '\n\tName: Jane Smith'
to ['Name:', 'Jane', 'Smith']
, just pass nothing (or None).
This almost solves your whole problem. There are two parts left.
First, you've only got two fields, the second of which can contain spaces. So, you only want one split, not as many as possible. So:
s.split(None, 1)
Next, you've still got those pesky colons. But you don't need to split on them. At least given the data you've shown us, the colon always appears at the end of the first field, with no space before and always space after, so you can just remove it:
key, value = s.split(None, 1)
key = key[:-1]
There are a million other ways to do this, of course; this is just the one that seems closest to what you were already trying.
Another solution is to use CSS adjacency and use h4 (or higher):
#### note
This is the note content
h4 {
display: none; /* hide */
}
h4 + p {
/* style the note however you want */
}
One way to do that is to make all your users' devices subscribe to a topic. That way when you target a message to a specific topic, all devices will get it. I think this how the Notifications section in the Firebase console does it.
$('#foo').children('div').length
Ahhh, the stupid linesize ... Here is what I do in my profile.sql - works only on unixes:
echo SET LINES $(tput cols) > $HOME/.login_tmp.sql
@$HOME/.login_tmp.sql
if you find an equivalent for tput on Windows, it might work there as well
Inline code takes higher precedence than the other ones. To call your other function func () call it from the f1 ().
Inside your function, add a line,
function fun () {
// Your code here
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
fun ();
}
Rewriting your whole code,
<!DOCTYPE html>
<html>
<head>
<script>
function fun()
{
alert("hello");
//validation code to see State field is mandatory.
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
fun ();
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post">
State: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
</form>
<table><tr><td id="Save" onclick="f1()">click</td></tr></table>
</body>
</html>
Here's how to print the complete list of files in the working tree which match patterns located anywhere in Git's multiple gitignore sources (if you're using GNU find
):
$ cd {your project directory}
$ find . -path ./.git -prune -o -print \
| git check-ignore --no-index --stdin --verbose
It will check all the files in the current branch of the repository (unless you've deleted them locally).
And it identifies the particular gitignore source lines, as well.
Git continues to track changes in some files which match gitignore patterns, simply because those files were added already. Usefully, the above command displays those files, too.
Negative gitignore patterns are also matched. However, these are easily distinguishable in the listing, because they begin with !
.
If you're using Windows, Git Bash includes GNU find
(as revealed by find --version
).
If the list is long (and you have rev
), you can display them by extension (somewhat), too:
$ cd {your project directory}
$ find . -path ./.git -prune -o -print \
| git check-ignore --no-index --stdin --verbose \
| rev | sort | rev
For more details, see man find
, man git-check-ignore
, man rev
, and man sort
.
The point of this whole approach is that Git (the software) is changing rapidly and is highly complex. By contrast, GNU's find
is extremely stable (at least, in its features used here). So, anyone who desires to be competitive by displaying their in-depth knowledge of Git will answer the question in a different way.
What's the best answer? This answer deliberately minimizes its reliance on Git knowledge, toward achieving the goal of stability and simplicity through modularity (information isolation), and is designed to last a long time.
Try this,
Using foreach
Loop:
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
// ...
}
}
Use it in OnRowCommand
event and get checked CheckBox value.
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];
Well, you can do it like so:
(function() {
var localByaka;
Object.defineProperty(window, 'Byaka', {
get: function() {
return localByaka;
},
set: function(val) {
localByaka = window.Byaka || val;
}
});
}());
window.Byaka = "foo"; //set constant
window.Byaka = "bar"; // try resetting it for shits and giggles
window.Byaka; // will allways return foo!
If you do this as above in global scope this will be a true constant, because you cannot overwrite the window object.
I've created a library to create constants and immutable objects in javascript. Its still version 0.2 but it does the trick nicely. http://beckafly.github.io/insulatejs
just use onkeypress event like below:
<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
Create a new file called files.txt and paste the URLs one per line. Then run the following command.
xargs -n 1 curl -O < files.txt
source: https://www.abeautifulsite.net/downloading-a-list-of-urls-automatically
From user @jamylak an alternative form of open("filename","w").close()
is
with open('filename.txt','w'): pass
You could do this simply by:
NOTE: you can find the right GApp version here:
I realize this is old, but maybe this function I created is useful to someone out there:
order_axis<-function(data, axis, column)
{
# for interactivity with ggplot2
arguments <- as.list(match.call())
col <- eval(arguments$column, data)
ax <- eval(arguments$axis, data)
# evaluated factors
a<-reorder(with(data, ax),
with(data, col))
#new_data
df<-cbind.data.frame(data)
# define new var
within(df,
do.call("<-",list(paste0(as.character(arguments$axis),"_o"), a)))
}
Now, with this function you can interactively plot with ggplot2, like this:
ggplot(order_axis(df, AXIS_X, COLUMN_Y),
aes(x = AXIS_X_o, y = COLUMN_Y)) +
geom_bar(stat = "identity")
As can be seen, the order_axis
function creates another dataframe with a new column named the same but with a _o
at the end. This new column has levels in ascending order, so ggplot2 automatically plots in that order.
This is somewhat limited (only works for character or factor and numeric combinations of columns and in ascending order) but I still find it very useful for plotting on the go.
To get Ant running on your Mac in 5 minutes, follow these steps.
Open up your terminal.
Perform these commands in order:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install ant
If you don't have Java installed yet, you will get the following error: "Error: An unsatisfied requirement failed this build."
Run this command next: brew cask install java
to fix this.
The installation will resume.
Check your version of by running this command:
ant -version
And you're ready to go!
Going Relative:
Going Absolute:
This can be done in one line, there's no need for a loop, be it a for-loop or an apply. Use unlist() instead :
# testdata
Df <- data.frame(
x = as.factor(sample(1:5,30,r=TRUE)),
y = as.factor(sample(1:5,30,r=TRUE)),
z = as.factor(sample(1:5,30,r=TRUE)),
w = as.factor(sample(1:5,30,r=TRUE))
)
##
Df[,c("y","w")] <- as.numeric(as.character(unlist(Df[,c("y","w")])))
str(Df)
Edit : for your code, this becomes :
id <- c(1,3:ncol(stats)))
stats[,id] <- as.numeric(as.character(unlist(stats[,id])))
Obviously, if you have a one-column data frame and you don't want the automatic dimension reduction of R to convert it to a vector, you'll have to add the drop=FALSE
argument.
That's because you have the Date in American format in line[i]
and UK format in the FormatString
.
11/20/2011
M / d/yyyy
I'm guessing you might need to change the FormatString to:
"M/d/yyyy h:mm"
You may also delete gradle file, if you don't use gradle any where else:
rm -Rfv ~/.gradle/
because .gradle folder contains cached artifacts that are no longer needed.
What you're looking for is min-height
and max-height
.
img {
max-width: 100%;
height: auto;
}
.item {
width: 120px;
min-height: 120px;
max-height: auto;
float: left;
margin: 3px;
padding: 3px;
}
If you are using Linux you can use the wget
module of Linux through the python shell. Here is a sample code snippet
import os
url = 'http://www.example.com/foo.zip'
os.system('wget %s'%url)
Plus those upvoted correct answers sometimes same error could be seen because of mismatched and different settings on SSL
part of webserver configurations. (Obviously when not using .htaccess
file).
One possibility:
String result = str.substring(0, index) + str.substring(index+1);
Note that the result is a new String (as well as two intermediate String objects), because Strings in Java are immutable.
Accepted answer Method 1 will not work for data frames with NaNs inside, as pd.np.nan != pd.np.nan
. I am not sure if this is the best way, but it can be avoided by
df1[~df1.astype(str).apply(tuple, 1).isin(df2.astype(str).apply(tuple, 1))]
It's slower, because it needs to cast data to string, but thanks to this casting pd.np.nan == pd.np.nan
.
Let's go trough the code. First we cast values to string, and apply tuple
function to each row.
df1.astype(str).apply(tuple, 1)
df2.astype(str).apply(tuple, 1)
Thanks to that, we get pd.Series
object with list of tuples. Each tuple contains whole row from df1
/df2
.
Then we apply isin
method on df1
to check if each tuple "is in" df2
.
The result is pd.Series
with bool values. True if tuple from df1
is in df2
. In the end, we negate results with ~
sign, and applying filter on df1
. Long story short, we get only those rows from df1
that are not in df2
.
To make it more readable, we may write it as:
df1_str_tuples = df1.astype(str).apply(tuple, 1)
df2_str_tuples = df2.astype(str).apply(tuple, 1)
df1_values_in_df2_filter = df1_str_tuples.isin(df2_str_tuples)
df1_values_not_in_df2 = df1[~df1_values_in_df2_filter]
A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.
I'd split both of your paths at the directory level. From there, find the point of divergence and work your way back to the assembly folder, prepending a '../' everytime you pass a directory.
Keep in mind however, that an absolute path works everywhere and is usually easier to read than a relative one. I personally wouldn't show an user a relative path unless it was absolutely necessary.
Paste the below code in the ActionResult of your controller and place the debugger at this point.
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
In my case i removed these lines
1-import javax.validation.constraints.NotNull;
2-import javax.validation.constraints.Size;
3- @NotNull
4- @Size(max = 3)
Hey Try This Code.
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "Data has been saved", true);
Cheers
When dealing with the HTML DOM (ie. this
), the array selector [0]
must be used to retrieve the jQuery element from the Javascript array.
$(this)[0].getAttribute('src');
I am calling the json on login button click
@IBAction func loginClicked(sender : AnyObject){
var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err1: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary
println("json2 :\(json2)")
if(err) {
println(err!.localizedDescription)
}
else {
var success = json2["success"] as? Int
println("Succes: \(success)")
}
})
task.resume()
}
Here, I have made a seperate dictionary for the parameters.
var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary
return params
}
Yes there are ways to load classes and to "unload" them later on. The trick is to implement your own classloader which resides between high level class loader (the System class loader) and the class loaders of the app server(s), and to hope that the app server's class loaders do delegate the classloading to the upper loaders.
A class is defined by its package, its name, and the class loader it originally loaded. Program a "proxy" classloader which is the first that is loaded when starting the JVM. Workflow:
java.x
and sun.x
to the system classloader (these must not be loaded through any other classloader than the system classloader).Done right there should not come a ClassCastException or LinkageError etc.
For more informations about class loader hierarchies (yes, that's exactly what you are implementing here ;- ) look at "Server-Based Java Programming" by Ted Neward - that book helped me implementing something very similar to what you want.
Just to point out the generic way to iterate over any map:
private <K, V> void iterateOverMap(Map<K, V> map) {
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
}
}
Not sure if this work everywhere.
I'm using ipython in ubuntu.
If you want to read file in current folder's sub-directory:
/current-folder/sub-directory/data.csv
your script is in current-folder simply try this:
import pandas as pd
path = './sub-directory/data.csv'
pd.read_csv(path)
And this for clearing all controls in form like textbox, checkbox, radioButton
you can add different types you want..
private void ClearTextBoxes(Control control)
{
foreach (Control c in control.Controls)
{
if (c is TextBox)
{
((TextBox)c).Clear();
}
if (c.HasChildren)
{
ClearTextBoxes(c);
}
if (c is CheckBox)
{
((CheckBox)c).Checked = false;
}
if (c is RadioButton)
{
((RadioButton)c).Checked = false;
}
}
}
Would using tail on N-1 lines and directing that into a file, followed by removing the old file, and renaming the new file to the old name do the job?
If i were doing this programatically, i would read through the file, and remember the file offset, after reading each line, so i could seek back to that position to read the file with one less line in it.
jQuery has the contains method. Here's a snippet for you:
<script type="text/javascript">
$(function() {
var foundin = $('*:contains("I am a simple string")');
});
</script>
The selector above selects any element that contains the target string. The foundin will be a jQuery object that contains any matched element. See the API information at: https://api.jquery.com/contains-selector/
One thing to note with the '*' wildcard is that you'll get all elements, including your html an body elements, which you probably don't want. That's why most of the examples at jQuery and other places use $('div:contains("I am a simple string")')
You need to stop all tracks (from webcam, microphone):
localStream.getTracks().forEach(track => track.stop());
If you want to remove all new line characters and replace them with some character (say comma) then you can use the following.
(Get-Content test.txt) -join ","
This works because Get-Content returns array of lines. You can see it as tokenize function available in many languages.
Had to debug a site for native Android browser and came here. So I tried weinre on an OS X 10.9 (as weinre server) with Firefox 30.0 (weinre client) and an Android 4.1.2 (target). I'm really, really surprised of the result.
sudo npm -g install weinre
weinre --boundHost YOUR.IP.ADDRESS.HERE
http://YOUR.IP.ADRESS.HERE:8080
<script src="http://YOUR.IP.ADDRESS.HERE:8080/target/target-script-min.js"></script>
Maybe 8080 isn't your default port. Then in step 4 you have to call weinre --httpPort YOURPORT --boundHost YOUR.IP.ADRESS.HERE
.
And I don't remember exactly when it was, maybe somewhere after step 5, I had to accept incoming connections prompt, of course.
Happy debugging
P.S. I'm still overwhelmed how good that works. Even elements-highlighting work
In case you have multiple images and you want to loop though them and show them 1 by 1 along with titles - this is what you can do. No need to explicitly define ax1, ax2, etc.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2, figsize=(6, 8))
for i in range(len(ax)):
for j in range(len(ax[i])):
## ax[i,j].imshow(test_images_gr[0].reshape(28,28))
ax[i,j].set_title('Title-' + str(i) + str(j))
To reference a commit, simply write its SHA-hash, and it'll automatically get turned into a link.
Below code causes Type safety Warning
Map<String, Object> myInput = (Map<String, Object>) myRequest.get();
Workaround
Create a new Map Object without mentioning the parameters because the type of object held within the list is not verified.
Step 1: Create a new temporary Map
Map<?, ?> tempMap = (Map<?, ?>) myRequest.get();
Step 2: Instantiate the main Map
Map<String, Object> myInput=new HashMap<>(myInputObj.size());
Step 3: Iterate the temporary Map and set the values into the main Map
for(Map.Entry<?, ?> entry :myInputObj.entrySet()){
myInput.put((String)entry.getKey(),entry.getValue());
}
The File
class represents the "idea" of a file, not an actual handle to use for I/O. This is why the File
class has a .exists()
method, to tell you if the file exists or not. (How can you have a File
object that doesn't exist?)
By contrast, constructing a new FileInputStream(new File("/my/file"))
gives you an actual stream to read bytes from.
After using samples from this question I've made complete version of pan & zoom app with proper zooming relative to mouse pointer. All pan & zoom code has been moved to separate class called ZoomBorder.
ZoomBorder.cs
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace PanAndZoom
{
public class ZoomBorder : Border
{
private UIElement child = null;
private Point origin;
private Point start;
private TranslateTransform GetTranslateTransform(UIElement element)
{
return (TranslateTransform)((TransformGroup)element.RenderTransform)
.Children.First(tr => tr is TranslateTransform);
}
private ScaleTransform GetScaleTransform(UIElement element)
{
return (ScaleTransform)((TransformGroup)element.RenderTransform)
.Children.First(tr => tr is ScaleTransform);
}
public override UIElement Child
{
get { return base.Child; }
set
{
if (value != null && value != this.Child)
this.Initialize(value);
base.Child = value;
}
}
public void Initialize(UIElement element)
{
this.child = element;
if (child != null)
{
TransformGroup group = new TransformGroup();
ScaleTransform st = new ScaleTransform();
group.Children.Add(st);
TranslateTransform tt = new TranslateTransform();
group.Children.Add(tt);
child.RenderTransform = group;
child.RenderTransformOrigin = new Point(0.0, 0.0);
this.MouseWheel += child_MouseWheel;
this.MouseLeftButtonDown += child_MouseLeftButtonDown;
this.MouseLeftButtonUp += child_MouseLeftButtonUp;
this.MouseMove += child_MouseMove;
this.PreviewMouseRightButtonDown += new MouseButtonEventHandler(
child_PreviewMouseRightButtonDown);
}
}
public void Reset()
{
if (child != null)
{
// reset zoom
var st = GetScaleTransform(child);
st.ScaleX = 1.0;
st.ScaleY = 1.0;
// reset pan
var tt = GetTranslateTransform(child);
tt.X = 0.0;
tt.Y = 0.0;
}
}
#region Child Events
private void child_MouseWheel(object sender, MouseWheelEventArgs e)
{
if (child != null)
{
var st = GetScaleTransform(child);
var tt = GetTranslateTransform(child);
double zoom = e.Delta > 0 ? .2 : -.2;
if (!(e.Delta > 0) && (st.ScaleX < .4 || st.ScaleY < .4))
return;
Point relative = e.GetPosition(child);
double absoluteX;
double absoluteY;
absoluteX = relative.X * st.ScaleX + tt.X;
absoluteY = relative.Y * st.ScaleY + tt.Y;
st.ScaleX += zoom;
st.ScaleY += zoom;
tt.X = absoluteX - relative.X * st.ScaleX;
tt.Y = absoluteY - relative.Y * st.ScaleY;
}
}
private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (child != null)
{
var tt = GetTranslateTransform(child);
start = e.GetPosition(this);
origin = new Point(tt.X, tt.Y);
this.Cursor = Cursors.Hand;
child.CaptureMouse();
}
}
private void child_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (child != null)
{
child.ReleaseMouseCapture();
this.Cursor = Cursors.Arrow;
}
}
void child_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
this.Reset();
}
private void child_MouseMove(object sender, MouseEventArgs e)
{
if (child != null)
{
if (child.IsMouseCaptured)
{
var tt = GetTranslateTransform(child);
Vector v = start - e.GetPosition(this);
tt.X = origin.X - v.X;
tt.Y = origin.Y - v.Y;
}
}
}
#endregion
}
}
MainWindow.xaml
<Window x:Class="PanAndZoom.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PanAndZoom"
Title="PanAndZoom" Height="600" Width="900" WindowStartupLocation="CenterScreen">
<Grid>
<local:ZoomBorder x:Name="border" ClipToBounds="True" Background="Gray">
<Image Source="image.jpg"/>
</local:ZoomBorder>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace PanAndZoom
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
In a nutshell answer.
A lot of answers already; wanted to jump on with a bit more.
docs:
For has_many, destroy and destroy_all will always call the destroy method of the record(s) being removed so that callbacks are run. However delete and delete_all will either do the deletion according to the strategy specified by the :dependent option, or if no :dependent option is given, then it will follow the default strategy. The default strategy is to do nothing (leave the foreign keys with the parent ids set), except for has_many :through, where the default strategy is delete_all (delete the join records, without running their callbacks).
The delete
verbage works differently for ActiveRecord::Association.has_many
and ActiveRecord::Base
. For the latter, delete will execute SQL DELETE
and bypass all validations/callbacks. The former will be executed based on the :dependent
option passed into the association. However, during testing, I found the following side effect where callbacks were only ran for delete
and not delete_all
dependent: :destroy
Example:
class Parent < ApplicationRecord
has_many :children,
before_remove: -> (_) { puts "before_remove callback" },
dependent: :destroy
end
class Child < ApplicationRecord
belongs_to :parent
before_destroy -> { puts "before_destroy callback" }
end
> child.delete # Ran without callbacks
Child Destroy (99.6ms) DELETE FROM "children" WHERE "children"."id" = $1 [["id", 21]]
> parent.children.delete(other_child) # Ran with callbacks
before_remove callback
before_destroy callback
Child Destroy (0.4ms) DELETE FROM "children" WHERE "children"."id" = $1 [["id", 22]]
> parent.children.delete_all # Ran without callbacks
Child Destroy (1.0ms) DELETE FROM "children" WHERE "children"."parent_id" = $1 [["parent_id", 1]]
//BIGINT UNIX TIMESTAMP CONVERSION upto Millisecond Accuracy
CREATE FUNCTION [dbo].[ConvertUnixTimestamp] (@Datetime [BIGINT]) RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(MILLISECOND, cast(@Datetime as bigint) % 1000,
DATEADD(SECOND, (cast(@Datetime as bigint) / 1000)%60,
DATEADD(MINUTE, ((cast(@Datetime as bigint) / 1000)/60)%60,
DATEADD(HOUR, ((cast(@Datetime as bigint) / 1000)/60)/60, '19700101'))))
END
well, the answer is yes... AND NO.
depends on the question. everybody here answered regarding Java >= 5, and some mentioned that Java < 5 does not feature covariant return types.
actually, the Java language spec >= 5 supports it, but the Java runtime does not. in particular, the JVM was not updated to support covariant return types.
in what was seen then as a "clever" move but ended up being one of the worst design decisions in Java's history, Java 5 implemented a bunch of new language features without modifying the JVM or the classfile spec at all. instead all features were implemented with trickery in javac: the compiler generates/uses plain classes for nested/inner classes, type erasure and casts for generics, synthetic accessors for nested/inner class private "friendship", synthetic instance fields for outer 'this' pointers, synthetic static fields for '.class' literals, etc, etc.
and covariant return types is yet more syntactic sugar added by javac.
for example, when compiling this:
class Base {
Object get() { return null; }
}
class Derived extends Base {
@Override
@SomeAnnotation
Integer get() { return null; }
}
javac will output two get methods in the Derived class:
Integer Integer:Derived:get() { return null; }
synthetic bridge Object Object:Derived:get() { return Integer:Derived:get(); }
the generated bridge method (marked synthetic
and bridge
in bytecode) is what actually overrides Object:Base:get()
because, to the JVM, methods with different return types are completely independent and cannot override each other. to provide the expected behavior, the bridge simply calls your "real" method. in the example above, javac will annotate both bridge and real methods in Derived with @SomeAnnotation.
note that you cannot hand-code this solution in Java < 5, because bridge and real methods only differ in return type and thus they cannot coexist in a Java program. but in the JVM world, method return types are part of the method signature (just like their arguments) and so the two methods named the same and taking the same arguments are nonetheless seen as completely independent by the JVM due to their differing return types, and can coexist.
(BTW, the types of fields are similarly part of the field signature in bytecode, so it is legal to have several fields of different types but named the same within a single bytecode class.)
so to answer your question fully: the JVM does not support covariant return types, but javac >= 5 fakes it at compile time with a coating of sweet syntactic sugar.
It depends on your file path. For me, the current directory was [project]\bin\Debug
, so I had to move to the parent folder twice.
Image image = Image.FromFile(@"..\..\Pictures\"+text+".png");
this.pictureBox1.Image = image;
To find your current directory, you can make a dummy label called label2 and write this:
this.label2.Text = System.IO.Directory.GetCurrentDirectory();
I know this is an old topic and there are certainly a lot of options, but I really prefer gibo
by Simon Whitaker. It's super simple to use, cross-platform (mac, *nix, and windows), and uses the github gitignore
repo so it is (basically) always up to date.
Make sure your local cache is up to date:
$ gibo --upgrade
From https://github.com/github/gitignore
* branch master -> FETCH_HEAD
Current branch master is up to date.
Search for the language/technology you need:
$ gibo --search android
Android
Display the .gitignore file:
$ gibo Android
### Android
# Built application files
*.apk
*.ap_
# Files for the Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
Now, append it to your project's .gitignore file:
$ gibo Android >> .gitignore
(Make sure you use >>
to append to your project's .gitignore file; one >
will overwrite it - as I've done many times on accident!)
I know this isn't answering the OP's exact question, but using gibo makes it so you pretty much don't have to think about 'the question' anymore! .. it's nice! ;)
Your server process has received a SIGPIPE
writing to a socket. This usually happens when you write to a socket fully closed on the other (client) side. This might be happening when a client program doesn't wait till all the data from the server is received and simply closes a socket (using close
function).
In a C program you would normally try setting to ignore SIGPIPE
signal or setting a dummy signal handler for it. In this case a simple error will be returned when writing to a closed socket. In your case a python seems to throw an exception that can be handled as a premature disconnect of the client.
This is about "Color Quantization" that has several approachs like MMCQ (Modified Median Cut Quantization) or OQ (Octree Quantization). Different approach use K-Means to obtain clusters of colors.
I have putted all together here, since I was finding a solution for tvOS
where there is a subset of XHTML, that has no <canvas/>
element:
Generate the Dominant Colors for an RGB image with XMLHttpRequest
Textarea respects the white-space attribute for the placeholder. https://www.w3schools.com/cssref/pr_text_white-space.asp
Setting it to pre-line solved the problem for me.
textarea {_x000D_
white-space: pre-line;_x000D_
}
_x000D_
<textarea placeholder='This is a line _x000D_
should this be a new line'></textarea>
_x000D_
p.s. in particular, I've found Row-Oriented examples helpful; since often that how records are stored externally.
Alternatively, if you want to install specific version of the package with the specific version of python, this is the way
sudo python2.7 -m pip install pyudev=0.16
if the "=" doesnt work, use ==
x@ubuntuserv:~$ sudo python2.7 -m pip install pyudev=0.16
Invalid requirement: 'pyudev=0.16' = is not a valid operator. Did you mean == ?
x@ubuntuserv:~$ sudo python2.7 -m pip install pyudev==0.16
works fine
It also has something to do with the version of JDK. If it does well in JDK6, maybe it will have the problem in JDK 7 described by you, because the implementation method in jdk 7 has been changed.
Look at this:
Description: The sorting algorithm used by java.util.Arrays.sort
and (indirectly) by java.util.Collections.sort
has been replaced. The new sort implementation may throw an IllegalArgumentException
if it detects a Comparable
that violates the Comparable
contract. The previous implementation silently ignored such a situation. If the previous behavior is desired, you can use the new system property, java.util.Arrays.useLegacyMergeSort
, to restore previous mergesort behaviour.
I don't know the exact reason. However, if you add the code before you use sort. It will be OK.
System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
Why not ask the U.S. Naval Observatory, the official timekeeper of the United States Navy?
import requests
from lxml import html
page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])
If you live in the D.C. area (like me) the latency might not be too bad...
Just use the function plot
as follows
figure()
...
plot(t, a)
plot(t, b)
plot(t, c)
As we can see from the answers posted, this is surprisingly not a trivial task. When faced with a task like this, it would seem that many programmers choose to throw common sense out the window, in order to produce the most obscure snippet they possibly can come up with.
Things to consider:
' '
.What I would do:
void remove_spaces (char* restrict str_trimmed, const char* restrict str_untrimmed)
{
while (*str_untrimmed != '\0')
{
if(!isspace(*str_untrimmed))
{
*str_trimmed = *str_untrimmed;
str_trimmed++;
}
str_untrimmed++;
}
*str_trimmed = '\0';
}
In this code, the source string "str_untrimmed" is left untouched, which is guaranteed by using proper const correctness. It does not crash if the source string contains nothing but a null termination. It always null terminates the destination string.
Memory allocation is left to the caller. The algorithm should only focus on doing its intended work. It removes all white spaces.
There are no subtle tricks in the code. It does not try to squeeze in as many operators as possible on a single line. It will make a very poor candidate for the IOCCC. Yet it will yield pretty much the same machine code as the more obscure one-liner versions.
When copying something, you can however optimize a bit by declaring both pointers as restrict
, which is a contract between the programmer and the compiler, where the programmer guarantees that the destination and source are not the same address (or rather, that the data they point to are only accessed through that very pointer and not through some other pointer). This allows more efficient optimization, since the compiler can then copy straight from source to destination without temporary memory in between.
What are native methods in Java and where should they be used?
Once you see a small example, it becomes clear:
Main.java:
public class Main {
public native int intMethod(int i);
public static void main(String[] args) {
System.loadLibrary("Main");
System.out.println(new Main().intMethod(2));
}
}
Main.c:
#include <jni.h>
#include "Main.h"
JNIEXPORT jint JNICALL Java_Main_intMethod(
JNIEnv *env, jobject obj, jint i) {
return i * i;
}
Compile and run:
javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
-I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main
Output:
4
Tested on Ubuntu 14.04 with Oracle JDK 1.8.0_45.
So it is clear that it allows you to:
This could be used to:
with the tradeoff of lower portability.
It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?
Example on GitHub for you to play with.
Here is the implementation VB.NET, this implementation will give you the result in KM or Miles based on an Enum value you pass.
Public Enum DistanceType
Miles
KiloMeters
End Enum
Public Structure Position
Public Latitude As Double
Public Longitude As Double
End Structure
Public Class Haversine
Public Function Distance(Pos1 As Position,
Pos2 As Position,
DistType As DistanceType) As Double
Dim R As Double = If((DistType = DistanceType.Miles), 3960, 6371)
Dim dLat As Double = Me.toRadian(Pos2.Latitude - Pos1.Latitude)
Dim dLon As Double = Me.toRadian(Pos2.Longitude - Pos1.Longitude)
Dim a As Double = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(Me.toRadian(Pos1.Latitude)) * Math.Cos(Me.toRadian(Pos2.Latitude)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2)
Dim c As Double = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)))
Dim result As Double = R * c
Return result
End Function
Private Function toRadian(val As Double) As Double
Return (Math.PI / 180) * val
End Function
End Class
You can open the project in the firebase, then you should click on the project overview, then goto project settings you will see the web API Key there.
Check your Project -> Properties -> Java Build Path has JDK
Library instead of JRE System Library
.
Go to Eclipse
installed directory, Search eclipse.ini
-> Open it
Search lines for containing any below values:
-Xms512m -Xmx512m -Xms1024m -Xmx1024m -Xms1G -Xmx1G
Just double it the memory size, Assume you have to change the
-Xms512m to -Xms1024m
Increasing the eclipse memory size will help eclipse
to gain more RAM size from your PC.
These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".
The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.
ffmpeg
vs the fake oneFor a while both Libav and FFmpeg separately developed their own version of ffmpeg
.
Libav then renamed their bizarro ffmpeg
to avconv
to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv
instead of their counterfeit version of ffmpeg
. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.
This message was removed upstream when the fake "ffmpeg
" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.
In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1
. Unfortunately the new "deprecated" message has caused additional user confusion.
Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg
is back in the repositories again.
To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.
If you are using avconv
then you are using Libav. If you are using ffmpeg
you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.
Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h
header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg
or avconv
and viewing the console output.
ffmpeg
The real ffmpeg
is in the repository, so you can install it with:
apt-get install ffmpeg
Your options are:
ffmpeg
,ffmpeg
,These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.
Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg
from the repository.
For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.
containerObject = new JSONObject(container);
if (containerObject.has("video")) {
//get Value of video
}
You can do:
string str = "Hello Marco !";
str = str.Substring(0, str.Length - 2);
Consider this approach, you don't need a for loop:
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(ExitingSqlTableName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
As others have said, there is now an option for Ctrl+Shf+V
for paste in Windows 10 Insider build #17643.
Unfortunately this isn't in my muscle memory and as a user of TTY terminals I'd like to use Shf+Ins
as I do on all the Linux boxes I connect to.
This is possible on Windows 10 if you install ConEmu which wraps the terminal in a new GUI and allows Shf+Ins
for paste. It also allows you to tweak the behaviour in the Properties.
Shf+Ins
works out of the box. I can't remember if you need to configure bash as one of the shells it uses but if you do, here is the task properties to add it:
Also allows tabbed Consoles (including different types, cmd.exe
, powershell
etc). I've been using this since early Windows 7 and in those days it made the command line on Windows usable!
edit: it's currently 2016-09-24, and PHP 5.4 has been released 2012-03-01, and support has ended 2015-09-01. Still, this answer seems to gain upvotes. If you're still using PHP < 5.4, your are creating a security risk and endagering your project. If you have no compelling reasons to stay at <5.4, or even already use version >= 5.4, do not use this answer, and just use PHP>= 5.4 (or, you know, a recent one) and implement the JsonSerializable interface
You would define a function, for instance named getJsonData();
, which would return either an array, stdClass
object, or some other object with visible parameters rather then private/protected ones, and do a json_encode($data->getJsonData());
. In essence, implement the function from 5.4, but call it by hand.
Something like this would work, as get_object_vars()
is called from inside the class, having access to private/protected variables:
function getJsonData(){
$var = get_object_vars($this);
foreach ($var as &$value) {
if (is_object($value) && method_exists($value,'getJsonData')) {
$value = $value->getJsonData();
}
}
return $var;
}
you may check the color before you click to change it.
function abc(){
var color = document.getElementById("test").style.color;
if(color==''){
//change
}else{
//change back
}
}
{background-color: transparent;}
It should be
yadayada.val.split(/\n/)
you're passing in a literal string to the split command, not a regex.
You use the cherry-pick command to get individual commits from one branch.
If the change(s) you want are not in individual commits, then use the method shown here to split the commit into individual commits. Roughly speaking, you use git rebase -i
to get the original commit to edit, then git reset HEAD^
to selectively revert changes, then git commit
to commit that bit as a new commit in the history.
There is another nice method here in Red Hat Magazine, where they use git add --patch
or possibly git add --interactive
which allows you to add just parts of a hunk, if you want to split different changes to an individual file (search in that page for "split").
Having split the changes, you can now cherry-pick just the ones you want.
Try to go back to the internet information services, right clink on the intranet you created and select edit permission.
When the wwwroot pop up windows open, select the sharing tab and click "share" on the drop down menu select the users and their permission level or just select everyone and for permission read and Right
You can simply use:
mvn --settings YourOwnSettings.xml clean install
or
mvn -s YourOwnSettings.xml clean install
I like indent
as mentioned above, but most often I want to format only a small section of the file that I'm working on. Since indent
can take code from stdin, its really simple:
:!indent
.astyle
takes stdin too, so you can use the same trick there.
NSString *string = [NSString stringWithFormat:@"%d", theinteger];
Use this
word-wrap: break-word;
overflow-wrap: break-word;
word-break: break-all;
The file value can either be an absolute path like "c:\logs\log.txt" or a relative path which I believe is relative to the bin directory.
As far as implementing it, I usually place the following at the top of any class I plan to log in:
private static readonly ILog Log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
Finally, you can use it like so:
Log.Debug("This is a DEBUG level message.");
Here, There are two things inside the domain
So you want to style those two sections as follows,
1. Style for the iFrame Section
It can style using CSS with that respected id
or class
name. You can just style it in your parent Style sheets also.
<style>
#my_iFrame{
height: 300px;
width: 100%;
position:absolute;
top:0;
left:0;
border: 1px black solid;
}
</style>
<iframe name='iframe1' id="my_iFrame" src="#" cellspacing="0"></iframe>
2. Style the Page Loaded inside the iFrame
This Styles can be loaded from the parent page with the help of Javascript
var cssFile = document.createElement("link")
cssFile.rel = "stylesheet";
cssFile.type = "text/css";
cssFile.href = "iFramePage.css";
then set that CSS file to the respected iFrame section
//to Load in the Body Part
frames['my_iFrame'].document.body.appendChild(cssFile);
//to Load in the Head Part
frames['my_iFrame'].document.head.appendChild(cssFile);
Here, You can edit the Head Part of the Page inside the iFrame using this way also
var $iFrameHead = $("#my_iFrame").contents().find("head");
$iFrameHead.append(
$("<link/>",{
rel: "stylesheet",
href: urlPath,
type: "text/css" }
));
In Ef .net core there are two options that you can do; first with data annotations:
public class Blog
{
public int BlogId { get; set; }
[Required]
public string Url { get; set; }
}
Or with fluent api:
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.IsRequired(false)//optinal case
.IsRequired()//required case
;
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
There are more details here
You could check this if you like. :)
Use this code if SavedFamilyCode is in the Report Filter:
Sub FilterPivotTable()
Application.ScreenUpdating = False
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = True
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").CurrentPage = _
"K123223"
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = False
Application.ScreenUpdating = True
End Sub
But if the SavedFamilyCode is in the Column or Row Labels use this code:
Sub FilterPivotTable()
Application.ScreenUpdating = False
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = True
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").PivotFilters. _
Add Type:=xlCaptionEquals, Value1:="K123223"
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = False
Application.ScreenUpdating = True
End Sub
Hope this helps you.
This is more commonly known as a null-coalescing operator. Javascript does not have one.
WebKit is a layout engine designed to allow web browsers to render web pages. The WebKit engine provides a set of classes to display web content in windows, and implements browser features such as following links when clicked by the user, managing a back-forward list, and managing a history of pages recently visited.
WebKit was originally created as a fork of KHTML as the layout engine for Apple's Safari; it is portable to many other computing platforms. It is also used in Google's Chrome Browser.
WebKit's WebCore and JavaScriptCore components are available under the GNU Lesser General Public License, and the rest of WebKit is available under a BSD-style license.
Source Wikipedia
For further information about layout engines you can look here
You can get this exception by just a simple/dumb mistake, by (for example) accidentally calling finish()
after having displayed an AlertDialog
, if you miss a break call statement in a switch statement...
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.new_button:
openMyAlertDialog();
break; <-- If you forget this the finish() method below
will be called while the dialog is showing!
case R.id.exit_button:
finish();
break;
}
}
The finish()
method will close the Activity
, but the AlertDialog
is still displaying!
So when you're staring intently at the code, looking for bad threading issues or complex coding and such, don't lose sight of the forest for the trees. Sometimes it can be just something as simple and dumb as a missing break statement. :)
I have just made use of a reference to a pointer to make all the pointers in a deleted binary tree except the root safe. To make the pointer safe we just have to set it to 0. I could not make the function that deletes the tree (keeping only the root) to accept a ref to a pointer since I am using the root (this pointer) as the first input to traverse left and right.
void BinTree::safe_tree(BinTree * &vertex ) {
if ( vertex!=0 ) { // base case
safe_tree(vertex->left); // left subtree.
safe_tree(vertex->right); // right subtree.
// delete vertex; // using this delete causes an error, since they were deleted on the fly using inorder_LVR. If inorder_LVR does not perform delete to the nodes, then, use delete vertex;
vertex=0; // making a safe pointer
}
} // end in
Bottom line, a reference to a pointer is invalid when the formal parameter is the (this) pointer.
String all = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String strLine;
while ((strLine = br.readLine()) != null){
all = all + strLine;
}
} catch (IOException e) {
Log.e("notes_err", e.getLocalizedMessage());
}
I've got solved my problem this way in EF on list of records from db
ListOfObjectToBeOrder.OrderBy(x => x.columnName).ToList();
You can use ElementRef as shown below,
DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.
import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[move]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight); //<<<===here
console.log('width---' + this.el.nativeElement.offsetWidth); //<<<===here
}
}
Same way you can use it within component itself wherever you need it.
You can use ARG
- see https://docs.docker.com/engine/reference/builder/#arg
The
ARG
instruction defines a variable that users can pass at build-time to the builder with thedocker build
command using the--build-arg <varname>=<value>
flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.
You can add this to the callback from $.post
$( '#newsletterform' ).each(function(){
this.reset();
});
You can't just call $( '#newsletterform' ).reset()
because .reset()
is a form object and not a jquery object, or something to that effect. You can read more about it here about half way down the page.
DELETE FROM blob
WHERE fileid NOT IN
(SELECT id
FROM files
WHERE id is NOT NULL/*This line is unlikely to be needed
but using NOT IN...*/
)
One of my first projects as a programmer was a gem called stagecoach that (among other things) allowed the automatic adding of a github issue number to every commit message on a branch, which is a part of the question that hasn't really been answered.
Essentially when creating a branch you'd use a custom command (something like stagecoach -b <branch_name> -g <issue_number>
), and the issue number would then be assigned to that branch in a yml file. There was then a commit hook that appended the issue number to the commit message automatically.
I wouldn't recommend it for production use as at the time I'd only been programming for a few months and I no longer maintain it, but it may be of interest to somebody.
Use TO_TIMESTAMP function
TO_TIMESTAMP(date_string,'YYYY-MM-DD HH24:MI:SS')
I'm guessing you want to center the box both vertically and horizontally, regardless of browser window size. Since you have a fixed width and height for the box, this should work:
Markup:
<div></div>
CSS:
div {
height: 200px;
width: 400px;
background: black;
position: fixed;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -200px;
}
The div should remain in the center of the screen even if you resize the browser. Just replace the margin-top and margin-left with half of the height and width of your table.
Edit: Credit goes to CSS-Tricks, where I got the original idea.
I agree with both previous answers. Basically, you want to use what is known as a "lightbox" - http://en.wikipedia.org/wiki/Lightbox_(JavaScript)
It is essentially a div than is created within the DOM of your current window/tab. In addition to the div that contains your dialog, a transparent overlay blocks the user from engaging all underlying elements. This can effectively create a modal dialog (i.e. user MUST make some kind of decision before moving on).
Use this function to check if a string is alphanumeric:
public boolean isAlphanumeric(String str)
{
char[] charArray = str.toCharArray();
for(char c:charArray)
{
if (!Character.isLetterOrDigit(c))
return false;
}
return true;
}
It saves having to import external libraries and the code can easily be modified should you later wish to perform different validation checks on strings.
ng generate component component_name was not working in my case because instead of using 'app' as project folder name, I renamed it to something else. I again changed it to app. Now, it is working fine
If your list of lists contains lists with varying number of elements then the answer of Ignacio Vazquez-Abrams will not work. Instead there are at least 3 options:
1) Make an array of arrays:
x=[[1,2],[1,2,3],[1]]
y=numpy.array([numpy.array(xi) for xi in x])
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'numpy.ndarray'>
2) Make an array of lists:
x=[[1,2],[1,2,3],[1]]
y=numpy.array(x)
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'list'>
3) First make the lists equal in length:
x=[[1,2],[1,2,3],[1]]
length = max(map(len, x))
y=numpy.array([xi+[None]*(length-len(xi)) for xi in x])
y
>>>array([[1, 2, None],
>>> [1, 2, 3],
>>> [1, None, None]], dtype=object)
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
The correct form, based on the original syntax, and correctly normalized is:
def gaussian(x, mu, sig):
return 1./(np.sqrt(2.*np.pi)*sig)*np.exp(-np.power((x - mu)/sig, 2.)/2)
#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;
println("hello");
That's How Python works. Try this :
from sqlitedbx import SqliteDBzz
Such that you can directly use the name without the enclosing module.Or just import the module and prepend 'sqlitedbx.' to your function,class etc
According to this: http://www.devcha.com/2008/03/svn-directory-svn-containing-working.html
Check-out the folder "blabla" to a different location and then copy its .svn folder back into the original "blabla".
You can also do it by toggling between display: block on hover and display:none without hover to produce the effect.
try this
var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');
function iterate(selector)
{
var result = '';
if ($(selector))
{
$(selector).each(function ()
{
if (result == '')
{
result = $(this).html();
}
else
{
result = result + "," + $(this).html();
}
});
}
}
Change the names of your inputs:
<input name="xyz[]" value="Lorem" />
<input name="xyz[]" value="ipsum" />
<input name="xyz[]" value="dolor" />
<input name="xyz[]" value="sit" />
<input name="xyz[]" value="amet" />
Then:
$_POST['xyz'][0] == 'Lorem'
$_POST['xyz'][4] == 'amet'
If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "xyz".
Note that this is probably the wrong solution. Obviously, it depends on the data you are sending.
Try adding the following to your eclipse.ini file:
-vm
C:\Program Files\Java\jdk1.7.0_01\bin\java.exe
You might also have to change the Dosgi.requiredJavaVersion to 1.7 in the same file.
The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject
You have not added the necessary jar file which will be having org.json.JSONObject
class to your classpath
.
You can Download it From Here
(Under Linux), I wanted to use the posts here suggesting the ls-files --ignored --exclude-standard | xargs git rm -r --cached
approach. However, (some of) the files to be removed had an embedded newline/LF/\n
in their names. Neither of the solutions:
git ls-files --ignored --exclude-standard | xargs -d"\n" git rm --cached
git ls-files --ignored --exclude-standard | sed 's/.*/"&"/' | xargs git rm -r --cached
cope with this situation (get errors about files not found).
git ls-files -z --ignored --exclude-standard | xargs -0 git rm -r --cached
git commit -am "Remove ignored files"
This uses the -z
argument to ls-files, and the -0
argument to xargs to cater safely/correctly for "nasty" characters in filenames.
In the manual page git-ls-files(1), it states:
When -z option is not used, TAB, LF, and backslash characters in pathnames are represented as \t, \n, and \\, respectively.
so I think my solution is needed if filenames have any of these characters in them.
An other regex
-based solution:
>>> strs = "foo\tbar\t\tspam"
>>> r = re.compile(r'([^\t]*)\t*')
>>> r.findall(strs)[:-1]
['foo', 'bar', 'spam']
Here is a simple solution I like:
Put your DB connection info in a YAML file in a secure location (do not version it in the code repo).
---
host: 'hostname'
port: port_number_integer
database: 'databasename'
user: 'username'
password: 'password'
Then load the conf in a dictionary, open the db connection and load the result set of the SQL query in a data frame:
import yaml
import pymysql
import pandas as pd
db_conf_path = '/path/to/db-conf.yaml'
# Load DB conf
with open(db_conf_path) as db_conf_file:
db_conf = yaml.safe_load(db_conf_file)
# Connect to the DB
db_connection = pymysql.connect(**db_conf)
# Load the data into a DF
query = '''
SELECT *
FROM my_table
LIMIT 10
'''
df = pd.read_sql(query, con=db_connection)
I have a use case that I don't quite see covered here, and will argue that this is a valid reason to use Thread.Sleep():
In a console application running cleanup jobs, I need to make a large amount of fairly expensive database calls, to a DB shared by thousands of concurrent users. In order to not hammer the DB and exclude others for hours, I'll need a pause between calls, in the order of 100 ms. This is not related to timing, just to yielding access to the DB for other threads.
Spending 2000-8000 cycles on context switching between calls that may take 500 ms to execute is benign, as does having 1 MB of stack for the thread, which runs as a single instance on a server.
Here's how you can mock your FileConnection
Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
.Throws(new IOException());
Then instantiate your Transfer class and use the mock in your method call
Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);
Update:
First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.
Since you are setting those properties using another dependency, I would write it like this:
public class Transfer
{
public Transfer(IInternalConfig internalConfig)
{
source = internalConfig.GetFileConnection("source");
destination = internalConfig.GetFileConnection("destination");
}
//you should consider making these private or protected fields
public virtual IFileConnection source { get; set; }
public virtual IFileConnection destination { get; set; }
public virtual void GetFile(IFileConnection connection,
string remoteFilename, string localFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void PutFile(IFileConnection connection,
string localFilename, string remoteFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void TransferFiles(string sourceName, string destName)
{
var tempName = Path.GetTempFileName();
GetFile(source, sourceName, tempName);
PutFile(destination, tempName, destName);
}
}
This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.
Overloading means having methods with same name but different signature Overriding means rewriting the virtual method of the base class.............
Check the jQuery FAQ...
You can use the length property of the jQuery collection returned by your selector:
if ( $('#myDiv').length ){}
There's a great blog post on this here:
http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/
Along with a demo here:
http://www.kylejlarson.com/files/iosdemo/
In summary, you can use the following on a div containing your main content:
.scrollable {
position: absolute;
top: 50px;
left: 0;
right: 0;
bottom: 0;
overflow: scroll;
-webkit-overflow-scrolling: touch;
}
The problem I think you're describing is when you try to scroll up within a div that is already at the top - it then scrolls up the page instead of up the div and causes a bounce effect at the top of the page. I think your question is asking how to get rid of this?
In order to fix this, the author suggests that you use ScrollFix to auto increase the height of scrollable divs.
It's also worth noting that you can use the following to prevent the user from scrolling up e.g. in a navigation element:
document.addEventListener('touchmove', function(event) {
if(event.target.parentNode.className.indexOf('noBounce') != -1
|| event.target.className.indexOf('noBounce') != -1 ) {
event.preventDefault(); }
}, false);
Unfortunately there are still some issues with ScrollFix (e.g. when using form fields), but the issues list on ScrollFix is a good place to look for alternatives. Some alternative approaches are discussed in this issue.
Other alternatives, also mentioned in the blog post, are Scrollability and iScroll
The ideal way to do it will be using "INSERT OVERWRITE DIRECTORY '/pathtofile' select * from temp where id > 100" instead of "hive -e 'select * from...' > /filepath.txt"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace data_seniens
{
class Program
{
static void Main(string[] args)
{
//new list
float [] x=new float[]{11.25f,18.0f,20.0f,10.75f,9.50f, 11.25f, 18.0f, 20.0f, 10.75f, 9.50f };
//variable
float eat_sleep_area=x[1]+x[3];
//print
foreach (var VARIABLE in x)
{
if (VARIABLE < x[7])
{
Console.WriteLine(VARIABLE);
}
}
//keep app run
Console.ReadLine();
}
}
}
The only thing that a computer can store is bytes.
To store anything in a computer, you must first encode it, i.e. convert it to bytes. For example:
MP3
, WAV
, etc.PNG
, JPEG
, etc. ASCII
, UTF-8
, etc.MP3
, WAV
, PNG
, JPEG
, ASCII
and UTF-8
are examples of encodings. An encoding is a format to represent audio, images, text, etc in bytes.
In Python, a byte string is just that: a sequence of bytes. It isn't human-readable. Under the hood, everything must be converted to a byte string before it can be stored in a computer.
On the other hand, a character string, often just called a "string", is a sequence of characters. It is human-readable. A character string can't be directly stored in a computer, it has to be encoded first (converted into a byte string). There are multiple encodings through which a character string can be converted into a byte string, such as ASCII
and UTF-8
.
'I am a string'.encode('ASCII')
The above Python code will encode the string 'I am a string'
using the encoding ASCII
. The result of the above code will be a byte string. If you print it, Python will represent it as b'I am a string'
. Remember, however, that byte strings aren't human-readable, it's just that Python decodes them from ASCII
when you print them. In Python, a byte string is represented by a b
, followed by the byte string's ASCII
representation.
A byte string can be decoded back into a character string, if you know the encoding that was used to encode it.
b'I am a string'.decode('ASCII')
The above code will return the original string 'I am a string'
.
Encoding and decoding are inverse operations. Everything must be encoded before it can be written to disk, and it must be decoded before it can be read by a human.
Now you may have a better solution to resolve this scenario, but other way which i preferred.
const arr = [1,3,12]
if( arr.includes(foo)) { // it will return true if you `foo` is one of array values else false
// code here
}
I preferred above solution over the indexOf check where you need to check index as well.
if ( arr.indexOf( foo ) !== -1 ) { }
I noticed that there are few example of using Java 8 stream to solve your problem but I think that this is the simplest one:
int[] intTab = String.valueOf(number).chars().map(Character::getNumericValue).toArray();
To be clear:
You use String.valueOf(number)
to convert int to String, then chars()
method to get an IntStream (each char from your string is now an Ascii number), then you need to run map()
method to get a numeric values of the Ascii number. At the end you use toArray()
method to change your stream into an int[] array.
I have this code:
<html>_x000D_
<head>_x000D_
<SCRIPT type=text/javascript>_x000D_
function deshabilitarBoton() { _x000D_
document.getElementById("boton").style.display = 'none';_x000D_
document.getElementById("envio").innerHTML ="<br><img src='img/loading.gif' width='16' height='16' border='0'>Generando..."; _x000D_
return true;_x000D_
} _x000D_
</SCRIPT>_x000D_
<title>untitled</title>_x000D_
</head>_x000D_
<body>_x000D_
<form name="form" action="ok.do" method="post" >_x000D_
<table>_x000D_
<tr>_x000D_
<td>Fecha inicio:</td>_x000D_
<td><input type="TEXT" name="fecha_inicio" id="fecha_inicio" /></td>_x000D_
</tr>_x000D_
</table>_x000D_
<div id="boton">_x000D_
<input type="submit" name="event" value="Enviar" class="button" onclick="return deshabilitarBoton()" />_x000D_
</div>_x000D_
<div id="envio">_x000D_
</div>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
There are many ways using them you can enable/disable any element :
Approach 1
$("#txtName").attr("disabled", true);
Approach 2
$("#txtName").attr("disabled", "disabled");
If you are using jQuery 1.7 or higher version then use prop(), instead of attr().
$("#txtName").prop("disabled", "disabled");
If you wish to enable any element then you just have to do opposite of what you did to make it disable. However jQuery provides another way to remove any attribute.
Approach 1
$("#txtName").attr("disabled", false);
Approach 2
$("#txtName").attr("disabled", "");
Approach 3
$("#txtName").removeAttr("disabled");
Again, if you are using jQuery 1.7 or higher version then use prop(), instead of attr(). That's is. This is how you enable or disable any element using jQuery.
getch () function returns two keycodes for arrow keys (and some other special keys), as mentioned in the comment by FatalError. It returns either 0 (0x00) or 224 (0xE0) first, and then returns a code identifying the key that was pressed.
For the arrow keys, it returns 224 first followed by 72 (up), 80 (down), 75 (left) and 77 (right). If the num-pad arrow keys (with NumLock off) are pressed, getch () returns 0 first instead of 224.
Please note that getch () is not standardized in any way, and these codes might vary from compiler to compiler. These codes are returned by MinGW and Visual C++ on Windows.
A handy program to see the action of getch () for various keys is:
#include <stdio.h>
#include <conio.h>
int main ()
{
int ch;
while ((ch = _getch()) != 27) /* 27 = Esc key */
{
printf("%d", ch);
if (ch == 0 || ch == 224)
printf (", %d", _getch ());
printf("\n");
}
printf("ESC %d\n", ch);
return (0);
}
This works for MinGW and Visual C++. These compilers use the name _getch () instead of getch () to indicate that it is a non-standard function.
So, you may do something like:
ch = _getch ();
if (ch == 0 || ch == 224)
{
switch (_getch ())
{
case 72:
/* Code for up arrow handling */
break;
case 80:
/* Code for down arrow handling */
break;
/* ... etc ... */
}
}
No, you must have an Intel Mac of some sort. I went to Best Buy and got a 24" iMac with 4G RAM for $1499 using their 18 month no interest promotion. I pay a minimum payment of something like $16 a month. As long as I pay the entire thing off within 18 months - no interest. That was the only way I was getting into iPhone development.
armhf
stands for "arm hard float", and is the name given to a debian port for arm processors (armv7+) that have hardware floating point support.
On the beaglebone black, for example:
:~$ dpkg --print-architecture
armhf
Although other commands (such as uname -a
or arch
) will just show armv7l
:~$ cat /proc/cpuinfo
processor : 0
model name : ARMv7 Processor rev 2 (v7l)
BogoMIPS : 995.32
Features : half thumb fastmult vfp edsp thumbee neon vfpv3 tls
...
The vfpv3
listed under Features
is what refers to the floating point support.
Incidentally, armhf
, if your processor supports it, basically supersedes Raspbian, which if I understand correctly was mainly a rebuild of armhf
with work arounds to deal with the lack of floating point support on the original raspberry pi's. Nowdays, of course, there's a whole ecosystem build up around Raspbian, so they're probably not going to abandon it. However, this is partly why the beaglebone runs straight debian, and that's ok even if you're used to Raspbian, unless you want some of the special included non-free software such as Mathematica.
It's just the method. You're not missing anything. The official documentation shows that you can use list unpacking to supply several paths:
s = "c:/,home,foo,bar,some.txt".split(",")
os.path.join(*s)
Note the *s
intead of just s
in os.path.join(*s)
. Using the asterisk will trigger the unpacking of the list, which means that each list argument will be supplied to the function as a separate argument.
I had your issue and got it working again (on windows 7).
My setup had actually worked at first. I installed postgres and then set up the system PATH variables with C:\Program Files\PostgreSQL\9.6\bin; C:\Program Files\PostgreSQL\9.6\lib
. The psql keyword in the command line gave no errors.
I deleted the PATH variables above one at a time to test if they were both really needed. Psql continued to work after I deleted the lib path, but stopped working after I deleted the bin path. When I returned bin, it still didn't work, and the same with lib. I closed and reopened the command line between tries, and checked the path. The problem lingered even though the path was identical to how it had been when working. I re-pasted it.
I uninstalled and reinstalled postgres. The problem lingered. It finally worked after I deleted the spaces between the "; C:..." in the paths and re-saved.
Not sure if it was really the spaces that were the culprit. Maybe the environment variables just needed to be altered and refreshed after the install.
I'm also still not sure if both lib and bin paths are needed since there seems to be some kind of lingering memory for old path configurations. I don't want to test it again though.
Just to show yet another option (for SQL Server 2008 and above):
Content is what is passed as children. View is the template of the current component.
The view is initialized before the content and ngAfterViewInit()
is therefore called before ngAfterContentInit()
.
** ngAfterViewInit()
is called when the bindings of the children directives (or components) have been checked for the first time. Hence its perfect for accessing and manipulating DOM with Angular 2 components. As @Günter Zöchbauer mentioned before is correct @ViewChild()
hence runs fine inside it.
Example:
@Component({
selector: 'widget-three',
template: `<input #input1 type="text">`
})
export class WidgetThree{
@ViewChild('input1') input1;
constructor(private renderer:Renderer){}
ngAfterViewInit(){
this.renderer.invokeElementMethod(
this.input1.nativeElement,
'focus',
[]
)
}
}
use this to upload a file to a remote location
#!/bin/bash
#$1 is the file name
#usage:this_script <filename>
HOST='your host'
USER="your user"
PASSWD="pass"
FILE="abc.php"
REMOTEPATH='/html'
ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASSWD
cd $REMOTEPATH
put $FILE
quit
END_SCRIPT
exit 0
The following solution should work quite well for what you are trying to do.
The JavaScript block is placed very late in the document so you don't have to worry about elements not existing.
You are setting a PHP variable at the top of the script and outputting just the value of the variable within the JavaScript block.
This way, you don't have to worry about escaping double-quotes or HEREDOCS (which is the recommended method if you REALLY must go there).
Javascript Embedding Example
<div id="helloContainer"><div>
<script type="text/javascript">
document.getElementById('helloContainer').innerHTML = '<?= $greeting; ?>';
</script>
It is just a matter of changing the port user by mysql:3308 to 3306
Just right click on wamp-> select tools
under Port Used By mysql:3308 clcik on "use a port other than 3308
In the text port text box appear : type 3306 and save. Wait until the wampserver restarts and get green.
Now run your PHP code, It will work. That's it - Good Luck
The square brackets in your code are used in the mysql documentation to indicate groups of optional parameters. They should not be in the actual query.
The only command you actually need is:
show tables;
If you want tables from a specific database, let's say the database "books", then it would be
show tables from books;
You only need the LIKE part if you want to find tables whose names match a certain pattern. e.g.,
show tables from books like '%book%';
would show you the names of tables that have "book" somewhere in the name.
Furthermore, just running the "show tables" query will not produce any output that you can see. SQL answers the query and then passes it to PHP, but you need to tell PHP to echo it to the page.
Since it sounds like you're very new to SQL, I'd recommend running the mysql client from the command line (or using phpmyadmin, if it's installed on your system). That way you can see the results of various queries without having to go through PHP's functions for sending queries and receiving results.
If you have to use PHP, here's a very simple demonstration. Try this code after connecting to your database:
$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result
echo($table[0] . "<BR>"); // print the table that was returned on that row.
}
I was going to add this just to be silly, but also because it shows newcomers the potential usefulness of aliasing functions and/or imports.
Having written it, I think this code is more readable (i.e. lower time to grasp intention) than the other answers to date, and readability is (usually) king.
from os.path import dirname as up
two_up = up(up(__file__))
Note: you only want to do this kind of thing if your module is very small, or contextually cohesive.
Just for those that need the VB.NET version of the top-answer:
Public Function ToQueryString(nvc As System.Collections.Specialized.NameValueCollection) As String
Dim array As String() = nvc.AllKeys.SelectMany(Function(key As String) nvc.GetValues(key), Function(key As String, value As String) String.Format("{0}={1}", System.Web.HttpUtility.UrlEncode(key), System.Web.HttpUtility.UrlEncode(value))).ToArray()
Return "?" + String.Join("&", array)
End Function
And the version without LINQ:
Public Function ToQueryString(nvc As System.Collections.Specialized.NameValueCollection) As String
Dim lsParams As New List(Of String)()
For Each strKey As String In nvc.AllKeys
Dim astrValue As String() = nvc.GetValues(strKey)
For Each strValue As String In astrValue
lsParams.Add(String.Format("{0}={1}", System.Web.HttpUtility.UrlEncode(strKey), System.Web.HttpUtility.UrlEncode(strValue)))
Next ' Next strValue
Next ' strKey
Dim astrParams As String() = lsParams.ToArray()
lsParams.Clear()
lsParams = Nothing
Return "?" + String.Join("&", astrParams)
End Function ' ToQueryString
And the C# version without LINQ:
public static string ToQueryString(System.Collections.Specialized.NameValueCollection nvc)
{
List<string> lsParams = new List<string>();
foreach (string strKey in nvc.AllKeys)
{
string[] astrValue = nvc.GetValues(strKey);
foreach (string strValue in astrValue)
{
lsParams.Add(string.Format("{0}={1}", System.Web.HttpUtility.UrlEncode(strKey), System.Web.HttpUtility.UrlEncode(strValue)));
} // Next strValue
} // Next strKey
string[] astrParams =lsParams.ToArray();
lsParams.Clear();
lsParams = null;
return "?" + string.Join("&", astrParams);
} // End Function ToQueryString
If I understand you correctly you are asking about including nested properties. If so :
.Include(x => x.ApplicationsWithOverrideGroup.NestedProp)
or
.Include("ApplicationsWithOverrideGroup.NestedProp")
or
.Include($"{nameof(ApplicationsWithOverrideGroup)}.{nameof(NestedProp)}")
OK, so within minutes after posting the question, I found the answer myself here: https://github.com/npm/npm/issues/2119#issuecomment-5321857
The issue seems to be that npm is not that great with HTTPS over a proxy. Changing the registry URL from HTTPS to HTTP fixed it for me:
npm config set registry http://registry.npmjs.org/
I still have to provide the proxy config (through Authoxy in my case), but everything works fine now.
Seems to be a common issue, but not well documented. I hope this answer here will make it easier for people to find if they run into this issue.
As already well noted, you can't have constructors on an Interface. But since this is such a highly ranked result in Google some 7 years later, I thought I would chip in here - specifically to show how you could use an abstract base class in tandem with your existing Interface and maybe cut down on the amount of refactoring needed in the future for similar situations. This concept has already been hinted at in some of the comments but I thought it would be worth showing how to actually do it.
So you have your main interface that looks like this so far:
public interface IDrawable
{
void Update();
void Draw();
}
Now create an abstract class with the constructor you want to enforce. Actually, since it's now available since the time you wrote your original question, we can get a little fancy here and use generics in this situation so that we can adapt this to other interfaces that might need the same functionality but have different constructor requirements:
public abstract class MustInitialize<T>
{
public MustInitialize(T parameters)
{
}
}
Now you'll need to create a new class that inherits from both the IDrawable interface and the MustInitialize abstract class:
public class Drawable : MustInitialize<GraphicsDeviceManager>, IDrawable
{
GraphicsDeviceManager _graphicsDeviceManager;
public Drawable(GraphicsDeviceManager graphicsDeviceManager)
: base (graphicsDeviceManager)
{
_graphicsDeviceManager = graphicsDeviceManager;
}
public void Update()
{
//use _graphicsDeviceManager here to do whatever
}
public void Draw()
{
//use _graphicsDeviceManager here to do whatever
}
}
Then just create an instance of Drawable and you're good to go:
IDrawable drawableService = new Drawable(myGraphicsDeviceManager);
The cool thing here is that the new Drawable class we created still behaves just like what we would expect from an IDrawable.
If you need to pass more than one parameter to the MustInitialize constructor, you can create a class that defines properties for all of the fields you'll need to pass in.
That is the function that I used for my project, and it works as expected.
function array_csv_download( $array, $filename = "export.csv", $delimiter=";" )
{
header( 'Content-Type: application/csv' );
header( 'Content-Disposition: attachment; filename="' . $filename . '";' );
// clean output buffer
ob_end_clean();
$handle = fopen( 'php://output', 'w' );
// use keys as column titles
fputcsv( $handle, array_keys( $array['0'] ) );
foreach ( $array as $value ) {
fputcsv( $handle, $value , $delimiter );
}
fclose( $handle );
// flush buffer
ob_flush();
// use exit to get rid of unexpected output afterward
exit();
}
Try setting the variable CMAKE_CXX_FLAGS
instead of CMAKE_C_FLAGS
:
set (CMAKE_CXX_FLAGS "-fexceptions")
The variable CMAKE_C_FLAGS
only affects the C compiler, but you are compiling C++ code.
Adding the flag to CMAKE_EXE_LINKER_FLAGS
is redundant.
$array[0] = 1;
$array[2] = 2;
$arrayTxt = implode( ',', $array);
$sql = "SELECT * FROM table WHERE some_id in ($arrayTxt)"
Sessions are server-side files that contain user information, while Cookies are client-side files that contain user information. Sessions have a unique identifier that maps them to specific users. This identifier can be passed in the URL or saved into a session cookie.
Most modern sites use the second approach, saving the identifier in a Cookie instead of passing it in a URL (which poses a security risk). You are probably using this approach without knowing it, and by deleting the cookies you effectively erase their matching sessions as you remove the unique session identifier contained in the cookies.
There is nothing you can do on your end (client side). You can not enable crossDomain calls yourself, the source (dailymotion.com) needs to have CORS enabled for this to work.
The only thing you can really do is to create a server side proxy script which does this for you. Are you using any server side scripts in your project? PHP, Python, ASP.NET etc? If so, you could create a server side "proxy" script which makes the HTTP call to dailymotion and returns the response. Then you call that script from your Javascript code, since that server side script is on the same domain as your script code, CORS will not be a problem.
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
go to FileZilla and select which folder you will be give 777 permission, then right click set permission 777 and select check box, then ok.
hyperlink1.NavigateUrl = "#"; or
hyperlink1.attributes["href"] = "#"; or
<asp:HyperLink NavigateUrl="#" runat="server" />
if os.path.isfile(path_to_file):
try:
open(path_to_file)
pass
except IOError as e:
print "Unable to open file"
Raising exceptions is considered to be an acceptable, and Pythonic, approach for flow control in your program. Consider handling missing files with IOErrors. In this situation, an IOError exception will be raised if the file exists but the user does not have read permissions.
Wireshark, Firebug, Fiddler all do similar things - capture network traffic.
Wireshark captures any kind of network packet. It can capture packet details below TCP/IP (HTTP is at the top). It does have filters to reduce the noise it captures.
Firebug tracks each request the browser page makes and captures the associated headers and the time taken for each stage of the request (DNS, receiving, sending, ...).
Fiddler works as an HTTP/HTTPS proxy. It captures every HTTP request the computer makes and records everything associated with it. It does allow things like converting post variables to a table form and editing/replaying requests. It doesn't, by default, capture localhost traffic in IE, see the FAQ for the workaround.
You will have to manually delete from the project explorer (your local machine hard drive), then delete the project in IntelliJ when it asks to re-open recent projects.
Note: From Graph API v8.0 you must provide the access token
for every UserID request you do.
Hitting the graph API:
https://graph.facebook.com/<user_id>/picture?height=1000&access_token=<any_of_above_token>
With firebase:
FirebaseUser user = mAuth.getCurrentUser();
String photoUrl = user.getPhotoUrl() + "/picture?height=1000&access_token=" +
loginResult.getAccessToken().getToken();
You get the token from registerCallback
just like this
LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
FirebaseUser user = mAuth.getCurrentUser();
String photoUrl = user.getPhotoUrl() + "/picture?height=1000&access_token=" + loginResult.getAccessToken().getToken();
}
@Override
public void onCancel() {
Log.d("Fb on Login", "facebook:onCancel");
}
@Override
public void onError(FacebookException error) {
Log.e("Fb on Login", "facebook:onError", error);
}
});
This is what documentation says:
Beginning October 24, 2020, an access token will be required for all UID-based queries. If you query a UID and thus must include a token:
- use a User access token for Facebook Login authenticated requests
- use a Page access token for page-scoped requests
- use an App access token for server-side requests
- use a Client access token for mobile or web client-side requests
We recommend that you only use a Client token if you are unable to use one of the other token types.
There are several good answers here, so let me provide a terrible one:
: you can type in anything below, doesnt have to match anything
yum whatprovides "me with a life"
: result of the above (some liberties taken with spacing):
Loaded plugins: fastestmirror
base | 3.6 kB 00:00
extras | 3.4 kB 00:00
updates | 3.4 kB 00:00
(1/4): extras/7/x86_64/primary_db | 166 kB 00:00
(2/4): base/7/x86_64/group_gz | 155 kB 00:00
(3/4): updates/7/x86_64/primary_db | 9.1 MB 00:04
(4/4): base/7/x86_64/primary_db | 5.3 MB 00:05
Determining fastest mirrors
* base: mirrors.xmission.com
* extras: mirrors.xmission.com
* updates: mirrors.xmission.com
base/7/x86_64/filelists_db | 6.2 MB 00:02
extras/7/x86_64/filelists_db | 468 kB 00:00
updates/7/x86_64/filelists_db | 5.3 MB 00:01
No matches found
: the key result above is that "primary_db" files were downloaded
: filelists are downloaded EVEN IF you have keepcache=0 in your yum.conf
: note you can limit this to "primary_db.sqlite" if you really want
find /var/cache/yum -name '*.sqlite'
: if you download/install a new repo, run the exact same command again
: to get the databases for the new repo
: if you know sqlite you can stop reading here
: if not heres a sample command to dump the contents
echo 'SELECT packages.name, GROUP_CONCAT(files.name, ", ") AS files FROM files JOIN packages ON (files.pkgKey = packages.pkgKey) GROUP BY packages.name LIMIT 10;' | sqlite3 -line /var/cache/yum/x86_64/7/base/gen/primary_db.sqlite
: remove "LIMIT 10" above for the whole list
: format chosen for proof-of-concept purposes, probably can be improved a lot
function return2tab (div)
{
document.addEventListener('keydown', function (ev) {
if (ev.key === "Enter" && ev.target.nodeName === 'INPUT') {
var focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]';
let ol= div.querySelectorAll(focusableElementsString);
for (let i=0; i<ol.length; i++) {
if (ol[i] === ev.target) {
let o= i<ol.length-1? ol[i+1]: o[0];
o.focus(); break;
}
}
ev.preventDefault();
}
});
}
The addLast() needs some optimisation as the while loop inside addLast() has O(n) complexity. Below is my implementation of LinkedList. Run the code with ll.addLastx(i) once and run it with ll.addLast(i) again , you can see their is a lot of difference in processing time of addLastx() with addLast().
Node.java
package in.datastructure.java.LinkedList;
/**
* Created by abhishek.panda on 07/07/17.
*/
public final class Node {
int data;
Node next;
Node (int data){
this.data = data;
}
public String toString(){
return this.data+"--"+ this.next;
}
}
LinkedList.java
package in.datastructure.java.LinkedList;
import java.util.ArrayList;
import java.util.Date;
public class LinkedList {
Node head;
Node lastx;
/**
* @description To append node at end looping all nodes from head
* @param data
*/
public void addLast(int data){
if(head == null){
head = new Node(data);
return;
}
Node last = head;
while(last.next != null) {
last = last.next;
}
last.next = new Node(data);
}
/**
* @description This keep track on last node and append to it
* @param data
*/
public void addLastx(int data){
if(head == null){
head = new Node(data);
lastx = head;
return;
}
if(lastx.next == null){
lastx.next = new Node(data);
lastx = lastx.next;
}
}
public String toString(){
ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
Node current = head;
while(current.next != null) {
arrayList.add(current.data);
current = current.next;
}
if(current.next == null) {
arrayList.add(current.data);
}
return arrayList.toString();
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
/**
* @description Checking the code optimization of append code
*/
Date startTime = new Date();
for (int i = 0 ; i < 100000 ; i++){
ll.addLastx(i);
}
Date endTime = new Date();
System.out.println("To total processing time : " + (endTime.getTime()-startTime.getTime()));
System.out.println(ll.toString());
}
}
doReturn( value1, value2, value3 ).when( method-call )
You can't set a number in an arbitrary place in the array without telling the array how big it needs to be. For your example: int[] array = new int[4];
You can't. You can use primitives (int, char, short, byte) and String (Strings in java 7 only) in switch. primitives can't be null.
Check i
in separate condition before switch.
You can use the built in xDocument.CreateReader() and an XmlNodeReader to convert back and forth.
Putting that into an Extension method to make it easier to work with.
using System;
using System.Xml;
using System.Xml.Linq;
namespace MyTest
{
internal class Program
{
private static void Main(string[] args)
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");
var xDocument = xmlDocument.ToXDocument();
var newXmlDocument = xDocument.ToXmlDocument();
Console.ReadLine();
}
}
public static class DocumentExtensions
{
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using(var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
}
}
Sources:
file_put_contents("filelist.txt", "");
You can redirect by using the header() function to modify the Location header.