$.getJSON
is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.
Alternatively you could use jQuery's $.when/.then(), similar to this:
var input = "netuetamundis"; var sID; $(document).ready(function () { $.when($.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/" + input + "?api_key=API_KEY_HERE", function () { obj = name; sID = obj.id; console.log(sID); })).then(function () { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function (stats) { console.log(stats); }); }); });
This would be more open for future modification and separates out the responsibility for the first call to know about the second call.
The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
Running npm i [email protected]
solved my issue.
I think that your problem was emerged from typescript and module version mismatch.This issue is very similar to your question and answers are very satisfying.
Here is I solved:
Open the extension settings:
And search for the variable you want to change, and unchecked/checked it
The variables you should consider are:
intelephense.diagnostics.undefinedTypes
intelephense.diagnostics.undefinedFunctions
intelephense.diagnostics.undefinedConstants
intelephense.diagnostics.undefinedClassConstants
intelephense.diagnostics.undefinedMethods
intelephense.diagnostics.undefinedProperties
intelephense.diagnostics.undefinedVariables
import React, { useState } from "react"
const inputTextValue = ({ initialValue }) => {
const [value, setValue] = useState(initialValue);
return {
value,
onChange: (e) => { setValue(e.target.value) }
};
};
export default () => {
const textValue = inputTextValue("");
return (<>
<input {...textValue} />
</>
);
}
/*"Solution I Tired Changed Name of Funtion in Captial "*/
import React, { useState } from "react"
const InputTextValue = ({ initialValue }) => {
const [value, setValue] = useState(initialValue);
return {
value,
onChange: (e) => { setValue(e.target.value) }
};
};
export default () => {
const textValue = InputTextValue("");
return (<>
<input {...textValue} />
</>
);
}
If you are using Typescript 3.7 or newer you can now also do:
const data = change?.after?.data();
if(!data) {
console.error('No data here!');
return null
}
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
Typescript is saying that change
or data
is possibly undefined
(depending on what onUpdate
returns).
So you should wrap it in a null/undefined check:
if(change && change.after && change.after.data){
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
}
If you are 100% sure that your object
is always defined then you can put this:
const data = change.after!.data();
A more production-ready way to handle this is to actually ensure that name
is present. Assuming this is a minimal example of a larger project that a group of people are involved with, you don't know how getPerson
will change in the future.
if (!person.name) {
throw new Error("Unexpected error: Missing name");
}
let name1: string = person.name;
Alternatively, you can type name1
as string | undefined
, and handle cases of undefined
further down. However, it's typically better to handle unexpected errors earlier on.
You can also let TypeScript infer the type by omitting the explicit type: let name1 = person.name
This will still prevent name1
from being reassigned as a number, for example.
try changing setDivSizeThrottleable
to
this.setDivSizeThrottleable = throttle(
() => {
if (this.isComponentMounted) {
this.setState({
pdfWidth: this.pdfWrapper!.getBoundingClientRect().width - 5,
});
}
},
500,
{ leading: false, trailing: true }
);
This has always worked for me:
type Props = {
children: JSX.Element;
};
new Buffer(number) // Old
Buffer.alloc(number) // New
new Buffer(string) // Old
Buffer.from(string) // New
new Buffer(string, encoding) // Old
Buffer.from(string, encoding) // New
new Buffer(...arguments) // Old
Buffer.from(...arguments) // New
Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.
The example in the other answer is unnecessarily complex. This would be more straightforward, if all you want to do is return the raw data objects for each document in a query or collection:
async getMarker() {
const snapshot = await firebase.firestore().collection('events').get()
return snapshot.docs.map(doc => doc.data());
}
Using Blob
as a source for an img
:
template:
<img [src]="url">
component:
public url : SafeResourceUrl;
constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
this.getImage('/api/image.jpg').subscribe(x => this.url = x)
}
public getImage(url: string): Observable<SafeResourceUrl> {
return this.http
.get(url, { responseType: 'blob' })
.pipe(
map(x => {
const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
}),
);
}
Further reference about trusting save values
You should define a key name while storing data to local storage which should be a string and value should be a string
localStorage.setItem('dataSource', this.dataSource.length);
and to print, you should use getItem
console.log(localStorage.getItem('dataSource'));
Assuming that onMove
is an event handler, it is likely that its context is something other than the instance of MyContainer
, i.e. this
points to something different.
You can manually bind the context of the function during the construction of the instance via Function.bind
:
class MyContainer extends Component {
constructor(props) {
super(props);
this.onMove = this.onMove.bind(this);
this.test = "this is a test";
}
onMove() {
console.log(this.test);
}
}
Also, test !== testVariable
.
To add background Image, React Native is based on component, the ImageBackground Component requires two props style={{}} and source={require('')}
<ImageBackground source={require('./wallpaper.jpg')} style={{width: '100%', height: '100%'}}>
<....yourContent Goes here...>
</ImageBackground>
This is TypeScript version of @Joel's answer. It is usable after Node 11.0:
import { promises as fs } from 'fs';
async function loadMonoCounter() {
const data = await fs.readFile('monolitic.txt', 'binary');
return Buffer.from(data);
}
In your onHandleSubmit
function, set your state to {city: ''}
again like this :
this.setState({ city: '' });
*NgIf can create problem here , so either use display none css or easier way is to Use [hidden]="!condition"
You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance
before trying to spy on the method.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const instance = app.instance()
const spy = jest.spyOn(instance, 'myClickFunc')
instance.forceUpdate();
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html
updated
might be what you're looking for. https://vuejs.org/v2/api/#updated
Strangely enough, the reason for my failure was about the CamelCase that I was applying to the component name. MyComponent
was giving me this error but then I renamed it to Mycomponent
and voila, it worked!!!
Here is how its done in Angular 6
<li *ngFor="let user of userObservable ; first as isFirst">
<span *ngIf="isFirst">default</span>
</li>
Note the change from let first = first
to first as isFirst
In my case (I'm using typescript) I was trying to simulate response with fake data where the data is assigned later on. My first attempt was with:
let response = {status: 200, data: []};
and later, on the assignment of the fake data it starts complaining that it is not assignable to type 'never[]'. Then I defined the response like follows and it accepted it..
let dataArr: MyClass[] = [];
let response = {status: 200, data: dataArr};
and assigning of the fake data:
response.data = fakeData;
It actually is working, but there is difference between null
and undefined
. You are actually assigning to uemail, which would return a value or null in case it does not exists. As per documentation.
For more information about the difference between the both of them, see this answer.
For a solution to this Garfty's answer may work, depending on what your requirement is. You may also want to have a look here.
the same problem also happened to me when i training my classification model. the reason caused this problem is as what the warning message said "in labels with no predicated samples", it will caused the zero-division when compute f1-score. I found another solution when i read sklearn.metrics.f1_score doc, there is a note as follows:
When true positive + false positive == 0, precision is undefined; When true positive + false negative == 0, recall is undefined. In such cases, by default the metric will be set to 0, as will f-score, and UndefinedMetricWarning will be raised. This behavior can be modified with zero_division
the zero_division
default value is "warn"
, you could set it to 0
or 1
to avoid UndefinedMetricWarning
.
it works for me ;) oh wait, there is another problem when i using zero_division
, my sklearn report that no such keyword argument by using scikit-learn 0.21.3. Just update your sklearn to the latest version by running pip install scikit-learn -U
Same error, I upgrade my Junit
and resolve it
org.junit.jupiter:junit-jupiter-api:5.0.0-M6
to
org.junit.jupiter:junit-jupiter-api:5.0.0
So I had this exact same issue and lost about 6 hours of my life searching, I had the
withCredentials: true
But the browser still didn't save the cookie until for some weird reason I had the idea to shuffle the configuration setting:
Axios.post(GlobalVariables.API_URL + 'api/login', {
email,
password,
honeyPot
}, {
withCredentials: true,
headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}});
Seems like you should always send the 'withCredentials' Key first.
so if you need want use this code )
import { useRoutes } from "./routes";
import { BrowserRouter as Router } from "react-router-dom";
export const App = () => {
const routes = useRoutes(true);
return (
<Router>
<div className="container">{routes}</div>
</Router>
);
};
// ./routes.js
import { Switch, Route, Redirect } from "react-router-dom";
export const useRoutes = (isAuthenticated) => {
if (isAuthenticated) {
return (
<Switch>
<Route path="/links" exact>
<LinksPage />
</Route>
<Route path="/create" exact>
<CreatePage />
</Route>
<Route path="/detail/:id">
<DetailPage />
</Route>
<Redirect path="/create" />
</Switch>
);
}
return (
<Switch>
<Route path={"/"} exact>
<AuthPage />
</Route>
<Redirect path={"/"} />
</Switch>
);
};
In my case I forgot to import and export my (new) elements called by the render in the index.js file.
I upgraded VS2017 from version 15.2 to 15.8. With version 15.8 here's what happened:
Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0 no longer worked for me! I had to change it to 10.0.17134.0 and then everything built again. After the upgrade and without making this change, I was getting the same header file errors.
I would have submitted this as a comment on one of the other answers but I don't have enough reputation yet.
Add your <script>
to the bottom of your <body>
, or add an event listener for DOMContentLoaded
following this StackOverflow question.
If that script executes in the <head>
section of the code, document.getElementsByClassName(...)
will return an empty array because the DOM is not loaded yet.
You're getting the Type Error
because you're referencing search_span[0]
, but search_span[0]
is undefined
.
This works when you execute it in Dev Tools because the DOM is already loaded.
Current route properties are present in this.$route
, this.$router
is the instance of router object which gives the configuration of the router. You can get the current route query using this.$route.query
Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register
parameter, independently of the module used.
Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:
---
- hosts: localhost
tasks:
- shell: ls
register: shell_result
- debug:
var: shell_result.stdout_lines
Here register
tells ansible to save the response of the module into the shell_result
variable, and then we use the debug
module to print the variable out.
An example run would look like the this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
changed: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"shell_result.stdout_lines": [
"play.yml"
]
}
Responses can contain multiple fields. stdout_lines
is one of the default fields you can expect from a module's response.
Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout
or stdout_lines
values, however the msg
field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.
Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v
, -vvv
and -vvvv
. For example when running the playbook with verbosity (-vvv
) you get this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
(...)
changed: [localhost] => {
"changed": true,
"cmd": "ls",
"delta": "0:00:00.007621",
"end": "2017-02-17 23:04:41.912570",
"invocation": {
"module_args": {
"_raw_params": "ls",
"_uses_shell": true,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"warn": true
},
"module_name": "command"
},
"rc": 0,
"start": "2017-02-17 23:04:41.904949",
"stderr": "",
"stdout": "play.retry\nplay.yml",
"stdout_lines": [
"play.retry",
"play.yml"
],
"warnings": []
}
As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines
is available, and its contents are what we expect.
To answer your main question about the jenkins_script
module, if you check its documentation, you can see that it returns the output in the output
field, so you might want to try the following:
tasks:
- jenkins_script:
script: (...)
register: jenkins_result
- debug:
var: jenkins_result.output
I got it done by only encoding the output using utf-8. Here is the code example
new_tweets = api.GetUserTimeline(screen_name = user,count=200)
result = new_tweets[0]
try: text = result.text
except: text = ''
with open(file_name, 'a', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(text)
i.e: do not encode when collecting data from api, encode the output (print or write) only.
this.input
is undefined until the ref
callback is called. Try setting this.input
to some initial value in your constructor.
From the React docs on refs, emphasis mine:
the callback will be executed immediately after the component is mounted or unmounted
USEFUL:
Use the official Angular Update Guide select your current version and the version you wish to upgrade to for the relevant upgrade guide. https://update.angular.io/
See GitHub repository Angular CLI diff for comparing Angular CLI changes. https://github.com/cexbrayat/angular-cli-diff/
UPDATED 26/12/2018:
Use the official Angular Update Guide mentioned in the useful section above. It provides the most up to date information with links to other resources that may be useful during the upgrade.
UPDATED 08/05/2018:
Angular CLI 1.7 introduced ng update
.
ng update
A new Angular CLI command to help simplify keeping your projects up to date with the latest versions. Packages can define logic which will be applied to your projects to ensure usage of latest features as well as making changes to reduce or eliminate the impact related to breaking changes.
Configuration information for ng update can be found here
1.7 to 6 update
CLI 1.7 does not support an automatic v6 update. Manually install @angular/cli via your package manager, then run the update migration schematic to finish the process.
npm install @angular/cli@^6.0.0
ng update @angular/cli --migrate-only --from=1
UPDATED 30/04/2017:
1.0 Update
You should now follow the Angular CLI migration guide
UPDATED 04/03/2017:
RC Update
You should follow the Angular CLI RC migration guide
UPDATED 20/02/2017:
Please be aware 1.0.0-beta.32 has breaking changes and has removed ng init and ng update
The pull request here states the following:
BREAKING CHANGE: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Update functionality will return to the CLI, until then manual updates of applications will need done.
The angular-cli CHANGELOG.md states the following:
BREAKING CHANGES - @angular/cli: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Once RC is released, we won't need to use those to update anymore as the step will be as simple as installing the latest version of the CLI.
UPDATED 17/02/2017:
Angular-cli has now been added to the NPM @angular package. You should now replace the above command with the following -
Global package:
npm uninstall -g angular-cli @angular/cli
npm cache clean
npm install -g @angular/cli@latest
Local project package:
rm -rf node_modules dist # On Windows use rmdir /s /q node_modules dist
npm install --save-dev @angular/cli@latest
npm install
ng init
ORIGINAL ANSWER
You should follow the steps from the README.md on GitHub for updating angular via the angular-cli.
Here they are:
Updating angular-cli
To update angular-cli to a new version, you must update both the global package and your project's local package.
Global package:
npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@latest
Local project package:
rm -rf node_modules dist tmp # On Windows use rmdir /s /q node_modules dist tmp
npm install --save-dev angular-cli@latest
npm install
ng init
Running ng init
will check for changes in all the auto-generated files created by ng new and allow you to update yours. You are offered four choices for each changed file: y (overwrite), n (don't overwrite), d (show diff between your file and the updated file) and h (help).
Carefully read the diffs for each code file, and either accept the changes or incorporate them manually after ng init finishes.
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>
I was face same problem ..... And I got solution by using typeof()
if (typeof(value) !== 'undefined' && value != null) {
console.log('Not Undefined and Not Null')
} else {
console.log('Undefined or Null')
}
You must have to use typeof()
to identified undefined
Here are some more console logging "pro tips":
console.table
var animals = [
{ animal: 'Horse', name: 'Henry', age: 43 },
{ animal: 'Dog', name: 'Fred', age: 13 },
{ animal: 'Cat', name: 'Frodo', age: 18 }
];
console.table(animals);
console.trace
Shows you the call stack for leading up to the console.
You can even customise your consoles to make them stand out
console.todo = function(msg) {
console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}
console.important = function(msg) {
console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}
console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);
If you really want to level up don't limit your self to the console statement.
Here is a great post on how you can integrate a chrome debugger right into your code editor!
https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037
Since Node.JS 11.0.0 (stable), and version 10.0.0 (experimental), you have access to file system methods that are already promisify'd and you can use them with try catch
exception handling rather than checking if the callback's returned value contains an error.
The API is very clean and elegant! Simply use .promises
member of fs
object:
import fs from 'fs';
const fsPromises = fs.promises;
async function listDir() {
try {
return fsPromises.readdir('path/to/dir');
} catch (err) {
console.error('Error occured while reading directory!', err);
}
}
listDir();
I dislike the chaining thens. The second then does not have access to status. As stated before 'response.json()' returns a promise. Returning the then result of 'response.json()' in a acts similar to a second then. It has the added bonus of being in scope of the response.
return fetch(url, params).then(response => {
return response.json().then(body => {
if (response.status === 200) {
return body
} else {
throw body
}
})
})
If you know the type will never be null
or undefined
, you should declare it as foo: Bar
without the ?
. Declaring a type with the ? Bar
syntax means it could potentially be undefined, which is something you need to check for.
In other words, the compiler is doing exactly what you're asking it to. If you want it to be optional, you'll need to the check later.
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
Since TypeScript 3.7 was released you can use optional chaining now.
Property example:
let x = foo?.bar.baz();
This is equvalent to:
let x = (foo === null || foo === undefined) ?
undefined :
foo.bar.baz();
Moreover you can call:
Optional Call
function(otherFn: (par: string) => void) {
otherFn?.("some value");
}
otherFn will be called only if otherFn won't be equal to null or undefined
Usage optional chaining in IF statement
This:
if (someObj && someObj.someProperty) {
// ...
}
can be replaced now with this
if (someObj?.someProperty) {
// ...
}
Ref. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html
Doing this works for me:
moment(new Date("27/04/2016")).format
Just to add a little further documentation to this page - I have been struggling with this problem for a while.
As said above, the easiest way to get the URL is via window.location.href
.
we can then extract parts of the URL through vanilla Javascript by using let urlElements = window.location.href.split('/')
We would then console.log(urlElements)
to see the Array of elements produced by calling .split() on the URL.
Once you have found which index in the array you want to access, you can then assigned this to a variable
let urlElelement = (urlElements[0])
And now you can use the value of urlElement, which will be the specific part of your URL, wherever you want.
The variable selectedHero
is null
in the template so you cannot bind selectedHero.name
as is. You need to use the elvis operator ?.
for this case:
<input [ngModel]="selectedHero?.name" (ngModelChange)="selectedHero.name = $event" />
The separation of the [(ngModel)]
into [ngModel]
and (ngModelChange)
is also needed because you can't assign to an expression that uses the elvis operator.
I also think you mean to use:
<h2>{{selectedHero?.name}} details!</h2>
instead of:
<h2>{{hero.name}} details!</h2>
Using this.props.children
is the idiomatic way to pass instantiated components to a react component
const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>
When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div
or span
):
const Label = props => <span>{props.children}</span>
const Button = props => {
const Inner = props.inner; // Note: variable name _must_ start with a capital letter
return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>
If what you want to do is to pass a children-like parameter as a prop, you can do that:
const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />
After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.
You are mixing the deprecated mysql extension with mysqli.
Try something like:
$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);
Make sure that in your input data, response[i]
and response[i][j]
, are not undefined
/null
.
If so, replace them with "".
Another quick "trick" (easy solution) is just to use [hidden] tag instead of *ngIf, just important to know that in that case Angular build the object and paint it under class:hidden this is why the ViewChild work without a problem. So it's important to keep in mind that you should not use hidden on heavy or expensive items that can cause performance issue
<div class="addTable" [hidden]="CONDITION">
For me, I just did a CTRL+C and YES .
And I restart by
ionic serve
This works for me.
Initializing the Canvas like below works for TypeScript/Angular solutions.
const canvas = <HTMLCanvasElement> document.getElementById("htmlElemId");
const context = canvas.getContext("2d");
Here are the different ways in which you can create an array of booleans in typescript:
let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();
let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();
let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];
let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();
let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();
You can access them using the index:
console.log(arr[5]);
and you add elements using push:
arr.push(true);
When creating the array you can supply the initial values:
let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);
catch function in your api should either return some data which could be handled by Api call in React class or throw new error which should be caught using a catch function in your React class code. Latter approach should be something like:
return fetch(url)
.then(function(response){
return response.json();
})
.then(function(json){
return {
city: json.name,
temperature: kelvinToF(json.main.temp),
description: _.capitalize(json.weather[0].description)
}
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
// ADD THIS THROW error
throw error;
});
Then in your React Class:
Api(region.latitude, region.longitude)
.then((data) => {
console.log(data);
this.setState(data);
}).catch((error)=>{
console.log("Api call error");
alert(error.message);
});
use a static defaultProps like:
export default class AddAddressComponent extends Component {
static defaultProps = {
provinceList: [],
cityList: []
}
render() {
let {provinceList,cityList} = this.props
if(cityList === undefined || provinceList === undefined){
console.log('undefined props')
}
...
}
AddAddressComponent.contextTypes = {
router: React.PropTypes.object.isRequired
}
AddAddressComponent.defaultProps = {
cityList: [],
provinceList: [],
}
AddAddressComponent.propTypes = {
userInfo: React.PropTypes.object,
cityList: PropTypes.array.isRequired,
provinceList: PropTypes.array.isRequired,
}
Taken from: https://github.com/facebook/react-native/issues/1772
If you wish to check the types, see how to use PropTypes in treyhakanson's or Ilan Hasanov's answer, or review the many answers in the above link.
This command works perfectly. I have 8GB ram in my laptop, So I set size=8192. It is all about ram and also you need set file name. I run npm run build command that's why I used build.js.
node --expose-gc --max-old-space-size=8192 node_modules/react-scripts/scripts/build.js
import * as utils from './utils.js';
If you do the above, you will be able to use functions in utils.js as
utils.someFunction()
There's no need for bind(this)
when you are using arrow functions:
setTimeout( ()=> {
// some code
}, 500)
If you are solely interested in outputting the JSON somewhere in your HTML, you could also use a pipe inside an interpolation. For example:
<p> {{ product | json }} </p>
I am not entirely sure it works for every AngularJS version, but it works perfectly in my Ionic App (which uses Angular 2+).
Sweet and Simple!
moment('2020-12-04T09:52:03.915Z').format('lll');
Dec 4, 2020 4:58 PM
moment.locale(); // en
moment().format('LT'); // 4:59 PM
moment().format('LTS'); // 4:59:47 PM
moment().format('L'); // 12/08/2020
moment().format('l'); // 12/8/2020
moment().format('LL'); // December 8, 2020
moment().format('ll'); // Dec 8, 2020
moment().format('LLL'); // December 8, 2020 4:59 PM
moment().format('lll'); // Dec 8, 2020 4:59 PM
moment().format('LLLL'); // Tuesday, December 8, 2020 4:59 PM
moment().format('llll'); // Tue, Dec 8, 2020 4:59 PM
If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below assuming you only care about adding objects to the observable, not deleting them.
If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:
this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));
<div class="message-list" *ngFor="let item of messages$ | async">
@Pantelis answer somehow steered me to a solution for a similar misunderstanding. A message board project I'm working on needs to show an optional image. I was having fits trying to get the src=imagefile to concatenate a fixed path and variable filename string until I saw the quirky use of "''" quotes :-)
<template id="symp-tmpl">
<div>
<div v-for="item in items" style="clear: both;">
<div v-if="(item.imagefile !== '[none]')">
<img v-bind:src="'/storage/userimages/' + item.imagefile">
</div>
sub: <span>@{{ item.subject }}</span>
<span v-if="(login == item.author)">[edit]</span>
<br>@{{ item.author }}
<br>msg: <span>@{{ item.message }}</span>
</div>
</div>
</template>
The reject
actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject()
the exception value is undefined
, hence the "undefined" part in the error that you get.
You do not show the code that uses the promise, but I reckon it is something like this:
var promise = doSth();
promise.then(function() { doSthHere(); });
Try adding an empty failure call, like this:
promise.then(function() { doSthHere(); }, function() {});
This will prevent the error to appear.
However, I would consider calling reject
only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.
This article helped me alot figuring out why it wasn't working for me either. It give me a lesson to think of the webpage loading and how angular 2 interacts as a timeline and not just the point in time i'm thinking of. I didn't see anyone else mention this point, so I will...
The reason the *ngIf is needed because it will try to check the length of that variable before the rest of the OnInit stuff happens, and throw the "length undefined" error. So thats why you add the ? because it won't exist yet, but it will soon.
This might cause due to your javascript code is looking at some json response and you received something else like text.
I am using create-react-app which comes with jest by default and enzyme 2.7.0.
This worked for me:
const wrapper = mount(<EditableText defaultValue="Hello" />);
const input = wrapper.find('input')[index]; // where index is the position of the input field of interest
input.node.value = 'Change';
input.simulate('change', input);
done();
You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.
The old router allows to pass data
but the new (RC.1
) router doesn't yet.
Update
data
was re-introduced in RC.4
How do I pass data in Angular 2 components while using Routing?
If you need run code after 100% loaded with image and files, test this in mounted()
:
document.onreadystatechange = () => {
if (document.readyState == "complete") {
console.log('Page completed with image and files!')
// fetch to next page or some code
}
}
More info: MDN Api onreadystatechange
You need to put your code into ngOnInit
and use the this
keyword:
ngOnInit() {
this.booksByStoreID = this.books.filter(
book => book.store_id === this.store.id);
}
You need ngOnInit
because the input store
wouldn't be set into the constructor:
ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.
(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)
In your code, the books filtering is directly defined into the class content...
The curly braces are used only for import when export is named. If the export is default then curly braces are not used for import.
I succeeded in doing this by binding the "this" to the function updateInputValue(evt) with
this.updateInputValue = this.updateInputValue.bind(this);
However input value={this.state.inputValue} ... turned out to be no good idea.
Here's the full code in babel ES6 :
class InputField extends React.Component{
constructor(props){
super(props);
//this.state={inputfield: "no value"};
this.handleClick = this.handleClick.bind(this);
this.updateInputValue = this.updateInputValue.bind(this);
}
handleClick(){
console.log("trying to add picture url");
console.log("value of input field : "+this.state.inputfield);
}
updateInputValue(evt){
//console.log("input field updated with "+evt.target.value);
this.state={inputfield: evt.target.value};
}
render(){
var r;
r=<div><input type="text" id="addpixinputfield"
onChange={this.updateInputValue} />
<input type="button" value="add" id="addpix" onClick={this.handleClick}/>
</div>;
return r;
}
}
What happened to me is I was exporting a function like this:
module.exports = () => {
const method = async (req, res) => {
}
return {
method
}
}
but I was calling it like this:
const main = require('./module');
instead
const main = require('./module')();
Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?
A very simple check that you can do:
Explanation 1:
if (value) {
// it will come inside
// If value is either undefined, null or ''(empty string)
}
Explanation 2:
(!value) ? "Case 1" : "Case 2"
If the value is either undefined , null or '' then Case 1 otherwise for any other value of value Case 2.
That is interesting subject.
You can play around with two lifecycle hooks to figure out how it works: ngOnChanges
and ngOnInit
.
Basically when you set default value to Input
that's mean it will be used only in case there will be no value coming on that component.
And the interesting part it will be changed before component will be initialized.
Let's say we have such components with two lifecycle hooks and one property coming from input
.
@Component({
selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
@Input() property: string = 'default';
ngOnChanges(changes) {
console.log('Changed', changes.property.currentValue, changes.property.previousValue);
}
ngOnInit() {
console.log('Init', this.property);
}
}
Situation 1
Component included in html without defined property
value
As result we will see in console:
Init default
That's mean onChange
was not triggered. Init was triggered and property
value is default
as expected.
Situation 2
Component included in html with setted property <cmp [property]="'new value'"></cmp>
As result we will see in console:
Changed
new value
Object {}
Init
new value
And this one is interesting. Firstly was triggered onChange
hook, which setted property
to new value
, and previous value was empty object! And only after that onInit
hook was triggered with new value of property
.
For nested html, use closest
<button (click)="toggle($event)" class="someclass" id="btn1">
<i class="fa fa-user"></i>
</button>
toggle(event) {
(event.target.closest('button') as Element).id;
}
You can create a reference to the enum in your component class (I just changed the initial character to be lower-case) and then use that reference from the template (plunker):
import {Component} from 'angular2/core';
enum CellType {Text, Placeholder}
class Cell {
constructor(public text: string, public type: CellType) {}
}
@Component({
selector: 'my-app',
template: `
<div [ngSwitch]="cell.type">
<div *ngSwitchCase="cellType.Text">
{{cell.text}}
</div>
<div *ngSwitchCase="cellType.Placeholder">
Placeholder
</div>
</div>
<button (click)="setType(cellType.Text)">Text</button>
<button (click)="setType(cellType.Placeholder)">Placeholder</button>
`,
})
export default class AppComponent {
// Store a reference to the enum
cellType = CellType;
public cell: Cell;
constructor() {
this.cell = new Cell("Hello", CellType.Text)
}
setType(type: CellType) {
this.cell.type = type;
}
}
Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.
Angular 5 Solution:
import {HttpClient} from '@angular/common/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = {} as any; // Set any options you like
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.httpClient.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Angular 4 Solution:
// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = new RequestOptions();
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.http.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
Make sure you're calling super()
as the first thing in your constructor.
You should set this
for setAuthorState
method
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
constructor(props) {
super(props);
this.handleAuthorChange = this.handleAuthorChange.bind(this);
}
handleAuthorChange(event) {
let {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
Another alternative based on arrow function
:
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
handleAuthorChange = (event) => {
const {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
Additionally, you can add with method function:
In HTML
<div [ngClass]="setClasses()">...</div>
In component.ts
// Set Dynamic Classes
setClasses() {
let classes = {
constantClass: true,
'conditional-class': this.item.id === 1
}
return classes;
}
This is how you can create a simple observable for static data.
let observable = Observable.create(observer => {
setTimeout(() => {
let users = [
{username:"balwant.padwal",city:"pune"},
{username:"test",city:"mumbai"}]
observer.next(users); // This method same as resolve() method from Angular 1
console.log("am done");
observer.complete();//to show we are done with our processing
// observer.error(new Error("error message"));
}, 2000);
})
to subscribe to it is very easy
observable.subscribe((data)=>{
console.log(data); // users array display
});
I hope this answer is helpful. We can use HTTP call instead static data.
I suggest use the common way of import.
First I will explain the way it called "relative import" maybe this way cause of some error
Second I will explain the common way of import.
FIRST:
In go version >= 1.12 there is some new tips about import file and somethings changed.
1- You should put your file in another folder for example I create a file in "model" folder and the file's name is "example.go"
2- You have to use uppercase when you want to import a file!
3- Use Uppercase for variables, structures and functions that you want to import in another files
Notice: There is no way to import the main.go in another file.
file directory is:
root
|_____main.go
|_____model
|_____example.go
this is a example.go:
package model
import (
"time"
)
var StartTime = time.Now()
and this is main.go you should use uppercase when you want to import a file. "Mod" started with uppercase
package main
import (
Mod "./model"
"fmt"
)
func main() {
fmt.Println(Mod.StartTime)
}
NOTE!!!
NOTE: I don't recommend this this type of import!
SECOND:
(normal import)
the better way import file is:
your structure should be like this:
root
|_____github.com
|_________Your-account-name-in-github
| |__________Your-project-name
| |________main.go
| |________handlers
| |________models
|
|_________gorilla
|__________sessions
and this is a example:
package main
import (
"github.com/gorilla/sessions"
)
func main(){
//you can use sessions here
}
so you can import "github.com/gorilla/sessions" in every where that you want...just import it.
I had a similar issue and thought I'd post in case someone else made the same mistake. First, one thing to consider is AfterViewInit
; you need to wait for the view to be initialized before you can access your @ViewChild
. However, my @ViewChild
was still returning null. The problem was my *ngIf
. The *ngIf
directive was killing my controls component so I couldn't reference it.
import {Component, ViewChild, OnInit, AfterViewInit} from 'angular2/core';
import {ControlsComponent} from './controls/controls.component';
import {SlideshowComponent} from './slideshow/slideshow.component';
@Component({
selector: 'app',
template: `
<controls *ngIf="controlsOn"></controls>
<slideshow (mousemove)="onMouseMove()"></slideshow>
`,
directives: [SlideshowComponent, ControlsComponent]
})
export class AppComponent {
@ViewChild(ControlsComponent) controls:ControlsComponent;
controlsOn:boolean = false;
ngOnInit() {
console.log('on init', this.controls);
// this returns undefined
}
ngAfterViewInit() {
console.log('on after view init', this.controls);
// this returns null
}
onMouseMove(event) {
this.controls.show();
// throws an error because controls is null
}
}
Hope that helps.
EDIT
As mentioned by @Ashg below, a solution is to use @ViewChildren
instead of @ViewChild
.
in case of a similar issue when I'm creating dockerfile I faced the same scenario:- I used below changed in mysql_connect function as:-
if($CONN = @mysqli_connect($DBHOST, $DBUSER, $DBPASS)){ //mysql_query("SET CHARACTER SET 'gbk'", $CONN);
Edit: isMounted
is deprecated and will probably be removed in later versions of React. See this and this, isMounted is an Antipattern.
As the warning states, you are calling this.setState
on an a component that was mounted but since then has been unmounted.
To make sure your code is safe, you can wrap it in
if (this.isMounted()) {
this.setState({'time': remainTimeInfo});
}
to ensure that the component is still mounted.
Write a new function for settimeout. Pls try this.
class CowtanApp extends Component {
constructor(props){
super(props);
this.state = {
timePassed: false
};
}
componentDidMount() {
this.setTimeout( () => {
this.setTimePassed();
},1000);
}
setTimePassed() {
this.setState({timePassed: true});
}
render() {
if (!this.state.timePassed){
return <LoadingPage/>;
}else{
return (
<NavigatorIOS
style = {styles.container}
initialRoute = {{
component: LoginPage,
title: 'Sign In',
}}/>
);
}
}
}
Performance Analysis For loops performs faster than map or foreach as number of elements in a array increases.
let array = [];
for (var i = 0; i < 20000000; i++) {
array.push(i)
}
console.time('map');
array.map(num => {
return num * 4;
});
console.timeEnd('map');
console.time('forEach');
array.forEach((num, index) => {
return array[index] = num * 4;
});
console.timeEnd('forEach');
console.time('for');
for (i = 0; i < array.length; i++) {
array[i] = array[i] * 2;
}
console.timeEnd('for');
Try as follows the return must be d, not d.data
ajax: {
"url": "xx/xxx/xxx",
"type": "GET",
"error": function (e) {
},
"dataSrc": function (d) {
return d
}
},
When you return something from a then()
callback, it's a bit magic. If you return a value, the next then()
is called with that value. However, if you return something promise-like, the next then()
waits on it, and is only called when that promise settles (succeeds/fails).
Source: https://web.dev/promises/#queuing-asynchronous-actions
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
You should notice that this
depends on how function is invoked
ie: when a function is called as a method of an object, its this
is set to the object the method is called on.
this
is accessible in JSX context as your component object, so you can call your desired method inline as this
method.
If you just pass reference to function/method, it seems that react will invoke it as independent function.
onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined
onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object
Wrapping components with braces if no default exports:
import {MyNavbar} from './comp/my-navbar.jsx';
or import multiple components from single module file
import {MyNavbar1, MyNavbar2} from './module';
If you are not giving export default then it throws an error. check if you have given module.exports = Speaker; //spelling mistake here you have written exoprts and check in all the modules whether you have exported correct.
Adding to https://stackoverflow.com/users/1638814/nvartolomei answer, which will probably fix your error.
Strictly answering your question, I just want to point out that the when:
statement is probably correct, but would look easier to read in multiline and still fulfill your logic:
when:
- sshkey_result.rc == 1
- github_username is undefined or
github_username |lower == 'none'
https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement
When I had similar issue it's happened because my lib was build using clang++
, and it's linked to libstdc++.so
by default on my system. While app binary was build using clang
and linked with -lc++
option.
Easiest way to check dependencies is to perform ldd libName.so
To fix it you should use the same library on in app and library.
Easiest way. Build library using clang++
and compile app using clang++
. Without extra linking options on both steps. Default stdlib will be used.
Build library with -stdlib=c++
and compile app with -lc++
. In this case both library and app will use libc++.so
.
Build library without extra options and link binary to -lstdc++
. In this case both library and app will use libstdc++.so
.
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
User in the init of class:
constructor() {
super()
this.state = {
email: ''
}
}
Then in some function:
handleSome = () => {
console.log(this.state.email)
};
And in the input:
<TextInput onChangeText={(email) => this.setState({email})}/>
If they are in the same controller class, it would be:
foreach ( $characters as $character) {
$num += $this->getFactorial($index) * $index;
$index ++;
}
Otherwise you need to create a new instance of the class, and call the method, ie:
$controller = new MyController();
foreach ( $characters as $character) {
$num += $controller->getFactorial($index) * $index;
$index ++;
}
you have many HTML and java script mistakes includes:
tag, using non UTF-8 encoding for form submission, no need,...
You must use document.forms.FORMNAME
or document.forms[0]
for first appear form in page
Corrected:
function validate_frm_new_user_request()_x000D_
{_x000D_
alert('test');_x000D_
var valid = true;_x000D_
_x000D_
if ( document.forms.frm_new_user_request.u_userid.value == "" )_x000D_
{_x000D_
alert ( "Please enter your valid ISID Information." );_x000D_
document.forms.frm_new_user_request.u_userid.focus();_x000D_
valid = false;_x000D_
console.log("FALSE::Empty Value ");_x000D_
}_x000D_
return valid;_x000D_
}
_x000D_
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title></title>_x000D_
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />_x000D_
_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<form method="post" action="" name="frm_new_user_request" id="frm_new_user_request" onsubmit="return validate_frm_new_user_request();">_x000D_
<center>_x000D_
<table>_x000D_
_x000D_
<tr align="left">_x000D_
<td><Label>ISID<em>*:</Label><input maxlength="15" id="u_userid" name="u_userid" size="20" type="text"/></td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td align="center" colspan="4">_x000D_
<input type="image" src="btn.png" border="0" ALT="Create New Request">_x000D_
_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
// person.js
'use strict';
module.exports = class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
display() {
console.log(this.firstName + " " + this.lastName);
}
}
// index.js
'use strict';
var Person = require('./person.js');
var someone = new Person("First name", "Last name");
someone.display();
U can use something like this....
function (field,value) {
var newItemOrder= value;
// Make sure user hasnt already added this item
angular.forEach(arr, function(item) {
if (newItemOrder == item.value) {
arr.splice(arr.pop(item));
} });
submitFields.push({"field":field,"value":value});
};
When using functional components, you will often get the TypeError: Cannot add property myNewProp, object is not extensible
error when trying to set new properties on props.children
. There is a work around to this by cloning the props and then cloning the child itself with the new props.
const MyParentComponent = (props) => {
return (
<div className='whatever'>
{props.children.map((child) => {
const newProps = { ...child.props }
// set new props here on newProps
newProps.myNewProp = 'something'
const preparedChild = { ...child, props: newProps }
return preparedChild
})}
</div>
)
}
When using ES6 code in React always use arrow functions, because the this context is automatically binded with it
Use this:
(videos) => {
this.setState({ videos: videos });
console.log(this.state.videos);
};
instead of:
function(videos) {
this.setState({ videos: videos });
console.log(this.state.videos);
};
However, the previous answer could still be confusing for some programmers. Most especially beginners who are most probably using an older book or tutorial. Or perhaps you still feel the facade is needed. Sure you can use it. Me for one I still love to use the facade, this is because some times while building my api I forget to use the '\' before the Response.
if you are like me, simply add
"use Response;"
above your class ...extends contoller. this should do.
with this you can now use:
$response = Response::json($posts, 200);
instead of:
$response = \Response::json($posts, 200);
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
The filter option filters only the first level subkey below ansible_facts
Make sure that you have php-xml module installed and enabled in php.ini
.
You can also change response format to json which is easier to handle. In that case you have to only add &format=json
to url query string.
$rest_url = "http://api.facebook.com/restserver.php?method=links.getStats&format=json&urls=".urlencode($source_url);
And then use json_decode()
to retrieve data in your script:
$result = json_decode($content, true);
$fb_like_count = $result['like_count'];
Fetch id basing on name
{
"roles": [
{
"id": 1,
"name": "admin",
},
{
"id": 3,
"name": "manager",
}
]
}
fetchIdBasingOnRole() {
const self = this;
if (this.employee.roles) {
var roleid = _.result(
_.find(this.getRoles, function(obj) {
return obj.name === self.employee.roles;
}),
"id"
);
}
return roleid;
},
First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:
global $db;
And I guess, when you wrote:
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
what you really wanted was:
if ($result->num_rows==1) { return true; } else { return false; }
The best answer I use to receive data from server and display it
constructor(props){
super(props);
this.state = {
items2 : [{}],
isLoading: true
}
}
componentWillMount (){
axios({
method: 'get',
responseType: 'json',
url: '....',
})
.then(response => {
self.setState({
items2: response ,
isLoading: false
});
console.log("Asmaa Almadhoun *** : " + self.state.items2);
})
.catch(error => {
console.log("Error *** : " + error);
});
})}
render() {
return(
{ this.state.isLoading &&
<i className="fa fa-spinner fa-spin"></i>
}
{ !this.state.isLoading &&
//external component passing Server data to its classes
<TestDynamic items={this.state.items2}/>
}
) }
You can also use
var XLSX = require('xlsx');
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;
console.log(XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]))
The order of execution is:
A
's constructorB
's constructorThe assignment occurs in B
's constructor after A
's constructor—_super
—has been called:
function B() {
_super.apply(this, arguments); // MyvirtualMethod called in here
this.testString = "Test String"; // testString assigned here
}
So the following happens:
var b = new B(); // undefined
b.MyvirtualMethod(); // "Test String"
You will need to change your code to deal with this. For example, by calling this.MyvirtualMethod()
in B
's constructor, by creating a factory method to create the object and then execute the function, or by passing the string into A
's constructor and working that out somehow... there's lots of possibilities.
pickBy uses identity by default:
_.pickBy({ a: null, b: 1, c: undefined, d: false });
The right way to iterate over objects is
Object.keys(someObject).map(function(item)...
Object.keys(someObject).forEach(function(item)...;
// ES way
Object.keys(data).map(item => {...});
Object.keys(data).forEach(item => {...});
DateTime
is not a function, but the class.
When you just reference a class like new DateTime()
PHP searches for the class in your current namespace. However the DateTime
class obviously doesn't exists in your controllers namespace but rather in root namespace.
You can either reference it in the root namespace by prepending a backslash:
$now = new \DateTime();
Or add an import statement at the top:
use DateTime;
$now = new DateTime();
You can use obj.constructor.name to check the "class" of an object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Function_names_in_classes
For Example
var error = new Error("ValidationError");
console.log(error.constructor.name);
The above line will log "Error" which is the class name of the object. This could be used with any classes in javascript, if the class is not using a property that goes by the name "name"
The issue of being forced to trigger('change')
drove me nuts, as I had custom code in the change
trigger, which should only trigger when the user changes the option in the dropdown. IMO, change should not be triggered when setting an init value at the start.
I dug deep and found the following: https://github.com/select2/select2/issues/3620
Example:
$dropDown.val(1).trigger('change.select2');
You can try this as well:
public function showstudents(){
$students = DB::table('student')->get();
return view("user/regprofile", ['students'=>$students]);
}
Also, use this variable in your view.blade
file to get students name and other columns:
{{$students['name']}}
You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL. Example:
<?php
$var1 = '';
if(isset($var1)){
echo 'This line is printed, because the $var1 is set.';
}
?>
This code will output "This line is printed, because the $var1 is set."
read more in https://stackhowto.com/how-to-check-if-a-variable-is-undefined-in-php/
The .map
function is only available on array.
It looks like data
isn't in the format you are expecting it to be (it is {} but you are expecting []).
this.setState({data: data});
should be
this.setState({data: data.conversations});
Check what type "data" is being set to, and make sure that it is an array.
Modified code with a few recommendations (propType validation and clearInterval):
var converter = new Showdown.converter();
var Conversation = React.createClass({
render: function() {
var rawMarkup = converter.makeHtml(this.props.children.toString());
return (
<div className="conversation panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">
{this.props.id}
{this.props.last_message_snippet}
{this.props.other_user_id}
</h3>
</div>
<div className="panel-body">
<span dangerouslySetInnerHTML={{__html: rawMarkup}} />
</div>
</div>
);
}
});
var ConversationList = React.createClass({
// Make sure this.props.data is an array
propTypes: {
data: React.PropTypes.array.isRequired
},
render: function() {
window.foo = this.props.data;
var conversationNodes = this.props.data.map(function(conversation, index) {
return (
<Conversation id={conversation.id} key={index}>
last_message_snippet={conversation.last_message_snippet}
other_user_id={conversation.other_user_id}
</Conversation>
);
});
return (
<div className="conversationList">
{conversationNodes}
</div>
);
}
});
var ConversationBox = React.createClass({
loadConversationsFromServer: function() {
return $.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data.conversations});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
/* Taken from
https://facebook.github.io/react/docs/reusable-components.html#mixins
clears all intervals after component is unmounted
*/
componentWillMount: function() {
this.intervals = [];
},
setInterval: function() {
this.intervals.push(setInterval.apply(null, arguments));
},
componentWillUnmount: function() {
this.intervals.map(clearInterval);
},
componentDidMount: function() {
this.loadConversationsFromServer();
this.setInterval(this.loadConversationsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="conversationBox">
<h1>Conversations</h1>
<ConversationList data={this.state.data} />
</div>
);
}
});
$(document).on("page:change", function() {
var $content = $("#content");
if ($content.length > 0) {
React.render(
<ConversationBox url="/conversations.json" pollInterval={20000} />,
document.getElementById('content')
);
}
})
Strictly stated you must check all of the following: defined, not empty AND not None.
For "normal" variables it makes a difference if defined and set or not set. See foo
and bar
in the example below. Both are defined but only foo
is set.
On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz
and xyz.msg
in the example below:
cat > test.yml <<EOF
- hosts: 127.0.0.1
vars:
foo: "" # foo is defined and foo == '' and foo != None
bar: # bar is defined and bar != '' and bar == None
tasks:
- debug:
msg : ""
register: xyz # xyz is defined and xyz != '' and xyz != None
# xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "foo is defined and foo == '' and foo != None"
when: foo is defined and foo == '' and foo != None
- debug:
msg: "bar is defined and bar != '' and bar == None"
when: bar is defined and bar != '' and bar == None
- debug:
msg: "xyz is defined and xyz != '' and xyz != None"
when: xyz is defined and xyz != '' and xyz != None
- debug:
msg: "{{ xyz }}"
- debug:
msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml
Webpack 4 Chunks and Hashes with Uglification by TerserPlugin
This can occur when Webpack uses chunks and hashes with minification and unglification via TerserPlugin (currently on version 1.2.3). In my case the error was narrowed down to the uglification by the Terser Plugin of my vendors.[contenthash].js
bundle which holds my node_modules
. Everything worked when not using hashes.
Solution was to exclude the bundle in the uglification options:
optimization: {
minimizer: [
new TerserPlugin({
chunkFilter: (chunk) => {
// Exclude uglification for the `vendors` chunk
if (chunk.name === 'vendors') {
return false;
}
return true;
},
}),
],
}
This is very useful to avoid errors when accessing properties of null or undefined objects.
null to undefined object
const obj = null;
const newObj = obj || undefined;
// newObj = undefined
undefined to empty object
const obj;
const newObj = obj || {};
// newObj = {}
// newObj.prop = undefined, but no error here
null to empty object
const obj = null;
const newObj = obj || {};
// newObj = {}
// newObj.prop = undefined, but no error here
Queries with $where
and $expr
are slow if there are too many documents.
Using $regex
is much faster than $where
, $expr
.
db.usercollection.find({
"name": /^[\s\S]{40,}$/, // name.length >= 40
})
or
db.usercollection.find({
"name": { "$regex": "^[\s\S]{40,}$" }, // name.length >= 40
})
This query is the same meaning with
db.usercollection.find({
"$where": "this.name && this.name.length >= 40",
})
or
db.usercollection.find({
"name": { "$exists": true },
"$expr": { "$gte": [ { "$strLenCP": "$name" }, 40 ] }
})
I tested each queries for my collection.
# find
$where: 10529.359ms
$expr: 5305.801ms
$regex: 2516.124ms
# count
$where: 10872.006ms
$expr: 2630.155ms
$regex: 158.066ms
The error is here:
hasLetter("a",words[]);
You are passing the first item of words
, instead of the array.
Instead, pass the array to the function:
hasLetter("a",words);
Problem solved!
Here's a breakdown of what the problem was:
I'm guessing in your browser (chrome throws a different error), words[] == words[0]
, so when you call hasLetter("a",words[]);
, you are actually calling hasLetter("a",words[0]);
. So, in essence, you are passing the first item of words to your function, not the array as a whole.
Of course, because words
is just an empty array, words[0]
is undefined
. Therefore, your function call is actually:
hasLetter("a", undefined);
which means that, when you try to access d[ascii]
, you are actually trying to access undefined[0]
, hence the error.
in mac os you can try brew install gradle
"Change to if (typeof $next == 'object' && $next.length) $next[0].offsetWidth" -did not help. if you convert Bootstrap 3 to php(for WordPress theme), when adding WP_Query ($loop = new WP_Query( $args );) insert $count = 0;. And and at the end before endwhile; add $count++;.
If you want to pass tslint
without setting strict-boolean-expressions
to allow-null-union
or allow-undefined-union
, you need to use isNullOrUndefined
from node
's util
module or roll your own:
// tslint:disable:no-null-keyword
export const isNullOrUndefined =
<T>(obj: T | null | undefined): obj is null | undefined => {
return typeof obj === "undefined" || obj === null;
};
// tslint:enable:no-null-keyword
Not exactly syntactic sugar but useful when your tslint rules are strict.
Hey there just ran into the same issue you did, the 3rd link down in google brought me to this bit of code that throws the error,
if (kernelFile == NULL) {
kernelFile = avdInfo_getKernelPath(avd);
if (kernelFile == NULL) {
derror( "This AVD's configuration is missing a kernel file!!" );
const char* sdkRootDir = getenv("ANDROID_SDK_ROOT");
if (sdkRootDir) {
derror( "ANDROID_SDK_ROOT is defined (%s) but cannot find kernel file in "
"%s" PATH_SEP "system-images" PATH_SEP
" sub directories", sdkRootDir, sdkRootDir);
} else {
derror( "ANDROID_SDK_ROOT is undefined");
}
exit(2);
to which the person wrote:
"/* If the kernel image name ends in "-armv7", then change the cpu * type automatically. This is a poor man's approach to configuration * management, but should allow us to get past building ARMv7 * system images with dex preopt pass"
So I went back in and downloaded the x86 intel atom version for my desired API level and was able to get the emulator up without the error. Hope it helps you too.....
When you do are doing:
p => {foo: "bar"}
JavaScript interpreter thinks you are opening a multi-statement code block, and in that block, you have to explicitly mention a return statement.
If your arrow function expression has a single statement, then you can use the following syntax:
p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})
But if you want to have multiple statements then you can use the following syntax:
p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}
In above example, first set of curly braces opens a multi-statement code block, and the second set of curly braces is for dynamic objects. In multi-statement code block of arrow function, you have to explicitly use return statements
For more details, check Mozilla Docs for JS Arrow Function Expressions
Use ??
instead or {{ $usersType ?? '' }}
I had this problem and it was because another script was deleting all of the tables and recreating them, but my table wasn't being recreated. I spent ages on this issue before I noticed that my table wasn't even visible on the page. Can you see your table before you initialize DataTables?
Essentially, the other script was doing:
let tables = $("table");
for (let i = 0; i < tables.length; i++) {
const table = tables[i];
if ($.fn.DataTable.isDataTable(table)) {
$(table).DataTable().destroy(remove);
$(table).empty();
}
}
And it should have been doing:
let tables = $("table.some-class-only");
... the rest ...
In CurrentGame
component you need to change initial state because you are trying use loop for participants
but this property is undefined
that's why you get error.,
getInitialState: function(){
return {
data: {
participants: []
}
};
},
also, as player
in .map
is Object
you should get properties from it
this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
// -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})
If you're working with a makefile and you ended up here like me, then this is probably what you're looking or:
If you're using a makefile, then you need to change cc
as shown below
my_executable : main.o
cc -o my_executable main.o
to
CC = g++
my_executable : main.o
$(CC) -o my_executable main.o
You can try one of the following:
Method 1:
MyProject
go build
./MyProject
You can do both steps at once by typing go build && ./MyProject
. Go files of the package main
are compiled to an executable.
Method 2:
go run *.go
. It won't create any executable but it runs.var express = require('express')
app = module.exports = express();
var secureServer = require('http').createServer(app);
secureServer.listen(3001);
var aws = require('aws-sdk')
var multer = require('multer')
var multerS3 = require('multer-s3')
aws.config.update({
secretAccessKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
accessKeyId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
region: 'us-east-1'
});
s3 = new aws.S3();
var upload = multer({
storage: multerS3({
s3: s3,
dirname: "uploads",
bucket: "Your bucket name",
key: function (req, file, cb) {
console.log(file);
cb(null, "uploads/profile_images/u_" + Date.now() + ".jpg"); //use
Date.now() for unique file keys
}
})
});
app.post('/upload', upload.single('photos'), function(req, res, next) {
console.log('Successfully uploaded ', req.file)
res.send('Successfully uploaded ' + req.file.length + ' files!')
})
There are two pages: Pageone.html :
<script>
var hello = "hi"
location.replace("http://example.com/PageTwo.html?" + hi + "");
</script>
PageTwo.html :
<script>
var link = window.location.href;
link = link.replace("http://example.com/PageTwo.html?","");
document.write("The variable contained this content:" + link + "");
</script>
Hope it helps!
Instead of returning a resultsArray
you return a promise for a results array and then then
that on the call site - this has the added benefit of the caller knowing the function is performing asynchronous I/O. Coding concurrency in JavaScript is based on that - you might want to read this question to get a broader idea:
function resultsByName(name)
{
var Card = Parse.Object.extend("Card");
var query = new Parse.Query(Card);
query.equalTo("name", name.toString());
var resultsArray = [];
return query.find({});
}
// later
resultsByName("Some Name").then(function(results){
// access results here by chaining to the returned promise
});
You can see more examples of using parse promises with queries in Parse's own blog post about it.
generally this problem occurred when we have called a function which has not been define in the program file, so to sort out this problem check whether have you called such function which has not been define in the program file.
UPDATED: As of angularjs 1.5, promise methods success and error have been deprecated. (see this answer)
from current docs:
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
you can use the function's other arguments like so:
error(function(data, status, headers, config) {
console.log(data);
console.log(status);
}
see $http docs:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Include: #include<stdlib.h>
and use System("cls")
instead of clrscr()
var request = require('request');
request({
url: "http://localhost:8001/xyz",
json: true,
headers: {
"content-type": "application/json",
},
body: JSON.stringify(requestData)
}, function(error, response, body) {
console.log(response);
});
While saving the response of get request, same error was thrown on Python 3.7 on window 10. The response received from the URL, encoding was UTF-8 so it is always recommended to check the encoding so same can be passed to avoid such trivial issue as it really kills lots of time in production
import requests
resp = requests.get('https://en.wikipedia.org/wiki/NIFTY_50')
print(resp.encoding)
with open ('NiftyList.txt', 'w') as f:
f.write(resp.text)
When I added encoding="utf-8" with the open command it saved the file with the correct response
with open ('NiftyList.txt', 'w', encoding="utf-8") as f:
f.write(resp.text)
yum update
helped me out. After I had
wget: symbol lookup error: wget: undefined symbol: psl_latest
If you're using Angular 1, I would recommend using Angular's built-in method:
angular.isDefined(value);
reference : https://docs.angularjs.org/api/ng/function/angular.isDefined
In my case, I've created a wrapper JS file in which I have the logic to select the correct variables according to my environment, dynamically.
I have these two functions, one it's a wrapper of a simple dotenv functionality, and the other discriminate between environments and set the result to the process.env object.
setEnvVariablesByEnvironment : ()=>{_x000D_
return new Promise((resolve)=>{_x000D_
_x000D_
if (process.env.NODE_ENV === undefined || process.env.NODE_ENV ==='development'){_x000D_
logger.info('Lower / Development environment was detected');_x000D_
_x000D_
environmentManager.getEnvironmentFromEnvFile()_x000D_
.then(envFile => {_x000D_
resolve(envFile);_x000D_
});_x000D_
_x000D_
}else{_x000D_
logger.warn('Production or Stage environment was detected.');_x000D_
resolve({_x000D_
payload: process.env,_x000D_
flag: true,_x000D_
status: 0,_x000D_
log: 'Returned environment variables placed in .env file.'_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
});_x000D_
} ,_x000D_
_x000D_
/*_x000D_
Get environment variables from .env file, using dotEnv npm module._x000D_
*/_x000D_
getEnvironmentFromEnvFile: () => {_x000D_
return new Promise((resolve)=>{_x000D_
logger.info('Trying to get configuration of environment variables from .env file');_x000D_
_x000D_
env.config({_x000D_
debug: (process.env.NODE_ENV === undefined || process.env.NODE_ENV === 'development')_x000D_
});_x000D_
_x000D_
resolve({_x000D_
payload: process.env,_x000D_
flag: true,_x000D_
status: 0,_x000D_
log: 'Returned environment variables placed in .env file.'_x000D_
});_x000D_
});_x000D_
},
_x000D_
So, in my server.js file i only added the reference:
const envManager = require('./lib/application/config/environment/environment-manager');
And in my entry-point (server.js), it's just simple as use it.
envManager.setEnvVariablesByEnvironment()
.then(envVariables=>{
process.env= envVariables.payload;
const port = process.env.PORT_EXPOSE;
microService.listen(port, '0.0.0.0' , () =>{
let welcomeMessage = `Micro Service started at ${Date.now()}`;
logger.info(welcomeMessage);
logger.info(`${configuration.about.name} port configured -> : ${port}`);
logger.info(`App Author: ${configuration.about.owner}`);
logger.info(`App Version: ${configuration.about.version}`);
logger.info(`Created by: ${configuration.about.author}`);
});
});
You are not getting value of $id=$_GET['id'];
And you are using it (before it gets initialised).
Use php's in built isset() function to check whether the variable is defied or not.
So, please update the line to:
$id = isset($_GET['id']) ? $_GET['id'] : '';
this setting worked for me:
Here's a response to your latest question about the difference between x86_64
and arm64
:
x86_64
architecture is required for running the 64bit simulator.
arm64
architecture is required for running the 64bit device (iPhone
5s, iPhone 6, iPhone 6 Plus, iPad Air, iPad mini with Retina
display).
For my case, Xcode 8.2.1, I had a Map Kit View in a view controller. So I went to
Build Phases > Link Binary With Libraries
and added MapKit.framework
, then it was fine.
I think this will also apply to other views that require framework.
P.S. Running on iOS 9 told me that there was an issue about Map Kit View, while on iOS 10 told me nothing!
Pass the object from controller to view, convert it to markup without encoding, and parse it to json.
@model IEnumerable<CollegeInformationDTO>
@section Scripts{
<script>
var jsArray = JSON.parse('@Html.Raw(Json.Encode(@Model))');
</script>
}
I am late for this but i want put some more solution relevant to this.
@GetMapping
public ResponseEntity<List<JSONObject>> getRole() {
return ResponseEntity.ok(service.getRole());
}
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"defer</script>
Add Defer to the end of your Script tag, it worked for me (;
Everything needs to be loaded in the correct order (:
status of 200 will be the default when using res.send
, res.json
, etc.
You can set the status like res.status(500).json({ error: 'something is wrong' });
Often I'll do something like...
router.get('/something', function(req, res, next) {
// Some stuff here
if(err) {
res.status(500);
return next(err);
}
// More stuff here
});
Then have my error middleware send the response, and do anything else I need to do when there is an error.
Additionally: res.sendStatus(status)
has been added as of version 4.9.0
http://expressjs.com/4x/api.html#res.sendStatus
Remember that your img is not really a DOM element but a javascript expression.
This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions
In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components
/** @jsx React.DOM */
var Hello = React.createClass({
render: function() {
return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
}
});
React.renderComponent(<Hello name="World" />, document.body);
I also encountered this same error and the fix for me was to include my child module in the main module array.
var myApp = angular.module('myApp', ['ngRoute', 'childModuleName']);
Yor $.post
has no data. You need to pass the form data. You can use serialize()
to post the form data. Try this
$("#post-btn").click(function(){
$.post("process.php", $('#reg-form').serialize() ,function(data){
alert(data);
});
});
Here is how you can do it:
std::string & trim(std::string & str)
{
return ltrim(rtrim(str));
}
And the supportive functions are implemeted as:
std::string & ltrim(std::string & str)
{
auto it2 = std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
str.erase( str.begin() , it2);
return str;
}
std::string & rtrim(std::string & str)
{
auto it1 = std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
str.erase( it1.base() , str.end() );
return str;
}
And once you've all these in place, you can write this as well:
std::string trim_copy(std::string const & str)
{
auto s = str;
return ltrim(rtrim(s));
}
Try this
Set up a virtualenv:
% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py
% sudo python /tmp/get-pip.py
These commands install pip into the global site-packages directory.
% sudo pip install virtualenv
and ditto for virtualenv:
% mkdir -p ~/.virtualenvs
I like my virtualenvs under one tree in my home directory called .virtualenvs
% virtualenv ~/.virtualenvs/lxmltest
Creates a virtualenv.
% . ~/.virtualenvs/lxmltest/bin/activate
Removes the need to specify the full path to pip/python in this virtualenv.
% pip install lxml
Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml
if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest
and start again from a new virtualenv.
I know I'm late to the party but I thought I'd add what I ended up using for this - which is to simply check if the file upload input does not contain a truthy value with the not operator & JQuery like so:
if (!$('#videoUploadFile').val()) {
alert('Please Upload File');
}
Note that if this is in a form, you may also want to wrap it with the following handler to prevent the form from submitting:
$(document).on("click", ":submit", function (e) {
if (!$('#videoUploadFile').val()) {
e.preventDefault();
alert('Please Upload File');
}
}
You simply misspelled $stateParam
, it should be $stateParams
(with an s). That's why you get undefined ;)
This solution also avoids hasOwnProperty()
as Object.keys returns an array of a given object's own enumerable properties.
Object.keys(obj).forEach(function (key) {
if(typeof obj[key] === 'undefined'){
delete obj[key];
}
});
and you can add this as null
or ''
for stricter cleaning.
FYI dataTables requires a well formed table. It must contain <thead>
and <tbody>
tags, otherwise it throws this error. Also check to make sure all your rows including header row have the same number of columns.
The following will throw error (no <thead>
and <tbody>
tags)
<table id="sample-table">
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
<tr>
<td>data-1</td>
<td>data-2</td>
</tr>
</table>
The following will also throw an error (unequal number of columns)
<table id="sample-table">
<thead>
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
</tr>
</tbody>
</table>
For more info read more here
Mysqli isn't installed on the new server. Run phpinfo() to confirm.
<?php
phpinfo();
I just migrate to angular 1.3.3 and I found that If I had multiple controllers in different files when app is override and I lost first declared containers.
I don't know if is a good practise, but maybe can be helpful for another one.
var app = app;
if(!app) {
app = angular.module('web', ['ui.bootstrap']);
}
app.controller('SearchCtrl', SearchCtrl);
The problem was caused because the page was an intranet site, & IE had compatibility mode set to default for this. IE11 does support addEventListener()
No prompt use:
dir /x
Procure o nome reduzido do diretório na linha do "Program Files (x86)"
27/08/2018 15:07 <DIR> PROGRA~2 Program Files (x86)
Coloque a seguinte configuração em php.ini para a opção:
extension_dir="C:\PROGRA~2\path\to\php\ext"
Acredito que isso resolverá seu problema.
Zorro
In most cases you have to initialize the array,
let list: number[] = [];
TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.
If you are calling a Python service, the code will look like below:
this.updateTalentSupplier=function(supplierObj){
var promise = $http({
method: 'POST',
url: bbConfig.BWS+'updateTalentSupplier/',
data:supplierObj,
withCredentials: false,
contentType:'application/json',
dataType:'json'
});
return promise; //Promise is returned
}
We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.
Here is how you can do it with for-in
loop.
var children = element.childNodes;
for(child in children){
console.log(children[child]);
}
The error "Cannot read property 'map' of undefined"
will be encountered if there is an error in the "this.props.data"
or there is no props.data array.
Better put condition to check the the array like
if(this.props.data){
this.props.data.map(........)
.....
}
the .data()
method is from jQuery. If you want to use this method you need to include the jQuery library and access the method like this:
function doStuff(item) {
var id = $(item).data('id');
}
I also updated your jsFiffle
UPDATE
with pure angularjs and the jqlite you can achieve the goal like this:
function doStuff(item) {
var id = angular.element(item).data('id');
}
You must not access the element with []
because then you get the pure DOM element without all the jQuery or jqlite extra methods.
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
If you do the following, you will be able to use opencv build from OpenCV_INSTALL_PATH.
cmake_minimum_required(VERSION 2.8)
SET(OpenCV_INSTALL_PATH /home/user/opencv/opencv-2.4.13/release/)
SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")
SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib")
LINK_DIRECTORIES(${OpenCV_LIB_DIR})
set(OpenCV_LIBS opencv_core opencv_imgproc opencv_calib3d opencv_video opencv_features2d opencv_ml opencv_highgui opencv_objdetect opencv_contrib opencv_legacy opencv_gpu)
# find_package( OpenCV )
project(edge.cpp)
add_executable(edge edge.cpp)
Hi, this will throw an error:
foreach ($product->sku as $sku){
// Code Here
}
because you cannot loop a model with a specific column ($product->sku) from the table.
So you must loop on the whole model:
foreach ($product as $p) {
// code
}
Inside the loop you can retrieve whatever column you want just adding "->[column_name]"
foreach ($product as $p) {
echo $p->sku;
}
Have a great day
ogdate
is itself a string, why are you trying to access it's value
property that it doesn't have ?
console.log(og_date.split('-'));
DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.
That is, try adding -lpthread
to your command line.
$.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: associated_buildsorprojects_form,
success:function(data){
// do console.log(data);
console.log(data);
// you'll find that what exactly inside data
// I do not prefer alter(data); now because, it does not
// completes requirement all the time
// After that you can easily put if condition that you do not want like
// if(data != '')
// if(data == null)
// or whatever you want
},
error: function(errorThrown){
alert(errorThrown);
alert("There is an error with AJAX!");
}
});
It sounds like your printMousePos
function should:
Currently, it does this:
See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.
It seems like you probably don't need that mousemove event at all; I would try something like this:
function printMousePos(e) {
var cursorX = e.pageX;
var cursorY = e.pageY;
document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}
your $(this).val() has no scope in your ajax call, because its not in change event function scope
May be you implemented that ajax call in your change event itself first, in that case it works fine. but when u created a function and calling that funciton in change event, scope for $(this).val() is not valid.
simply get the value using id selector instead of
$(#CourseSelect).val()
whole code should be like this:
$(document).ready(function ()
{
$("#CourseSelect").change(loadTeachers);
loadTeachers();
});
function loadTeachers()
{
$.ajax({ type:'GET', url:'/Manage/getTeachers/' + $(#CourseSelect).val(), dataType:'json', cache:false,
success:function(data)
{
$('#TeacherSelect').get(0).options.length = 0;
$.each(data, function(i, teacher)
{
var option = $('<option />');
option.val(teacher.employeeId);
option.text(teacher.name);
$('#TeacherSelect').append(option);
});
}, error:function(){ alert("Error while getting results"); }
});
}
ExpressJS Issue:
Most of the middleware is removed from express 4. check out: http://www.github.com/senchalabs/connect#middleware For multipart middleware like busboy, busboy-connect, formidable, flow, parted is needed.
This example works using connect-busboy middleware.
create /img and /public folders.
Use the folder structure:
\server.js
\img\"where stuff is uploaded to"
\public\index.html
SERVER.JS
var express = require('express'); //Express Web Server
var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path'); //used for file path
var fs = require('fs-extra'); //File System - for file manipulation
var app = express();
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));
/* ==========================================================
Create a Route (/upload) to handle the Form submission
(handle POST requests to /upload)
Express v4 Route definition
============================================================ */
app.route('/upload')
.post(function (req, res, next) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
//Path where image will be uploaded
fstream = fs.createWriteStream(__dirname + '/img/' + filename);
file.pipe(fstream);
fstream.on('close', function () {
console.log("Upload Finished of " + filename);
res.redirect('back'); //where to go next
});
});
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});
INDEX.HTML
<!DOCTYPE html>
<html lang="en" ng-app="APP">
<head>
<meta charset="UTF-8">
<title>angular file upload</title>
</head>
<body>
<form method='post' action='upload' enctype="multipart/form-data">
<input type='file' name='fileUploaded'>
<input type='submit'>
</body>
</html>
The following will work with formidable SERVER.JS
var express = require('express'); //Express Web Server
var bodyParser = require('body-parser'); //connects bodyParsing middleware
var formidable = require('formidable');
var path = require('path'); //used for file path
var fs =require('fs-extra'); //File System-needed for renaming file etc
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
/* ==========================================================
bodyParser() required to allow Express to see the uploaded files
============================================================ */
app.use(bodyParser({defer: true}));
app.route('/upload')
.post(function (req, res, next) {
var form = new formidable.IncomingForm();
//Formidable uploads to operating systems tmp dir by default
form.uploadDir = "./img"; //set upload directory
form.keepExtensions = true; //keep file extension
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
console.log("form.bytesReceived");
//TESTING
console.log("file size: "+JSON.stringify(files.fileUploaded.size));
console.log("file path: "+JSON.stringify(files.fileUploaded.path));
console.log("file name: "+JSON.stringify(files.fileUploaded.name));
console.log("file type: "+JSON.stringify(files.fileUploaded.type));
console.log("astModifiedDate: "+JSON.stringify(files.fileUploaded.lastModifiedDate));
//Formidable changes the name of the uploaded file
//Rename the file to its original name
fs.rename(files.fileUploaded.path, './img/'+files.fileUploaded.name, function(err) {
if (err)
throw err;
console.log('renamed complete');
});
res.end();
});
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});
To state the obvious, the cup represents outerScopeVar
.
Asynchronous functions be like...
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
d
: integerEg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
Your plunker is firing off
angular.element(document.getElementById('MyController')).scope().myfunction('test');
Before anything is rendered.
You can verify that by wrapping it in a timeout
setTimeout(function() {
angular.element(document.getElementById('MyController')).scope().myfunction('test');
}, 1000);
You also need to acutally add an ID to your div.
<div ng-app='MyModule' ng-controller="MyController" id="MyController">
I changed in express 4.0 the basic authentication with http-auth, the code is:
var auth = require('http-auth');
var basic = auth.basic({
realm: "Web."
}, function (username, password, callback) { // Custom authentication method.
callback(username === "userName" && password === "password");
}
);
app.get('/the_url', auth.connect(basic), routes.theRoute);
This works for me
$('.someclass').click(function() {
$varName = $(this).data('fulltext');
console.log($varName);
});
I think jQuery cannot find the element.
First of all find the element
var rowTemplate= document.getElementsByName("rowTemplate");
or
var rowTemplate = document.getElementById("rowTemplate");
or
var rowTemplate = $('#rowTemplate');
Then try your code again
rowTemplate.html().replace(....)
If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:
Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.
Basically, you can do something like this:
function doCall(urlToCall) {
return co(function *(){
var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}
Then,
var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.
By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
I don't think jQuery itself includes datetimepicker. You must use jQuery UI instead (src="jquery.ui").
1) Make sure that your file is really sent from the client side. For example you can check it in Chrome Console: screenshot
2) Here is the basic example of NodeJS backend:
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
app.use(fileUpload()); // Don't forget this line!
app.post('/upload', function(req, res) {
console.log(req.files);
res.send('UPLOADED!!!');
});
I think best way is check if request is of type "OPTIONS" return 200 from middle ware. It worked for me.
express.use('*',(req,res,next) =>{
if (req.method == "OPTIONS") {
res.status(200);
res.send();
}else{
next();
}
});
I faced the same error, but only with files cloned from git that were assigned to a proprietary plugin. I realized that even after cloning the files from git, I needed to create a new project or import a project in eclipse and this resolved the error.
Further to the solution above... I would use a MultiTrigger to allow the MouseOver highlights to continue to work after selection such that your ListViewItem's style will be:
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="True" />
<Condition Property="IsMouseOver" Value="False" />
</MultiTrigger.Conditions>
<MultiTrigger.Setters>
<Setter Property="Background" Value="{x:Null}" />
<Setter Property="BorderBrush" Value="{x:Null}" />
</MultiTrigger.Setters>
</MultiTrigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
You can get the device ip address by this way:
adb shell ip route > addrs.txt
#Case 1:Nexus 7
#192.168.88.0/23 dev wlan0 proto kernel scope link src 192.168.89.48
#Case 2: Smartsian T1,Huawei C8813
#default via 192.168.88.1 dev eth0 metric 30
#8.8.8.8 via 192.168.88.1 dev eth0 metric 30
#114.114.114.114 via 192.168.88.1 dev eth0 metric 30
#192.168.88.0/23 dev eth0 proto kernel scope link src 192.168.89.152 metric 30
#192.168.88.1 dev eth0 scope link metric 30
ip_addrs=$(awk {'if( NF >=9){print $9;}'} addrs.txt)
echo "the device ip address is $ip_addrs"
I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# simulate a time-consuming task by sleeping
time.sleep(5)
# `release` will add 1 to `sema`, allowing other
# processes blocked on it to continue
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
# once 20 processes are running, the following `acquire` call
# will block the main process since `sema` has been reduced
# to 0. This loop will continue only after one or more
# previously created processes complete.
sema.acquire()
p = Process(target=f, args=(i, sema))
all_processes.append(p)
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The following code is more structured since it acquires and releases sema
in the same function. However, it will consume too much resources if total_task_num
is very large:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# `sema` is acquired and released in the same
# block of code here, making code more readable,
# but may lead to problem.
sema.acquire()
time.sleep(5)
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
p = Process(target=f, args=(i, sema))
all_processes.append(p)
# the following line won't block after 20 processes
# have been created and running, instead it will carry
# on until all 1000 processes are created.
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The above code will create total_task_num
processes but only concurrency
processes will be running while other processes are blocked, consuming precious system resources.
If you're interested in learning a language which supports massive parallelism better go for OpenCL since you don't have an NVIDIA GPU. You can run OpenCL on Intel CPUs, but at best you can learn to program SIMDs. Optimization on CPU and GPU are different. I really don't think you can use Intel card for GPGPU.
CTRL+/ on windows, no need to select whole line, Just use key combination on line which you want to comment out.
It is not good practice to save the value that is returned from JSON.stringify(userData)
to a cookie; it can lead to a bug in some browsers.
Before using it, you should convert it to base64 (using btoa
), and when reading it, convert from base64 (using atob
).
val = JSON.stringify(userData)
val = btoa(val)
write_cookie(val)
The TypeError
is happening because k
is a list, since it is created using a slice from another list with the line k = list[0:j]
. This should probably be something like k = ' '.join(list[0:j])
, so you have a string instead.
In addition to this, your if
statement is incorrect as noted by Jesse's answer, which should read if k not in d
or if not k in d
(I prefer the latter).
You are also clearing your dictionary on each iteration since you have d = {}
inside of your for
loop.
Note that you should also not be using list
or file
as variable names, since you will be masking builtins.
Here is how I would rewrite your code:
d = {}
with open("filename.txt", "r") as input_file:
for line in input_file:
fields = line.split()
j = fields.index("x")
k = " ".join(fields[:j])
d.setdefault(k, []).append(" ".join(fields[j+1:]))
The dict.setdefault()
method above replaces the if k not in d
logic from your code.
The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).
You can use the GUI to do the installation, or you can script the installation of msbuild:
vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet
Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:
You can find documentation about the other available CLI switches here.
The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet
there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin
.
If you don't see them there, try running without --quiet
to see any error messages that may occur during installation.
Giving write permissions to all IIS_USRS group is a bad idea from the security point of view. You dont need to do that and you can go with giving permissions only to system user running the application pool.
If you are using II7 (and I guess you do) do the following.
Note #1: if you see ApplicationPoolIdentity in #3 you need to reference this system user like this IIS AppPool{application_pool_name} . For example IIS AppPool\DefaultAppPool
Note #2: when adding this user make sure to set correct locations in the Select Users or Groups dialog. This needs to be set to local machine because this is local account.
I find that the OS Utils from Swingx does the job.
If you're using maven I would do something like this:
Being production your default profile:
<properties>
<activeProfile>production</activeProfile>
</properties>
And as an example of other profiles:
<profiles>
<!--Your default profile... selected if none specified-->
<profile>
<id>production</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<activeProfile>production</activeProfile>
</properties>
</profile>
<!--Profile 2-->
<profile>
<id>development</id>
<properties>
<activeProfile>development</activeProfile>
</properties>
</profile>
<!--Profile 3-->
<profile>
<id>otherprofile</id>
<properties>
<activeProfile>otherprofile</activeProfile>
</properties>
</profile>
<profiles>
In your application.properties you'll have to set:
spring.profiles.active=@activeProfile@
This works for me every time, hope it solves your problem.
You can try this
click Help>Install New Software on the menu bar
use
Date date = new Date();
String strDate = sdf.format(date);
intead Of
Calendar cal = Calendar.getInstance();
String strDate = sdf.format(cal.getTime());
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
// Embarcadero C++ Builder
// convertion string to wstring
string str1 = "hello";
String str2 = str1; // typedef UnicodeString String; -> str2 contains now u"hello";
// convertion wstring to string
String str2 = u"hello";
string str1 = UTF8string(str2).c_str(); // -> str1 contains now "hello"
I have tested the following and this does work. The answer by gordyii was close but had the multiplication of 100 in the wrong place and had some missing parenthesis.
Select Grade, (Count(Grade)* 100 / (Select Count(*) From MyTable)) as Score
From MyTable
Group By Grade
Here is a working example for strict json parsing with gson library:
public static JsonElement parseStrict(String json) {
// throws on almost any non-valid json
return new Gson().getAdapter(JsonElement.class).fromJson(json);
}
See also my other detailed answer in How to check if JSON is valid in Java using GSON with more info and extended test case with various non-valid examples.
input:not([value=""])
This works because we are selecting the input only when there isn't an empty string.
https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...
<?php
require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
$getID3 = new getID3();
$filename="/fire/My Documents/video/ferrari1.mpg";
$fileinfo = $getID3->analyze($filename);
$width=$fileinfo['video']['resolution_x'];
$height=$fileinfo['video']['resolution_y'];
echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
echo '<pre>';print_r($fileinfo);echo '</pre>';
?>
To create a uniqueString based on unique identifier of device in iOS 6:
#import <AdSupport/ASIdentifierManager.h>
NSString *uniqueString = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
NSLog(@"uniqueString: %@", uniqueString);
position()
. E.G.:
<countNo><xsl:value-of select="position()" /></countNo>
Leveraging the power of java.util.Optional#map()
:
List<Car> requiredCars = cars.stream()
.filter (car ->
Optional.ofNullable(car)
.map(Car::getName)
.map(name -> name.startsWith("M"))
.orElse(false) // what to do if either car or getName() yields null? false will filter out the element
)
.collect(Collectors.toList())
;
Remove your defines at the top
#if DEBUG
Console.WriteLine("Mode=Debug");
#else
Console.WriteLine("Mode=Release");
#endif
Three years later, I ran into the same problem. Here's my solution, everybody feel free to cut-n-paste. The simplest things keep us up all night! Running on an ATMega, and Adafruit Feather M0:
void setup() {
// turn on Serial so we can see...
Serial.begin(9600);
// the culprit:
uint8_t my_str[6]; // an array big enough for a 5 character string
// give it something so we can see what it's doing
my_str[0] = 'H';
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0; // be sure to set the null terminator!!!
// can we see it?
Serial.println((char*)my_str);
// can we do logical operations with it as-is?
Serial.println((char*)my_str == 'Hello');
// okay, it can't; wrong data type (and no terminator!), so let's do this:
String str((char*)my_str);
// can we see it now?
Serial.println(str);
// make comparisons
Serial.println(str == 'Hello');
// one more time just because
Serial.println(str == "Hello");
// one last thing...!
Serial.println(sizeof(str));
}
void loop() {
// nothing
}
And we get:
Hello // as expected
0 // no surprise; wrong data type and no terminator in comparison value
Hello // also, as expected
1 // YAY!
1 // YAY!
6 // as expected
Hope this helps someone!
I came up with the same problem, and open setting.json file, add the following:
"workbench.editor.enablePreview": false
From a Windows Server OS execute the following command for a dump of the entire Active Director:
csvde -f test.csv
This command is very broad and will give you more than necessary information. To constrain the records to only user records, you would instead want:
csvde -f test.csv -r objectClass=user
You can further restrict the command to give you only the fields you need relevant to the search requested such as:
csvde -f test.csv -r objectClass=user -l DN, sAMAccountName, department, memberOf
If you have an Exchange server and each user associated with a live person has a mailbox (as opposed to generic accounts for kiosk / lab workstations) you can use mailNickname in place of sAMAccountName.
You may want to consider using <<<
e.g.
<<<VARIABLE
this is some
random text
that I'm typing
here and I will end it with the
same word I started it with
VARIABLE
More info at: http://php.net/manual/en/language.types.string.php
Btw - Some Coding environments don't know how to handle the above syntax.
List<Person> roster = ...;
Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(), p -> p)
);
that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)
Try this code once-
public class FindPeopleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home,
container, false);
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateDetail();
}
});
return rootView;
}
public void updateDetail() {
Intent intent = new Intent(getActivity(), MainActivityList.class);
startActivity(intent);
}
}
And as suggested by Raghunandan remove below code from your fragment_home.xml
-
android:onClick="goToAttract"
here is the workaround sample.
function redirect_post($url, array $data)
{
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function closethisasap() {
document.forms["redirectpost"].submit();
}
</script>
</head>
<body onload="closethisasap();">
<form name="redirectpost" method="post" action="<? echo $url; ?>">
<?php
if ( !is_null($data) ) {
foreach ($data as $k => $v) {
echo '<input type="hidden" name="' . $k . '" value="' . $v . '"> ';
}
}
?>
</form>
</body>
</html>
<?php
exit;
}
This answer includes GitHub as many folks have asked about that too.
Git (locally) has a directory (.git
) which you commit your files to and this is your 'local repository'. This is different from systems like SVN where you add and commit to the remote repository immediately.
Git stores each version of a file that changes by saving the entire file. It is also different from SVN in this respect as you could go to any individual version without 'recreating' it through delta changes.
Git doesn't 'lock' files at all and thus avoids the 'exclusive lock' functionality for an edit (older systems like pvcs come to mind), so all files can always be edited, even when off-line. It actually does an amazing job of merging file changes (within the same file!) together during pulls or fetches/pushes to a remote repository such as GitHub. The only time you need to do manual changes (actually editing a file) is if two changes involve the same line(s) of code.
Branches allow you to preserve the main code (the 'master' branch), make a copy (a new branch) and then work within that new branch. If the work takes a while or master gets a lot of updates since the branch was made then merging or rebasing (often preferred for better history and easier to resolve conflicts) against the master branch should be done. When you've finished, you merge the changes made in the branch back in to the master repository. Many organizations use branches for each piece of work whether it is a feature, bug or chore item. Other organizations only use branches for major changes such as version upgrades.
Fork: With a branch you control and manage the branch, whereas with a fork someone else controls accepting the code back in.
Broadly speaking, there are two main approaches to doing branches. The first is to keep most changes on the master branch, only using branches for larger and longer-running things like version changes where you want to have two branches available for different needs. The second is whereby you basically make a branch for every feature request, bug fix or chore and then manually decide when to actually merge those branches into the main master branch. Though this sounds tedious, this is a common approach and is the one that I currently use and recommend because this keeps the master branch cleaner and it's the master that we promote to production, so we only want completed, tested code, via the rebasing and merging of branches.
The standard way to bring a branch 'in' to master is to do a merge
. Branches can also be "rebased" to 'clean up' history. It doesn't affect the current state and is done to give a 'cleaner' history.
Basically, the idea is that you branched from a certain point (usually from master). Since you branched, 'master' itself has since moved forward from that branching point. It will be 'cleaner' (easier to resolve issues and the history will be easier to understand) if all the changes you have done in a branch are played against the current state of master with all of its latest changes. So, the process is: save the changes; get the 'new' master, and then reapply (this is the rebase part) the changes again against that. Be aware that rebase, just like merge, can result in conflicts that you have to manually resolve (i.e. edit and fix).
One guideline to note:
Only rebase if the branch is local and you haven't pushed it to remote yet!
This is mainly because rebasing can alter the history that other people see which may include their own commits.
These are the branches that are named origin/branch_name
(as opposed to just branch_name
). When you are pushing and pulling the code to/from remote repositories this is actually the mechanism through which that happens. For example, when you git push
a branch called building_groups
, your branch goes first to origin/building_groups
and then that goes to the remote repository. Similarly, if you do a git fetch building_groups
, the file that is retrieved is placed in your origin/building_groups
branch. You can then choose to merge this branch into your local copy. Our practice is to always do a git fetch
and a manual merge rather than just a git pull
(which does both of the above in one step).
Getting new branches: At the initial point of a clone you will have all the branches. However, if other developers add branches and push them to the remote there needs to be a way to 'know' about those branches and their names in order to be able to pull them down locally. This is done via a git fetch
which will get all new and changed branches into the locally repository using the tracking branches (e.g., origin/
). Once fetch
ed, one can git branch --remote
to list the tracking branches and git checkout [branch]
to actually switch to any given one.
Merging is the process of combining code changes from different branches, or from different versions of the same branch (for example when a local branch and remote are out of sync). If one has developed work in a branch and the work is complete, ready and tested, then it can be merged into the master
branch. This is done by git checkout master
to switch to the master
branch, then git merge your_branch
. The merge will bring all the different files and even different changes to the same files together. This means that it will actually change the code inside files to merge all the changes.
When doing the checkout
of master
it's also recommended to do a git pull origin master
to get the very latest version of the remote master merged into your local master. If the remote master changed, i.e., moved forward
, you will see information that reflects that during that git pull
. If that is the case (master changed) you are advised to git checkout your_branch
and then rebase
it to master so that your changes actually get 'replayed' on top of the 'new' master. Then you would continue with getting master up-to-date as shown in the next paragraph.
If there are no conflicts, then master will have the new changes added in. If there are conflicts, this means that the same files have changes around similar lines of code that it cannot automatically merge. In this case git merge new_branch
will report that there's conflict(s) to resolve. You 'resolve' them by editing the files (which will have both changes in them), selecting the changes you want, literally deleting the lines of the changes you don't want and then saving the file. The changes are marked with separators such as ========
and <<<<<<<<
.
Once you have resolved any conflicts you will once again git add
and git commit
those changes to continue the merge (you'll get feedback from git during this process to guide you).
When the process doesn't work well you will find that git merge --abort
is very handy to reset things.
If you have done work in a lot of small steps, e.g., you commit code as 'work-in-progress' every day, you may want to 'squash' those many small commits into a few larger commits. This can be particularly useful when you want to do code reviews with colleagues. You don't want to replay all the 'steps' you took (via commits), you want to just say here is the end effect (diff) of all of my changes for this work in one commit.
The key factor to evaluate when considering whether to do this is whether the multiple commits are against the same file or files more than once (better to squash commits in that case). This is done with the interactive rebasing tool. This tool lets you squash commits, delete commits, reword messages, etc. For example, git rebase -i HEAD~10
(note: that's a ~
, not a -
) brings up the following:
Be careful though and use this tool 'gingerly'. Do one squash/delete/reorder at a time, exit and save that commit, then reenter the tool. If commits are not contiguous you can reorder them (and then squash as needed). You can actually delete commits here too, but you really need to be sure of what you are doing when you do that!
There are two main approaches to collaboration in Git repositories. The first, detailed above, is directly via branches that people pull and push from/to. These collaborators have their SSH keys registered with the remote repository. This will let them push directly to that repository. The downside is that you have to maintain the list of users. The other approach - forking - allows anybody to 'fork' the repository, basically making a local copy in their own Git repository account. They can then make changes and when finished send a 'pull request' (really it's more of a 'push' from them and a 'pull' request for the actual repository maintainer) to get the code accepted.
This second method, using forks, does not require someone to maintain a list of users for the repository.
GitHub (a remote repository) is a remote source that you normally push and pull those committed changes to if you have (or are added to) such a repository, so local and remote are actually quite distinct. Another way to think of a remote repository is that it is a .git
directory structure that lives on a remote server.
When you 'fork' - in the GitHub web browser GUI you can click on this button - you create a copy ('clone') of the code in your GitHub account. It can be a little subtle first time you do it, so keep making sure you look at whose repository a code base is listed under - either the original owner or 'forked from' and you, e.g., like this:
Once you have the local copy, you can make changes as you wish (by pulling and pushing them to a local machine). When you are done then you submit a 'pull request' to the original repository owner/admin (sounds fancy but actually you just click on this: ) and they 'pull' it in.
More common for a team working on code together is to 'clone' the repository (click on the 'copy' icon on the repository's main screen). Then, locally type git clone
and paste. This will set you up locally and you can also push and pull to the (shared) GitHub location.
As indicated in the section on GitHub, a clone is a copy of a repository. When you have a remote repository you issue the git clone
command against its URL and you then end up with a local copy, or clone, of the repository. This clone has everything, the files, the master branch, the other branches, all the existing commits, the whole shebang. It is this clone that you do your adds and commits against and then the remote repository itself is what you push those commits to. It's this local/remote concept that makes Git (and systems similar to it such as Mercurial) a DVCS (Distributed Version Control System) as opposed to the more traditional CVSs (Code Versioning Systems) such as SVN, PVCS, CVS, etc. where you commit directly to the remote repository.
Visualization of the core concepts can be seen at
http://marklodato.github.com/visual-git-guide/index-en.html and
http://ndpsoftware.com/git-cheatsheet.html#loc=index
If you want a visual display of how the changes are working, you can't beat the visual tool gitg
(gitx
for macOS) with a GUI that I call 'the subway map' (esp. London Underground), great for showing who did what, how things changes, diverged and merged, etc.
You can also use it to add, commit and manage your changes!
Although gitg/gitx is fairly minimal, the number of GUI tools continues to expand. Many Mac users use brotherbard's fork of gitx and for Linux, a great option is smart-git with an intuitive yet powerful interface:
Note that even with a GUI tool, you will probably do a lot of commands at the command line.
For this, I have the following aliases in my ~/.bash_aliases
file (which is called from my ~/.bashrc
file for each terminal session):
# git
alias g='git status'
alias gcob='git checkout -b '
alias gcom='git checkout master'
alias gd='git diff'
alias gf='git fetch'
alias gfrm='git fetch; git reset --hard origin/master'
alias gg='git grep '
alias gits='alias | grep "^alias g.*git.*$"'
alias gl='git log'
alias gl1='git log --oneline'
alias glf='git log --name-status'
alias glp='git log -p'
alias gpull='git pull '
alias gpush='git push '
AND I have the following "git aliases" in my ~/.gitconfig
file - why have these ?
So that branch completion (with the TAB key) works !
So these are:
[alias]
co = checkout
cob = checkout -b
Example usage: git co [branch]
<- tab completion for branches will work.
You may find https://learngitbranching.js.org/ useful in learning some of the base concepts. Screen shot:
Video: https://youtu.be/23JqqcLPss0
You make changes, add and commit them (but don't push) and then oh! you realize you are in master!
git reset [filename(s)]
git checkout -b [name_for_a_new_branch]
git add [file(s)]
git commit -m "A useful message"
Voila! You've moved that 'master' commit to its own branch !
You mess up some files while working in a local branch and simply want to go back to what you had the last time you did a git pull
:
git reset --hard origin/master # You will need to be comfortable doing this!
You start making changes locally, you edit half a dozen files and then, oh crap, you're still in the master (or another) branch:
git checkout -b new_branch_name # just create a new branch
git add . # add the changes files
git commit -m"your message" # and commit them
You mess up one particular file in your current branch and want to basically 'reset' that file (lose changes) to how it was the the last time you pulled it from the remote repository:
git checkout your/directories/filename
This actually resets the file (like many Git commands it is not well named for what it is doing here).
You make some changes locally, you want to make sure you don't lose them while you do a git reset
or rebase
: I often make a manual copy of the entire project (cp -r ../my_project ~/
) when I am not sure if I might mess up in Git or lose important changes.
You are rebasing but things gets messed up:
git rebase --abort # To abandon interactive rebase and merge issues
Add your Git branch to your PS1
prompt (see https://unix.stackexchange.com/a/127800/10043), e.g.
The branch is selenium_rspec_conversion
.
"""
merge_image takes three parameters first two parameters specify
the two images to be merged and third parameter i.e. vertically
is a boolean type which if True merges images vertically
and finally saves and returns the file_name
"""
def merge_image(img1, img2, vertically):
images = list(map(Image.open, [img1, img2]))
widths, heights = zip(*(i.size for i in images))
if vertically:
max_width = max(widths)
total_height = sum(heights)
new_im = Image.new('RGB', (max_width, total_height))
y_offset = 0
for im in images:
new_im.paste(im, (0, y_offset))
y_offset += im.size[1]
else:
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset, 0))
x_offset += im.size[0]
new_im.save('test.jpg')
return 'test.jpg'
To enable disable Wifi use the WifiManager
class to get system(android device) services for Wifi :
WifiManager wifi =(WifiManager)getSystemService(Context.WIFI_SERVICE);
Now the object wifi
of the WifiManager
class is used to get the wifi status:
if(wifi.isWifiEnabled())
//Perform Operation
else
//Other Operation
And most importantly do not forget to give the following permission in your Android Manifest File:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
To get detailed info and full sample code of the project for enable/disable Wifi on android visit my website link.
Here is a small tool scanip that will help you to get all ip addresses and their corresponding mac addresses in the network (Works on Linux).
In addition to all of the other answers, if you are sending HTML emails that contain URLs as linking text, make sure that the URL matches the linking text. I know that Thunderbird automatically flags them as being a scam if not.
The wrong way:
Go to your account now: <a href="http://www.paypal.com.phishers-anonymous.org/">http://www.paypal.com</a>
The right way:
Go to your account now: <a href="http://www.yourdomain.org/">http://www.yourdomain.org</a>
Or use an unrelated linking text instead of a URL:
<a href="http://www.yourdomain.org/">Click here to go to your account</a>
SET STATISTICS TIME ON
SELECT *
FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;
SET STATISTICS TIME OFF;
And see the message tab it will look like this:
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 10 ms.
(778 row(s) affected)
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
There is an eclipse.ini (sts.ini) parameter that can help:
-Djava.net.useSystemProxies=true
A lot of effort wasted on this trivial setting each time I change the work environment... See one of the related bugs on eclipse bugzilla.
The brief points:
If the request header had already been set, then the new value MUST be concatenated to the existing value using a U+002C COMMA followed by a U+0020 SPACE for separation.
UAs MAY give the User-Agent header an initial value, but MUST allow authors to append values to it.
However - After searching through the framework XHR in jQuery they don't allow you to change the User-Agent or Referer headers. The closest thing:
// Set header so the called script knows that it's an XMLHttpRequest
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
I'm leaning towards the opinion that what you want to do is being denied by a security policy in FF - if you want to pass some custom Referer
type header you could always do:
xhr.setRequestHeader('X-Alt-Referer', 'http://www.google.com');
Mock Objects.
A mock DateTime that returns a Now that's appropriate for your test.
Simply use the "utf-8-sig" codec:
fp = open("file.txt")
s = fp.read()
u = s.decode("utf-8-sig")
That gives you a unicode
string without the BOM. You can then use
s = u.encode("utf-8")
to get a normal UTF-8 encoded string back in s
. If your files are big, then you should avoid reading them all into memory. The BOM is simply three bytes at the beginning of the file, so you can use this code to strip them out of the file:
import os, sys, codecs
BUFSIZE = 4096
BOMLEN = len(codecs.BOM_UTF8)
path = sys.argv[1]
with open(path, "r+b") as fp:
chunk = fp.read(BUFSIZE)
if chunk.startswith(codecs.BOM_UTF8):
i = 0
chunk = chunk[BOMLEN:]
while chunk:
fp.seek(i)
fp.write(chunk)
i += len(chunk)
fp.seek(BOMLEN, os.SEEK_CUR)
chunk = fp.read(BUFSIZE)
fp.seek(-BOMLEN, os.SEEK_CUR)
fp.truncate()
It opens the file, reads a chunk, and writes it out to the file 3 bytes earlier than where it read it. The file is rewritten in-place. As easier solution is to write the shorter file to a new file like newtover's answer. That would be simpler, but use twice the disk space for a short period.
As for guessing the encoding, then you can just loop through the encoding from most to least specific:
def decode(s):
for encoding in "utf-8-sig", "utf-16":
try:
return s.decode(encoding)
except UnicodeDecodeError:
continue
return s.decode("latin-1") # will always work
An UTF-16 encoded file wont decode as UTF-8, so we try with UTF-8 first. If that fails, then we try with UTF-16. Finally, we use Latin-1 — this will always work since all 256 bytes are legal values in Latin-1. You may want to return None
instead in this case since it's really a fallback and your code might want to handle this more carefully (if it can).
Adapted from ChapMic's answer to suite my particular need.
Only specify your database name, then sort all the tables in descending order - from LARGEST to SMALLEST table inside selected database. Needs only 1 variable to be replaced = your database name.
SELECT
table_name AS `Table`,
round(((data_length + index_length) / 1024 / 1024), 2) AS `size`
FROM information_schema.TABLES
WHERE table_schema = "YOUR_DATABASE_NAME_HERE"
ORDER BY size DESC;
1) PYTHONPATH
is an environment variable which you can set to add additional directories where python will look for modules and packages. e.g.:
# make python look in the foo subdirectory of your home directory for
# modules and packages
export PYTHONPATH=${PYTHONPATH}:${HOME}/foo
Here I use the sh
syntax. For other shells (e.g. csh
,tcsh
), the syntax would be slightly different. To make it permanent, set the variable in your shell's init file (usually ~/.bashrc).
2) Ubuntu comes with python already installed. There may be reasons for installing other (independent) python versions, but I've found that to be rarely necessary.
3) The folder where your modules live is dependent on PYTHONPATH
and where the directories were set up when python was installed. For the most part, the installed stuff you shouldn't care about where it lives -- Python knows where it is and it can find the modules. Sort of like issuing the command ls
-- where does ls
live? /usr/bin
? /bin
? 99% of the time, you don't need to care -- Just use ls
and be happy that it lives somewhere on your PATH
so the shell can find it.
4) I'm not sure I understand the question. 3rd party modules usually come with install instructions. If you follow the instructions, python should be able to find the module and you shouldn't have to care about where it got installed.
5) Configure PYTHONPATH
to include the directory where your module resides and python will be able to find your module.
Oftentimes you see the suggestion use use keyword arguments, with default values, instead. Look into that.
On fedora/rhel/centos you need to
sudo yum install -y python3-devel
before
mkvirtualenv -p /usr/bin/python3.3 test-3.3
pip install numpy
otherwise you'll get
SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel.
Here is what you want to put in the project's Post-build event command line:
copy /Y "$(TargetDir)$(ProjectName).dll" "$(SolutionDir)lib\$(ProjectName).dll"
EDIT: Or if your target name is different than the Project Name.
copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)lib\$(TargetName).dll"
Just updating here solution suggested by @ken-kinder for Python 2 to work for Python 3:
import urllib
urllib.request.urlopen(target_url).read()
This is for the searchers,
The best I did is,
$('#myDiv *').attr("disabled", true);
$('#myDiv *').fadeTo('slow', .6);
As others have pointed out, listeners have to be registered in order to read these streams. Also note that Debug.Write
will only function if the DEBUG
build flag is set, while Trace.Write
will only function if the TRACE
build flag is set.
Setting the DEBUG
and/or TRACE
flags is easily done in the project properties in Visual Studio or by supplying the following arguments to csc.exe
/define:DEBUG;TRACE
Look no more for IP addresses not being set in the expected header. Just do the following to inspect the whole server variables and figure out which one is suitable for your case:
print_r($_SERVER);
I suppose you can open Java files in Visual Studio and just use the command line tools directly. I don't think you'd get syntax highlighting or autocompletion though.
Eclipse is really not all that different from Visual Studio, and there are a lot of tools that are designed to make Android development more comfortable that work from within Eclipse.
>>> text = 'lipsum'
>>> text[3:]
'sum'
See the official documentation on strings for more information and this SO answer for a concise summary of the notation.
I had the same problem with Tensorflow 2.0.0 in PyCharm. PyCharm did not recognize tensorflow.keras; I updated my PyCharm and the problem was resolved!
This worked for me. Repeatedly calls a function updating the graph every time.
import matplotlib.pyplot as plt
import matplotlib.animation as anim
def plot_cont(fun, xmax):
y = []
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
def update(i):
yi = fun()
y.append(yi)
x = range(len(y))
ax.clear()
ax.plot(x, y)
print i, ': ', yi
a = anim.FuncAnimation(fig, update, frames=xmax, repeat=False)
plt.show()
"fun" is a function that returns an integer. FuncAnimation will repeatedly call "update", it will do that "xmax" times.
There is no such method as slideLeft() and slideRight() which looks like slideUp() and slideDown(), but you can simulate these effects using jQuery’s animate() function.
HTML Code:
<div class="text">Lorem ipsum.</div>
JQuery Code:
$(document).ready(function(){
var DivWidth = $(".text").width();
$(".left").click(function(){
$(".text").animate({
width: 0
});
});
$(".right").click(function(){
$(".text").animate({
width: DivWidth
});
});
});
You can see an example here: How to slide toggle a DIV from Left to Right?
This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:
//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
// If the no button was pressed ...
if (result == DialogResult.No)
{
...
}
Hope it helps
This should works
.center-div {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
text-align: center;_x000D_
min-height: 100vh;_x000D_
}
_x000D_
<div class="center-div">Center Div</div>
_x000D_
Copy the global variable to a variable in the scope in your controller.
function MyCtrl($scope) {
$scope.variable1 = variable1;
}
Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).
But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.
Look up double.TryParse()
if you're talking about numbers like 1
, -2
and 3.14159
. Some others are suggesting int.TryParse()
, but that will fail on decimals.
string candidate = "3.14159";
if (double.TryParse(candidate, out var parsedNumber))
{
// parsedNumber is a valid number!
}
EDIT: As Lukasz points out below, we should be mindful of the thread culture when parsing numbers with a decimal separator, i.e. do this to be safe:
double.TryParse(candidate, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var parsedNumber)
Download and Install package here: https://atom.io/packages/script
To execute the python command in atom use the below shortcuts:
For Windows/Linux, it's SHIFT + Ctrl + B OR Ctrl + SHIFT + B
If you're on Mac, press ? + I
for item in get_list():
return item
Create a java module to be initially run when starting your app. This module would be extending the android Application class and would initialize any global app variables and also contain app-wide utility routines -
public class MyApplicationName extends Application {
private final String PACKAGE_NAME = "com.mysite.myAppPackageName";
public String getPackageName() { return PACKAGE_NAME; }
}
Of course, this could include logic to obtain the package name from the android system; however, the above is smaller, faster and cleaner code than obtaining it from android.
Be sure to place an entry in your AndroidManifest.xml file to tell android to run your application module before running any activities -
<application
android:name=".MyApplicationName"
...
>
Then, to obtain the package name from any other module, enter
MyApp myApp = (MyApp) getApplicationContext();
String myPackage = myApp.getPackageName();
Using an application module also gives you a context for modules that need but don't have a context.
Best way to make drop down list:
grid.Column("PriceType",canSort:true,header: "PriceType",format: @<span>
<span id="[email protected]">@item.PriceTypeDescription</span>
@Html.DropDownList("PriceType"+(int)item.ShoppingCartID,new SelectList(MvcApplication1.Services.ExigoApiContext.CreateODataContext().PriceTypes.Select(s => new { s.PriceTypeID, s.PriceTypeDescription }).AsEnumerable(),"PriceTypeID", "PriceTypeDescription",Convert.ToInt32(item.PriceTypeId)), new { @class = "PriceType",@style="width:120px;display:none",@selectedvalue="selected"})
</span>),
The method show()
must be called from the User-Interface (UI) thread, while doInBackground()
runs on different thread which is the main reason why AsyncTask
was designed.
You have to call show()
either in onProgressUpdate()
or in onPostExecute()
.
For example:
class ExampleTask extends AsyncTask<String, String, String> {
// Your onPreExecute method.
@Override
protected String doInBackground(String... params) {
// Your code.
if (condition_is_true) {
this.publishProgress("Show the dialog");
}
return "Result";
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
connectionProgressDialog.dismiss();
downloadSpinnerProgressDialog.show();
}
}
I don't know is this what you're looking for
List keys = new ArrayList(map.keySet());
int index = keys.indexOf(element);
This is an old question, but is still regularly viewed/needed. I want to post to caution readers like me that whitespace as mentioned in the OP's question is not the same as Regex's definition, to include newlines, tabs, and space characters -- Git asks you to be explicit. See some options here: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration
As stated, git diff -b
or git diff --ignore-space-change
will ignore spaces at line ends. If you desire that setting to be your default behavior, the following line adds that intent to your .gitconfig file, so it will always ignore the space at line ends:
git config --global core.whitespace trailing-space
In my case, I found this question because I was interested in ignoring "carriage return whitespace differences", so I needed this:
git diff --ignore-cr-at-eol
or
git config --global core.whitespace cr-at-eol
from here.
You can also make it the default only for that repo by omitting the --global parameter, and checking in the settings file for that repo. For the CR problem I faced, it goes away after check-in if warncrlf or autocrlf = true in the [core] section of the .gitconfig file.
The Node object is the primary data type for the entire DOM.
A node can be an element node, an attribute node, a text node, or any other of the node types explained in the "Node types" chapter.
An XML element is everything from (including) the element's start tag to (including) the element's end tag.
If you want to make a new copy of an object or array, you must explicitly copy the properties of the object or the elements of the array, for example:
var arr1 = ['a','b','c'];
var arr2 = [];
for (var i=0; i < arr1.length; i++) {
arr2[i] = arr1[i];
}
You can search for more information on Google about immutable primitive values and mutable object references.
Older versions of Python would only allow a single simple statement after for ...:
if ...:
or similar block introductory statements.
I see that one can have multiple simple statements on the same line as any of these. However, there are various combinations that don't work. For example we can:
for i in range(3): print "Here's i:"; print i
... but, on the other hand, we can't:
for i in range(3): if i % 2: print "That's odd!"
We can:
x=10
while x > 0: print x; x-=1
... but we can't:
x=10; while x > 0: print x; x-=1
... and so on.
In any event all of these are considered to be extremely NON-pythonic. If you write code like this then experience Pythonistas will probably take a dim view of your skills.
It's marginally acceptable to combine multiple statements on a line in some cases. For example:
x=0; y=1
... or even:
if some_condition(): break
... for simple break
continue
and even return
statements or assigments.
In particular if one needs to use a series of elif
one might use something like:
if keystroke == 'q': break
elif keystroke == 'c': action='continue'
elif keystroke == 'd': action='delete'
# ...
else: action='ask again'
... then you might not irk your colleagues too much. (However, chains of elif
like that scream to be refactored into a dispatch table ... a dictionary that might look more like:
dispatch = {
'q': foo.break,
'c': foo.continue,
'd': foo.delete
}
# ...
while True:
key = SomeGetKey()
dispatch.get(key, foo.try_again)()
Bit late for reply but this should do the trick
Type myType = Type.GetType("AssemblyQualifiedName");
your assembly qualified name should be like this
"Boom.Bam.Class, Boom.Bam, Version=1.0.0.262, Culture=neutral, PublicKeyToken=e16dba1a3c4385bd"
Some awk
version.
awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'
When pattern found, set c=5
If c
is true, print and decrease number of c
I made a annotation library that can do the cast for you. check this out. https://github.com/zeroarst/callbackfragment/
@CallbackFragment
public class MyFragment extends Fragment {
@Callback
interface FragmentCallback {
void onClickButton(MyFragment fragment);
}
private FragmentCallback mCallback;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt1
mCallback.onClickButton(this);
break;
case R.id.bt2
// Because we give mandatory = false so this might be null if not implemented by the host.
if (mCallbackNotForce != null)
mCallbackNotForce.onClickButton(this);
break;
}
}
}
It then generates a subclass of your fragment. And just add it to FragmentManager.
public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), "MY_FRAGM")
.commit();
}
Toast mToast;
@Override
public void onClickButton(MyFragment fragment) {
if (mToast != null)
mToast.cancel();
mToast = Toast.makeText(this, "Callback from " + fragment.getTag(), Toast.LENGTH_SHORT);
mToast.show();
}
}
Posed question
Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.
Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.
Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:
Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.
Application-specific question
However, returning to your task, I'd research 2 topics:
Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:
Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."
(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.
Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.
(link)
Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).
(link) - they explore both accuracy and MSE, considering the latter to be better
Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.
(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.
Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.
About approaches, not metrics
Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.
I prefer to use:
string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
What does ToFileTime() do?
Converts the value of the current DateTime object to a Windows file time.
public long ToFileTime()
A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file.
Something like this happened when I changed the build target to 3.2. After digging around I found that a had named the jar lib folder "lib" instead of "libs". I just renamed it to libs and updated the references on the Java build path and everything was working again. Maybe this will help someone...
A compiler independent way, but not processor independent way to get these:
int inf = 0x7F800000;
return *(float*)&inf;
int nan = 0x7F800001;
return *(float*)&nan;
This should work on any processor which uses the IEEE 754 floating point format (which x86 does).
UPDATE: Tested and updated.
In MySQL, these symbols are used to delimit a query `
,"
,'
and ()
.
"
or '
are used for enclosing string-like values "26-01-2014 00:00:00"
or '26-01-2014 00:00:00'
. These symbols are only for strings, not aggregate functions like now
, sum
, or max
.
`
is used for enclosing table or column names, e.g. select `column_name` from `table_name` where id='2'
(
and )
simply enclose parts of a query e.g. select `column_name` from `table_name` where (id='2' and gender='male') or name='rakesh'
.
You could just try using return false (return false overrides default behaviour on every DOM element) like that :
myform.onsubmit = function ()
{
// do what you want
return false
}
and then submit your form using myform.submit()
or alternatively :
mybutton.onclick = function ()
{
// do what you want
return false
}
Also, if you use type="button"
your form will not be submitted.
I use Shift + F12 to show the Console again (or Window > Restore Default Layout).
To enable that, I have previously saved the layout WITH the console open as default (Window > Store Current Layout as Default).
Read from the controlling terminal device:
read input </dev/tty
more info: http://compgroups.net/comp.unix.shell/Fixing-stdin-inside-a-redirected-loop
The object must contain a field which will be used as the Primary Key
, if you have a field named Id
then this will by default be the primary key of the object to which Entity Framework will link to.
Otherwise, you should add the [Key]
attribute above that field you wanna use as the Primary Key
, and you'll also need to add the namespace System.ComponentModel.DataAnnotations
:
public class myClass
{
public int Id { get; set; }
[Key]
public string Name { get; set; }
}
The y-combinator implements anonymous recursion. So instead of
function fib( n ){ if( n<=1 ) return n; else return fib(n-1)+fib(n-2) }
you can do
function ( fib, n ){ if( n<=1 ) return n; else return fib(n-1)+fib(n-2) }
of course, the y-combinator only works in call-by-name languages. If you want to use this in any normal call-by-value language, then you will need the related z-combinator (y-combinator will diverge/infinite-loop).
This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array()
then pass the variable into your function, VBA will be happy.
Sub test()
Dim fString As String
Dim arr() As Variant
arr = Array("foo", "bar")
fString = processArr(arr)
End Sub
Also your function processArr()
could be written as:
Function processArr(arr() As Variant) As String
processArr = Replace(Join(arr()), " ", "")
End Function
If you are into the whole brevity thing.
This error message is displayed if the path you pass to Bitmap.Save()
is invalid (folder doesn't exist etc).
sqlitejdbc code can be downloaded using git from https://github.com/crawshaw/sqlitejdbc.
# git clone https://github.com/crawshaw/sqlitejdbc.git sqlitejdbc
...
# cd sqlitejdbc
# make
Note: Makefile requires curl binary to download sqlite libraries/deps.
In Java, this return value fails with jQuery Ajax GET:
return Response.status(200).entity(pojoObj).build();
But this works:
ResponseBuilder rb = Response.status(200).entity(pojoObj);
return rb.header("Access-Control-Allow-Origin", "*").build();
----
Full class:
@Path("/password")
public class PasswordStorage {
@GET
@Produces({ MediaType.APPLICATION_JSON })
public Response getRole() {
Contact pojoObj= new Contact();
pojoObj.setRole("manager");
ResponseBuilder rb = Response.status(200).entity(pojoObj);
return rb.header("Access-Control-Allow-Origin", "*").build();
//Fails jQuery: return Response.status(200).entity(pojoObj).build();
}
}
Here is the most straight forward and simple method I found to install go on Ubuntu 14.04 without any ppa or any other tool.
As of now, The version of GO is 1.7
Get the Go 1.7.tar.gz using wget
wget https://storage.googleapis.com/golang/go1.7.linux-amd64.tar.gz
Extract it and copy it to /usr/local/
sudo tar -C /usr/local -xzvf go1.7.linux-amd64.tar.gz
You have now successfully installed GO. Now You have to set Environment Variables so you can use the go
command from anywhere.
To achieve this we need to add a line to .bashrc
So,
sudo nano ~/.bashrc
and add the following line to the end of file.
export PATH="/usr/local/go/bin:$PATH"
Now, All the commands in go/bin
will work.
Check if the install was successful by doing
go version
For offline Documentation you can do
godoc -http=:6060
Offline documentation will be available at http://localhost:6060
NOTE:
Some people here are suggesting to change the PATH variable.
It is not a good choice.
Changing that to /usr/local/go/bin
is temporary and it'll reset once you close terminal.
go
command will only work in terminal in which you changed the value of PATH.
You'll not be able to use any other command like ls, nano
or just about everything because everything else is in /usr/bin
or in other locations. All those things will stop working and it'll start giving you error.
However, this is permanent and does not disturbs anything else.
To do POST you'll need to have a form.
<form action="employee.action" method="post">
<input type="submit" value="Employee1" />
</form>
There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.
Some tricks: Make a link use POST instead of GET and How do you post data with a link
Edit: to load response on a frame you can target your form to your frame:
<form action="employee.action" method="post" target="myFrame">
Use the affix
component included with Bootstrap. Start with a 'navbar-static-top' and this will change it to fixed
when the height of your header (content above the navbar) is reached...
$('#nav').affix({
offset: {
top: $('header').height()
}
});
You have probably installed Eclipse for Java Developers instead of Eclipse IDE for Enterprise Java Developers, server tab and some other are not available.
You don't have to uninstall. Just rerun eclipse-inst-win64.exe and choose Java EE IDE
The issue with reading single Excel Cell in .Net
comes from the fact, that the empty cell is evaluated to a Null
. Thus, one cannot use its .Value
or .Value2
properties, because an error shows up.
To return an empty string, when the cell is Null
the Convert.ToString(Cell)
can be used in the following way:
Excel.Workbook wkb = Open(excel, filePath);
Excel.Worksheet wk = (Excel.Worksheet)excel.Worksheets.get_Item(1);
for (int i = 1; i < 5; i++)
{
string a = Convert.ToString(wk.Cells[i, 1].Value2);
Console.WriteLine(a);
}
In your particular case the issue seem to be with accessing the site from non-canonical url (www.site.com vs. site.com).
Instead of fixing CORS issue (which may require writing proxy to server fonts with proper CORS headers depending on service provider) you can normalize your Urls to always server content on canonical Url and simply redirect if one requests page without "www.".
Alternatively you can upload fonts to different server/CDN that is known to have CORS headers configured or you can easily do so.
Compared the 3 methods
D2_list=[list(range(100))]*100
t1=time.time()
for i in range(10**5):
for j in range(10):
b=[k[j] for k in D2_list]
D2_list_time=time.time()-t1
array=np.array(D2_list)
t1=time.time()
for i in range(10**5):
for j in range(10):
b=array[:,j]
Numpy_time=time.time()-t1
D2_trans = list(zip(*D2_list))
t1=time.time()
for i in range(10**5):
for j in range(10):
b=D2_trans[j]
Zip_time=time.time()-t1
print ('2D List:',D2_list_time)
print ('Numpy:',Numpy_time)
print ('Zip:',Zip_time)
The Zip method works best. It was quite useful when I had to do some column wise processes for mapreduce jobs in the cluster servers where numpy was not installed.
I assume you want lowercase the text. Solution is pretty simple:
ggVGu
Explanation:
There is a little known feature, which makes this even better. You can use a configurable default value instead of a hard-coded one, here is an example:
config.properties:
timeout.default=30
timeout.myBean=60
context.xml:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>config.properties</value>
</property>
</bean>
<bean id="myBean" class="Test">
<property name="timeout" value="${timeout.myBean:${timeout.default}}" />
</bean>
To use the default while still being able to easily override later, do this in config.properties:
timeout.myBean = ${timeout.default}
If you are trying to build this function within an R package or simply want to reduce complexity, you can do the following:
test_func <- function(df, column) {
if (column %in% colnames(df)) {
return(max(df[, column, with=FALSE]))
} else {
stop(cat(column, "not in data.frame columns."))
}
}
The argument with=FALSE
"disables the ability to refer to columns as if they are variables, thereby restoring the “data.frame mode” (per CRAN documentation). The if statement is a quick way to catch if the column name provided is within the data.frame. Could also use tryCatch error handling here.
You might want to consider using EventBus for decoupled events .. You can listen for events very easily. You can also make sure the event is being received on the ui thread (instead of calling runOnUiThread.. for yourself for every event subscription)
https://github.com/greenrobot/EventBus
from Github:
Android optimized event bus that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality
The simplest way is use return View.
return View("ViewName");
Remember, the physical name of the "ViewName" should be something like ViewName.cshtml in your project, if your are using MVC C# / .NET.
just a FYI
string clean = Regex.Replace(q, @"[^a-zA-Z0-9\s]", string.Empty);
would actually be better like
string clean = Regex.Replace(q, @"[^\w\s]", string.Empty);
I couldn't get PSL's answer working for me so I found all I have to do is set the div holding the modal content with style="display: table;"
. The modal content itself says how big it wants to be and the modal accommodates it.
Most folks have answered how a downloaded image's dimensions can be known so I'll just try to answer other part of the question - knowing downloaded image's file-size.
You can do this using resource timing api. Very specifically transferSize, encodedBodySize and decodedBodySize properties can be used for the purpose.
Check out my answer here for code snippet and more information if you seek : JavaScript - Get size in bytes from HTML img src
Allow me to put it precisely. Most of the answers have already explained, provided diagrams and examples as well.
So my answer would just be a one-liner. My own words: “An abstract factory pattern adds on the abstract layer over multiple factory method implementations. It means an abstract factory contains or composite one or more than one factory method pattern”
For anyone who wants a quick-fix, this simply replaces all single quotes with double quotes:
import json
predictions = []
def get_top_k_predictions(predictions_path):
'''load the predictions'''
with open (predictions_path) as json_lines_file:
for line in json_lines_file:
predictions.append(json.loads(line.replace("'", "\"")))
get_top_k_predictions("/sh/sh-experiments/outputs/john/baseline_1000/test_predictions.jsonl")
I have the same issue with primeNg DataTable. After trying and crying, I've fixed the issue by using this code.
private deepArrayCopy(arr: SelectItem[]): SelectItem[] {
const result: SelectItem[] = [];
if (!arr) {
return result;
}
const arrayLength = arr.length;
for (let i = 0; i <= arrayLength; i++) {
const item = arr[i];
if (item) {
result.push({ label: item.label, value: item.value });
}
}
return result;
}
For initializing backup value
backupData = this.deepArrayCopy(genericItems);
For resetting changes
genericItems = this.deepArrayCopy(backupData);
The magic bullet is to recreate items by using {}
instead of calling constructor.
I've tried new SelectItem(item.label, item.value)
which doesn't work.
I got it working by selecting the original layout I had in the W / H selection. Storyboard is working as expected and the error is gone.
Be also sure that you are developing for iOS 8.0. Check that from the project's general settings.
You just have to ask for the legend once, outside of your loop.
For example, in this case I have 4 subplots, with the same lines, and a single legend.
from matplotlib.pyplot import *
ficheiros = ['120318.nc', '120319.nc', '120320.nc', '120321.nc']
fig = figure()
fig.suptitle('concentration profile analysis')
for a in range(len(ficheiros)):
# dados is here defined
level = dados.variables['level'][:]
ax = fig.add_subplot(2,2,a+1)
xticks(range(8), ['0h','3h','6h','9h','12h','15h','18h','21h'])
ax.set_xlabel('time (hours)')
ax.set_ylabel('CONC ($\mu g. m^{-3}$)')
for index in range(len(level)):
conc = dados.variables['CONC'][4:12,index] * 1e9
ax.plot(conc,label=str(level[index])+'m')
dados.close()
ax.legend(bbox_to_anchor=(1.05, 0), loc='lower left', borderaxespad=0.)
# it will place the legend on the outer right-hand side of the last axes
show()
just adding my 2 cents .
if specifically looking to find total free space only in Data files or only in Log files in all the databases, we can use "data_space_id" column. 1 is for data files and 0 for log files.
CODE:
Create Table ##temp
(
DatabaseName sysname,
Name sysname,
spacetype sysname,
physical_name nvarchar(500),
size decimal (18,2),
FreeSpace decimal (18,2)
)
Exec sp_msforeachdb '
Use [?];
Insert Into ##temp (DatabaseName, Name,spacetype, physical_name, Size, FreeSpace)
Select DB_NAME() AS [DatabaseName], Name, ***data_space_id*** , physical_name,
Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2))/1024 as nvarchar) SizeGB,
Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2)/1024 as decimal(18,2)) -
Cast(FILEPROPERTY(name, ''SpaceUsed'') * 8.0/1024.0 as decimal(18,2))/1024 as nvarchar) As FreeSpaceGB
From sys.database_files'
select
databasename
, sum(##temp.FreeSpace)
from
##temp
where
##temp.spacetype = 1
group by
DatabaseName
drop table ##temp
Add to your JS:
jQuery(document).ready(function($) {
$("body").css({
'padding-top': $(".navbar").outerHeight() + 'px'
})
});
These are called "match variables". As previously mentioned they contain the text from your last regular expression match.
More information is in Essential Perl. (Ctrl + F for 'Match Variables' to find the corresponding section.)
It should be (-###
is similar to -v
):
echo | gcc -### -E - -march=native
To show the "real" native flags for gcc.
You can make them appear more "clearly" with a command:
gcc -### -E - -march=native 2>&1 | sed -r '/cc1/!d;s/(")|(^.* - )//g'
and you can get rid of flags with -mno-* with:
gcc -### -E - -march=native 2>&1 | sed -r '/cc1/!d;s/(")|(^.* - )|( -mno-[^\ ]+)//g'
Try this one:
<button class="button" onclick="$('#target').toggle();">
Show/Hide
</button>
<div id="target" style="display: none">
Hide show.....
</div>
function user() {
parent::Model();
}
=> class name is User, construct name is User.
function User() {
parent::Model();
}
The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.
Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.
This will get ALL parameters from the request. For Debugging purposes only:
@RequestMapping (value = "/promote", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView renderPromotePage (HttpServletRequest request) {
Map<String, String[]> parameters = request.getParameterMap();
for(String key : parameters.keySet()) {
System.out.println(key);
String[] vals = parameters.get(key);
for(String val : vals)
System.out.println(" -> " + val);
}
ModelAndView mv = new ModelAndView();
mv.setViewName("test");
return mv;
}
I think it's a matter of preference. I personally use:
if($something){
$execute_something;
}
In case anyone had the same problem: check this as @PravinS suggested. I used the exact same code as shown there and it worked for me perfectly.
This is the relevant part of the server code that helped:
if (isset($_POST['btnUpload']))
{
$url = "URL_PATH of upload.php"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
$headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
$postfields = array("filedata" => "@$filedata", "filename" => $filename);
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true
); // cURL options
curl_setopt_array($ch, $options);
curl_exec($ch);
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
if ($info['http_code'] == 200)
$errmsg = "File uploaded successfully";
}
else
{
$errmsg = curl_error($ch);
}
curl_close($ch);
}
else
{
$errmsg = "Please select the file";
}
}
html form should look something like:
<form action="uploadpost.php" method="post" name="frmUpload" enctype="multipart/form-data">
<tr>
<td>Upload</td>
<td align="center">:</td>
<td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
<td> </td>
<td align="center"> </td>
<td><input name="btnUpload" type="submit" value="Upload" /></td>
</tr>
For managing DataBase Objects in SQL Server i would suggest using Server Management Objects
When code is parsed by the JavaScript interpreter, it gets broken into pieces called "tokens". When a token cannot be classified into one of the four basic token types, it gets labelled "ILLEGAL" on most implementations, and this error is thrown.
The same error is raised if, for example, you try to run a js file with a rogue @
character, a misplaced curly brace, bracket, "smart quotes", single quotes not enclosed properly (e.g. this.run('dev1)
) and so on.
A lot of different situations can cause this error. But if you don't have any obvious syntax error or illegal character, it may be caused by an invisible illegal character. That's what this answer is about.
There is an invisible character in the code, right after the semicolon. It's the Unicode U+200B
Zero-width space character (a.k.a. ZWSP
, HTML entity ​
). That character is known to cause the Unexpected token ILLEGAL
JavaScript syntax error.
I can't tell for sure, but my bet is on jsfiddle. If you paste code from there, it's very likely to include one or more U+200B
characters. It seems the tool uses that character to control word-wrapping on long strings.
UPDATE 2013-01-07
After the latest jsfiddle update, it's now showing the character as a red dot like codepen does. Apparently, it's also not inserting
U+200B
characters on its own anymore, so this problem should be less frequent from now on.UPDATE 2015-03-17
Vagrant appears to sometimes cause this issue as well, due to a bug in VirtualBox. The solution, as per this blog post is to set
sendfile off;
in your nginx config, orEnableSendfile Off
if you use Apache.
It's also been reported that code pasted from the Chrome developer tools may include that character, but I was unable to reproduce that with the current version (22.0.1229.79 on OSX).
The character is invisible, do how do we know it's there? You can ask your editor to show invisible characters. Most text editors have this feature. Vim, for example, displays them by default, and the ZWSP
shows as <u200b>
. You can also debug it online: jsbin displays the character as a red dot on its code panes (but seems to remove it after saving and reloading the page). CodePen.io also displays it as a dot, and keeps it even after saving.
That character is not something bad, it can actually be quite useful. This example on Wikipedia demonstrates how it can be used to control where a long string should be wrapped to the next line. However, if you are unaware of the character's presence on your markup, it may become a problem. If you have it inside of a string (e.g., the nodeValue
of a DOM element that has no visible content), you might expect such string to be empty, when in fact it's not (even after applying String.trim
).
ZWSP
can also cause extra whitespace to be displayed on an HTML page, for example when it's found between two <div>
elements (as seen on this question). This case is not even reproducible on jsfiddle, since the character is ignored there.
Another potential problem: if the web page's encoding is not recognized as UTF-8, the character may actually be displayed (as ​
in latin1, for example).
If ZWSP
is present on CSS code (inline code, or an external stylesheet), styles can also not be parsed properly, so some styles don't get applied (as seen on this question).
I couldn't find any mention to that specific character on the ECMAScript Specification (versions 3 and 5.1). The current version mentions similar characters (U+200C
and U+200D
) on Section 7.1, which says they should be treated as IdentifierPart
s when "outside of comments, string literals, and regular expression literals". Those characters may, for example, be part of a variable name (and var x\u200c;
indeed works).
Section 7.2 lists the valid White space characters (such as tab, space, no-break space, etc.), and vaguely mentions that any other Unicode “space separator” (category “Zs”) should be treated as white space. I'm probably not the best person to discuss the specs in this regard, but it seems to me that U+200B
should be considered white space according to that, when in fact the implementations (at least Chrome and Firefox) appear to treat them as an unexpected token (or part of one), causing the syntax error.
#define _kisiOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
if (_kisiOS7) {
NSLog(@"iOS7 or greater")
}
else {
NSLog(@"Less than iOS7");
}
I really like this pattern in async/await capable Express/Mongoose apps:
app.delete('/:idToDelete', asyncHandler(async (req, res) => {
const deletedItem = await YourModel
.findByIdAndDelete(req.params.idToDelete) // This method is the nice method for deleting
.catch(err => res.status(400).send(err.message))
res.status(200).send(deletedItem)
}))
The answer to this question simply put is: Don't use BOOLEAN with Oracle-- PL/SQL is dumb and it doesn't work. Use another data type to run your process.
A note to SSRS report developers with Oracle datasource: You can use BOOLEAN parameters, but be careful how you implement. Oracle PL/SQL does not play nicely with BOOLEAN, but you can use the BOOLEAN value in the Tablix Filter if the data resides in your dataset. This really tripped me up, because I have used BOOLEAN parameter with Oracle data source. But in that instance I was filtering against Tablix data, not SQL query.
If the data is NOT in your SSRS Dataset Fields, you can rewrite the SQL something like this using an INTEGER parameter:
__
<ReportParameter Name="paramPickupOrders">
<DataType>Integer</DataType>
<DefaultValue>
<Values>
<Value>0</Value>
</Values>
</DefaultValue>
<Prompt>Pickup orders?</Prompt>
<ValidValues>
<ParameterValues>
<ParameterValue>
<Value>0</Value>
<Label>NO</Label>
</ParameterValue>
<ParameterValue>
<Value>1</Value>
<Label>YES</Label>
</ParameterValue>
</ParameterValues>
</ValidValues>
</ReportParameter>
...
<Query>
<DataSourceName>Gmenu</DataSourceName>
<QueryParameters>
<QueryParameter Name=":paramPickupOrders">
<Value>=Parameters!paramPickupOrders.Value</Value>
</QueryParameter>
<CommandText>
where
(:paramPickupOrders = 0 AND ordh.PICKUP_FLAG = 'N'
OR :paramPickupOrders = 1 AND ordh.PICKUP_FLAG = 'Y' )
If the data is in your SSRS Dataset Fields, you can use a tablix filter with a BOOLEAN parameter:
__
</ReportParameter>
<ReportParameter Name="paramFilterOrdersWithNoLoad">
<DataType>Boolean</DataType>
<DefaultValue>
<Values>
<Value>false</Value>
</Values>
</DefaultValue>
<Prompt>Only orders with no load?</Prompt>
</ReportParameter>
...
<Tablix Name="tablix_dsMyData">
<Filters>
<Filter>
<FilterExpression>
=(Parameters!paramFilterOrdersWithNoLoad.Value=false)
or (Parameters!paramFilterOrdersWithNoLoad.Value=true and Fields!LOADNUMBER.Value=0)
</FilterExpression>
<Operator>Equal</Operator>
<FilterValues>
<FilterValue DataType="Boolean">=true</FilterValue>
</FilterValues>
</Filter>
</Filters>
I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.
Hello I have only a MINOR classname edit, and so far this is how iv divulged it. i think i need to pass in multpile parameters to the helper,
server.js
app.engine('handlebars', ViewEngine({
"helpers":{
isActive: (val, options)=>{
if (val === 3 || val === 0){
return options.fn(this)
}
}
}
}));
header.handlebars
<ul class="navlist">
<li class="navitem navlink {{#isActive 0}}active{{/isActive}}"
><a href="#">Home</a></li>
<li class="navitem navlink {{#isActive 1}}active{{/isActive}}"
><a href="#">Trending</a></li>
<li class="navitem navlink {{#isActive 2}}active{{/isActive}}"
><a href="#">People</a></li>
<li class="navitem navlink {{#isActive 3}}active{{/isActive}}"
><a href="#">Mystery</a></li>
<li class="navitem navbar-search">
<input type="text" id="navbar-search-input" placeholder="Search...">
<button type="button" id="navbar-search-button"><i class="fas fa-search"></i></button>
</li>
</ul>
Swift 3 and 4 as global var:
var documentsDirectory: URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
}
As FileManager extension:
extension FileManager {
static var documentsDirectory: URL {
return `default`.urls(for: .documentDirectory, in: .userDomainMask).last!
}
var documentsDirectory: URL {
return urls(for: .documentDirectory, in: .userDomainMask).last!
}
}
Another Alternative for the command line that is easier than fighting with quotation marks is to put the json into a file, and use the @ prefix of curl parameters, e.g. with the following in json.txt:
{ "syncheader" : {
"servertimesync" : "20131126121749",
"deviceid" : "testDevice"
}
}
then in my case I issue:
curl localhost:9000/sync -H "Content-type:application/json" -X POST -d @json.txt
Keeps the json more readable too.
Edit: CMake now has builtin support for this. See new answer.
You can also force the build of the dependent target in a secondary make process
See my answer on a related topic.
Perhaps useful online checker PEP8 : http://pep8online.com/
I am fairly new to Docker. I was cleaning up some initial testing mess and was not able to remove a volume either. I had stopped all the running instances, performed a docker rmi -f $(docker image ls -q)
, but still received the Error response from daemon: unable to remove volume: remove uuid: volume is in use
.
I did a docker system prune
and it cleaned up what was needed to remove the last volume:
[0]$ docker system prune
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all dangling images
- all build cache
Are you sure you want to continue? [y/N] y
Deleted Containers:
... about 15 containers UUID's truncated
Total reclaimed space: 2.273MB
[0]$ docker volume ls
DRIVER VOLUME NAME
local uuid
[0]$ docker volume rm uuid
uuid
[0]$
The client and daemon API must both be at least 1.25 to use this command. Use the
docker version
command on the client to check your client and daemon API versions.
Materialised view - a table on a disk that contains the result set of a query
Non-materiased view - a query that pulls data from the underlying table
You can create TIMESTAMP field in table on the SQLite, see this:
CREATE TABLE my_table (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR(64),
sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);
INSERT INTO my_table(name, sqltime) VALUES('test1', '2010-05-28T15:36:56.200');
INSERT INTO my_table(name, sqltime) VALUES('test2', '2010-08-28T13:40:02.200');
INSERT INTO my_table(name) VALUES('test3');
This is the result:
SELECT * FROM my_table;
Here's what I would use:
(?<!\S)stackoverflow(?!\S)
In other words, match "stackoverflow" if it's not preceded by a non-whitespace character and not followed by a non-whitespace character.
This is neater (IMO) than the "space-or-anchor" approach, and it doesn't assume the string starts and ends with word characters like the \b
approach does.
You can format the datetime to the Y-M-D portion:
DATE_FORMAT(datetime, '%Y-%m-%d')
If you wish to allow accent (see RFC 5322) and allow new domain extension like .quebec. use this expression:
/\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/
$(document).ready(function() {_x000D_
var input = $('.input_field');_x000D_
var result = $('.test_result');_x000D_
var regExpression = /\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/;_x000D_
_x000D_
$('.btnTest').click(function(){_x000D_
var isValid = regExpression.test(input.val());_x000D_
if (isValid)_x000D_
result.html('<span style="color:green;">This email is valid</span>');_x000D_
else_x000D_
result.html('<span style="color:red;">This email is not valid</span>');_x000D_
_x000D_
});_x000D_
_x000D_
});
_x000D_
body {_x000D_
padding: 40px;_x000D_
}_x000D_
_x000D_
label {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type=text] {_x000D_
width: 20em_x000D_
}_x000D_
.test_result {_x000D_
font-size:4em;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label for="search_field">Input</label>_x000D_
<input type='text' class='input_field' />_x000D_
<button type="button" class="btnTest">_x000D_
Test_x000D_
</button>_x000D_
<br/>_x000D_
<div class="test_result">_x000D_
Not Tested_x000D_
</div>
_x000D_
In place of 1.+ use the latest version of crashlytics -
dependencies {
classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
}
you should use this way -
dependencies {
classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:2.6.8'
}
your problem will be resolved for sure. Happy coding !!
Same article on my blog(I like formatting more)
I wrote small article which describe how to make access to your android database thread safe.
Assuming you have your own SQLiteOpenHelper.
public class DatabaseHelper extends SQLiteOpenHelper { ... }
Now you want to write data to database in separate threads.
// Thread 1
Context context = getApplicationContext();
DatabaseHelper helper = new DatabaseHelper(context);
SQLiteDatabase database = helper.getWritableDatabase();
database.insert(…);
database.close();
// Thread 2
Context context = getApplicationContext();
DatabaseHelper helper = new DatabaseHelper(context);
SQLiteDatabase database = helper.getWritableDatabase();
database.insert(…);
database.close();
You will get following message in your logcat and one of your changes will not be written.
android.database.sqlite.SQLiteDatabaseLockedException: database is locked (code 5)
This is happening because every time you create new SQLiteOpenHelper object you are actually making new database connection. If you try to write to the database from actual distinct connections at the same time, one will fail. (from answer above)
To use database with multiple threads we need to make sure we are using one database connection.
Let’s make singleton class Database Manager which will hold and return single SQLiteOpenHelper object.
public class DatabaseManager {
private static DatabaseManager instance;
private static SQLiteOpenHelper mDatabaseHelper;
public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
if (instance == null) {
instance = new DatabaseManager();
mDatabaseHelper = helper;
}
}
public static synchronized DatabaseManager getInstance() {
if (instance == null) {
throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
" is not initialized, call initialize(..) method first.");
}
return instance;
}
public SQLiteDatabase getDatabase() {
return new mDatabaseHelper.getWritableDatabase();
}
}
Updated code which write data to database in separate threads will look like this.
// In your application class
DatabaseManager.initializeInstance(new MySQLiteOpenHelper());
// Thread 1
DatabaseManager manager = DatabaseManager.getInstance();
SQLiteDatabase database = manager.getDatabase()
database.insert(…);
database.close();
// Thread 2
DatabaseManager manager = DatabaseManager.getInstance();
SQLiteDatabase database = manager.getDatabase()
database.insert(…);
database.close();
This will bring you another crash.
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase
Since we are using only one database connection, method getDatabase() return same instance of SQLiteDatabase object for Thread1 and Thread2. What is happening, Thread1 may close database, while Thread2 is still using it. That’s why we have IllegalStateException crash.
We need to make sure no-one is using database and only then close it. Some folks on stackoveflow recommended to never close your SQLiteDatabase. This will result in following logcat message.
Leak found
Caused by: java.lang.IllegalStateException: SQLiteDatabase created and never closed
public class DatabaseManager {
private int mOpenCounter;
private static DatabaseManager instance;
private static SQLiteOpenHelper mDatabaseHelper;
private SQLiteDatabase mDatabase;
public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
if (instance == null) {
instance = new DatabaseManager();
mDatabaseHelper = helper;
}
}
public static synchronized DatabaseManager getInstance() {
if (instance == null) {
throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
" is not initialized, call initializeInstance(..) method first.");
}
return instance;
}
public synchronized SQLiteDatabase openDatabase() {
mOpenCounter++;
if(mOpenCounter == 1) {
// Opening new database
mDatabase = mDatabaseHelper.getWritableDatabase();
}
return mDatabase;
}
public synchronized void closeDatabase() {
mOpenCounter--;
if(mOpenCounter == 0) {
// Closing database
mDatabase.close();
}
}
}
Use it as follows.
SQLiteDatabase database = DatabaseManager.getInstance().openDatabase();
database.insert(...);
// database.close(); Don't close it directly!
DatabaseManager.getInstance().closeDatabase(); // correct way
Every time you need database you should call openDatabase() method of DatabaseManager class. Inside this method, we have a counter, which indicate how many times database is opened. If it equals to one, it means we need to create new database connection, if not, database connection is already created.
The same happens in closeDatabase() method. Every time we call this method, counter is decreased, whenever it goes to zero, we are closing database connection.
Now you should be able to use your database and be sure it's thread safe.
I think you would be look at String class, there are multiple ways to do it. What about substring(int,int)
and indexOf(int)
lastIndexOf(int)
?
Maybe the following is what you are looking for:
SELECT name, pathfilename
FROM table1
NATURAL JOIN table2
NATURAL JOIN table3
WHERE name = 'John';
I give you two answers. npm combined with other tools is powerful but requires some work to setup. If you just want to download some libraries, you might want to use Library Manager instead (released in Visual Studio 15.8).
First add package.json in the root of you project. Add the following content:
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"gulp": "3.9.1",
"del": "3.0.0"
},
"dependencies": {
"jquery": "3.3.1",
"jquery-validation": "1.17.0",
"jquery-validation-unobtrusive": "3.2.10",
"bootstrap": "3.3.7"
}
}
This will make NPM download Bootstrap, JQuery and other libraries that is used in a new asp.net core project to a folder named node_modules. Next step is to copy the files to an appropriate place. To do this we will use gulp, which also was downloaded by NPM. Then add a new file in the root of you project named gulpfile.js. Add the following content:
/// <binding AfterBuild='default' Clean='clean' />
/*
This file is the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/
var gulp = require('gulp');
var del = require('del');
var nodeRoot = './node_modules/';
var targetPath = './wwwroot/lib/';
gulp.task('clean', function () {
return del([targetPath + '/**/*']);
});
gulp.task('default', function () {
gulp.src(nodeRoot + "bootstrap/dist/js/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/js"));
gulp.src(nodeRoot + "bootstrap/dist/css/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/css"));
gulp.src(nodeRoot + "bootstrap/dist/fonts/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/fonts"));
gulp.src(nodeRoot + "jquery/dist/jquery.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
gulp.src(nodeRoot + "jquery/dist/jquery.min.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
gulp.src(nodeRoot + "jquery/dist/jquery.min.map").pipe(gulp.dest(targetPath + "/jquery/dist"));
gulp.src(nodeRoot + "jquery-validation/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation/dist"));
gulp.src(nodeRoot + "jquery-validation-unobtrusive/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation-unobtrusive"));
});
This file contains a JavaScript code that is executed when the project is build and cleaned. It’s will copy all necessary files to lib2 (not lib – you can easily change this). I have used the same structure as in a new project, but it’s easy to change files to a different location. If you move the files, make sure you also update _Layout.cshtml. Note that all files in the lib2-directory will be removed when the project is cleaned.
If you right click on gulpfile.js, you can select Task Runner Explorer. From here you can run gulp manually to copy or clean files.
Gulp could also be useful for other tasks like minify JavaScript and CSS-files:
https://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp?view=aspnetcore-2.1
Right click on you project and select Manage client side-libraries. The file libman.json is now open. In this file you specify which library and files to use and where they should be stored locally. Really simple! The following file copies the default libraries that is used when creating a new ASP.NET Core 2.1 project:
{
"version": "1.0",
"defaultProvider": "cdnjs",
"libraries": [
{
"library": "[email protected]",
"files": [ "jquery.js", "jquery.min.map", "jquery.min.js" ],
"destination": "wwwroot/lib/jquery/dist/"
},
{
"library": "[email protected]",
"files": [ "additional-methods.js", "additional-methods.min.js", "jquery.validate.js", "jquery.validate.min.js" ],
"destination": "wwwroot/lib/jquery-validation/dist/"
},
{
"library": "[email protected]",
"files": [ "jquery.validate.unobtrusive.js", "jquery.validate.unobtrusive.min.js" ],
"destination": "wwwroot/lib/jquery-validation-unobtrusive/"
},
{
"library": "[email protected]",
"files": [
"css/bootstrap.css",
"css/bootstrap.css.map",
"css/bootstrap.min.css",
"css/bootstrap.min.css.map",
"css/bootstrap-theme.css",
"css/bootstrap-theme.css.map",
"css/bootstrap-theme.min.css",
"css/bootstrap-theme.min.css.map",
"fonts/glyphicons-halflings-regular.eot",
"fonts/glyphicons-halflings-regular.svg",
"fonts/glyphicons-halflings-regular.ttf",
"fonts/glyphicons-halflings-regular.woff",
"fonts/glyphicons-halflings-regular.woff2",
"js/bootstrap.js",
"js/bootstrap.min.js",
"js/npm.js"
],
"destination": "wwwroot/lib/bootstrap/dist"
},
{
"library": "[email protected]",
"files": [ "list.js", "list.min.js" ],
"destination": "wwwroot/lib/listjs"
}
]
}
If you move the files, make sure you also update _Layout.cshtml.
$("select[name='CCards'] option:selected")
should do the trick
See jQuery documentation for more detail: http://api.jquery.com/selected-selector/
UPDATE:
if you need the index of the selected option, you need to use the .index()
jquery method:
$("select[name='CCards'] option:selected").index()
Just one more idea to detect:
DebugMode.h
#import <Foundation/Foundation.h>
@interface DebugMode: NSObject
+(BOOL) isDebug;
@end
DebugMode.m
#import "DebugMode.h"
@implementation DebugMode
+(BOOL) isDebug {
#ifdef DEBUG
return true;
#else
return false;
#endif
}
@end
add into header bridge file:
#include "DebugMode.h"
usage:
DebugMode.isDebug()
It is not needed to write something inside project properties swift flags.
I got tired of seeing this page with its by-now stale references to defunct Codehaus pages so I asked on the Maven Users mailing list and got some more up-to-date answers.
I would say that the best (and most authoritative) answer contained in my link above is the one contributed by Hervé BOUTEMY:
here is the core reference: http://maven.apache.org/ref/3-LATEST/maven-model-builder/
it does not explain everyting that can be found in POM or in settings, since there are so much info available but it points to POM and settings descriptors and explains everything that is not POM or settings
Apart from the information given by David M. Lloyd one could add that the mechanism that allows this is called target typing.
The idea is that the type the compiler assigns to a lambda expressions or a method references does not depend only on the expression itself, but also on where it is used.
The target of an expression is the variable to which its result is assigned or the parameter to which its result is passed.
Lambda expressions and method references are assigned a type which matches the type of their target, if such a type can be found.
See the Type Inference section in the Java Tutorial for more information.
This can be done by using:
Response.Redirect("http://localhost/YourControllerName/ActionMethodName?querystring1=querystringvalue1&querystring2=querystringvalue2&querystring3=querystringvalue3");
You could also set onclick to call your function like this:
foo.onclick = function() { callYourJSFunction(arg1, arg2); };
This way, you can pass arguments too. .....
Try removing the position
from header
and add overflow
to container
:
#container {
position:relative;
width:80%;
height:auto;
overflow:auto;
}
#header {
width:80%;
height:50px;
padding:10px;
}
The conversion in SQL server fails sometimes not because of the Date or Time formats used, It is Merely because you are trying to store wrong data that is not acceptable to the system.
Example:
Create Table MyTable (MyDate);
Insert Into MyTable(MyDate) Values ('2015-02-29');
The SQL server will throw the following error:
Conversion failed when converting date and/or time from character string.
The reason for this error is simply there is no such date (Feb-29) in Year (2015).
To get the fields info too, you can use the following:
SELECT TABLE_SCHEMA, TABLE_NAME,
COLUMN_NAME, substring(DATA_TYPE, 1,1) AS DATA_TYPE
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA NOT IN("information_schema", "mysql", "performance_schema")
ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION
Try this (update, not after update)
CREATE TRIGGER [dbo].[xxx_update] ON [dbo].[MYTABLE]
FOR UPDATE
AS
BEGIN
UPDATE MYTABLE
SET mytable.CHANGED_ON = GETDATE()
,CHANGED_BY = USER_NAME(USER_ID())
FROM inserted
WHERE MYTABLE.ID = inserted.ID
END
SOLVED
After banging my head on the wall for a couple days with this issue, it was looking like the problem had something to do with the content type negotiation between the client and server. I dug deeper into that using Fiddler to check the request details coming from the client app, here's a screenshot of the raw request as captured by fiddler:
What's obviously missing there is the Content-Type
header, even though I was setting it as seen in the code sample in my original post. I thought it was strange that the Content-Type
never came through even though I was setting it, so I had another look at my other (working) code calling a different Web API service, the only difference was that I happened to be setting the req.ContentType
property prior to writing to the request body in that case. I made that change to this new code and that did it, the Content-Type
was now showing up and I got the expected success response from the web service. The new code from my .NET client now looks like this:
req.Method = "POST"
req.ContentType = "application/json"
lstrPagingJSON = JsonSerializer(Of Paging)(lPaging)
bytData = Encoding.UTF8.GetBytes(lstrPagingJSON)
req.ContentLength = bytData.Length
reqStream = req.GetRequestStream()
reqStream.Write(bytData, 0, bytData.Length)
reqStream.Close()
'// Content-Type was being set here, causing the problem
'req.ContentType = "application/json"
That's all it was, the ContentType
property just needed to be set prior to writing to the request body
I believe this behavior is because once content is written to the body it is streamed to the service endpoint being called, any other attributes pertaining to the request need to be set prior to that. Please correct me if I'm wrong or if this needs more detail.
To enable bcmath
in Arch Linux
or Manjaro
Edit php.ini
nano /etc/php/php.ini
Uncomment bcmath
(remove semicolon)
extension=bcmath
If you are using Apache server reload the server by
sudo systemctl reload apache.server
Or
sudo systemctl realod httpd
If you don't use Apache
sudo systemctl reload php-fpm.service
To see the activated modules
php -m
To make sure the php-fpm
is installed and activated, search for it
php -m | grep bcmath
@variable
is very useful if calling stored procedures from an application written in Java , Python etc.
There are ocassions where variable values are created in the first call and needed in functions of subsequent calls.
The advantage can be seen in Oracle PL/SQL where these variables have 3 different scopes:
I have developed an architecture in which the complete code is written in PL/SQL. These are called from a middle-ware written in Java. There are two types of middle-ware. One to cater calls from a client which is also written in Java. The other other one to cater for calls from a browser. The client facility is implemented 100 percent in JavaScript. A command set is used instead of HTML and JavaScript for writing application in PL/SQL.
I have been looking for the same facility to port the codes written in PL/SQL to another database. The nearest one I have found is Postgres. But all the variables have function scope.
@
in MySQLI am happy to see that at least this @
facility is there in MySQL. I don't think Oracle will build same facility available in PL/SQL to MySQL stored procedures since it may affect the sales of Oracle database.
Returns only objects from the array whose property name
is not "Kristian"
var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });
var someArray = [_x000D_
{name:"Kristian", lines:"2,5,10"},_x000D_
{name:"John", lines:"1,19,26,96"},_x000D_
{name:"Kristian", lines:"2,58,160"},_x000D_
{name:"Felix", lines:"1,19,26,96"}_x000D_
];_x000D_
_x000D_
var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });_x000D_
_x000D_
console.log(noKristianArray);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Like that, both of the sentences will be executed even before the page has finished loading.
Here is your error, you are missing a ';' Change:
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
To:
echo 'alert("review your answer");';
echo 'window.location= "index.php";';
Then a suggestion: You really should trigger that logic after some event. So, for instance:
document.getElementById("myBtn").onclick=function(){
alert("review your answer");
window.location= "index.php";
};
Another suggestion, use jQuery
Why not just use key name on dictionary, C# has this:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("UserID", "test");
string userIDFromDictionaryByKey = dict["UserID"];
If you look at the tip suggestion:
In Java 11 the java.nio.file.Files
class was extended by two new utility methods to write a string into a file. The first method (see JavaDoc here) uses the charset UTF-8 as default:
Files.writeString(Path.of("my", "path"), "My String");
And the second method (see JavaDoc here) allows to specify an individual charset:
Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);
Both methods have an optional Varargs parameter for setting file handling options (see JavaDoc here). The following example would create a non-existing file or append the string to an existing one:
Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
strSearch in this case is probably null (not simply empty).
Try using
String.IsNullOrEmpty(strSearch)
if you are just trying to determine if the string doesn't have any contents.
You could use np.isreal
to check the type of each element (applymap applies a function to each element in the DataFrame):
In [11]: df.applymap(np.isreal)
Out[11]:
a b
item
a True True
b True True
c True True
d False True
e True True
If all in the row are True then they are all numeric:
In [12]: df.applymap(np.isreal).all(1)
Out[12]:
item
a True
b True
c True
d False
e True
dtype: bool
So to get the subDataFrame of rouges, (Note: the negation, ~, of the above finds the ones which have at least one rogue non-numeric):
In [13]: df[~df.applymap(np.isreal).all(1)]
Out[13]:
a b
item
d bad 0.4
You could also find the location of the first offender you could use argmin:
In [14]: np.argmin(df.applymap(np.isreal).all(1))
Out[14]: 'd'
As @CTZhu points out, it may be slightly faster to check whether it's an instance of either int or float (there is some additional overhead with np.isreal):
df.applymap(lambda x: isinstance(x, (int, float)))
It depends on what compiler you're using.
For example, if you are using Visual C++ .NET 2010 Express, run Visual C++ 2010 Express Command Prompt from the start menu, and you can simply compile and run the code.
> cl /EHsc mycode.cpp
> mycode.exe
or from the regular command line, you can run vcvars32.bat
first to set up the environment. Alternatively search for setvcvars.cmd
(part of a FLOSS project) and use that to even locate the installed VS and have it call vcvars32.bat
for you.
Please check your compiler's manual for command lines.
Another solution is to put data definition into a separate file.
The idea is to write data common for both model and migration into a separate file, then require it in both the migration and the model. Then in the model we can add validations, while the migration is already good to go.
In order to not clutter this post with tons of code i wrote a GitHub gist.
See it here: https://gist.github.com/igorvolnyi/f7989fc64006941a7d7a1a9d5e61be47
Aliases can be used only if they were introduced in the preceding step. So aliases in the SELECT
clause can be used in the ORDER BY
but not the GROUP BY
clause.
Reference: Microsoft T-SQL Documentation for further reading.
FROM
ON
JOIN
WHERE
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP
Hope this helps.
You can use the not
function rather than the :not
selector:
$(".content a").not(this).hide("slow")
An even simpler way to do this is to use jQuery's toggleClass() method
CSS
.newClass{visibility: hidden}
HTML
<a href="#" class=trigger>Trigger Element </a>
<div class="hidden_element">Some Content</div>
JS
$(document).ready(function(){
$(".trigger").click(function(){
$(".hidden_element").toggleClass("newClass");
});
});
Target= "_blank"
This does it in html, give it a try in C#
Just to keep it backward compatible I load Crockfords JSON-library from cloudflare CDN if no native JSON support is given (for simplicity using jQuery):
function winHasJSON(){
json_data = JSON.stringify(obj);
// ... (do stuff with json_data)
}
if(typeof JSON === 'object' && typeof JSON.stringify === 'function'){
winHasJSON();
} else {
$.getScript('//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min.js', winHasJSON)
}
https://docs.angularjs.org/guide/$location#html-link-rewriting
In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.
Links that contain target element Example:
<a href="/ext/link?a=b" target="_self">link</a>
Absolute links that go to a different domain Example:
<a href="http://angularjs.org/">link</a>
Links starting with '/' that lead to a different base path when base is defined Example:
<a href="/not-my-base/link">link</a>
So in your case, you should add a target attribute like so...
<a target="_self" href="example.com/uploads/asd4a4d5a.pdf" download="foo.pdf">
To assign, you should use p=p+1;
instead of p+1=p;
int main()
{
int x[3]={4,5,6};
int *p=x;
p=p+1; /*You just needed to switch the terms around*/
cout<<p<<endl;
getch();
}
To use the standard sleep function add the following in your .cpp file:
#include <unistd.h>
As of Qt version 4.8, the following sleep functions are available:
void QThread::msleep(unsigned long msecs)
void QThread::sleep(unsigned long secs)
void QThread::usleep(unsigned long usecs)
To use them, simply add the following in your .cpp file:
#include <QThread>
Reference: QThread (via Qt documentation): http://doc.qt.io/qt-4.8/qthread.html
Otherwise, perform these steps...
Modify the project file as follows:
CONFIG += qtestlib
Note that in newer versions of Qt you will get the following error:
Project WARNING: CONFIG+=qtestlib is deprecated. Use QT+=testlib instead.
... so, instead modify the project file as follows:
QT += testlib
Then, in your .cpp file, be sure to add the following:
#include <QtTest>
And then use one of the sleep functions like so:
usleep(100);
You can check your Adapter.
1 - MyLayoutBinding binding = MyLayoutBinding.inflate(layoutInflater);
2 - MyLayoutBinding binding = MyLayoutBinding.inflate(layoutInflater, viewGroup, false);
I had a same problem like you when I used 1. You can try 2.
I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:
- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"
would return:
ok: [localhost] => {
"msg": [
"172.16.1.100"
]
}
I tried this in one of the codeacademy exercises (reversing chars in a string without using reversed nor :: -1)
def reverse(text):
chars= []
l = len(text)
last = l-1
for i in range (l):
chars.append(text[last])
last-=1
result= ""
for c in chars:
result += c
return result
print reverse('hola')
I arrived at this page looking to turn off scale mode for good, so I figured I would share what I found:
VBoxManage setextradata global GUI/Input/MachineShortcuts "ScaleMode=None"
Running this in my host's terminal worked like a charm for me.
Source: https://forums.virtualbox.org/viewtopic.php?f=8&t=47821
As pointed out by @Chris the problem is likely to to low memory. We started experiencing it when we allocated too much RAM to MySQL (innodb_buffer_pool_size
).
To ensure there's enough RAM for Redis and other services we reduced innodb_buffer_pool_size
on MySQL.
You could use IIF
statement like in the next example:
SELECT
IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
TABLE_NAME
Following on @Anorak answer, i added this extension to String and sent an inset as a parameter, because a lot of times you will need a padding to your text. Anyway, maybe some you will find this usefull.
extension String {
func heightForWithFont(font: UIFont, width: CGFloat, insets: UIEdgeInsets) -> CGFloat {
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width + insets.left + insets.right, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = self
label.sizeToFit()
return label.frame.height + insets.top + insets.bottom
}
}
You can define a static constructor for the class that will check that the type T is an enum and throw an exception if it is not. This is the method mentioned by Jeffery Richter in his book CLR via C#.
internal sealed class GenericTypeThatRequiresAnEnum<T> {
static GenericTypeThatRequiresAnEnum() {
if (!typeof(T).IsEnum) {
throw new ArgumentException("T must be an enumerated type");
}
}
}
Then in the parse method, you can just use Enum.Parse(typeof(T), input, true) to convert from string to the enum. The last true parameter is for ignoring case of the input.
I had to set both HighlightBrushKey and ControlBrushKey to get it to be correctly styled. Otherwise, whilst it has focus this will correctly use the transparent HighlightBrusKey. Bt, if the control loses focus (whilst it is still highlighted) then it uses the ControlBrushKey.
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</Style.Resources>
When Using .Net 4.5 and above, use InactiveSelectionHighlightBrushKey
instead of ControlBrushKey
:
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
</Style.Resources>
Hope this helps someone out.
I had the same issue. When developing I wanted to bypass screens. I was navigating from one view controller to another in viewDidLoad by calling a selector method.
The issue is that we should let the ViewController finish transitioning before transitioning to another ViewController.
This solved my problem: The delay is necessary to allow ViewControllers finish transitioning before transitioning to another.
self.perform(#selector(YOUR SELECTOR METHOD), with: self, afterDelay: 0.5)
You can also use the constant service as such. Defining the function outside of the constant call allows it to be recursive as well.
function doSomething( a, b ) {
return a + b;
};
angular.module('moduleName',[])
// Define
.constant('$doSomething', doSomething)
// Usage
.controller( 'SomeController', function( $doSomething ) {
$scope.added = $doSomething( 100, 200 );
})
;
In Angular 5, the query params are accessed by subscribing to this.route.queryParams
(note that later Angular versions recommend queryParamMap
, see also other answers).
Example: /app?param1=hallo¶m2=123
param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
console.log('Called Constructor');
this.route.queryParams.subscribe(params => {
this.param1 = params['param1'];
this.param2 = params['param2'];
});
}
whereas, the path variables are accessed by this.route.snapshot.params
Example: /param1/:param1/param2/:param2
param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
this.param1 = this.route.snapshot.params.param1;
this.param2 = this.route.snapshot.params.param2;
}
the issue of too long content @beenotung can be resolved by this css class :
.col{
max-width :20% !important;
}
example fork from @jpoveda
I tried the solutions above and it looks like on rails 5.* the second agument by default is the value of the input form, what worked for me was:
text_field_tag :attr, "", placeholder: "placeholder text"
Here is my minimalist example, using a macro.
Use double brackets enable_if((...))
when using more complex expressions.
template<bool b, std::enable_if_t<b, int> = 0>
using helper_enable_if = int;
#define enable_if(value) typename = helper_enable_if<value>
struct Test
{
template<enable_if(false)>
void run();
}
Up through C++03, your first example was valid, but used a deprecated implicit conversion--a string literal should be treated as being of type char const *
, since you can't modify its contents (without causing undefined behavior).
As of C++11, the implicit conversion that had been deprecated was officially removed, so code that depends on it (like your first example) should no longer compile.
You've noted one way to allow the code to compile: although the implicit conversion has been removed, an explicit conversion still works, so you can add a cast. I would not, however, consider this "fixing" the code.
Truly fixing the code requires changing the type of the pointer to the correct type:
char const *p = "abc"; // valid and safe in either C or C++.
As to why it was allowed in C++ (and still is in C): simply because there's a lot of existing code that depends on that implicit conversion, and breaking that code (at least without some official warning) apparently seemed to the standard committees like a bad idea.
I think that LINQ join clause isn't the correct solution to this problem, because of join clause purpose isn't to accumulate data in such way as required for this task solution. The code to merge created separate collections becomes too complicated, maybe it is OK for learning purposes, but not for real applications. One of the ways how to solve this problem is in the code below:
class Program
{
static void Main(string[] args)
{
List<FirstName> firstNames = new List<FirstName>();
firstNames.Add(new FirstName { ID = 1, Name = "John" });
firstNames.Add(new FirstName { ID = 2, Name = "Sue" });
List<LastName> lastNames = new List<LastName>();
lastNames.Add(new LastName { ID = 1, Name = "Doe" });
lastNames.Add(new LastName { ID = 3, Name = "Smith" });
HashSet<int> ids = new HashSet<int>();
foreach (var name in firstNames)
{
ids.Add(name.ID);
}
foreach (var name in lastNames)
{
ids.Add(name.ID);
}
List<FullName> fullNames = new List<FullName>();
foreach (int id in ids)
{
FullName fullName = new FullName();
fullName.ID = id;
FirstName firstName = firstNames.Find(f => f.ID == id);
fullName.FirstName = firstName != null ? firstName.Name : string.Empty;
LastName lastName = lastNames.Find(l => l.ID == id);
fullName.LastName = lastName != null ? lastName.Name : string.Empty;
fullNames.Add(fullName);
}
}
}
public class FirstName
{
public int ID;
public string Name;
}
public class LastName
{
public int ID;
public string Name;
}
class FullName
{
public int ID;
public string FirstName;
public string LastName;
}
If real collections are large for HashSet formation instead foreach loops can be used the code below:
List<int> firstIds = firstNames.Select(f => f.ID).ToList();
List<int> LastIds = lastNames.Select(l => l.ID).ToList();
HashSet<int> ids = new HashSet<int>(firstIds.Union(LastIds));//Only unique IDs will be included in HashSet
What you have should work. If, however, the spaces provided are defaulting to... something else? You can use the whitespace regex:
str = "Hello I'm your String";
String[] splited = str.split("\\s+");
This will cause any number of consecutive spaces to split your string into tokens.
As a side note, I'm not sure "splited" is a word :) I believe the state of being the victim of a split is also "split". It's one of those tricky grammar things :-) Not trying to be picky, just figured I'd pass it on!
The only real clean way to uninstall VS (Visual Studio, whatever version it is) is to completely reinstall the whole OS. If you don't, more compatibility problems might surface.
Permanent solution
Starting from scratch (clean install, VS never installed on the OS), the best way to avoid all those problems is to install and run VS from a VM (virtual machine) as stated by Default in the comments above. This way, and as long as Microsoft doesn't do anything to improve its whole platform to be more user-friendly, switching from a version to another will be quick and easy and the main partition of the HDD (or SSD in my case) won't be filed with all the garbage that VS leaves behind.
Of course, the disadvantage is speed. The program will be slower in pretty much every way. But honestly, who uses VS for its speed? Even on the latest enthusiast-platforms, it takes ages to install. Even if VS might start up faster on a high-end SSD, it's just slow.
Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:
private DataTable LoadExcelData(string fileName)
{
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);
myCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
return dt;
}
You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.
you can use tar, with --exclude option , and then untar it in destination. eg
cd /source_directory
tar cvf test.tar --exclude=dir_to_exclude *
mv test.tar /destination
cd /destination
tar xvf test.tar
see the man page of tar for more info
You can iterate through the array and set a "flag" value if strpos
returns false
.
$flag = false;
foreach ($find_letters as $letter)
{
if (strpos($string, $letter) === false)
{
$flag = true;
}
}
Then check the value of $flag
.
Perhaps not in the context that you have it, but you could use
SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA
You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.
I believe the best way to do this is to use the LocalTimezone
class defined in the datetime.tzinfo
documentation (goto http://docs.python.org/library/datetime.html#tzinfo-objects and scroll down to the "Example tzinfo classes" section):
Assuming Local
is an instance of LocalTimezone
t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=utc)
local_t = t.astimezone(Local)
then str(local_t)
gives:
'2009-07-11 04:44:59.193982+10:00'
which is what you want.
(Note: this may look weird to you because I'm in New South Wales, Australia which is 10 or 11 hours ahead of UTC)
I have the same question: PHP Fatal error: Call to undefined function json_decode()
, but I run php under cygwin on Windows. When I run php -m
, I found that there is no json module installed. So I run cygwin setup.exe again, check json package from the configuration interface, and the problem is solved.
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
Yes, you can use numpy
for that.
import numpy as np
a = arange(3,dtype=float)
a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf
a # is now [nan,inf,-inf]
np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True
I used
Utilities.formatString("%04d", iThe_TWO_to_FOUR_DIGIT)
which gives up to 4 leading 0s
NOTE: THIS REQUIRES Google's apps-script Utilities:
https://developers.google.com/apps-script/reference/utilities/utilities#formatstringtemplate-args
Maybe the suggested solutions here worked in 2009, but ive tested all of this upvoted answers and nobody is working in any browsers.
only solution i found working is this: (but its a bit ugly to use i think)
<form method="post" name="form">
<input type="submit" value="dosomething" onclick="javascript: form.action='actionurl1';"/>
<input type="submit" value="dosomethingelse" onclick="javascript: form.action='actionurl2';"/>
using System.IO;
//...
string[] files;
if (Directory.Exists(Path)) {
files = Directory.GetFiles(Path, @"*.xml", SearchOption.TopDirectoryOnly);
//...