You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
You are missing a closing h2 tag. It should be:
<h2><!-- Content --></h2>
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.
include.prepload.js file will have a line something like below. probably as the last line.
//# sourceMappingURL=include.prepload.js.map
Delete it and the error will go away.
In my case, I had to deactivate AdBlock and it worked fine.
Simply Update the Chrome browser to the latest version available.
Try to restart the server and launch it back using npm start
According to your package.json, you're using Angular 8.3, but you've imported angular/cdk v9. You can downgrade your angular/cdk version or you can upgrade your Angular version to v9 by running:
ng update @angular/core @angular/cli
That will update your local angular version to 9. Then, just to sync material, run:
ng update @angular/material
Fixed by adding crossorigin to the script tag.
From: https://code.jquery.com/
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org
We experienced this problem on pages with long Base64 strings. The problem occurs because we use CloudFlare.
Details: https://community.cloudflare.com/t/err-http2-protocol-error/119619.
Key section from the forum post:
After further testing on Incognito tabs on multiple browsers, then doing the changes on the code from a BASE64 to a real .png image, the issue never happened again, in ANY browser. The .png had around 500kb before becoming a base64,so CloudFlare has issues with huge lines of text on same line (since base64 is a long string) as a proxy between the domain and the heroku. As mentioned before, directly hitting Heroku url also never happened the issue.
The temporary hack is to disable HTTP/2 on CloudFlare.
Hope someone else can produce a better solution that doesn't require disabling HTTP/2 on CloudFlare.
As the new feature comes, SameSite=None
cookies must also be marked as Secure
or they will be rejected.
One can find more information about the change on chromium updates and on this blog post
Note: not quite related directly to the question, but might be useful for others who landed here as it was my concern at first during development of my website:
if you are seeing the warning from question that lists some 3rd party sites (in my case it was google.com, huh) - that means they need to fix it and it's nothing to do with your site. Of course unless the warning mentions your site, in which case adding Secure
should fix it.
$ which chromedriver
/usr/local/bin/chromedriver
$ chromedriver --version
ChromeDriver 78.0.3904.105
I downloaded a zip file from https://chromedriver.chromium.org/downloads
It says "If you are using Chrome version 79, please download ChromeDriver 79.0.3945.36"
and I was using Chrome version 79. (I checked chrome://settings/help
) Apparently, the error for me was "This version of ChromeDriver only supports Chrome version 78"
And then I clicked the zip file and move that "chromedriver" file into /usr/local/bin/
directory. That solved the issue.
$ which chromedriver
$ chromedriver --version
ChromeDriver 79.0.3945.36
I also came across the same error. I just opened another non-running Juputer notebook and an error is automatically gone.
For me it was Auto Tab Discard
, which throws that error on pinned tabs. I created a bug report, https://github.com/rNeomy/auto-tab-discard/issues/101.
Try to download HERE and use this latest chrome driver version.
https://sites.google.com/a/chromium.org/chromedriver/downloads
EDIT:
Try this:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
d = webdriver.Chrome('/home/PycharmProjects/chromedriver',chrome_options=chrome_options)
d.get('https://www.google.nl/')
I get the same error when using Gulp. The solution is to switch to Gulp version 3.9.1, both for the local version and the CLI version.
sudo npm install -g [email protected]
Run in the project's folder
npm install [email protected]
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
dataType:'jsonp',
You are making a JSONP request, but the server is responding with JSON.
The browser is refusing to try to treat the JSON as JSONP because it would be a security risk. (If the browser did try to treat the JSON as JSONP then it would, at best, fail).
See this question for more details on what JSONP is. Note that is a nasty hack to work around the Same Origin Policy that was used before CORS was available. CORS is a much cleaner, safer, and more powerful solution to the problem.
It looks like you are trying to make a cross-origin request and are throwing everything you can think of at it in one massive pile of conflicting instructions.
You need to understand how the Same Origin policy works.
See this question for an in-depth guide.
Now a few notes about your code:
contentType: 'application/json',
Remove that.
dataType:'jsonp',
Remove this. (You could make the server respond with JSONP instead, but CORS is better).
responseType:'application/json',
This is not an option supported by jQuery.ajax. Remove this.
xhrFields: { withCredentials: false },
This is the default. Unless you are setting it to true with ajaxSetup, remove this.
headers: { 'Access-Control-Allow-Credentials' : true, 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Methods':'GET', 'Access-Control-Allow-Headers':'application/json', },
I ran into same issue, i am using UBUNTU, PYTHON and OPERA browser. in my case the problem was originated because i had an outdated version of operadriver.
Solution: 1. Make sure you install latest opera browser version ( do not use opera beta or opera developer), for that go to the official opera site and download from there the latest opera_stable version.
unzip operadriver_linux64.zip
sudo mv operadriver /usr/bin/operadriver
sudo chown root:root /usr/bin/operadriver
sudo chmod +x /usr/bin/operadriver
in my case latest was 80.0.3987 as you can see
Additionally i also installed chromedriver (but since i did it before testing, i do not know of this is needed) in order to install chromedriver, follow the steps on previous step :v
Enjoy and thank me!
Sample selenium code
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Opera()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.quit()
At least you can use this:
document.addEventListener('click', musicPlay);
function musicPlay() {
document.getElementById('ID').play();
document.removeEventListener('click', musicPlay);
}
The music starts when the user clicks anywhere at the page.
It removes also instantly the EventListener, so if you use the audio controls the user can mute or pause it and the music doesn't start again when he clicks somewhere else..
Running ng serve --open after creating and going into my new project "frontend" gave this error:
After creating the project, you need to run
npm install
to install all the dependencies listed in package.json
I struggled with the same problem just a minute ago. My project was generated using the v 1.6.0 of angular-cli.
1. npm update -g @angular/cli
2. editing my package.json changing the line
"@angular/cli": "1.6.0",
to
"@angular/cli": "^1.6.0",
3. npm update
I hope my help is effective ?
The best solution i found out is to mute the video
HTML
<video loop muted autoplay id="videomain">
<source src="videoname.mp4" type="video/mp4">
</video>
Here is what worked for me (Angular 7):
First import HttpClientModule in your app.module.ts if you didn't:
import { HttpClientModule } from '@angular/common/http';
...
imports: [
HttpClientModule
],
Then change your service
@Injectable()
export class FooService {
to
@Injectable({
providedIn: 'root'
})
export class FooService {
Hope it helps.
Edit:
providedIn
Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in one of the following injectors:
'root' : The application-level injector in most apps.
'platform' : A special singleton platform injector shared by all applications on the page.
'any' : Provides a unique instance in every module (including lazy modules) that injects the token.
Be careful platform
is available only since Angular 9 (https://blog.angular.io/version-9-of-angular-now-available-project-ivy-has-arrived-23c97b63cfa3)
Read more about Injectable here: https://angular.io/api/core/Injectable
I had the SAME issue today and it was driving me nuts!!! What I had done was upgrade to node 8.10 and upgrade my NPM to the latest I uninstalled angular CLI
npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
I then verified my Cache from NPM if it wasn't up to date I cleaned it and ran the install again
if npm version is < 5 then use npm cache clean --force
npm install -g @angular/cli@latest
and created a new project file and create a new angular project.
You should use the new HttpClient
. You can find more information here.
http
.get<any>('url', {observe: 'response'})
.subscribe(resp => {
console.log(resp.headers.get('X-Token'));
});
When using MatAutocompleteModule in your angular application, you need to import Input Module also in app.module.ts
Please import below:
import { MatInputModule } from '@angular/material';
urllib
is a standard python library (built-in) so you don't have to install it. just import it if you need to use request
by:
import urllib.request
if it's not work maybe you compiled python in wrong way, so be kind and give us more details.
Things become complicated when you want to post files via multipart/form-data
, especially multiple binary files. Below is a working example:
const FormData = require('form-data')
const fs = require('fs')
const path = require('path')
const formData = new FormData()
formData.append('files[]', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json')
formData.append('files[]', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png')
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData, {
headers: formData.getHeaders()
})
headers: {'Content-Type': 'multipart/form-data' }
I prefer headers: formData.getHeaders()
async
and await
above, you can change them to plain Promise statements if you don't like themheaders: { ...yourHeaders, ...formData.getHeaders() }
Newly added content below:
Browser's FormData
is different from the NPM package 'form-data'. The following code works for me in browser:
HTML:
<input type="file" id="image" accept="image/png"/>
JavaScript:
const formData = new FormData()
// add a non-binary file
formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')
// add a binary file
const element = document.getElementById('image')
const file = element.files[0]
formData.append('files[]', file, file.name)
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)
You have not provided providers in your module:
<strike>import { HttpModule } from '@angular/http';</strike>
import { HttpClientModule, HttpClient } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
BrowserAnimationsModule,
FormsModule,
AppRoutingModule
],
providers: [ HttpClientModule, ... ]
// ...
})
export class MyModule { /* ... */ }
You will need to add the HttpClientTestingModule
to the TestBed configuration when running ng test
and getting the "No provider for HttpClient" error:
// Http testing module and mocking controller
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
// Other imports
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
describe('HttpClient testing', () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
});
// Inject the http service and test controller for each test
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
});
it('works', () => {
});
});
If you are using .NET Core application, this solution might help!
Moreover this might not be an Angular or other request error in your front end application
First, you have to add the Microsoft CORS Nuget package:
Install-Package Microsoft.AspNetCore.Cors
You then need to add the CORS services in your startup.cs. In your ConfigureServices method you should have something similar to the following:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
Next, add the CORS middleware to your app. In your startup.cs you should have a Configure method. You need to have it similar to this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
app.UseCors( options =>
options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseMvc();
}
The options lambda is a fluent API so you can add/remove any extra options you need. You can actually use the option “AllowAnyOrigin” to accept any domain, but I highly recommend you do not do this as it opens up cross origin calls from anyone. You can also limit cross origin calls to their HTTP Method (GET/PUT/POST etc), so you can only expose GET calls cross domain etc.
System.setProperty("webdriver.chrome.driver",
"D:\\Lib\\chrome_driver_latest\\chromedriver_win32\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--allow-running-insecure-content");
chromeOptions.addArguments("--window-size=1920x1080");
chromeOptions.addArguments("--disable-gpu");
chromeOptions.setHeadless(true);
ChromeDriver driver = new ChromeDriver(chromeOptions);
--generate-config
command on the anaconda prompt. jupyter_notebook_config.py
file. Find the c.NotebookApp.Browser like this:
c.NotebookApp.browser = 'c:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
Works on mine.
Generally it is a versioning issue. Node.js v8 cannot compile with angular-cli 6.0 or later. angularcli v6 and above will work for lastest node versions. Please make sure if your node version is v8, then you need to install angular-cli upto 1.7.4. enter ng -v command in cmd and check the cli and node versions.
Even adding responseType, I dealt with it for days with no success. Finally I got it. Make sure that in your backend script you don't define header as -("Content-Type: application/json);
Becuase if you turn it to text but backend asks for json, it will return an error...
Note for Chrome Browser released in 2020.
A future release of Chrome will only deliver cookies with cross-site requests if they are set with
SameSite=None
andSecure
.
So if your backend server does not set SameSite=None, Chrome will use SameSite=Lax by default and will not use this cookie with { withCredentials: true } requests.
More info https://www.chromium.org/updates/same-site.
Firefox and Edge developers also want to release this feature in the future.
Spec found here: https://tools.ietf.org/html/draft-west-cookie-incrementalism-01#page-8
npm install -g npm-install-peers
it will add all the missing peers and remove all the error
}, "proxy": "http://localhost:8080", "devDependencies": {
use proxy in package.json
IE11 uses an older version of the Grid specification.
The properties you are using don't exist in the older grid spec. Using prefixes makes no difference.
Here are three problems I see right off the bat.
repeat()
The repeat()
function doesn't exist in the older spec, so it isn't supported by IE11.
You need to use the correct syntax, which is covered in another answer to this post, or declare all row and column lengths.
Instead of:
.grid {
display: -ms-grid;
display: grid;
-ms-grid-columns: repeat( 4, 1fr );
grid-template-columns: repeat( 4, 1fr );
-ms-grid-rows: repeat( 4, 270px );
grid-template-rows: repeat( 4, 270px );
grid-gap: 30px;
}
Use:
.grid {
display: -ms-grid;
display: grid;
-ms-grid-columns: 1fr 1fr 1fr 1fr; /* adjusted */
grid-template-columns: repeat( 4, 1fr );
-ms-grid-rows: 270px 270px 270px 270px; /* adjusted */
grid-template-rows: repeat( 4, 270px );
grid-gap: 30px;
}
Older spec reference: https://www.w3.org/TR/2011/WD-css3-grid-layout-20110407/#grid-repeating-columns-and-rows
span
The span
keyword doesn't exist in the older spec, so it isn't supported by IE11. You'll have to use the equivalent properties for these browsers.
Instead of:
.grid .grid-item.height-2x {
-ms-grid-row: span 2;
grid-row: span 2;
}
.grid .grid-item.width-2x {
-ms-grid-column: span 2;
grid-column: span 2;
}
Use:
.grid .grid-item.height-2x {
-ms-grid-row-span: 2; /* adjusted */
grid-row: span 2;
}
.grid .grid-item.width-2x {
-ms-grid-column-span: 2; /* adjusted */
grid-column: span 2;
}
Older spec reference: https://www.w3.org/TR/2011/WD-css3-grid-layout-20110407/#grid-row-span-and-grid-column-span
grid-gap
The grid-gap
property, as well as its long-hand forms grid-column-gap
and grid-row-gap
, don't exist in the older spec, so they aren't supported by IE11. You'll have to find another way to separate the boxes. I haven't read the entire older spec, so there may be a method. Otherwise, try margins.
There was some discussion in the old spec about grid item auto placement, but the feature was never implemented in IE11. (Auto placement of grid items is now standard in current browsers).
So unless you specifically define the placement of grid items, they will stack in cell 1,1.
Use the -ms-grid-row
and -ms-grid-column
properties.
In HTML file you can add ngIf for you pattern like this
<div class="form-control-feedback" *ngIf="Mobile.errors && (Mobile.dirty || Mobile.touched)">
<p *ngIf="Mobile.errors.pattern" class="text-danger">Number Only</p>
</div>
In .ts file you can add the Validators pattern - "^[0-9]*$"
this.Mobile = new FormControl('', [
Validators.required,
Validators.pattern("^[0-9]*$"),
Validators.minLength(8),
]);
For forms, use the [FromForm]
attribute instead of the [FromBody]
attribute.
The below controller works with ASP.NET Core 1.1:
public class MyController : Controller
{
[HttpPost]
public async Task<IActionResult> Submit([FromForm] MyModel model)
{
//...
}
}
Note: [FromXxx]
is required if your controller is annotated with [ApiController]
. For normal view controllers it can be omitted.
Am afraid this question has been answered a few times, Pls take a look at the following if it's related
In case you are using NodeJS/Express as back-end and ReactJS/axios as front-end within a development environment in MacOS, you need to run both sides under https. Below is what it finally worked for me (after many hours of deep dive & testing):
Step 1: Create an SSL certificate
Just follow the steps from How to get HTTPS working on your local development environment in 5 minutes
You will end up with a couple of files to be used as credentials to run the https server and ReactJS web:
server.key & server.crt
You need to copy them in the root folders of both the front and back ends (in a Production environment, you might consider copying them in ./ssh for the back-end).
Step 2: Back-end setup
I read a lot of answers proposing the use of 'cors' package or even setting ('Access-Control-Allow-Origin', '*'), which is like saying: "Hackers are welcome to my website". Just do like this:
import express from 'express';
const emailRouter = require('./routes/email'); // in my case, I was sending an email through a form in ReactJS
const fs = require('fs');
const https = require('https');
const app = express();
const port = 8000;
// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', (req, res, next) => {
res.header("Access-Control-Allow-Origin", "https://localhost:3000");
next();
});
// Routes definition
app.use('/email', emailRouter);
// HTTPS server
const credentials = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(port, () => {
console.log(`Back-end running on port ${port}`);
});
In case you want to test if the https is OK, you can replace the httpsServer constant by the one below:
https.createServer(credentials, (req: any, res: any) => {
res.writeHead(200);
res.end("hello world from SSL\n");
}).listen(port, () => {
console.log(`HTTPS server listening on port ${port}...`);
});
And then access it from a web browser: https://localhost:8000/
Step 3: Front-end setup
This is the axios request from the ReactJS front-end:
await axios.get(`https://localhost:8000/email/send`, {
params: {/* whatever data you want to send */ },
headers: {
'Content-Type': 'application/json',
}
})
And now, you need to launch your ReactJS web in https mode using the credentials for SSL we already created. Type this in your MacOS terminal:
HTTPS=true SSL_CRT_FILE=server.crt SSL_KEY_FILE=server.key npm start
At this point, you are sending a request from an https connection at port 3000 from your front-end, to be received by an https connection at port 8000 by your back-end. CORS should be happy with this ;)
On chrome when are in the SVG URL, you can do CTRL+S or CMD+S and it automatically propose you to save the page as an .SVG try it out : https://upload.wikimedia.org/wikipedia/commons/9/90/Benjamin_Franklin-10_Dollar_Bill_Portrait-Vector.svg
A simpler way which eliminates checking if the app can open the url.
loadInBrowser = () => {
Linking.openURL(this.state.url).catch(err => console.error("Couldn't load page", err));
};
Calling it with a button.
<Button title="Open in Browser" onPress={this.loadInBrowser} />
Here is a very simple way to create an IP certificate that Chrome will trust.
The ssl.conf file...
[ req ]
default_bits = 4096
distinguished_name = req_distinguished_name
req_extensions = req_ext
prompt = no
[ req_distinguished_name ]
commonName = 192.168.1.10
[ req_ext ]
subjectAltName = IP:192.168.1.10
Where, of course 192.168.1.10 is the local network IP we want Chrome to trust.
Create the certificate:
openssl genrsa -out key1.pem
openssl req -new -key key1.pem -out csr1.pem -config ssl.conf
openssl x509 -req -days 9999 -in csr1.pem -signkey key1.pem -out cert1.pem -extensions req_ext -extfile ssl.conf
rm csr1.pem
On Windows import the certificate into the Trusted Root Certificate Store on all client machines. On Android Phone or Tablet download the certificate to install it. Now Chrome will trust the certificate on windows and Android.
On windows dev box the best place to get openssl.exe is from "c:\Program Files\Git\usr\bin\openssl.exe"
Add this config to your webpack config file when using webpack-dev-server (you can still specify the host as 0.0.0.0).
devServer: {
disableHostCheck: true,
host: '0.0.0.0',
port: 3000
}
If the blob is instantiated with data from an F4M manifest (check the Network Tab in Chrome's Developer Tools), you can download the video file using the php script posted here: https://n1njahacks.wordpress.com/2015/01/29/how-to-save-hds-flash-streams-from-any-web-page/
By putting:
if ($manifest == '')
$manifest = $_GET['manifest'];
before:
if ($manifest)
you could even run it on a webserver, using requests with the query string: ?manifest=[manifest url]
.
Note that you'll probably want to use an FTP client to retrieve the downloaded video file and clean up after the script (it leaves all the downloaded video parts).
I am having visual studio 2017 , and this simple few click has fix internet issue for Android emulator.
I was able to solve this issue in Chrome by turning off the Calendly Chrome extension which I had recently installed. May not be Calendly specific so I would recommend turning off any newly installed Chrome extensions. Below are the steps I took:
Try to delete that "angular/cli": "1.0.0-beta.28.3",
in the devDependencies
it is useless , and add instead of it "@angular/compiler-cli": "^2.3.1",
(since it is the current version, else add it by npm i --save-dev @angular/compiler-cli
), then in your root app folder run those commands:
rm -r node_modules
(or delete your node_modules
folder manually)npm cache clean
(npm > v5 add --force
so: npm cache clean --force
)npm install
You need to specify the path where your chromedriver is located.
Place chromedriver on your system path, or where your code is.
If not using a system path, link your chromedriver.exe
(For non-Windows users, it's just called chromedriver
):
browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
(Set executable_path
to the location where your chromedriver is located.)
If you've placed chromedriver on your System Path, you can shortcut by just doing the following:
browser = webdriver.Chrome()
If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:
chmod +x chromedriver
That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium
It's currently working, I've just changed the operator >
in order to work in the snippet, take a look:
window.onload = function() {_x000D_
_x000D_
if (window.location.href.indexOf("test") <= -1) {_x000D_
var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
search_span[0].style.color = "blue";_x000D_
search_span[0].style.fontWeight = "bold";_x000D_
search_span[0].style.fontSize = "40px";_x000D_
_x000D_
}_x000D_
_x000D_
}
_x000D_
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
_x000D_
"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript
and took 83ms of runtime
are alerting you there's probably an opportunity to speed up your script.
("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)
In order to send data from child component create property decorated with output() in child component and in the parent listen to the created event. Emit this event with new values in the payload when ever it needed.
@Output() public eventName:EventEmitter = new EventEmitter();
to emit this event:
this.eventName.emit(payloadDataObject);
I am getting this issue when using owl carousal and scrolling the images.
So get solved just adding below CSS in your page.
.owl-carousel {
-ms-touch-action: pan-y;
touch-action: pan-y;
}
or
.owl-carousel {
-ms-touch-action: none;
touch-action: none;
}
I have received this error in react.js. If you have a button in the form that you want to act like a button and not submit the form, you must give it type="button". Otherwise it tries to submit the form. I believe vaskort answered this with some documentation you can check out.
I can't guarantee that this will work for every new iPad Pro which will be released but this works pretty well as of 2019:
@media only screen and (min-width: 1024px) and (max-height: 1366px)
and (-webkit-min-device-pixel-ratio: 1.5) and (hover: none) {
/* ... */
}
You can try ES6 Modules in Google Chrome Beta (61) / Chrome Canary.
Reference Implementation of ToDo MVC by Paul Irish - https://paulirish.github.io/es-modules-todomvc/
I've basic demo -
//app.js
import {sum} from './calc.js'
console.log(sum(2,3));
//calc.js
let sum = (a,b) => { return a + b; }
export {sum};
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h1>ES6</h1>
<script src="app.js" type="module"></script>
</body>
</html>
Hope it helps!
Remove :
npm uninstall -g angular-cli
Reinstall (with yarn)
# npm install --global yarn
yarn global add @angular/cli@latest
ng set --global packageManager=yarn # This will help ng-cli to use yarn
Reinstall (with npm)
npm install --global @angular/cli@latest
Another way is to not use global install, and add /node_modules/.bin
folder in the PATH, or use npm scripts. It will be softer to upgrade.
Problem solved! I just figured out how to solve the issue, but I would still like to know if this is normal behavior or not.
It seems that even though the Websocket connection establishes correctly (indicated by the 101 Switching Protocols request), it still defaults to long-polling. The fix was as simple as adding this option to the Socket.io connection function:
{transports: ['websocket']}
So the code finally looks like this:
const app = express();
const server = http.createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
console.log('connected socket!');
socket.on('greet', function(data) {
console.log(data);
socket.emit('respond', { hello: 'Hey, Mr.Client!' });
});
socket.on('disconnect', function() {
console.log('Socket disconnected');
});
});
and on the client:
var socket = io('ws://localhost:3000', {transports: ['websocket']});
socket.on('connect', function () {
console.log('connected!');
socket.emit('greet', { message: 'Hello Mr.Server!' });
});
socket.on('respond', function (data) {
console.log(data);
});
And the messages now appear as frames:
This Github issue pointed me in the right direction. Thanks to everyone who helped out!
Forced reflow often happens when you have a function called multiple times before the end of execution.
For example, you may have the problem on a smartphone, but not on a classic browser.
I suggest using a setTimeout
to solve the problem.
This isn't very important, but I repeat, the problem arises when you call a function several times, and not when the function takes more than 50 ms. I think you are mistaken in your answers.
setTimeOut
based on the duration of the violation.At the time this was posted, neither of the previous answers worked for me.
This approach uses a visible password field to capture the password from the user and a hidden password field to pass the password to the server. The visible password field is blanked before the form is submitted, but not with a form submit
event handler (see explanation on the next paragraph). This approach transfers the visible password field value to the hidden password field as soon as possible (without unnecessary overhead) and then wipes out the visible password field. If the user tabs back into the visible password field, the value is restored. It uses the placeholder to display ??? after the field was wiped out.
I tried clearing the visible password field on the form onsubmit
event, but the browser seems to be inspecting the values before the event handler and prompts the user to save the password. Actually, if the alert
at the end of passwordchange
is uncommented, the browser still prompts to save the password.
function formsubmit(e) {
document.getElementById('form_password').setAttribute('placeholder', 'password');
}
function userinputfocus(e) {
//Just to make the browser mark the username field as required
// like the password field does.
e.target.value = e.target.value;
}
function passwordfocus(e) {
e.target.setAttribute('placeholder', 'password');
e.target.setAttribute('required', 'required');
e.target.value = document.getElementById('password').value;
}
function passwordkeydown(e) {
if (e.key === 'Enter') {
passwordchange(e.target);
}
}
function passwordblur(e) {
passwordchange(e.target);
if (document.getElementById('password').value !== '') {
var placeholder = '';
for (i = 0; i < document.getElementById('password').value.length; i++) {
placeholder = placeholder + '?';
}
document.getElementById('form_password').setAttribute('placeholder', placeholder);
} else {
document.getElementById('form_password').setAttribute('placeholder', 'password');
}
}
function passwordchange(password) {
if (password.getAttribute('placeholder') === 'password') {
if (password.value === '') {
password.setAttribute('required', 'required');
} else {
password.removeAttribute('required');
var placeholder = '';
for (i = 0; i < password.value.length; i++) {
placeholder = placeholder + '?';
}
}
document.getElementById('password').value = password.value;
password.value = '';
//This alert will make the browser prompt for a password save
//alert(e.type);
}
}
_x000D_
#form_password:not([placeholder='password'])::placeholder {
color: red; /*change to black*/
opacity: 1;
}
_x000D_
<form onsubmit="formsubmit(event)" action="/action_page.php">
<input type="hidden" id="password" name="password" />
<input type="text" id="username" name="username" required
autocomplete="off" placeholder="username"
onfocus="userinputfocus(event)" />
<input type="password" id="form_password" name="form_password" required
autocomplete="off" placeholder="password"
onfocus="passwordfocus(event)"
onkeydown="passwordkeydown(event)"
onblur="passwordblur(event)"/>
<br />
<input type="submit"/>
_x000D_
The .success
syntax was correct up to Angular v1.4.3.
For versions up to Angular v.1.6, you have to use then
method. The then()
method takes two arguments: a success
and an error
callback which will be called with a response object.
Using the then()
method, attach a callback
function to the returned promise
.
Something like this:
app.controller('MainCtrl', function ($scope, $http){
$http({
method: 'GET',
url: 'api/url-api'
}).then(function (response){
},function (error){
});
}
See reference here.
Shortcut
methods are also available.
$http.get('api/url-api').then(successCallback, errorCallback);
function successCallback(response){
//success code
}
function errorCallback(error){
//error code
}
The data you get from the response is expected to be in JSON
format.
JSON is a great way of transporting data, and it is easy to use within AngularJS
The major difference between the 2 is that .then()
call returns a promise
(resolved with a value returned from a callback
) while .success()
is more traditional way of registering callbacks
and doesn't return a promise
.
I followed each of the suggestions here (I'm using Angular 7), but nothing worked. My app refused to acknowledge that @angular/material existed, so it showed an error on this line:
import { MatCheckboxModule } from '@angular/material';
Even though I was using the --save
parameter to add Angular Material to my project:
npm install --save @angular/material @angular/cdk
...it refused to add anything to my "package.json
" file.
I even tried deleting the package-lock.json
file, as some articles suggest that this causes problems, but this had no effect.
To fix this issue, I had to manually add these two lines to my "package.json
" file.
{
"devDependencies": {
...
"@angular/material": "~7.2.2",
"@angular/cdk": "~7.2.2",
...
What I can't tell is whether this is an issue related to using Angular 7, or if it's been around for years....
At the time of writing this I have discovered that chromedriver 2.46 or 2.36 works well with Chrome 75.0.3770.100
Documentation here: http://chromedriver.chromium.org/downloads states align driver and browser alike but I found I had issues even with the most up-to-date driver when using Chrome 75
I am running Selenium 2 on Windows 10 Machine.
Google has added a new feature since the last answer was posted here.
You can now add the controlList
attribute as shown here:
<video width="512" height="380" controls controlsList="nodownload">
<source data-src="mov_bbb.ogg" type="video/mp4">
</video>
You can find all options of the controllist attribute here:
https://developers.google.com/web/updates/2017/03/chrome-58-media-updates#controlslist
In case anyone stumbles with this problem again, the accepted solution did work for older versions of ionic and app scripts, I had used it many times in the past, but last week, after I updated some stuff, it got broken again, and this fix wasn't working anymore as this was already solved on the current version of app-scripts, most of the info is referred on this post https://forum.ionicframework.com/t/ionic-cordova-run-android-livereload-cordova-not-available/116790/18 but I'll make it short here:
First make sure you have this versions on your system
cli packages: (xxxx\npm\node_modules)
@ionic/cli-utils : 1.19.2 ionic (Ionic CLI) : 3.20.0
global packages:
cordova (Cordova CLI) : not installed
local packages:
@ionic/app-scripts : 3.1.9 Cordova Platforms : android 7.0.0 Ionic Framework : ionic-angular 3.9.2
System:
Node : v10.1.0 npm : 5.6.0
An this on your package.json
"@angular/cli": "^6.0.3", "@ionic/app-scripts": "^3.1.9", "typescript": "~2.4.2"
Now remove your platform with ionic cordova platform rm what-ever Then DELETE the node_modules and plugins folder and MAKE SURE the platform was deleted inside the platforms folder.
Finally, run
npm install ionic cordova platform add what-ever ionic cordova run
And everything should be working again
An answer from 2020. The following code solves this. A lot of people new to selenium seem to have to get past this step. Install the chromedriver and put it inside a folder on your desktop. Also make sure to put the selenium python project in the same folder as where the chrome driver is located.
Change USER_NAME and FOLDER in accordance to your computer.
For Windows
driver = webdriver.Chrome(r"C:\Users\USER_NAME\Desktop\FOLDER\chromedriver")
For Linux/Mac
driver = webdriver.Chrome("/home/USER_NAME/FOLDER/chromedriver")
adding muted="muted"
property to HTML5 tag solved my issue
What you are looking for is a simple directive like:
location ~* \.(?:manifest|appcache|html?|xml|json)$ {
expires -1;
}
The above will not cache the extensions within the (). You can configure different directives for different file types.
Press CMD + ,
than click in show develop menu in menu bar. After that click Option + CMD + i
to open and close the inspector
As soon as I disabled the DuckDuckGo Privacy Essentials plugin it disappeared. Bit annoying as the fonts I was serving was from localhost so shouldn't be anything to do with a slow network connection.
I had the same problem but none of all those solutions worked for me. After further investigation, I found out that an undesired import was in one of my component.
I use setTimeout
function in app.component but for any reason Visual Studio added import { setTimeout } from 'timer';
where it was not needed. Removing this line fixed the issue.
So remember to check your imports before going further. Hope it may help someone.
@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.
<input
value={get(data, "api_key")}
styleName="input-wrap"
title={get(data, "api_key")}
ref={apikeyObjRef}
/>
<div
onClick={() => {
apikeyObjRef.current.select();
if (document.execCommand("copy")) {
document.execCommand("copy");
}
}}
styleName="copy"
>
??
</div>
If you are like me, and starring at your angular/ionic typescript, which looks like..
getPdf(endpoint: string): Observable<Blob> {
let url = this.url + '/' + endpoint;
let token = this.msal.accessToken;
console.log(token);
return this.http.post<Blob>(url, {
headers: new HttpHeaders(
{
'Access-Control-Allow-Origin': 'https://localhost:5100',
'Access-Control-Allow-Methods': 'POST',
'Content-Type': 'application/pdf',
'Authorization': 'Bearer ' + token,
'Accept': '*/*',
}),
//responseType: ResponseContentType.Blob,
});
}
And while you are setting options but can't seem to figure why they aren't anywhere..
Well.. if you were like me and started this post
from a copy/paste of a get
, then...
Change to:
getPdf(endpoint: string): Observable<Blob> {
let url = this.url + '/' + endpoint;
let token = this.msal.accessToken;
console.log(token);
return this.http.post<Blob>(url, null, { // <----- notice the null *****
headers: new HttpHeaders(
{
'Authorization': 'Bearer ' + token,
'Accept': '*/*',
}),
//responseType: ResponseContentType.Blob,
});
}
also had same problem once,
if you are unable to solve the problem you can run the following command on command line
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security
Note: you have to navigate to the installation path of your chrome.
For example:cd C:\Program Files\Google\Chrome\Application
A developer session chrome browser will be opened, you can now launch your app on the new chrome browse.
I hope this should be helpful
Unlike jQuery
in order to read raw JSON
you will need to decode it in PHP.
print_r(json_decode(file_get_contents("php://input"), true));
php://input
is a read-only stream that allows you to read raw data from the request body.
$_POST
is form variables, you will need to switch to form
radiobutton in postman
then use:
foo=bar&foo2=bar2
To post raw json
with jquery
:
$.ajax({
"url": "/rest/index.php",
'data': JSON.stringify({foo:'bar'}),
'type': 'POST',
'contentType': 'application/json'
});
I've encounterd this problem, and here is my solution for Angular, I wrapped my Angular's asset folder in encodeURIComponent() function. It worked. But still, I'd like to know more about the risk of this solution if there's any:
```const URL = ${encodeURIComponent(
/assets/office/file_2.pdf)}
window.open(URL)
I used Angular 9, so this is my url when I clicked open local file:
```http://localhost:4200/%2Fassets%2Foffice%2Ffile_2.pdf```
There are multiple possible causes for this error:
1) When you put the property 'x' inside brackets you are trying to bind to it. Therefore first thing to check is if the property 'x' is defined in your component with an Input()
decorator
Your html file:
<body [x]="...">
Your class file:
export class YourComponentClass {
@Input()
x: string;
...
}
(make sure you also have the parentheses)
2) Make sure you registered your component/directive/pipe classes in NgModule:
@NgModule({
...
declarations: [
...,
YourComponentClass
],
...
})
See https://angular.io/guide/ngmodule#declare-directives for more details about declare directives.
3) Also happens if you have a typo in your angular directive. For example:
<div *ngif="...">
^^^^^
Instead of:
<div *ngIf="...">
This happens because under the hood angular converts the asterisk syntax to:
<div [ngIf]="...">
As described by Gideon, this is a known issue with Chrome that has been open for more than 5 years with no apparent interest in fixing it.
Unfortunately, in my case, the window.onunload = function() { debugger; }
workaround didn't work either. So far the best workaround I've found is to use Firefox, which does display response data even after a navigation. The Firefox devtools also have a lot of nice features missing in Chrome, such as syntax highlighting the response data if it is html and automatically parsing it if it is JSON.
I faced this issue too. I was using jquery.poptrox.min.js
for image popping and zooming and I received an error which said:
“Uncaught TypeError: a.indexOf is not a function” error.
This is because indexOf
was not supported in 3.3.1/jquery.min.js
so a simple fix to this is to change it to an old version 2.1.0/jquery.min.js
.
This fixed it for me.
I followed my frnd suggestion and it worked like a gem for me:
Working Code:
1) Downloaded chromedriver.
2) Code is
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Sel {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Downloads\\chromedriver_win32\\chromedriver.exe"); // path of chromedriver
WebDriver driver = new ChromeDriver();
driver.get("https://google.ca");
driver.manage().window().maximize();
driver.getTitle();
}
}
<script type="text/javascript">
$(window).ready(function () {
alert("Window Loaded");
});
</script>
I was facing this issue and fixed by putting a check in form attribute. This issue can happen when the FormGroup is not initialized.
<form [formGroup]="loginForm" *ngIf="loginForm">
OR
<form [formGroup]="loginForm" *ngIf="this.loginForm">
This will not render the form until it is initialized.
I had the same issue displaying my side navigation panel height to 100%.
My steps to fix it was to:
In the index.css file ------
.html {
height: 100%;
}
.body {
height:100%;
}
In the sidePanel.css (this was giving me issues):
.side-panel {
height: 100%;
position: fixed; <--- this is what made the difference and scaled to 100% correctly
}
Other attributes were taken out for clarity, but I think the issue lies with scaling the height to 100% in nested containers like how you are trying to scale height in your nested containers. The parent classes height will need to be applied the 100%. - What i'm curious about is why fixed: position corrects the scale and fails without it; this is something i'll learn eventually with some more practice.
I've been working with react for a week now and i'm a novice to web developing, but I wanted to share a fix that I discovered with scaling height to 100%; I hope this helps you or anyone who has a similar issue. Good luck!
I came across the same issue on Android Emulator, where I tried to access an external HTTPS URL with a valid certificate. But fetching that URL in react-native failed
'fetch error:', { [TypeError: Network request failed]
sourceURL: 'http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false' }
1) To find out the exact error in the logs, I first enabled 'Debug JS Remotely' using Cmd + M on the app
2) The error reported was
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
3) I added the URL's valid certificate using this method -> STEP 2
http://lpains.net/articles/2018/install-root-ca-in-android/
This certificate gets added to the User tab.
4) Add the attribute android:networkSecurityConfig
attribute to AndroidManifest.xml
Add a Network Security Configuration file
res/xml/network_security_config.xml:
<network-security-config>
<base-config>
<trust-anchors>
<certificates src="user"/>
<certificates src="system"/>
</trust-anchors>
</base-config>
</network-security-config>
This should work and give you an expected response.
if you have a string of date, then you should try this.
const FORMAT = "YYYY ddd MMM DD HH:mm";
const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300
const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019
or try this :
const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);
Old Answer (July 2016):
You can't directly debug Chrome for iOS due to restrictions on the published WKWebView
apps, but there are a few options already discussed in other SO threads:
If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.
WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.
You could try and create a simple WKWebView
browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.
There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView
, Chrome for iOS would be debuggable.
Update January 2018:
Since my answer back in 2016, some work has been done to improve things.
There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.
Check out the getting started guide in the repo, which is quite detailed.
If you are interesting, you can read up on the background and architecture here.
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
I have tested a full layout using flexbox it contains header, footer, main body with left, center and right panels and the panels can contain menu items or footer and headers that should scroll. Pretty complex
IE11 and even IE EDGE have some problems displaying the flex content but it can be overcome. I have tested it in most browsers and it seems to work.
Some fixed i have applies are IE11 height bug, Adding height:100vh and min-height:100% to the html/body. this also helps to not have to set height on container in the dom. Also make the body/html a flex container. Otherwise IE11 will compress the view.
html,body {
display: flex;
flex-flow:column nowrap;
height:100vh; /* fix IE11 */
min-height:100%; /* fix IE11 */
}
A fix for IE EDGE that overflows the flex container: overflow:hidden on main flex container. if you remove the overflow, IE EDGE wil push the content out of the viewport instead of containing it inside the flex main container.
main{
flex:1 1 auto;
overflow:hidden; /* IE EDGE overflow fix */
}
You can see my testing and example on my codepen page. I remarked the important css parts with the fixes i have applied and hope someone finds it useful.
Here is a work around. You can use filter instead of find; but filter returns an array of matching objects. find
only returns the first match inside an array. So, why not use filter as following;
data.filter(function (x) {
return x.Id === e
})[0];
I had the same issue and found out that you need to switch drivers because support was dropped. Instead of using the Firefox Driver, you need to use the Marionette Driver in order to run your tests. I am currently working through the setup myself and can post some suggested steps if you'd like when I have a working example.
Here are the steps I followed to get this working on my Java environment on Mac (worked for me in my Linux installations (Fedora, CentOS and Ubuntu) as well):
mkdir -p /opt/marionette
)$PATH
to include the executable (also, edit your .bash_profile
if you want)chmod +x /opt/marionette/wires-x.x.x
so that it is executableQuick Note
Still not working as expected, but at least gets the browser launched now. Need to figure out why - right now it looks like I need to rewrite my tests to get it to work.
Java Snippet
WebDriver browser = new MarionetteDriver();
System.setProperty("webdriver.gecko.driver", "/opt/marionette/wires-0.7.1-OSX");
In chrome lastest. Add following css it auto hide address bar (URL bar) when scroll!
html { height: 100vh; }
body { height: 100%; }
And this is why: https://developers.google.com/web/updates/2016/12/url-bar-resizing
Hope to helpful!
There are two problems in your code.
dbConfig.php
<?php
$conn=mysqli_connect("localhost","root","password","testDB");
if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
?>
index.php
include('dbConfig.php');
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="$1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>test</title>
</head>
<body>
<?php
if(isset($_POST['save']))
{
$sql = "INSERT INTO users (username, password, email)
VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";
$result = mysqli_query($conn,$sql);
}
?>
<form action="index.php" method="post">
<label id="first"> First name:</label><br/>
<input type="text" name="username"><br/>
<label id="first">Password</label><br/>
<input type="password" name="password"><br/>
<label id="first">Email</label><br/>
<input type="text" name="email"><br/>
<button type="submit" name="save">save</button>
</form>
</body>
</html>
A missing intermediate certificate might be the problem.
You may want to check your https://hostname with curl, openssl or a website like https://www.digicert.com/help/.
No idea why Chrome (possibly) sometimes has problems validating these certs.
Unexpected token < in JSON at position 0
A simple solution to this error is to write a comment in styles.less
file.
When you don't have a PC on hand, you could use Eruda, which is devtools for mobile browsers https://github.com/liriliri/eruda
It is provided as embeddable javascript and also a bookmarklet (pasting bookmarklet in chrome removes the javascript: prefix, so you have to type it yourself)
Based from this thread, you need to bookmark chrome://settings/languages
and then Drag and Drop the language to make it default. You have to click on the Display Google Chrome in this Language button and completely restart Chrome.
I'm using react with TypeScript and the following worked for me
wrapper.find('input').getDOMNode<HTMLInputElement>().value = 'Hello';
wrapper.find('input').simulate('change');
Setting the value directly
wrapper.find('input').instance().value = 'Hello'`
was causing me a compile warning.
It's the last selected DOM node index. Chrome assigns an index to each DOM node you select. So $0
will always point to the last node you selected, while $1
will point to the node you selected before that. Think of it like a stack of most recently selected nodes.
As an example, consider the following
<div id="sunday"></div>
<div id="monday"></div>
<div id="tuesday"></div>
Now you opened the devtools console and selected #sunday
, #monday
and #tuesday
in the mentioned order, you will get ids like:
$0 -> <div id="tuesday"></div>
$1 -> <div id="monday"></div>
$2 -> <div id="sunday"></div>
Note: It Might be useful to know that the node is selectable in your scripts (or console), for example one popular use for this is angular element selector, so you can simply pick your node, and run this:
angular.element($0).scope()
Voila you got access to node scope via console.
I just ran into this. As mentioned in this answer, using mode: "no-cors"
will give you an opaque response
, which doesn't seem to return data in the body.
opaque: Response for “no-cors” request to cross-origin resource. Severely restricted.
In my case I was using Express
. After I installed cors for Express and configured it and removed mode: "no-cors"
, I was returned a promise. The response data will be in the promise, e.g.
fetch('http://example.com/api/node', {
// mode: 'no-cors',
method: 'GET',
headers: {
Accept: 'application/json',
},
},
).then(response => {
if (response.ok) {
response.json().then(json => {
console.log(json);
});
}
});
The error is because you are including the script links at two places which will do the override and re-initialization of date-picker
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />_x000D_
_x000D_
_x000D_
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
$('.dateinput').datepicker({ format: "yyyy/mm/dd" });_x000D_
}); _x000D_
</script>_x000D_
_x000D_
<!-- Bootstrap core JavaScript_x000D_
================================================== -->_x000D_
<!-- Placed at the end of the document so the pages load faster -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
_x000D_
So exclude either src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"
or src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"
It will work..
Run all Collection in a folder in parallel:
'use strict';
global.Promise = require('bluebird');
const path = require('path');
const newman = Promise.promisifyAll(require('newman'));
const fs = Promise.promisifyAll(require('fs'));
const environment = 'postman_environment.json';
const FOLDER = path.join(__dirname, 'Collections_Folder');
let files = fs.readdirSync(FOLDER);
files = files.map(file=> path.join(FOLDER, file))
console.log(files);
Promise.map(files, file => {
return newman.runAsync({
collection: file, // your collection
environment: path.join(__dirname, environment), //your env
reporters: ['cli']
});
}, {
concurrency: 2
});
Check if you're using some Chrome extension (Night mode or something else). Disable that and see if the 'inject' gone.
You could just pass a static value (or a variable from *ngFor
or whatever)
<button (click)="toggle(1)" class="someclass">
<button (click)="toggle(2)" class="someclass">
Unchecked the content type in Postman and postman automatically detect the content type based on your input in the run time.
Our team occasionally sees this using Vue, axios and a C# WebApi. Adding a route attribute on the endpoint you're trying to hit fixes it for us.
[Route("ControllerName/Endpoint")]
[HttpOptions, HttpPost]
public IHttpActionResult Endpoint() { }
Tracing helped me find what the problem was (Thank you Fabian for that suggestion). I found with further testing that I could get the client certificate to work on another server (Windows Server 2012). I was testing this on my development machine (Window 7) so I could debug this process. So by comparing the trace to an IIS Server that worked and one that did not I was able to pinpoint the relevant lines in the trace log. Here is a portion of a log where the client certificate worked. This is the setup right before the send
System.Net Information: 0 : [17444] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [17444] SecureChannel#54718731 - We have user-provided certificates. The server has not specified any issuers, so try all the certificates.
System.Net Information: 0 : [17444] SecureChannel#54718731 - Selected certificate:
Here is what the trace log looked like on the machine where the client certificate failed.
System.Net Information: 0 : [19616] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [19616] SecureChannel#54718731 - We have user-provided certificates. The server has specified 137 issuer(s). Looking for certificates that match any of the issuers.
System.Net Information: 0 : [19616] SecureChannel#54718731 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [19616] Using the cached credential handle.
Focusing on the line that indicated the server specified 137 issuers I found this Q&A that seemed similar to my issue. The solution for me was not the one marked as an answer since my certificate was in the trusted root. The answer is the one under it where you update the registry. I just added the value to the registry key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL
Value name: SendTrustedIssuerList Value type: REG_DWORD Value data: 0 (False)
After adding this value to the registry it started to work on my Windows 7 machine. This appears to be a Windows 7 issue.
You should enable CORS to get it working.
From Chorme v81 the params --user-data-dir=
requires an actual parameter, whereas in the past it didn't.
Something like this works fine for me
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="\tmp\chrome_test"
The SSL errors are often thrown by network management software such as Cyberroam.
To answer your question,
you will have to enter badidea into Chrome every time you visit a website.
You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors
For me, as I was using pretty standard React fetch calls, this could have been fixed using some of the AWS Console and Lambda fixes above, but my Lambda returned the right headers (I was also using Proxy mode) and I needed to package my application up into a SAM Template, so I could not spend my time clicking around the console.
I noticed that all of the CORS stuff worked fine UNTIL I put Cognito Auth onto my application. I just basically went very slow doing a SAM package / SAM deploy with more and more configurations until it broke and it broke as soon as I added Auth to my API Gateway. I spent a whole day clicking around wonderful discussions like this one, looking for an easy fix, but then ended up having to actually read about what CORS was doing. I'll save you the reading and give you another easy fix (at least for me).
Here is an example of an API Gateway template that finally worked (YAML):
Resources:
MySearchApi:
Type: AWS::Serverless::Api
Properties:
StageName: 'Dev'
Cors:
AllowMethods: "'OPTIONS, GET'"
AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
AllowOrigin: "'*'"
Auth:
DefaultAuthorizer: MyCognitoSearchAuth
Authorizers:
MyCognitoSearchAuth:
UserPoolArn: "<my hardcoded user pool ARN>"
AuthType: "COGNITO_USER_POOLS"
AddDefaultAuthorizerToCorsPreflight: False
Note the AddDefaultAuthorizerToCorsPreflight at the bottom. This defaults to True if you DON'T have it in your template, as as far as I can tell from my reading. And, when True, it sort of blocks the normal OPTIONS behavior to announce what the Resource supports in terms of Allowed Origins. Once I explicitly added it and set it to False, all of my issues were resolved.
The implication is that if you are having this issue and want to diagnose it more completely, you should visit your Resources in API Gateway and check to see if your OPTIONS method contains some form of Authentication. Your GET or POST needs Auth, but if your OPTIONS has Auth enabled on it, then you might find yourself in this situation. If you are clicking around the AWS console, then try removing from OPTIONS, re-deploy, then test. If you are using SAM CLI, then try my fix above.
I was having the same issue, if you have enabled Display intranet sites in Compatibility View the polyfills.ts won't work, you still need to add the following line as has been told.
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
Me too I encountered this issue.
The only alternative is to define a width (or max-width) in the child elements. IE 11 is a bit stupid, and me I just spent 20 minutes to realize this solution.
.parent {
display: flex;
flex-direction: column;
width: 800px;
border: 1px solid red;
align-items: center;
}
.child {
border: 1px solid blue;
max-width: 800px;
@media (max-width:960px){ // <--- Here we go. The text won't wrap ? we will make it break !
max-width: 600px;
}
@media (max-width:600px){
max-width: 400px;
}
@media (max-width:400px){
max-width: 150px;
}
}
<div class="parent">
<div class="child">
Lorem Ipsum is simply dummy text of the printing and typesetting industry
</div>
<div class="child">
Lorem Ipsum is simply dummy text of the printing and typesetting industry
</div>
</div>
try FileSaver.js
library. it might help.
Selenium 4 is already included this feature now, you can directly
open new Tab or new Window with any URL.
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver(options);
driver.get("www.Url1.com");
// below code will open Tab for you as well as switch the control to new Tab
driver.switchTo().newWindow(WindowType.TAB);
// below code will navigate you to your desirable Url
driver.get("www.Url2.com");
download Maven dependencies, this is what I downloaded -
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>3.7.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
you can refer: https://codoid.com/selenium-4-0-command-to-open-new-window-tab/
watch video : https://www.youtube.com/watch?v=7SpCMkUKq-Y&t=8s
google out for - WebDriverManager selenium 4
This question are greatly described here
https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
TL;DR You are still always able to autoplay muted
videos
Also, if you're want to autoplay videos on iOS add playsInline
attribute, because by default iOS tries to fullscreen videos
https://webkit.org/blog/6784/new-video-policies-for-ios/
We call it the "ant" menu. Guess it was a good time to change since everyone had just gotten used to the hamburger.
Here is how to do a quick check to see if n.fn.init[0]
is caused by your DOM-elements not loading in time. Delay your selector function by wrapping it in setTimeout
function like this:
function timeout(){
...your selector function that returns n.fn.init[0] goes here...
}
setTimeout(timeout, 5000)
This will cause your selector function to execute with a 5 second delay, which should be enough for pretty much anything to load.
This is just a coarse hack to check if DOM is ready for your selector function or not. This is not a (permanent) solution.
The preferred ways to check if the DOM is loaded before executing your function are as follows:
1) Wrap your selector function in
$(document).ready(function(){ ... your selector function... };
2) If that doesn't work, use DOMContentLoaded
3) Try window.onload, which waits for all the images to load first, so its least preferred
window.onload = function () { ... your selector function... }
4) If you are waiting for a library to load that loads in several steps or has some sort of delay of its own, then you might need some complicated custom solution. This is what happened to me with "MathJax" library. This question discusses how to check when MathJax library loaded its DOM elements, if it is of any help.
5) Finally, you can stick with hard-coded setTimeout
function, making it maybe 1-3 seconds. This is actually the very least preferred method in my opinion.
This list of fixes is probably far from perfect so everyone is welcome to edit it.
If your are using Chrome, try adding an opentype (OTF) version of your font as shown below:
...
url('icomoon.otf') format('opentype'),
...
Cheers!
As with @user3006381 above, my issue was not just relative URLs but that webpack was placing the files as if they were javascript files. Their contents were all basically:
module.exports = __webpack_public_path__ + "7410dd7fd1616d9a61625679285ff5d4.eot";
in the fonts directory instead of the real fonts and the font files were in the output folder under hash codes. To fix this, I had to change the test on my url-loader (in my case my image processor) to not load the fonts folder. I still had to set output.publicPath in webpack.config.js as @will-madden notes in his excellent answer.
In case of Request to a REST Service:
You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:
@CrossOrigin(origins = "http://localhost:8080")
Very good tutorial: https://spring.io/guides/gs/rest-service-cors/
As of now, Postman comes with its own "Console." Click the terminal-like icon on the bottom left to open the console. Send a request, and you can inspect the request from within Postman's console.
Javier covered Notifications and current limitations.
My suggestion: window.postMessage
while we wait for the handicapped browser to catch up, else Worker.postMessage()
to still be operating with Web Workers.
These can be the fallback option with dialog box message display handler, for when a Notification feature test fails or permission is denied.
Notification has-feature and denied-permission check:
if (!("Notification" in window) || (Notification.permission === "denied") ) {
// use (window||Worker).postMessage() fallback ...
}
I had the same error, though the problem was that I had a typo in the url
url: 'http://api.example.com/TYPO'
The API had a redirect to another domain for all URL's that is wrong (404 errors).
So fixing the typo to the correct URL fixed it for me.
I have had a similar issue in iOS 8, 9 and 10 and the info above couldn't fix it, however I did discover a solution after a day of working on this. Granted it won't work for everyone but in my case my items were stacked in a column and had 0 height when it should have been content height. Switching the css to be row and wrap fixed the issue. This only works if you have a single item and they are stacked but since it took me a day to find this out I thought I should share my fix!
.wrapper {
flex-direction: column; // <-- Remove this line
flex-direction: row; // <-- replace it with
flex-wrap: wrap; // <-- Add wrapping
}
.item {
width: 100%;
}
Similar to @??? I had the wrong application type configured for a dll. I guess that the project type changed due to some bad copy pasting, as @Daniel Struhl suggested.
How to verify:
Right click on the project -> properties
-> Configuration Properties
-> General
-> Project Defaults
-> Configuration Type
.
Check if this field contains the correct type, e.g. "Dynamic Library (.dll)" in case the project is a dll.
I encounter same error, and incognito mode also has same issue. I resolve this issue by clear Chrome history.
As far as I can tell, this is currently not possible - a cast is always needed.
To make it possible, the .d.ts of react would need to be modified so that the signature of the onChange of a SELECT element used a new SelectFormEvent. The new event type would expose target, which exposes value. Then the code could be typesafe.
Otherwise there will always be the need for a cast to any.
I could encapsulate all that in a MYSELECT tag.
You can try to use the parameter "enable-automation"
var options = new ChromeOptions();
// hide selenium
options.AddExcludedArguments(new List<string>() { "enable-automation" });
var driver = new ChromeDriver(ChromeDriverService.CreateDefaultService(), options);
But, I want to warn that this ability was fixed in ChromeDriver 79.0.3945.16. So probably you should use older versions of chrome.
Also, as another option, you can try using InternetExplorerDriver instead of Chrome. As for me, IE does not block at all without any hacks.
And for more info try to take a look here:
Selenium webdriver: Modifying navigator.webdriver flag to prevent selenium detection
Unable to hide "Chrome is being controlled by automated software" infobar within Chrome v76
With a React Native running in the emulator,
Press ctrl+m (for Linux, I suppose it's the same for Windows and ?+m for Mac OS X)
or run the following in terminal:
adb shell input keyevent 82
As stated in this answer not all browsers support the standard way. It is not a good idea to use for robust user experience. And if you use it, you cannot ask too much.
Instead use time-picker libraries. For example: TimePicker.js is a zero dependency and lightweight library. Use it like:
var timepicker = new TimePicker('time', {_x000D_
lang: 'en',_x000D_
theme: 'dark'_x000D_
});_x000D_
timepicker.on('change', function(evt) {_x000D_
_x000D_
var value = (evt.hour || '00') + ':' + (evt.minute || '00');_x000D_
evt.element.value = value;_x000D_
_x000D_
});
_x000D_
<script src="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>_x000D_
<link href="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div>_x000D_
<input type="text" id="time" placeholder="Time">_x000D_
</div>
_x000D_
This answer is for complete AWS beginners:
I had this issue but it was because I was trying to run a command from a tutorial inside my Mac computer. What I actually needed to do was SSH into my AWS machine, and then run the same command there. Ta Da, it worked:
Click this button in your EC2 instance, to be able to copy the SSH command. setup your SSH keys https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html and then you can SSH into your machine
Once here, you can run your sudo apt-get
command.
Hope this helps other beginners
OK, here is one solution I have come up with which is pretty messed up.
I put the full label text into the div using the fontFamily label attribute. Then I use querySelectorAll to match the resulting style attributes to pull out the refs and rewrite the tags once the map has loaded:
var label = "A123";
var marker = new google.maps.Marker({
position: latLon,
label: {
text: label,
// Add in the custom label here
fontFamily: 'Roboto, Arial, sans-serif, custom-label-' + label
},
map: map,
icon: {
path: 'custom icon path',
fillColor: '#000000',
labelOrigin: new google.maps.Point(26.5, 20),
anchor: new google.maps.Point(26.5, 43),
scale: 1
}
});
google.maps.event.addListener(map, 'idle', function() {
var labels = document.querySelectorAll("[style*='custom-label']")
for (var i = 0; i < labels.length; i++) {
// Retrieve the custom labels and rewrite the tag content
var matches = labels[i].getAttribute('style').match(/custom-label-(A\d\d\d)/);
labels[i].innerHTML = matches[1];
}
});
This seems pretty brittle. Are there any approaches which are less awful?
This error means that file was not found. Either path is wrong or file is not present where you want it to be. Try to access it by entering source address in your browser to check if it really is there. Browse the directories on server to ensure the path is correct. You may even copy and paste the relative path to be certain it is alright.
In my case, I've just downloaded the missing file directly from here: https://gitlab.com/mailman/mailman-website/raw/a97d6b4c5b29594004e3855f1ab1222449d0c211/content/fonts/glyphicons-halflings-regular.woff2
Just set the path variable to JDK bin in environment variables.
Variable Name : PATH
Variable Value : C:\Program Files\Java\jdk1.8.0_31\bin
But the best practice is to set JAVA_HOME and PATH as follow.
Variable Name : JAVA_HOME
Variable Value : C:\Program Files\Java\jdk1.8.0_31
Variable Name : PATH
Variable Value : %JAVA_HOME%\bin
ACCESS_COARSE_LOCATION
, ACCESS_FINE_LOCATION
, and WRITE_EXTERNAL_STORAGE
are all part of the Android 6.0 runtime permission system. In addition to having them in the manifest as you do, you also have to request them from the user at runtime (using requestPermissions()
) and see if you have them (using checkSelfPermission()
).
One workaround in the short term is to drop your targetSdkVersion
below 23.
But, eventually, you will want to update your app to use the runtime permission system.
For example, this activity works with five permissions. Four are runtime permissions, though it is presently only handling three (I wrote it before WRITE_EXTERNAL_STORAGE
was added to the runtime permission roster).
/***
Copyright (c) 2015 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.permmonger;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String[] INITIAL_PERMS={
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_CONTACTS
};
private static final String[] CAMERA_PERMS={
Manifest.permission.CAMERA
};
private static final String[] CONTACTS_PERMS={
Manifest.permission.READ_CONTACTS
};
private static final String[] LOCATION_PERMS={
Manifest.permission.ACCESS_FINE_LOCATION
};
private static final int INITIAL_REQUEST=1337;
private static final int CAMERA_REQUEST=INITIAL_REQUEST+1;
private static final int CONTACTS_REQUEST=INITIAL_REQUEST+2;
private static final int LOCATION_REQUEST=INITIAL_REQUEST+3;
private TextView location;
private TextView camera;
private TextView internet;
private TextView contacts;
private TextView storage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
location=(TextView)findViewById(R.id.location_value);
camera=(TextView)findViewById(R.id.camera_value);
internet=(TextView)findViewById(R.id.internet_value);
contacts=(TextView)findViewById(R.id.contacts_value);
storage=(TextView)findViewById(R.id.storage_value);
if (!canAccessLocation() || !canAccessContacts()) {
requestPermissions(INITIAL_PERMS, INITIAL_REQUEST);
}
}
@Override
protected void onResume() {
super.onResume();
updateTable();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actions, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.camera:
if (canAccessCamera()) {
doCameraThing();
}
else {
requestPermissions(CAMERA_PERMS, CAMERA_REQUEST);
}
return(true);
case R.id.contacts:
if (canAccessContacts()) {
doContactsThing();
}
else {
requestPermissions(CONTACTS_PERMS, CONTACTS_REQUEST);
}
return(true);
case R.id.location:
if (canAccessLocation()) {
doLocationThing();
}
else {
requestPermissions(LOCATION_PERMS, LOCATION_REQUEST);
}
return(true);
}
return(super.onOptionsItemSelected(item));
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
updateTable();
switch(requestCode) {
case CAMERA_REQUEST:
if (canAccessCamera()) {
doCameraThing();
}
else {
bzzzt();
}
break;
case CONTACTS_REQUEST:
if (canAccessContacts()) {
doContactsThing();
}
else {
bzzzt();
}
break;
case LOCATION_REQUEST:
if (canAccessLocation()) {
doLocationThing();
}
else {
bzzzt();
}
break;
}
}
private void updateTable() {
location.setText(String.valueOf(canAccessLocation()));
camera.setText(String.valueOf(canAccessCamera()));
internet.setText(String.valueOf(hasPermission(Manifest.permission.INTERNET)));
contacts.setText(String.valueOf(canAccessContacts()));
storage.setText(String.valueOf(hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)));
}
private boolean canAccessLocation() {
return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
}
private boolean canAccessCamera() {
return(hasPermission(Manifest.permission.CAMERA));
}
private boolean canAccessContacts() {
return(hasPermission(Manifest.permission.READ_CONTACTS));
}
private boolean hasPermission(String perm) {
return(PackageManager.PERMISSION_GRANTED==checkSelfPermission(perm));
}
private void bzzzt() {
Toast.makeText(this, R.string.toast_bzzzt, Toast.LENGTH_LONG).show();
}
private void doCameraThing() {
Toast.makeText(this, R.string.toast_camera, Toast.LENGTH_SHORT).show();
}
private void doContactsThing() {
Toast.makeText(this, R.string.toast_contacts, Toast.LENGTH_SHORT).show();
}
private void doLocationThing() {
Toast.makeText(this, R.string.toast_location, Toast.LENGTH_SHORT).show();
}
}
(from this sample project)
For the requestPermissions() function, should the parameters just be "ACCESS_COARSE_LOCATION"? Or should I include the full name "android.permission.ACCESS_COARSE_LOCATION"?
I would use the constants defined on Manifest.permission
, as shown above.
Also, what is the request code?
That will be passed back to you as the first parameter to onRequestPermissionsResult()
, so you can tell one requestPermissions()
call from another.
Postman will query Google API impersonating a Web Application
Generate an OAuth 2.0 token:
Create an OAuth 2.0 client ID
getpostman.com
to the Authorized domains. Click Save.https://www.getpostman.com/oauth2/callback
Client ID
and Client secret
fields for later useIn Postman select Authorization tab and select "OAuth 2.0" type. Click 'Get New Access Token'
https://www.getpostman.com/oauth2/callback
https://accounts.google.com/o/oauth2/auth
https://accounts.google.com/o/oauth2/token
Client ID
generated in the step 2 (e.g., '123456789012-abracadabra1234546789blablabla12.apps.googleusercontent.com')Client secret
generated in the step 2 (e.g., 'ABRACADABRAus1ZMGHvq9R-L')Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests
response header, indicating that the browser supports it (and in fact prefers it).
It took me 30mins of Googling, but I finally found it buried in the W3 spec.
The confusion comes because the header in the spec was HTTPS: 1
, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:
"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842
Their fix was to rename it to Upgrade-Insecure-Requests: 1
, and the spec has since been updated to match.
Anyway, here is the explanation from the W3 spec (as it appeared at the time)...
The
HTTPS
HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide....
When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.
When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a
Strict-Transport-Security
header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].
For any of you calling back to the same server for your IFRAME, pass this simple header inside the IFRAME page:
Content-Security-Policy: frame-ancestors 'self'
Or, add this to your web server's CSP configuration.
The webbrowser
module looks promising: https://www.youtube.com/watch?v=jU3P7qz3ZrM
import webbrowser
webbrowser.open('http://google.co.kr', new=2)
Because that's exactly how the spec says it should work. The number input can accept floating-point numbers, including negative symbols and the e
or E
character (where the exponent is the number after the e
or E
):
A floating-point number consists of the following parts, in exactly the following order:
- Optionally, the first character may be a "
-
" character.- One or more characters in the range "
0—9
".- Optionally, the following parts, in exactly the following order:
- a "
.
" character- one or more characters in the range "
0—9
"- Optionally, the following parts, in exactly the following order:
- a "
e
" character or "E
" character- optionally, a "
-
" character or "+
" character- One or more characters in the range "
0—9
".
From the documentation:
get cookie from response
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies
{'example_cookie_name': 'example_cookie_value'}
give cookie back to server on subsequent request
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)`
In my case i found better to use "string.search".
var str = "Some very very very long string";
var n = str.search("very");
In case it would be helpful for someone.
Make sure that you have made the content-type
as application/json
in header request and Post from body under the raw tab.
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay",
"arrayObjectName" : [{
"Id" : 1,
"Name": "ABC" },
{
"Id" : 2,
"Name" : "XYZ"
}],
"intArrayName" : [111,222,333],
"stringArrayName" : ["a","b","c"]
}
var seconds = 2000 ; // or "2000"
seconds = parseInt(seconds) //because moment js dont know to handle number in string format
var format = Math.floor(moment.duration(seconds,'seconds').asHours()) + ':' + moment.duration(seconds,'seconds').minutes() + ':' + moment.duration(seconds,'seconds').seconds();
The self answer given by MagngooSasa did the trick, but for anyone else trying to understand the answer, here are a few bit more details:
When developing Cordova apps with Visual Studio, I tried to import a remote JavaScript file [located here http://Guess.What.com/MyScript.js], but I have the error mentioned in the title.
Here is the meta tag before, in the index.html file of the project:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
Here is the corrected meta tag, to allow importing a remote script:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *;**script-src 'self' http://onlineerp.solution.quebec 'unsafe-inline' 'unsafe-eval';** ">
And no more error!
Delete platforms/android folder and try to rebuild. That helped me a lot.
(Visual Studio Tools for Apache Cordova)
The accepted answer didn't work for me, I had to add a value to the href attribute:
<link rel="shortcut icon" href="#" />
For Google chrome Version 56.0.2924.87 (Latest Release) cookies are found inside profile1 folder.
If you browse that you can find variety of information.
There is a separate file called "Cookies". Also the Cache folder is inside this folder.
Path : C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Profile 1
Remember to replace user_name.
For Version 61.0.3163.100
Path :
C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Default
Inside this folder there is Cookies file and Cache folder.
Basically it is a chrome plug in. After installing the extention, you also need to make sure the extention is enabled from chrome side.
As others have said startsWith and endsWith are part of ES6 and not available in IE11. Our company always uses lodash library as a polyfill solution for IE11. https://lodash.com/docs/4.17.4
_.startsWith([string=''], [target], [position=0])
I had the dependencies as specified @Greg post. I still faced the issue and could be able to resolve it by adding following additional jackson dependency:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.7.4</version>
</dependency>
Sometimes this problem happens when you upload/download the fonts using the wrong FTP method. Fonts must be FTP-ed using binary method, not ASCII. (Depending on your mood, it may feel counterintuitive, lol). If you ftp the font files using ASCII method, you can get this error message. If you ftp your files with an 'auto' method, and you get this error message, try ftp forcing the binary method.
try
ini_set('max_execution_time', $time);
$articles = Article::all();
where $time
is in seconds, set it to 0 for no time. make sure to make it 60 back after your function finish
You can add your URLs to VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification.
protected $except = [
"your url",
"your url/abc"
];
You must use an integer value for the CURLOPT_SSLVERSION
value, not a string as listed above
Try this:
curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 6); //Integer NOT string TLS v1.2
http://php.net/manual/en/function.curl-setopt.php
value should be an integer for the following values of the option parameter:
CURLOPT_SSLVERSION
One of
CURL_SSLVERSION_DEFAULT (0)
CURL_SSLVERSION_TLSv1 (1)
CURL_SSLVERSION_SSLv2 (2)
CURL_SSLVERSION_SSLv3 (3)
CURL_SSLVERSION_TLSv1_0 (4)
CURL_SSLVERSION_TLSv1_1 (5)
CURL_SSLVERSION_TLSv1_2 (6).
There is maybe a solution (but i didnt test it) : you could use CSP (Content Security Policy) to enable your remote domain and browsers will maybe skip the CORS OPTIONS request verification.
I if find some time, I will test that and update this post !
CSP : https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Content-Security-Policy
CSP Specification : https://www.w3.org/TR/CSP/
I am not sure,how you are opening popup or say model in your code. But you can try something like this..
<html ng-app="MyApp">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script type="text/javascript">
var myApp = angular.module("MyApp", []);
myApp.controller('MyController', function ($scope) {
$scope.open = function(){
var modalInstance = $modal.open({
templateUrl: '/assets/yourOpupTemplatename.html',
backdrop:'static',
keyboard:false,
controller: function($scope, $modalInstance) {
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
$scope.ok = function () {
$modalInstance.close();
};
}
});
}
});
</script>
</head>
<body ng-controller="MyController">
<button class="btn btn-primary" ng-click="open()">Test Modal</button>
<!-- Confirmation Dialog -->
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="cancel()">No</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
</div>
</div>
</div>
</div>
<!-- End of Confirmation Dialog -->
</body>
</html>
I had the same problem with my application. My project uses DevOps and The problem was because of the unhealthy computes. Replacing them fixed the issue for me
Using PHP i've found a quite simple way to do this. Guys, Just Use something like this
<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
<datalist id="customers">
<?php
$querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
$resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());
while ($row_this = mysqli_fetch_array($resultSnamex)) {
echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
<input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
}
?>
</datalist>
The Code Above lets the form carry the id of the option also selected.
I see the discussions still talk about the old way of setting up chromedriver by downloading the binary and configuring the path manually.
This can be done automatically using webdriver-manager
pip install webdriver-manager
Now the above code in the question will work simply with below change,
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
The same can be used to set Firefox, Edge and ie binaries.
When using GetAsync with the HttpClient you can add the authorization headers like so:
httpClient.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", "Your Oauth token");
This does add the authorization header for the lifetime of the HttpClient so is useful if you are hitting one site where the authorization header doesn't change.
Here is an detailed SO answer
This is related to Content-Type
. As you might have noticed from other discussions and answers to this question some people were able to solve it by setting Content-Type: 'application/json'
. Unfortunately in my case it didn't work, my POST request was still empty on the server side.
However, if you try with jQuery's $.post()
and it's working, the reason is probably because of jQuery using Content-Type: 'x-www-form-urlencoded'
instead of application/json
.
data = Object.keys(data).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])).join('&')
fetch('/api/', {
method: 'post',
credentials: "include",
body: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
Replace
<a href="http://www.foracure.org.au" target="_blank"></a>
with
<a href="#" onclick='window.open("http://www.foracure.org.au");return false;'></a>
in your code and will work in Chrome and other browsers.
Thanks Anurag
on Mac edit .bash_profile use code or vim
code ~/.bash_profile
export ANDROID_SDK_ROOT=~/Library/Android/sdk
export ANDROID_HOME=~/Library/Android/sdk
Update
As of jQuery 3.0, the new syntax is just .on:
see this answer here and the code:
$('iframe').on('load', function() {
// do stuff
});
This comes from the official site of Chome-devtools and it helps. Here i quote:
- Queuing If a request is queued it indicated that:
- The request was postponed by the rendering engine because it's considered lower priority than critical resources (such as scripts/styles). This often happens with images.
- The request was put on hold to wait for an unavailable TCP socket that's about to free up.
- The request was put on hold because the browser only allows six TCP connections per origin on HTTP 1. Time spent making disk cache entries (typically very quick.)
- Stalled/Blocking Time the request spent waiting before it could be sent. It can be waiting for any of the reasons described for Queueing. Additionally, this time is inclusive of any time spent in proxy negotiation.
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
5 years have passed and this essential requirement didn't get ignored by the Chrome devs.
While they offer no method to edit the data like in Firefox, they offer a full XHR replay.
This allows to debug ajax calls.
"Replay XHR" will repeat the entire transmission.
If you need to set the user header string in the curl request, you can use the -H
option to set user agent like:
curl -H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36" http://stackoverflow.com/questions/28760694/how-to-use-curl-to-get-a-get-request-exactly-same-as-using-chrome
Updated user-agent form newest Chrome at 02-22-2021
Using a proxy tool like Charles Proxy really helps make short work of something like what you are asking. Here is what I do, using this SO page as an example (as of July 2015 using Charles version 3.10):
You now have a cURL request you can run in a terminal that will mirror the request your browser made. Here is what my request to this page looked like (with the cookie header removed):
curl -H "Host: stackoverflow.com" -H "Cache-Control: max-age=0" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36" -H "HTTPS: 1" -H "DNT: 1" -H "Referer: https://www.google.com/" -H "Accept-Language: en-US,en;q=0.8,en-GB;q=0.6,es;q=0.4" -H "If-Modified-Since: Thu, 23 Jul 2015 20:31:28 GMT" --compressed http://stackoverflow.com/questions/28760694/how-to-use-curl-to-get-a-get-request-exactly-same-as-using-chrome
To open the Eye Dropper simply:
Its main functionality is to inspect pixel color values by clicking them though with its new features you can also see your page's existing colors palette or material design palette by clicking on the two arrows icon at the bottom. It can get quite handy when designing your page.
window.scrollTo(0,1);
this will help you but this javascript is may not work in all browsers
If you are using PHP, try using <?php flush(); ?>
after </head>
and before </body>
or whatever section you want to output quickly (like the header or content). It will output the actually code without waiting for php to end. Don't use this function all the time, or the speed increase won't be noticable.
When you call a Linq statement like this:
// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));
You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:
var count = Enumerable.Count(x, s => s.StartsWith("x"));
So the error you are getting above is because the first parameter, source
(which would be x
in the sample above) is null.
This can occur on android too not just computers. Was browsing using Kiwi when the site I was on began to endlessly redirect so I cut net access to close it out and noticed my phone had DL'd something f.txt
in my downloaded files.
Deleted it and didn't open.
In my case this was caused by the flexie script which was part of the "CDNJS Selections" app offered by Cloudflare.
According to Cloudflare "This app is being deprecated in March 2015". I turned it off and the message disappeared instantly.
You can access the apps by visiting https://www.cloudflare.com/a/cloudflare-apps/yourdomain.com
Add type="text/babel"
to the script that includes the .jsx file and add this: <script src="https://npmcdn.com/[email protected]/browser.min.js"></script>
If you wanted to pre-process your DOCX files, rather than waiting until runtime you could convert them into HTML first by using a file conversion API such as Zamzar. You could use the API to programatically convert from DOCX to HMTL, save the output to your server and then serve that HTML up to your end users.
Conversion is pretty easy:
curl https://api.zamzar.com/v1/jobs \
-u API_KEY: \
-X POST \
-F "[email protected]" \
-F "target_format=html5"
This would remove any runtime dependencies on Google & Microsoft's services (for example if they were down, or you were rate limited by them).
It also has the benefit that you could extend to other filetypes if you wanted (PPTX, XLS, DOC etc)
Visibility is an animatable property according to the spec, but transitions on visibility do not work gradually, as one might expect. Instead transitions on visibility delay hiding an element. On the other hand making an element visible works immediately. This is as it is defined by the spec (in the case of the default timing function) and as it is implemented in the browsers.
This also is a useful behavior, since in fact one can imagine various visual effects to hide an element. Fading out an element is just one kind of visual effect that is specified using opacity. Other visual effects might move away the element using e.g. the transform property, also see http://taccgl.org/blog/css-transition-visibility.html
It is often useful to combine the opacity transition with a visibility transition! Although opacity appears to do the right thing, fully transparent elements (with opacity:0) still receive mouse events. So e.g. links on an element that was faded out with an opacity transition alone, still respond to clicks (although not visible) and links behind the faded element do not work (although being visible through the faded element). See http://taccgl.org/blog/css-transition-opacity-for-fade-effects.html.
This strange behavior can be avoided by just using both transitions, the transition on visibility and the transition on opacity. Thereby the visibility property is used to disable mouse events for the element while opacity is used for the visual effect. However care must be taken not to hide the element while the visual effect is playing, which would otherwise not be visible. Here the special semantics of the visibility transition becomes handy. When hiding an element the element stays visible while playing the visual effect and is hidden afterwards. On the other hand when revealing an element, the visibility transition makes the element visible immediately, i.e. before playing the visual effect.
I just spent the morning dealing with this. The problem wasn't that I had a certificate missing. It was that I had an extra.
I started out with my ssl.conf containing my server key and three files provided by my SSL certificate authority:
# Server Certificate:
SSLCertificateFile /etc/pki/tls/certs/myserver.cer
# Server Private Key:
SSLCertificateKeyFile /etc/pki/tls/private/myserver.key
# Server Certificate Chain:
SSLCertificateChainFile /etc/pki/tls/certs/AddTrustExternalCARoot.pem
# Certificate Authority (CA):
SSLCACertificateFile /etc/pki/tls/certs/InCommonServerCA.pem
It worked fine on desktops, but Chrome on Android gave me err_cert_authority_invalid
A lot of headaches, searching and poor documentation later, I figured out that it was the Server Certificate Chain:
SSLCertificateChainFile /etc/pki/tls/certs/AddTrustExternalCARoot.pem
That was creating a second certificate chain which was incomplete. I commented out that line, leaving me with
# Server Certificate:
SSLCertificateFile /etc/pki/tls/certs/myserver.cer
# Server Private Key:
SSLCertificateKeyFile /etc/pki/tls/private/myserver.key
# Certificate Authority (CA):
SSLCACertificateFile /etc/pki/tls/certs/InCommonServerCA.pem
and now it's working on Android again. This was on Linux running Apache 2.2.
The Reason
You are not opening the page through a server, like Apache, so when the browser tries to obtain the resource it thinks it is from a separate domain, which is not allowed. Though some browsers do allow it.
The Solution
Run inetmgr and host your page locally and browse as http://localhost:portnumber/PageName.html or through a web server like Apache, nginx, node etc.
Alternatively use a different browser No error was shown when directly opening the page using Firefox and Safari. It comes only for Chrome and IE(xx).
If you are using code editors like Brackets, Sublime or Notepad++, those apps handle this error automatically.
The root of the answer is that the person asking the question needs to have a JavaScript interpreter to get what they are after. What I have found is I am able to get all of the information I wanted on a website in json before it was interpreted by JavaScript. This has saved me a ton of time in what would be parsing html hoping each webpage is in the same format.
So when you get a response from a website using requests really look at the html/text because you might find the javascripts JSON in the footer ready to be parsed.
"C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe"
.Paste the value into Location of the item, and append --kiosk <your url>
:
"C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe" --kiosk http://www.google.com
Press Apply, then OK.
When I tried @PaulSamsotha's solution with Jersey client 2.21.1, there was 400 error. It worked when I added following in my client code:
MediaType contentType = MediaType.MULTIPART_FORM_DATA_TYPE;
contentType = Boundary.addBoundary(contentType);
Response response = t.request()
.post(Entity.entity(multipartEntity, contentType));
instead of hardcoded MediaType.MULTIPART_FORM_DATA
in POST request call.
The reason this is needed is because when you use a different Connector (like Apache) for the Jersey Client, it is unable to alter outbound headers, which is required to add a boundary to the Content-Type. This limitation is explained in the Jersey Client docs. So if you want to use a different Connector, then you need to manually create the boundary.
I tried changing year
to a different term, and it worked.
public_methods : {
get: function() {
return this._year;
},
set: function(newValue) {
if(newValue > this.originYear) {
this._year = newValue;
this.edition += newValue - this.originYear;
}
}
}
I was having the same problem with 3 of 4 inline svgs I was using, and they only disappeared (in one case, partially) on IE11.
I had <meta http-equiv="x-ua-compatible" content="ie=edge">
on the page.
In the end, the problem was extra clipping paths on the svg file. I opened the files on Illustrator, removed the clipping path (normally at the bottom of the layers) and now they're all working.
Internet explorer has a reset to factory button and luckily so does chrome! try the link below and let us know. the other option is to stop chrome and delete the c:\users\%username%\appdata\local\google folder entirely then reinstall chrome but this will loose all you local settings and data.
Google doc on how to factory reset: https://support.google.com/chrome/answer/3296214?hl=en
Here is the formula
create a new rule in conditional formating based on a formula. Use the following formula and apply it to $A:$A
=NOT(ISERROR(MATCH(A1,$B$1:$B$1000,0)))
here is the example sheet to download if you encounter problems
UPDATE
here is @pnuts's suggestion which works perfect as well:
=MATCH(A1,B:B,0)>0
Create openssl.conf
file:
[req]
default_bits = 2048
default_keyfile = oats.key
encrypt_key = no
utf8 = yes
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = US
ST = Cary
L = Cary
O = BigCompany
CN = *.myserver.net
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = myserver.net
DNS.2 = *.myserver.net
Run this comand:
openssl req -x509 -sha256 -nodes -days 3650 -newkey rsa:2048 -keyout app.key -out app.crt -config openssl.conf
Output files app.crt
and app.key
work for me.
Around 1:51 in the video, notice how she puts a <script>
tag in there? The way it works is like this:
Create an html file (that's just a text file with a .html
ending) somewhere on your computer. In the same folder that you put index.html
, put a javascript file (that's just a textfile with a .js
ending - let's call it game.js
). Then, in your index.html
file, put some html that includes the script tag with game.js
, like Mary did in the video. index.html
should look something like this:
<html>
<head>
<script src="game.js"></script>
</head>
</html>
Now, double click on that file in finder, and it should open it up in your browser. To open up the console to see the output of your javascript code, hit Command-alt-j (those three buttons at the same time).
Good luck on your journey, hope it's as fun for you as it has been for me so far :)
In my case, the setting was HKEY_CURRENT_USER\Software\Policies\Google\Chrome
I deleted Chrome
and everything is fine now.
Found the solution after some searching.
You need to add a <meta>
tag in your <head>
containing name="theme-color"
, with your HEX code as the content value. For example:
<meta name="theme-color" content="#999999" />
If the android device has native dark-mode
enabled, then this meta
tag is ignored.
Chrome for Android does not use the color on devices with native
dark-mode
enabled.
By default Spring OAuth requires basic HTTP authentication. If you want to switch it off with Java based configuration, you have to allow form authentication for clients like this:
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.allowFormAuthenticationForClients();
}
}
multipart/form-data
Note. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.
Please consult the appendix for information about security issues for forms.
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
The content type "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of "multipart/form-data" is available at the [IANA] registry.
A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.
As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows:
Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by
%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A').
The control names/values are listed in the order they appear in the document. The name is separated from the value by
=' and name/value pairs are separated from each other by `&'.
application/x-www-form-urlencoded
the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:
MyVariableOne=ValueOne&MyVariableTwo=ValueTwo
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
You can get the port number by using server.address().port
like in below code:
var http = require('http');
var serverFunction = function (req, res) {
if (req.url == '/') {
console.log('get method');
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('Hello World');
}
}
var server = http.createServer(serverFunction);
server.listen(3002, function () {
console.log('server is listening on port:', server.address().port);
});
If you want to concatenate the input, then replace printf("%s\n", buffer);
with strcat(big_buffer, buffer);
. Also create and initialize the big buffer at the beginning: char *big_buffer = new char[BIG_BUFFERSIZE];
big_buffer[0] = '\0';
. You should also prevent a buffer overrun by verifying the current buffer length plus the new buffer length does not exceed the limit: if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
. The modified program would look like this:
#include <stdio.h>
#include <string.h>
#define BUFFERSIZE 10
#define BIG_BUFFERSIZE 1024
int main (int argc, char *argv[])
{
char buffer[BUFFERSIZE];
char *big_buffer = new char[BIG_BUFFERSIZE];
big_buffer[0] = '\0';
printf("Enter a message: \n");
while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
{
if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
{
strcat(big_buffer, buffer);
}
}
return 0;
}
First you can use a Paginator. This is as simple as:
$allUsers = User::paginate(15);
$someUsers = User::where('votes', '>', 100)->paginate(15);
The variables will contain an instance of Paginator class. all of your data will be stored under data
key.
Or you can do something like:
Old versions Laravel.
Model::all()->take(10)->get();
Newer version Laravel.
Model::all()->take(10);
For more reading consider these links:
I also agree with the OP that all these things should come with Python already set. I guess we will have to deal with it until that day comes. Here is a solution that actually worked for me :
installing easy_install faster and easier
I hope it helps you or anyone with the same problem!
I take it from your question that your hover effect changes the content of your page. In that case, my advice is to:
touchstart
and mouseenter
.mouseleave
, touchmove
and click
.Alternatively, you can edit your page that there is no content change.
In order to simulate a mouse, browsers such as Webkit mobile fire the following events if a user touches and releases a finger on touch screen (like iPad) (source: Touch And Mouse on html5rocks.com):
touchstart
touchmove
touchend
mouseover
mouseenter
mouseover
, mouseenter
or mousemove
event changes the page content, the following events are never fired.mousemove
mousedown
mouseup
click
It does not seem possible to simply tell the webbrowser to skip the mouse events.
What's worse, if a mouseover event changes the page content, the click event is never fired, as explained on Safari Web Content Guide - Handling Events, in particular figure 6.4 in One-Finger Events. What exactly a "content change" is, will depend on browser and version. I've found that for iOS 7.0, a change in background color is not (or no longer?) a content change.
To recap:
touchstart
and mouseenter
.mouseleave
, touchmove
and click
.Note that there is no action on touchend
!
This clearly works for mouse events: mouseenter
and mouseleave
(slightly improved versions of mouseover
and mouseout
) are fired, and add and remove the hover.
If the user actually click
s a link, the hover effect is also removed. This ensure that it is removed if the user presses the back button in the web browser.
This also works for touch events: on touchstart the hover effect is added. It is '''not''' removed on touchend. It is added again on mouseenter
, and since this causes no content changes (it was already added), the click
event is also fired, and the link is followed without the need for the user to click again!
The 300ms delay that a browser has between a touchstart
event and click
is actually put in good use because the hover effect will be shown during this short time.
If the user decides to cancel the click, a move of the finger will do so just as normal. Normally, this is a problem since no mouseleave
event is fired, and the hover effect remains in place. Thankfully, this can easily be fixed by removing the hover effect on touchmove
.
That's it!
Note that it is possible to remove the 300ms delay, for example using the FastClick library, but this is out of scope for this question.
I've found the following problems with the following alternatives:
touchend
: This will incorrectly follow the link, even if the user only wanted to scroll or zoom, without the intention of actually clicking the link.touchend
that is used as a if-condition in subsequent mouse events to prevents state changes at that point in time. The variable is reset in the click event. See Walter Roman's answer on this page. This is a decent solution if you really don't want a hover effect on touch interfaces. Unfortunately, this does not work if a touchend
is fired for another reason and no click event is fired (e.g. the user scrolled or zoomed), and is subsequently trying to following the link with a mouse (i.e on a device with both mouse and touch interface).mouseover
or mousemove
event.Just add this to the page and no other worries, will handle rest for you:
$('input').live('click mousedown mouseup focus keydown change blur', function(e) {
console.log(e);
});
You can also use console.log('Input event:' + e.type) to make it easier.
To use the Like Button and have the Open Graph inspect your website, you need an application.
So you need to associate the Like Button with a fb:app_id
If you want other users to see the administration page for your website on Facebook you add fb:admins
. So if you are the developer of the application and the website owner there is no need to add fb:admins
Try this listeners=PLAINTEXT://localhost:9092 It must be helpful
Many thanks
Try adding a Closing event to the window. Add this code to the event handler.
e.Cancel = true;
This will prevent the window from closing. This has the same effect as hiding the close button.
You can avoid having your filename embedded in the NUMOFLINES variable by using redirection from JAVA_TAGS_FILE, rather than passing the filename as an argument to wc. For example:
NUMOFLINES=$(wc -l < "$JAVA_TAGS_FILE")
The wc utility will not print the name of the file in its output if input is taken from a pipe or redirection operator. Consider these various examples:
# wc shows filename when the file is an argument
$ wc -l /etc/passwd
41 /etc/passwd
# filename is ignored when piped in on standard input
$ cat /etc/passwd | wc -l
41
# unusual redirection, but wc still ignores the filename
$ < /etc/passwd wc -l
41
# typical redirection, taking standard input from a file
$ wc -l < /etc/passwd
41
As you can see, the only time wc will print the filename is when its passed as an argument, rather than as data on standard input. In some cases, you may want the filename to be printed, so it's useful to understand when it will be displayed.
This one worked for me
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
Button1_Click
End If
End Sub
using System;
using System.IO;
class Test
{
public static void Main()
{
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
Console.WriteLine("Drive {0}", d.Name);
Console.WriteLine(" Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
Console.WriteLine(" Volume label: {0}", d.VolumeLabel);
Console.WriteLine(" File system: {0}", d.DriveFormat);
Console.WriteLine(
" Available space to current user:{0, 15} bytes",
d.AvailableFreeSpace);
Console.WriteLine(
" Total available space: {0, 15} bytes",
d.TotalFreeSpace);
Console.WriteLine(
" Total size of drive: {0, 15} bytes ",
d.TotalSize);
}
}
}
}
/*
This code produces output similar to the following:
Drive A:\
Drive type: Removable
Drive C:\
Drive type: Fixed
Volume label:
File system: FAT32
Available space to current user: 4770430976 bytes
Total available space: 4770430976 bytes
Total size of drive: 10731683840 bytes
Drive D:\
Drive type: Fixed
Volume label:
File system: NTFS
Available space to current user: 15114977280 bytes
Total available space: 15114977280 bytes
Total size of drive: 25958948864 bytes
Drive E:\
Drive type: CDRom
The actual output of this code will vary based on machine and the permissions
granted to the user executing it.
*/
List<WebElement> wb=driver.findElements(By.xpath(newXpath));
for(WebElement we: wb){
if(we.isDisplayed() && we.isEnabled())
{
we.click();
break;
}
}
}
Another and easy way using cat command
cat filename | awk '{print $2,$3,$4,$5,$6,$1}' > newfilename
You may try this way. just use a function to get your object
def get_object(self, id):
try:
return Comment.objects.get(pk=id)
except Comment.DoesNotExist:
return False
With Java 7 or above you could use
ThreadLocalRandom.current().nextInt(int origin, int bound)
Javadoc: ThreadLocalRandom.nextInt
Although not secure, (no offense or anything), just stick the header function after you set the session variable
while($row = mysql_fetch_assoc($result))
{
$_SESSION["user"] = $username;
}
header('Location: /profile.php');
In your button1_click function you are using '==' for button2.Enabled == true;
This should be button2.Enabled = true;
Here's what I do:
Generate a hidden iFrame with the data you would like to post. Since you still control that iFrame, same origin does not apply. Then submit the form in that iFrame to the ssl page. The ssl page then redirects to a non-ssl page with status messages. You have access to the iFrame.
This is to help anyone who comes here looking for a solution that wants a pure approach. I would recommend understanding this problem because it can happen in lots of different places not just with a JS Buffer object. By understanding why the problem exists and how to solve it you will improve your ability to solve other problems in the future since this one is so fundamental.
For those of us that have to deal with these problems in other languages it is quite natural to devise a solution, but there are people who may not realize how to abstract away the complexities and implement a generally efficient dynamic buffer. The code below may have potential to be optimized further.
I have left the read method unimplemented to keep the example small in size.
The realloc
function in C (or any language dealing with intrinsic allocations) does not guarantee that the allocation will be expanded in size with out moving the existing data - although sometimes it is possible. Therefore most applications when needing to store a unknown amount of data will use a method like below and not constantly reallocate, unless the reallocation is very infrequent. This is essentially how most file systems handle writing data to a file. The file system simply allocates another node and keeps all the nodes linked together, and when you read from it the complexity is abstracted away so that the file/buffer appears to be a single contiguous buffer.
For those of you who wish to understand the difficulty in just simply providing a high performance dynamic buffer you only need to view the code below, and also do some research on memory heap algorithms and how the memory heap works for programs.
Most languages will provide a fixed size buffer for performance reasons, and then provide another version that is dynamic in size. Some language systems opt for a third-party system where they keep the core functionality minimal (core distribution) and encourage developers to create libraries to solve additional or higher level problems. This is why you may question why a language does not provide some functionality. This small core functionality allows costs to be reduced in maintaining and enhancing the language, however you end up having to write your own implementations or depending on a third-party.
var Buffer_A1 = function (chunk_size) {
this.buffer_list = [];
this.total_size = 0;
this.cur_size = 0;
this.cur_buffer = [];
this.chunk_size = chunk_size || 4096;
this.buffer_list.push(new Buffer(this.chunk_size));
};
Buffer_A1.prototype.writeByteArrayLimited = function (data, offset, length) {
var can_write = length > (this.chunk_size - this.cur_size) ? (this.chunk_size - this.cur_size) : length;
var lastbuf = this.buffer_list.length - 1;
for (var x = 0; x < can_write; ++x) {
this.buffer_list[lastbuf][this.cur_size + x] = data[x + offset];
}
this.cur_size += can_write;
this.total_size += can_write;
if (this.cur_size == this.chunk_size) {
this.buffer_list.push(new Buffer(this.chunk_size));
this.cur_size = 0;
}
return can_write;
};
/*
The `data` parameter can be anything that is array like. It just must
support indexing and a length and produce an acceptable value to be
used with Buffer.
*/
Buffer_A1.prototype.writeByteArray = function (data, offset, length) {
offset = offset == undefined ? 0 : offset;
length = length == undefined ? data.length : length;
var rem = length;
while (rem > 0) {
rem -= this.writeByteArrayLimited(data, length - rem, rem);
}
};
Buffer_A1.prototype.readByteArray = function (data, offset, length) {
/*
If you really wanted to implement some read functionality
then you would have to deal with unaligned reads which could
span two buffers.
*/
};
Buffer_A1.prototype.getSingleBuffer = function () {
var obuf = new Buffer(this.total_size);
var cur_off = 0;
var x;
for (x = 0; x < this.buffer_list.length - 1; ++x) {
this.buffer_list[x].copy(obuf, cur_off);
cur_off += this.buffer_list[x].length;
}
this.buffer_list[x].copy(obuf, cur_off, 0, this.cur_size);
return obuf;
};
the html element break line depend of it's white-space
style property.
in the most of the elements the default white-space
is auto
, which mean break line when the text come to the width of the element.
if you want the text break by \n
you have to give to the parent element the style:
white space: pre-line
, which will read the \n
and break the line, or
white-space: pre
which will also read \t
etc.
note: to write \n
as break-line and not as a string , you have to use a double quoted string ("\n"
)
if you not wanna use a white space, you always welcome to use the HTML Element for break line, which is <br/>
I think the best option in Terms of performance (or in any terms) is to Distinct using the The IEqualityComparer interface.
Although implementing each time a new comparer for each class is cumbersome and produces boilerplate code.
So here is an extension method which produces a new IEqualityComparer on the fly for any class using reflection.
Usage:
var filtered = taskList.DistinctBy(t => t.TaskExternalId).ToArray();
Extension Method Code
public static class LinqExtensions
{
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
{
GeneralPropertyComparer<T, TKey> comparer = new GeneralPropertyComparer<T,TKey>(property);
return items.Distinct(comparer);
}
}
public class GeneralPropertyComparer<T,TKey> : IEqualityComparer<T>
{
private Func<T, TKey> expr { get; set; }
public GeneralPropertyComparer (Func<T, TKey> expr)
{
this.expr = expr;
}
public bool Equals(T left, T right)
{
var leftProp = expr.Invoke(left);
var rightProp = expr.Invoke(right);
if (leftProp == null && rightProp == null)
return true;
else if (leftProp == null ^ rightProp == null)
return false;
else
return leftProp.Equals(rightProp);
}
public int GetHashCode(T obj)
{
var prop = expr.Invoke(obj);
return (prop==null)? 0:prop.GetHashCode();
}
}
You didn't mention the fancy indexing capabilities of dataframes, e.g.:
>>> df = pd.DataFrame({"class":[1,1,1,2,2], "value":[1,2,3,4,5]})
>>> df[df["class"]==1].sum()
class 3
value 6
dtype: int64
>>> df[df["class"]==1].sum()["value"]
6
>>> df[df["class"]==1].count()["value"]
3
You could replace df["class"]==1
by another condition.
I think this is what you're looking for. NEW_BAL
is the sum of QTY
s subtracted from the balance:
SELECT master_table.ORDERNO,
master_table.ITEM,
SUM(master_table.QTY),
stock_bal.BAL_QTY,
(stock_bal.BAL_QTY - SUM(master_table.QTY)) AS NEW_BAL
FROM master_table INNER JOIN
stock_bal ON master_bal.ITEM = stock_bal.ITEM
GROUP BY master_table.ORDERNO,
master_table.ITEM
If you want to update the item balance with the new balance, use the following:
UPDATE stock_bal
SET BAL_QTY = BAL_QTY - (SELECT SUM(QTY)
FROM master_table
GROUP BY master_table.ORDERNO,
master_table.ITEM)
This assumes you posted the subtraction backward; it subtracts the quantities in the order from the balance, which makes the most sense without knowing more about your tables. Just swap those two to change it if I was wrong:
(SUM(master_table.QTY) - stock_bal.BAL_QTY) AS NEW_BAL
This tries to improve print_r()
output formatting in console applications:
function pretty_printr($array) {
$string = print_r($array, TRUE);
foreach (preg_split("/((\r?\n)|(\r\n?))/", $string) as $line) {
$trimmed_line = trim($line);
// Skip useless lines.
if (!$trimmed_line || $trimmed_line === '(' || $trimmed_line === ')' || $trimmed_line === 'Array') {
continue;
}
// Improve lines ending with empty values.
if (substr_compare($trimmed_line, '=>', -2) === 0) {
$line .= "''";
}
print $line . PHP_EOL;
}
}
Example:
[activity_score] => 0
[allow_organisation_contact] => 1
[cover_media] => Array
[image] => Array
[url] => ''
[video] => Array
[url] => ''
[oembed_html] => ''
[thumb] => Array
[url] => ''
[created_at] => 2019-06-25T09:50:22+02:00
[description] => example description
[state] => published
[fundraiser_type] => anniversary
[end_date] => 2019-09-25
[event] => Array
[goal] => Array
[cents] => 40000
[currency] => EUR
[id] => 37798
[your_reference] => ''
To use the least amount of space you should use a CHAR field constrained to 'Y' or 'N'. Oracle doesn't support BOOLEAN, BIT, or TINYINT data types, so CHAR's one byte is as small as you can get.
This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.
On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it
error instead when making a request to a local URL that is not served, eg: localhost:5000
. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:
[Errno 99] Cannot assign requested address
(if called from within the container), or[Errno 0] Error
(if called from outside of the container).You can reproduce this error and the behaviour described above as follows:
Start a dummy container (note: this will pull the python image if not found locally):
docker run --name serv1 -p 5000:5000 -dit python
Then for [Errno 0] Error
enter a Python console on host, while for [Errno 99] Cannot assign requested address
access a Python console on the container by calling:
docker exec -it -u 0 serv1 python
And then in either case call:
import urllib.request
urllib.request.urlopen('https://localhost:5000')
I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it
rather than trying to fix their cause - although please advise if that's a bad idea.
I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address
point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl
conflicts, docker network issues, TIME_WAIT
being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.
In the question above the right answer would be to use Mock
, or to be more precise create_autospec
(because it will add spec to the mock methods of the class you are mocking), the defined spec
on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some
from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch
class MyClass:
@staticmethod
def method(foo, bar):
print(foo)
def something(some_class: MyClass):
arg = 1
# Would fail becuase of wrong parameters passed to methd.
return some_class.method(arg)
def second(some_class: MyClass):
arg = 1
return some_class.unexisted_method(arg)
class TestSomethingTestCase(TestCase):
def test_something_with_autospec(self):
mock = create_autospec(MyClass)
mock.method.return_value = True
# Fails because of signature misuse.
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_something(self):
mock = Mock() # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
mock.method.return_value = True
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
class TestSecondTestCase(TestCase):
def test_second_with_autospec(self):
mock = Mock(spec=MyClass)
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second(self):
mock = Mock()
mock.unexisted_method.return_value = True
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
The test cases with defined spec used fail because methods called from something
and second
functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock
will display.
As a side note there is one more option: use patch.object to mock just the class method which is called with.
The good use cases for patch would be the case when the class is used as inner part of function:
def something():
arg = 1
return MyClass.method(arg)
Then you will want to use patch as a decorator to mock the MyClass.
<style>
p{
width: 70%
word-wrap: break-word;
}
</style>
This wasn't working in my case. It worked fine after adding following style.
<style>
p{
width: 70%
word-break: break-all;
}
</style>
It is varchar
and not var_char
CREATE DATABASE IF NOT EXISTS courses;
USE courses;
CREATE TABLE IF NOT EXISTS teachers(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
addr VARCHAR(255) NOT NULL,
phone INT NOT NULL
);
You should use a SQL tool to visualize possbile errors like MySQL Workbench.
As of September 2016 (VSCode 1.6), this is now officially supported.
Add the following to your settings.json
file:
"editor.formatOnSave": true
I think I found the answer:
In the .service
file, I needed to add /bin/bash
before the path to the script.
For example, for backup.service:
ExecStart=/bin/bash /home/user/.scripts/backup.sh
As opposed to:
ExecStart=/home/user/.scripts/backup.sh
I'm not sure why. Perhaps fish
. On the other hand, I have another script running for my email, and the service file seems to run fine without /bin/bash
. It does use default.target
instead multi-user.target
, though.
Most of the tutorials I came across don't prepend /bin/bash
, but I then saw this SO answer which had it, and figured it was worth a try.
The service file executes the script, and the timer is listed in systemctl --user list-timers
, so hopefully this will work.
Update: I can confirm that everything is working now.
by far the best C++ GUI library out there is Qt, it's comprehensive, easy to learn, really fast, and multiplattform.
ah, it recently got a LGPL license, so now you can download it for free and include on commercial programs
Just use the Date
property:
var today = DateTime.Today;
var q = db.Games.Where(t => t.StartDate.Date >= today)
.OrderBy(t => t.StartDate);
Note that I've explicitly evaluated DateTime.Today
once so that the query is consistent - otherwise each time the query is executed, and even within the execution, Today
could change, so you'd get inconsistent results. For example, suppose you had data of:
Entry 1: March 8th, 8am
Entry 2: March 10th, 10pm
Entry 3: March 8th, 5am
Entry 4: March 9th, 8pm
Surely either both entries 1 and 3 should be in the results, or neither of them should... but if you evaluate DateTime.Today
and it changes to March 9th after it's performed the first two checks, you could end up with entries 1, 2, 4.
Of course, using DateTime.Today
assumes you're interested in the date in the local time zone. That may not be appropriate, and you should make absolutely sure you know what you mean. You may want to use DateTime.UtcNow.Date
instead, for example. Unfortunately, DateTime
is a slippery beast...
EDIT: You may also want to get rid of the calls to DateTime
static properties altogether - they make the code hard to unit test. In Noda Time we have an interface specifically for this purpose (IClock
) which we'd expect to be injected appropriately. There's a "system time" implementation for production and a "stub" implementation for testing, or you can implement it yourself.
You can use the same idea without using Noda Time, of course. To unit test this particular piece of code you may want to pass the date in, but you'll be getting it from somewhere - and injecting a clock means you can test all the code.
create table Table1
(
id varchar(2),
name varchar(2),
PRIMARY KEY (id)
)
Create table Table1_Addr
(
addid varchar(2),
Address varchar(2),
PRIMARY KEY (addid)
)
Create table Table1_sal
(
salid varchar(2),`enter code here`
addid varchar(2),
id varchar(2),
PRIMARY KEY (salid),
index(addid),
index(id),
FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
FOREIGN KEY (id) REFERENCES Table1(id)
)
Replace <p> </p>
with
Add as many
as needed.
I solved the same problem by this. Just sharing it.
The usual way to use assertRaises
is to call a function:
self.assertRaises(TypeError, test_function, args)
to test that the function call test_function(args) raises a TypeError.
The problem with self.testListNone[:1]
is that Python evaluates the expression immediately, before the assertRaises
method is called. The whole reason why test_function
and args
is passed as separate arguments to self.assertRaises
is to allow assertRaises
to call test_function(args)
from within a try...except
block, allowing assertRaises
to catch the exception.
Since you've defined self.testListNone = None
, and you need a function to call, you might use operator.itemgetter like this:
import operator
self.assertRaises(TypeError, operator.itemgetter, (self.testListNone,slice(None,1)))
since
operator.itemgetter(self.testListNone,slice(None,1))
is a long-winded way of saying self.testListNone[:1]
, but which separates the function (operator.itemgetter
) from the arguments.
This site allows you to view a packages tree as a node graph in 2D or 3D.
http://npm.anvaka.com/#/view/2d/waterline
Great work from @Avanka!
Yes, there is.
Surprising, huh? You can get a specific value from a multiple return using a simple mute
function:
package main
import "fmt"
import "strings"
func µ(a ...interface{}) []interface{} {
return a
}
type A struct {
B string
C func()(string)
}
func main() {
a := A {
B:strings.TrimSpace(µ(E())[1].(string)),
C:µ(G())[0].(func()(string)),
}
fmt.Printf ("%s says %s\n", a.B, a.C())
}
func E() (bool, string) {
return false, "F"
}
func G() (func()(string), bool) {
return func() string { return "Hello" }, true
}
https://play.golang.org/p/IwqmoKwVm-
Notice how you select the value number just like you would from a slice/array and then the type to get the actual value.
You can read more about the science behind that from this article. Credits to the author.
You want to use the .getline function in cin.
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
Took the example from here. Check it out for more info and examples.
std::vector<T>(input_iterator, input_iterator)
, in your case foo = std::vector<T>(myVec.begin () + 100000, myVec.begin () + 150000);
, see for example here
As of 2015, this is the best way (Java 8):
tourists.removeIf(Objects::isNull);
Note: This code will throw java.lang.UnsupportedOperationException
for fixed-size lists (such as created with Arrays.asList), including immutable lists.
Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.
First of all, there is no difference between View.OnClickListener
and OnClickListener
. If you just use View.OnClickListener
directly, then you don't need to write-
import android.view.View.OnClickListener
You set an OnClickListener instance (e.g. myListener
named object)as the listener to a view via setOnclickListener()
. When a click
event is fired, that myListener
gets notified and it's onClick(View view)
method is called. Thats where we do our own task.
Hope this helps you.
Method that returns locale from string exists in commons-lang library:
LocaleUtils.toLocale(localeAsString)
The -H 'Cache-Control: no-cache'
argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.
curl "http://www.example.com?foo123"
You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s
, which will return the seconds since epoch.
curl "http://www.example.com?$(date +%s)"
No, only native iOS applications support push notifications.
UPDATE:
Mac OS X 10.9 & Safari 7 websites can now also send push notifications, but this still does not apply to iOS.
Read the Notification Programming Guide for Websites. Also check out WWDC 2013 Session 614.
Even I faced the same issue - when checked on dashboard I found following Error. As the data was coming through Flume and had interrupted in between due to which may be there was inconsistency in few files.
Caused by: org.apache.hadoop.hive.serde2.SerDeException: org.codehaus.jackson.JsonParseException: Unexpected end-of-input within/between OBJECT entries
Running on fewer files it worked. Format consistency was the reason in my case.
Changing mvn clean
to mvn clean --file *.pom
fixed this issue for me.
A somewhat clumsy ascii-art to demonstrate the mechanism:
The join()
is presumably called by the main-thread. It could also be called by another thread, but would needlessly complicate the diagram.
join
-calling should be placed in the track of the main-thread, but to express thread-relation and keep it as simple as possible, I choose to place it in the child-thread instead.
without join:
+---+---+------------------ main-thread
| |
| +........... child-thread(short)
+.................................. child-thread(long)
with join
+---+---+------------------***********+### main-thread
| | |
| +...........join() | child-thread(short)
+......................join()...... child-thread(long)
with join and daemon thread
+-+--+---+------------------***********+### parent-thread
| | | |
| | +...........join() | child-thread(short)
| +......................join()...... child-thread(long)
+,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, child-thread(long + daemonized)
'-' main-thread/parent-thread/main-program execution
'.' child-thread execution
'#' optional parent-thread execution after join()-blocked parent-thread could
continue
'*' main-thread 'sleeping' in join-method, waiting for child-thread to finish
',' daemonized thread - 'ignores' lifetime of other threads;
terminates when main-programs exits; is normally meant for
join-independent tasks
So the reason you don't see any changes is because your main-thread does nothing after your join
.
You could say join
is (only) relevant for the execution-flow of the main-thread.
If, for example, you want to concurrently download a bunch of pages to concatenate them into a single large page, you may start concurrent downloads using threads, but need to wait until the last page/thread is finished before you start assembling a single page out of many. That's when you use join()
.
This has been answered for the most part, but I will expand...
Step 1
My goal was to enable zoom at certain times, and disable it at others.
// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');
// ...later...
// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');
Step 2
The viewport tag would update, but pinch zoom was still active!! I had to find a way to get the page to pick up the changes...
It's a hack solution, but toggling the opacity of body did the trick. I'm sure there are other ways to accomplish this, but here's what worked for me.
// after updating viewport tag, force the page to pick up changes
document.body.style.opacity = .9999;
setTimeout(function(){
document.body.style.opacity = 1;
}, 1);
Step 3
My problem was mostly solved at this point, but not quite. I needed to know the current zoom level of the page so I could resize some elements to fit on the page (think of map markers).
// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;
I hope this helps somebody. I spent several hours banging my mouse before finding a solution.
Consider two ways of doing the same thing:
PreparedStatement stmt = conn.createStatement("INSERT INTO students VALUES('" + user + "')");
stmt.execute();
Or
PreparedStatement stmt = conn.prepareStatement("INSERT INTO student VALUES(?)");
stmt.setString(1, user);
stmt.execute();
If "user" came from user input and the user input was
Robert'); DROP TABLE students; --
Then in the first instance, you'd be hosed. In the second, you'd be safe and Little Bobby Tables would be registered for your school.
This answer is not exactly what you want, but it might be useful in some cases. If you know the element has some dimensions when displayed, you can also use this:
var hasDisplayNone = (element.offsetHeight === 0 && element.offsetWidth === 0);
EDIT: Why this might be better than direct check of CSS display
property? Because you do not need to check all parent elements. If some parent element has display: none
, its children are hidden too but still has element.style.display !== 'none'
.
Try to see, if the service "SQL Server (MSSQLSERVER)" it's started, this solved my problem.
you can keep your withdraw and deposit methods static if you want however you'd have to write it like the code below. sb = starting balance and eB = ending balance.
Account account = new Account(1122, 20000, 4.5);
double sB = Account.withdraw(account.getBalance(), 2500);
double eB = Account.deposit(sB, 3000);
System.out.println("Balance is " + eB);
System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
account.setDateCreated(new Date());
System.out.println("The account was created " + account.getDateCreated());
Another simple way:
Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')
Select your required commit, and check it by
git show HEAD
git show HEAD~1
git show HEAD~2
till you get the required commit. To make the HEAD point to that, do
git reset --hard HEAD~1
or git reset --hard HEAD~2
or whatever.
This error comes when there is error in your query syntax check field names table name, mean check your query syntax.
var link = $("#me").closest(":has(h3 span b)").find('span b').text();
So far best solution that I've made:
function convertHtmlToJQueryObject(html){
var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
return $(htmlDOMObject.documentElement);
}
This thread does not have enough solutions to choose from, thus here my solution, it does not require tools like sed
or awk
:
grep '^\[section\]' -A 999 config.ini | tail -n +2 | grep -B 999 '^\[' | head -n -1 | grep '^key' | cut -d '=' -f 2
If your are to expect sections with more than 999 lines, feel free to adapt the example above. Note that you may want to trim the resulting value, to remove spaces or a comment string after the value. Remove the ^
if you need to match keys that do not start at the beginning of the line, as in the example of the question. Better, match explicitly for white spaces and tabs, in such a case.
If you have multiple values in a given section you want to read, but want to avoid reading the file multiple times:
CONFIG_SECTION=$(grep '^\[section\]' -A 999 config.ini | tail -n +2 | grep -B 999 '^\[' | head -n -1)
KEY1=$(echo ${CONFIG_SECTION} | tr ' ' '\n' | grep key1 | cut -d '=' -f 2)
echo "KEY1=${KEY1}"
KEY2=$(echo ${CONFIG_SECTION} | tr ' ' '\n' | grep key2 | cut -d '=' -f 2)
echo "KEY2=${KEY2}"
Maybe a naive approach is sufficient here: Build a list of all 2x2 squares on your plane, order them by their sum (in descending order).
First, select the highest-valued square into your "paw list". Then, iteratively pick 4 of the next-best squares that don't intersect with any of the previously found squares.
With SemaphoreSlim
you can achieve parallelism control.
var bag = new ConcurrentBag<object>();
var maxParallel = 20;
var throttler = new SemaphoreSlim(initialCount: maxParallel);
var tasks = myCollection.Select(async item =>
{
try
{
await throttler.WaitAsync();
var response = await GetData(item);
bag.Add(response);
}
finally
{
throttler.Release();
}
});
await Task.WhenAll(tasks);
var count = bag.Count;
string s = @"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
I know this post is old, sorry for that.
You can also type 10x
for cols and x2
for rows, if you want to have only one attribute.
[textarea* your-message x3 class:form-control] <!-- only rows -->
[textarea* your-message 10x class:form-control] <!-- only columns -->
[textarea* your-message 10x3 class:form-control] <!-- both -->
Seems you are looking for ORDER BY
in DESC
ending order with LIMIT clause:
SELECT
*
FROM
scores
ORDER BY score DESC
LIMIT 10
Of course SELECT *
could seriously affect performance, so use it with caution.
I would recommend using a hash instead of a param string:
data = {id: id, name: name}
The "Leader key" is a way of extending the power of VIM's shortcuts by using sequences of keys to perform a command. The default leader key is backslash. Therefore, if you have a map of <Leader>Q, you can perform that action by typing \Q.
I would recommend using x86 version of jvm. When I first got my new laptop (x64), I wanted to go x64 all the way (jvm, jdk, jre, eclipse, etc..). But once I finished setting everything up I realized that the Android SDK wasn't x64, so I had issues. Go back to x86 jvm and you should be ok.
EDIT: 11/14/13
I've seen some recent activity and figured I would elaborate a little more.
I did not say it would not work with x64, I just recommended using x86.
Here is a good post on the advantages / disadvantages of x64 JDK. Benefits of 64bit Java platform
Thought process: To what end? Why am I trying to using 64 bit JDK? Just because I have a 64-bit OS? Do I need any of the features of 64-bit JDK? Are there any extra features in the 64-bit JDK?! Why won't this s*** play nice together!? F*** it I'm going 32-bit.
Fast HTML Demo code: Based on what I know about SFML C++ graphics library:
Save this as an HTML file with UTF-8 Encoding and run it. Feel free to refactor, I just like using japanese variables because they are concise and don't take up much space
Rarely are you going to want to set ONE arbitrary pixel and display it on the screen. So use the
PutPix(x,y, r,g,b,a)
method to draw numerous arbitrary pixels to a back-buffer. (cheap calls)
Then when ready to show, call the
Apply()
method to display the changes. (expensive call)
Full .HTML file code below:
<!DOCTYPE HTML >
<html lang="en">
<head>
<title> back-buffer demo </title>
</head>
<body>
</body>
<script>
//Main function to execute once
//all script is loaded:
function main(){
//Create a canvas:
var canvas;
canvas = attachCanvasToDom();
//Do the pixel setting test:
var test_type = FAST_TEST;
backBufferTest(canvas, test_type);
}
//Constants:
var SLOW_TEST = 1;
var FAST_TEST = 2;
function attachCanvasToDom(){
//Canvas Creation:
//cccccccccccccccccccccccccccccccccccccccccc//
//Create Canvas and append to body:
var can = document.createElement('canvas');
document.body.appendChild(can);
//Make canvas non-zero in size,
//so we can see it:
can.width = 800;
can.height= 600;
//Get the context, fill canvas to get visual:
var ctx = can.getContext("2d");
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect(0,0,can.width-1, can.height-1);
//cccccccccccccccccccccccccccccccccccccccccc//
//Return the canvas that was created:
return can;
}
//THIS OBJECT IS SLOOOOOWW!
// ? == "pen"
//T? == "Type:Pen"
function T?(canvas){
//Publicly Exposed Functions
//PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//
this.PutPix = _putPix;
//PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//
if(!canvas){
throw("[NilCanvasGivenToPenConstruct]");
}
var _ctx = canvas.getContext("2d");
//Pixel Setting Test:
// only do this once per page
//? =="image"
//? =="data"
//??=="image data"
//? =="pen"
var _?? = _ctx.createImageData(1,1);
// only do this once per page
var _? = _??.data;
function _putPix(x,y, r,g,b,a){
_?[0] = r;
_?[1] = g;
_?[2] = b;
_?[3] = a;
_ctx.putImageData( _??, x, y );
}
}
//Back-buffer object, for fast pixel setting:
//? =="butt,rear" using to mean "back-buffer"
//T?=="type: back-buffer"
function T?(canvas){
//Publicly Exposed Functions
//PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//
this.PutPix = _putPix;
this.Apply = _apply;
//PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//
if(!canvas){
throw("[NilCanvasGivenToPenConstruct]");
}
var _can = canvas;
var _ctx = canvas.getContext("2d");
//Pixel Setting Test:
// only do this once per page
//? =="image"
//? =="data"
//??=="image data"
//? =="pen"
var _w = _can.width;
var _h = _can.height;
var _?? = _ctx.createImageData(_w,_h);
// only do this once per page
var _? = _??.data;
function _putPix(x,y, r,g,b,a){
//Convert XY to index:
var dex = ( (y*4) *_w) + (x*4);
_?[dex+0] = r;
_?[dex+1] = g;
_?[dex+2] = b;
_?[dex+3] = a;
}
function _apply(){
_ctx.putImageData( _??, 0,0 );
}
}
function backBufferTest(canvas_input, test_type){
var can = canvas_input; //shorthand var.
if(test_type==SLOW_TEST){
var t? = new T?( can );
//Iterate over entire canvas,
//and set pixels:
var x0 = 0;
var x1 = can.width - 1;
var y0 = 0;
var y1 = can.height -1;
for(var x = x0; x <= x1; x++){
for(var y = y0; y <= y1; y++){
t?.PutPix(
x,y,
x%256, y%256,(x+y)%256, 255
);
}}//next X/Y
}else
if(test_type==FAST_TEST){
var t? = new T?( can );
//Iterate over entire canvas,
//and set pixels:
var x0 = 0;
var x1 = can.width - 1;
var y0 = 0;
var y1 = can.height -1;
for(var x = x0; x <= x1; x++){
for(var y = y0; y <= y1; y++){
t?.PutPix(
x,y,
x%256, y%256,(x+y)%256, 255
);
}}//next X/Y
//When done setting arbitrary pixels,
//use the apply method to show them
//on screen:
t?.Apply();
}
}
main();
</script>
</html>
This will unstage all files you might have staged with git add
:
git reset
This will revert all local uncommitted changes (should be executed in repo root):
git checkout .
You can also revert uncommitted changes only to particular file or directory:
git checkout [some_dir|file.txt]
Yet another way to revert all uncommitted changes (longer to type, but works from any subdirectory):
git reset --hard HEAD
This will remove all local untracked files, so only git tracked files remain:
git clean -fdx
WARNING:
-x
will also remove all ignored files, including ones specified by.gitignore
! You may want to use-n
for preview of files to be deleted.
To sum it up: executing commands below is basically equivalent to fresh git clone
from original source (but it does not re-download anything, so is much faster):
git reset
git checkout .
git clean -fdx
Typical usage for this would be in build scripts, when you must make sure that your tree is absolutely clean - does not have any modifications or locally created object files or build artefacts, and you want to make it work very fast and to not re-clone whole repository every single time.
Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.
I came here for a reminder of how to set up the query but the existing examples were hard to follow. Here is an example with more explanation.
SQLiteDatabase db = helper.getReadableDatabase();
String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";
Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
Parameters
table
: the name of the table you want to querycolumns
: the column names that you want returned. Don't return data that you don't need.selection
: the row data that you want returned from the columns (This is the WHERE clause.)selectionArgs
: This is substituted for the ?
in the selection
String above.groupBy
and having
: This groups duplicate data in a column with data having certain conditions. Any unneeded parameters can be set to null.orderBy
: sort the datalimit
: limit the number of results to returnThe most simple and the correct way is to use Record type Record<string, string>
const myVar : Record<string, string> = {
key1: 'val1',
key2: 'val2',
}
If notepad is already started, you should write:
// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
//...
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
}
GetProcessesByName
returns an array of processes, so you should get the first one (or find the one you want).
If you want to start notepad
and send the key, you should write:
Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
The only situation in which the code may not work is when notepad
is started as Administrator and your application is not.
The certification installation step whatever mentioned here is correct https://stackoverflow.com/a/35200795/865220
But if you are having a pain of individually having to enable SSL Proxy for each and every new url like me, then to enable for all host names just enter * into the host and port names list in the SSL Proxying Settings like this:
DateTime
is not standard nullable type. If you want assign null to DateTime
type of variable, you have to use DateTime?
type which supports null value.
If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:
if (dateTimeVariable == default(DateTime))
{
//do work for dateTimeVariable == null situation
}
It may be helpful for someone, although there is no precise answer to this question.
My soap url has a non-standard port(9087 for example), and firewall blocked that request and I took each time this error:
ERROR - 2017-12-19 20:44:11 --> Fatal Error - SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://soalurl.test:9087/orawsv?wsdl' : failed to load external entity "http://soalurl.test:9087/orawsv?wsdl"
I allowed port in firewall and solved the error!
Use the where
command. The first result in the list is the one that will execute.
C:\> where notepad C:\Windows\System32\notepad.exe C:\Windows\notepad.exe
According to this blog post, where.exe
is included with Windows Server 2003 and later, so this should just work with Vista, Win 7, et al.
On Linux, the equivalent is the which
command, e.g. which ssh
.
You can access your array keys like so:
foreach ($array as $key => $value)
An old question with lots of answers, so another one won't be an issue. Some general functions to get the start and end of all sorts of time units.
For startOf and endOf week, the start day of the week defaults to Sunday (0) but any day can be passed (Monday - 1, Tuesday - 2, etc.). Only uses Gregorian calendar though.
The functions don't mutate the source date, so to see if a date is in the same week as some other date (week starting on Monday):
if (d >= startOf('week', d1, 1) && d <= endOf('week', d1, 1)) {
// d is in same week as d1
}
or in the current week starting on Sunday:
if (d >= startOf('week') && d <= endOf('week')) {
// d is in the current week
}
// Returns a new Date object set to start of given unit_x000D_
// For start of week, accepts any day as start_x000D_
function startOf(unit, date = new Date(), weekStartDay = 0) {_x000D_
// Copy original so don't modify it_x000D_
let d = new Date(date);_x000D_
let e = new Date(d);_x000D_
e.setHours(23,59,59,999);_x000D_
// Define methods_x000D_
let start = {_x000D_
second: d => d.setMilliseconds(0),_x000D_
minute: d => d.setSeconds(0,0),_x000D_
hour : d => d.setMinutes(0,0,0),_x000D_
day : d => d.setHours(0,0,0,0),_x000D_
week : d => {_x000D_
start.day(d);_x000D_
d.setDate(d.getDate() - d.getDay() + weekStartDay);_x000D_
if (d > e) d.setDate(d.getDate() - 7);_x000D_
},_x000D_
month : d => {_x000D_
start.day(d);_x000D_
d.setDate(1);_x000D_
},_x000D_
year : d => {_x000D_
start.day(d);_x000D_
d.setMonth(0, 1);_x000D_
},_x000D_
decade: d => {_x000D_
start.year(d);_x000D_
let year = d.getFullYear();_x000D_
d.setFullYear(year - year % 10);_x000D_
},_x000D_
century: d => {_x000D_
start.year(d);_x000D_
let year = d.getFullYear();_x000D_
d.setFullYear(year - year % 100);_x000D_
},_x000D_
millenium: d => {_x000D_
start.year(d);_x000D_
let year = d.getFullYear();_x000D_
d.setFullYear(year - year % 1000);_x000D_
}_x000D_
}_x000D_
start[unit](d);_x000D_
return d;_x000D_
}_x000D_
_x000D_
// Returns a new Date object set to end of given unit_x000D_
// For end of week, accepts any day as start day_x000D_
// Requires startOf_x000D_
function endOf(unit, date = new Date(), weekStartDay = 0) {_x000D_
// Copy original so don't modify it_x000D_
let d = new Date(date);_x000D_
let e = new Date(date);_x000D_
e.setHours(23,59,59,999);_x000D_
// Define methods_x000D_
let end = {_x000D_
second: d => d.setMilliseconds(999),_x000D_
minute: d => d.setSeconds(59,999),_x000D_
hour : d => d.setMinutes(59,59,999),_x000D_
day : d => d.setHours(23,59,59,999),_x000D_
week : w => {_x000D_
w = startOf('week', w, weekStartDay);_x000D_
w.setDate(w.getDate() + 6);_x000D_
end.day(w);_x000D_
d = w;_x000D_
},_x000D_
month : d => {_x000D_
d.setMonth(d.getMonth() + 1, 0);_x000D_
end.day(d);_x000D_
}, _x000D_
year : d => {_x000D_
d.setMonth(11, 31);_x000D_
end.day(d);_x000D_
},_x000D_
decade: d => {_x000D_
end.year(d);_x000D_
let y = d.getFullYear();_x000D_
d.setFullYear(y - y % 10 + 9);_x000D_
},_x000D_
century: d => {_x000D_
end.year(d);_x000D_
let y = d.getFullYear();_x000D_
d.setFullYear(y - y % 100 + 99);_x000D_
},_x000D_
millenium: d => {_x000D_
end.year(d);_x000D_
let y = d.getFullYear();_x000D_
d.setFullYear(y - y % 1000 + 999);_x000D_
}_x000D_
}_x000D_
end[unit](d);_x000D_
return d;_x000D_
}_x000D_
_x000D_
// Examples_x000D_
let d = new Date();_x000D_
_x000D_
['second','minute','hour','day','week','month','year',_x000D_
'decade','century','millenium'].forEach(unit => {_x000D_
console.log(('Start of ' + unit).padEnd(18) + ': ' +_x000D_
startOf(unit, d).toString());_x000D_
console.log(('End of ' + unit).padEnd(18) + ': ' +_x000D_
endOf(unit, d).toString());_x000D_
});
_x000D_
Combining R.. and PickBoy answers for brevity
long strtol (const char *String, char **EndPointer, int Base)
// examples
strtol(s, NULL, 10);
strtol(s, &s, 10);
desc keyspaces will do it for you.
You can also use map:
a = [1, 1, 1, 1, 1]
b = 1
list(map(lambda x: x + b, a))
It gives:
[2, 2, 2, 2, 2]
For Spring Boot 2.+, make sure you are using spring.servlet
instead of spring.http
.
---
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
If you have to use tomcat, you might end up creating EmbeddedServletContainerCustomizer, which is not really nice thing to do.
If you can live without tomat, you could replace tomcat with e.g. undertow and avoid this issue at all.
I think that it is better (for my expirience) to use: :first-of-type
, :nth-of-type()
, :last-of-type
. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type
, than *-child
selectors.
The other answers didn't work for me. I found the answer in their documentation:
http://api.highcharts.com/highcharts#Series
Using this method (see JSFiddle example):
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
// the button action
$('#button').click(function() {
chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4] );
});
just remove "520_"
utf8mb4_unicode_520_ci
? utf8mb4_unicode_ci
Send the data from the form:
$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
type: "PUT"
url: url
dataType: "script"
data: postData
You could use very easily reflection to list all properties, methods and values.
For Gecko based browsers you can use the .toSource() method:
var data = new Object();
data["firstname"] = "John";
data["lastname"] = "Smith";
data["age"] = 21;
alert(data.toSource()); //Will return "({firstname:"John", lastname:"Smith", age:21})"
But since you use Firebug, why not just use console.log?
$books[] = [
'title' => 'Mytitle',
'author' => 'MyAuthor,
];
//pass data to other view
return view('myView.blade.php')->with('books');
or
return view('myView.blade.php','books');
or
return view('myView.blade.php',compact('books'));
----------------------------------------------------
//to use this on myView.blade.php
<script>
myVariable = {!! json_encode($books) !!};
console.log(myVariable);
</script>
NEW ELEMENTS
As an addendum to the comprehensive answers above to highlight critical points if you want the click to attach to new elements:
How about this one: typically it is recommended that you do not expose a List object to external users of an assembly, rather expose an IEnumerable. But it is lot easier to use a List object inside the assembly, because you get the array syntax, and all other List methods. So, I typically have a internal property exposing a List to be used inside the assembly.
Comments are welcome about this approach.
You can also create a varible and then assign it for a text. It is cool because you can assign it two or more texts.
To assign a variable do that
public partial class Sayfa1 : Form
Font Normal = new Font("Segoe UI", 9, FontStyle.Bold);
public Sayfa1()
This varible is not assigned to any text yet.To do it write the name of the text(Look proporties -> (Name)) then write ".Font" then call the name of your font variable.
lupusToolStripMenuItem.Font = Normal;
Now you have a text assigned to a Normal font. I hope I could be helpful.
Add a second });
.
When properly indented, your code reads
$(function() {
$("#mewlyDiagnosed").hover(function() {
$("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
}, function() {
$("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
});
MISSING!
You never closed the outer $(function() {
.
I was faced with a slightly different scenario, in that I only wanted to not allow the user to change the selected value based on an earlier selectbox. What I ended up doing was just disabling all the other non-selected options in the selectbox using
$('#toSelect')find(':not(:selected)').prop('disabled',true);
Sorry to post answer for very old thread. my answer may help other in future.
string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);
//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
DataTable dtUniqRecords = new DataTable();
dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
return dtUniqRecords;
}
The code is taken from http://blogs.microsoft.co.il/blogs/shay/archive/2009/03/06/real-world-error-hadnling-in-asp-net-mvc-rc2.aspx and works in ASP.net MVC 1.0 as well
Here's how I handle http exceptions:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
// Log the exception.
ILogger logger = Container.Resolve<ILogger>();
logger.Error(exception);
Response.Clear();
HttpException httpException = exception as HttpException;
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
if (httpException == null)
{
routeData.Values.Add("action", "Index");
}
else //It's an Http Exception, Let's handle it.
{
switch (httpException.GetHttpCode())
{
case 404:
// Page not found.
routeData.Values.Add("action", "HttpError404");
break;
case 500:
// Server error.
routeData.Values.Add("action", "HttpError500");
break;
// Here you can handle Views to other error codes.
// I choose a General error template
default:
routeData.Values.Add("action", "General");
break;
}
}
// Pass exception details to the target error View.
routeData.Values.Add("error", exception);
// Clear the error on server.
Server.ClearError();
// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
// Call target Controller and pass the routeData.
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(
new HttpContextWrapper(Context), routeData));
}
In my case, delete from /etc/hosts
Actually you can fix it with following steps -
cls.__dict__
{'isFilled':True}
or {'isFilled':False}
depending upon what you have set.del cls.__dict__['isFilled']
In this case, we delete the entry which overrides the method as mentioned by BrenBarn.
Here is a very simple jade
file that have a loop in it. Jade is very sensitive about white space. After loop definition line (for
) you should give an indent(tab) to stuff that want to go inside the loop. You can do this without {}
:
- var arr=['one', 'two', 'three'];
- var s = 'string';
doctype html
html
head
body
section= s
- for (var i=0; i<3; i++)
div= arr[i]
git status
output tells you three things by default:
When you did git commit
, it committed to your local repository, thus #3 shows nothing to commit, however, #2 should show that you need to push or pull if you have setup the tracking branch.
If you find the output of git status verbose and difficult to comprehend, try using git status -sb
this is less verbose and will show you clearly if you need to push or pull. In your case, the output would be something like:
master...origin/master [ahead 1]
git status
is pretty useful, in the workflow you described do a git status -sb
: after touching the file, after adding the file and after committing the file, see the difference in the output, it will give you more clarity on untracked, tracked and committed files.
Update #1
This answer is applicable if there was a misunderstanding in reading the git status output. However, as it was pointed out, in the OPs case, the upstream was not set correctly. For that, Chris Mae's answer is correct.
You'll never know for sure if a string is URL-encoded or if it was supposed to have the sequence %2B
in it. Instead, it probably depends on where the string came from, i.e. if it was hand-crafted or from some application.
Is it better to search the string for characters which would be encoded, which aren't, and if any exist then its not encoded.
I think this is a better approach, since it would take care of things that have been done programmatically (assuming the application would not have left a non-encoded character behind).
One thing that will be confusing here... Technically, the %
"should be" encoded if it will be present in the final value, since it is a special character. You might have to combine your approaches to look for should-be-encoded characters as well as validating that the string decodes successfully if none are found.
I solved this by putting two CardViews in a RelativeLayout. One with background of the border color and the other one with the image. (or whatever you wish to use)
Note the margin added to top and start for the second CardView. In my case I decided to use a 2dp thick border.
<android.support.v7.widget.CardView
android:id="@+id/user_thumb_rounded_background"
android:layout_width="36dp"
android:layout_height="36dp"
app:cardCornerRadius="18dp"
android:layout_marginEnd="6dp">
<ImageView
android:id="@+id/user_thumb_background"
android:background="@color/colorPrimaryDark"
android:layout_width="36dp"
android:layout_height="36dp" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="@+id/user_thumb_rounded"
android:layout_width="32dp"
android:layout_height="32dp"
app:cardCornerRadius="16dp"
android:layout_marginTop="2dp"
android:layout_marginStart="2dp"
android:layout_marginEnd="6dp">
<ImageView
android:id="@+id/user_thumb"
android:src="@drawable/default_profile"
android:layout_width="32dp"
android:layout_height="32dp" />
</android.support.v7.widget.CardView>
I got here googling for C# compiler error CS0176, through (duplicate) question Static member instance reference issue.
In my case, the error happened because I had a static method and an extension method with the same name. For that, see Static method and extension method with same name.
[May be this should have been a comment. Sorry that I don't have enough reputation yet.]
For those who use Google Guava:
import com.google.common.html.HtmlEscapers;
[...]
String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = HtmlEscapers.htmlEscaper().escape(source);
It's possible to get this done using seaborn.lineplot()
but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:
# imports
import seaborn as sns
import numpy as np
import pandas as pd
# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])
# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)
# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>
And we get the following plot:
file__IO = input('\nEnter file name here to analize with path:: ')
with open(file__IO, 'r') as f:
data = f.read()
line = data.splitlines()
words = data.split()
spaces = data.split(" ")
charc = (len(data) - len(spaces))
print('\n Line number ::', len(line), '\n Words number ::', len(words), '\n Spaces ::', len(spaces), '\n Charecters ::', (len(data)-len(spaces)))
I tried this code & it works as expected.
The PDF Focus .Net can do it in such way:
1. PDF to TIFF
SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();
string pdfPath = @"c:\My.pdf";
string imageFolder = @"c:\images\";
f.OpenPdf(pdfPath);
if (f.PageCount > 0)
{
//Save all PDF pages to image folder as tiff images, 200 dpi
int result = f.ToImage(imageFolder, "page",System.Drawing.Imaging.ImageFormat.Tiff, 200);
}
2. PDF to Multipage-TIFF
//Convert PDF file to Multipage TIFF file
SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();
string pdfPath = @"c:\Document.pdf";
string tiffPath = @"c:\Result.tiff";
f.OpenPdf(pdfPath);
if (f.PageCount > 0)
{
f.ToMultipageTiff(tiffPath, 120) == 0)
{
System.Diagnostics.Process.Start(tiffPath);
}
}
Here is a sed solution:
sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt
You're already prepending the hash sign in your showDialog()
function, and you're missing single quotes in your second code snippet. You should also return false
from the handler to prevent a postback from occurring. Try:
<asp:Button ID="ButtonAdd" runat="server" Text="Add"
OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />
Mine got smoother not by wrapping each child but wrapping whole markup with a helper div. Like this:
<div class="accordeonBigWrapper">
<div class="panel-group accordion partnersAccordeonWrapper" id="partnersAccordeon" role="tablist" aria-multiselectable="false">
accordeon markup inside...
</div>
</div>
The best use case I can think of is in caching AJAX responses. Here's a modified example from Rebecca Murphey's intro post on the topic:
var cache = {};
function getData( val ){
// return either the cached value or jqXHR object wrapped Promise
return $.when(
cache[ val ] ||
$.ajax('/foo/', {
data: { value: val },
dataType: 'json',
success: function( resp ){
cache[ val ] = resp;
}
})
);
}
getData('foo').then(function(resp){
// do something with the response, which may
// or may not have been retrieved using an
// XHR request.
});
Basically, if the value has already been requested once before it's returned immediately from the cache. Otherwise, an AJAX request fetches the data and adds it to the cache. The $.when
/.then
doesn't care about any of this; all you need to be concerned about is using the response, which is passed to the .then()
handler in both cases. jQuery.when()
handles a non-Promise/Deferred as a Completed one, immediately executing any .done()
or .then()
on the chain.
Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.
Another real world example using the $.when
helper:
$.when($.getJSON('/some/data/'), $.get('template.tpl')).then(function (data, tmpl) {
$(tmpl) // create a jQuery object out of the template
.tmpl(data) // compile it
.appendTo("#target"); // insert it into the DOM
});
It turns out this can be nicely expressed in a vectorized fashion:
> df = pd.DataFrame({'a':[0,0,1,1], 'b':[0,1,0,1]})
> df = df[(df.T != 0).any()]
> df
a b
1 0 1
2 1 0
3 1 1
A variation I've been using for a while it if helps anyone.
The caller has to explicitly request that untrusted certifications are required and places the callback back into it's default state upon completion.
/// <summary>
/// Helper method for returning the content of an external webpage
/// </summary>
/// <param name="url">URL to get</param>
/// <param name="allowUntrustedCertificates">Flags whether to trust untrusted or self-signed certificates</param>
/// <returns>HTML of the webpage</returns>
public static string HttpGet(string url, bool allowUntrustedCertificates = false) {
var oldCallback = ServicePointManager.ServerCertificateValidationCallback;
string webPage = "";
try {
WebRequest req = WebRequest.Create(url);
if (allowUntrustedCertificates) {
// so we can query self-signed certificates
ServicePointManager.ServerCertificateValidationCallback =
((sender, certification, chain, sslPolicyErrors) => true);
}
WebResponse resp = req.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream())) {
webPage = sr.ReadToEnd().Trim();
sr.Close();
}
return webPage;
}
catch {
// if the remote site fails to response (or we have no connection)
return null;
}
finally {
ServicePointManager.ServerCertificateValidationCallback = oldCallback;
}
}
I built a tool for meta generation. It pre-configures entries for Facebook, Google+ and Twitter, and you can use it free here: http://www.groovymeta.com
To answer the question a bit more, OG
tags (Open Graph) tags work similarly to meta tags, and should be placed in the HEAD section of your HTML file. See Facebook's best practises for more information on how to use OG tags effectively.
Unfortunately, the height
property in CSS is not as reliable as it should be. Therefore, Javascript will have to be used to set the height style of the element in question to the height of the users viewport. And yes, this can be done without absolute positioning...
<!DOCTYPE html>
<html>
<head>
<title>Test by Josh</title>
<style type="text/css">
* { padding:0; margin:0; }
#test { background:#aaa; height:100%; width:100%; }
</style>
<script type="text/javascript">
window.onload = function() {
var height = getViewportHeight();
alert("This is what it looks like before the Javascript. Click OK to set the height.");
if(height > 0)
document.getElementById("test").style.height = height + "px";
}
function getViewportHeight() {
var h = 0;
if(self.innerHeight)
h = window.innerHeight;
else if(document.documentElement && document.documentElement.clientHeight)
h = document.documentElement.clientHeight;
else if(document.body)
h = document.body.clientHeight;
return h;
}
</script>
</head>
<body>
<div id="test">
<h1>Test</h1>
</div>
</body>
</html>
from command console, if you get this error you can avoid it by typing
c:\> sqlplus /nolog
then you can connect
SQL> conn user/pass @host:port/service
This means that your server is sending "text/html"
instead of the already supported types.
My solution was to add "text/html"
to acceptableContentTypes
set in AFURLResponseSerialization
class. Just search for "acceptableContentTypes" and add @"text/html"
to the set manually.
Of course, the ideal solution is to change the type sent from the server, but for that you will have to talk with the server team.
If you have floats you can write a function and then use that e.g.
#!/bin/bash
function float_gt() {
perl -e "{if($1>$2){print 1} else {print 0}}"
}
x=3.14
y=5.20
if [ $(float_gt $x $y) == 1 ] ; then
echo "do stuff with x"
else
echo "do stuff with y"
fi
You can also use,
parent.jQuery("#testdiv").attr("style", content from form);
To add to Mehrdad answer ,
namespace Math
{
class Matrix
{
public:
[...]
}
std::ostream& operator<< (std::ostream& stream, const Math::Matrix& matrix);
}
In your implementation
std::ostream& operator<<(std::ostream& stream,
const Math::Matrix& matrix) {
matrix.print(stream); //assuming you define print for matrix
return stream;
}
With C++11 for measuring the execution time of a piece of code, we can use the now() function:
auto start = chrono::steady_clock::now();
// Insert the code that will be timed
auto end = chrono::steady_clock::now();
// Store the time difference between start and end
auto diff = end - start;
If you want to print the time difference between start and end in the above code, you could use:
cout << chrono::duration <double, milli> (diff).count() << " ms" << endl;
If you prefer to use nanoseconds, you will use:
cout << chrono::duration <double, nano> (diff).count() << " ns" << endl;
The value of the diff variable can be also truncated to an integer value, for example, if you want the result expressed as:
diff_sec = chrono::duration_cast<chrono::nanoseconds>(diff);
cout << diff_sec.count() << endl;
For more info click here
In modern browsers you can use :placeholder-shown
to target the empty input (not to be confused with ::placeholder
).
input:placeholder-shown {
border: 1px solid red; /* Red border only if the input is empty */
}
More info and browser support: https://css-tricks.com/almanac/selectors/p/placeholder-shown/
If your input rows are lists rather than dictionaries, then the following is a simple solution:
import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])
pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
# A B C
# 0 1 2 3
# 1 4 5 6
After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))
HTML:
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>
jQuery:
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
In the upload.php
file you can access the data passed with $_FILES['file']
.
Thanks everyone for trying to help:)
I took the answer from here (with some changes) MDN
You can call sortable
on a <tbody>
instead of on the individual rows.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>?
<script>
$('tbody').sortable();
</script>
$(function() {_x000D_
$( "tbody" ).sortable();_x000D_
});
_x000D_
_x000D_
table {_x000D_
border-spacing: collapse;_x000D_
border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
_x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
<tr> _x000D_
<td>5</td>_x000D_
<td>6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>7</td>_x000D_
<td>8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>9</td> _x000D_
<td>10</td>_x000D_
</tr> _x000D_
</tbody> _x000D_
</table>
_x000D_
VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.
Here is how to install it:
C:\Windows
called MSJAVA.DLL
. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.SETUP.EXE
, select Run As Administrator
.C:\Program Files\Microsoft Visual Studio\VB98\
After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.
Edit: Updated dead link to point to a different page with the same instructions
Edit: Updated the answer with the actual instructions in the post as the link kept dying
From Get-ScriptDirectory to the Rescue blog entry ...
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
If one really want to resize an array you could do something like this:
String[] arr = {"a", "b", "c"};
System.out.println(Arrays.toString(arr));
// Output is: [a, b, c]
arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
arr[3] = "d";
arr[4] = "e";
arr[5] = "f";
System.out.println(Arrays.toString(arr));
// Output is: [a, b, c, d, e, f, null, null, null, null]
You can use is_uploaded_file()
:
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
From the docs:
Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.
This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.
EDIT: I'm using this in my FileUpload class, in case it helps:
public function fileUploaded()
{
if(empty($_FILES)) {
return false;
}
$this->file = $_FILES[$this->formField];
if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
$this->errors['FileNotExists'] = true;
return false;
}
return true;
}
Why cant we just use eval()?
def install():
print "In install"
New method
def installWithOptions(var1, var2):
print "In install with options " + var1 + " " + var2
And then you call the method as below
method_name1 = 'install()'
method_name2 = 'installWithOptions("a","b")'
eval(method_name1)
eval(method_name2)
This gives the output as
In install
In install with options a b
No its not. Use Meyers CSS reset :) http://meyerweb.com/eric/tools/css/reset/
For modern browsers all you need is this CSS:
img {
pointer-events: none;
}
Older browsers will still allow pointer events on the images, but the CSS above will take care of the vast majority of visitors to your site, and used in conjunction with the contextmenu
methods should give you a very solid solution.
Try:
SELECT *
FROM table
WHERE datetime >
CONVERT(DATETIME,
CONVERT(VARCHAR(20),
CONVERT(DATETIME, '2010-07-20 03:21:52'), 120))
Or if your date is an actual datetime value:
DECLARE @date DATETIME
SET @date = GETDATE()
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(20), @date, 120))
The conversion to style 120 cuts off the milliseconds...
Based on your question, I believe the answer is how to trigger a blur, not just (or even) set the event:
$('#textArea').trigger('blur');
You can always try putting this code in your main css without modifying the bootstrap file what is most recommended so you keep consistency if in a future you update the bootstrap file.
.tooltip-inner {
background-color: #FF0000;
}
.tooltip.right .tooltip-arrow {
border-right: 5px solid #FF0000;
}
Notice that this example is for a right tooltip. The tooltip-inner property changes the tooltip BG color, the other one changes the arrow color.
How about creating your own Custom Panel class? That way you won't have to worry about overriding Bootstrap.
HTML
<div class="panel panel-custom-horrible-red">
<div class="panel-heading">
<h3 class="panel-title">Panel title</h3>
</div>
<div class="panel-body">
Panel content
</div>
</div>
CSS
.panel-custom-horrible-red {
border-color: #ff0000;
}
.panel-custom-horrible-red > .panel-heading {
background: #ff0000;
color: #ffffff;
border-color: #ff0000;
}
Fiddle: https://jsfiddle.net/x05f4crg/1/
since basestring
isn't defined in Python3, this little trick might help to make the code compatible:
try: # check whether python knows about 'basestring'
basestring
except NameError: # no, it doesn't (it's Python3); use 'str' instead
basestring=str
after that you can run the following test on both Python2 and Python3
isinstance(myvar, basestring)
You can use standard looping constructs or iterator/listiterator for the same :
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
double sum = 0;
Iterator<Integer> iter1 = list.iterator();
while (iter1.hasNext()) {
sum += iter1.next();
}
double average = sum / list.size();
System.out.println("Average = " + average);
If using Java 8, you could use Stream or IntSream operations for the same :
OptionalDouble avg = list.stream().mapToInt(Integer::intValue).average();
System.out.println("Average = " + avg.getAsDouble());
Reference : Calculating average of arraylist
Here' a good tool from a documented and very famous npm library that does the xml <-> js conversions very well: differently from some (maybe all) of the above proposed solutions, it converts xml comments also.
var obj = {name: "Super", Surname: "Man", age: 23};
var builder = new xml2js.Builder();
var xml = builder.buildObject(obj);
You can also check whether div has specific children or not,
if($('#myDiv').has('select').length>0)
{
// Do something here.
console.log("you can log here");
}
Double check your text with the Hex Editor Plug-in. In your case there may have been some control characters which have crept into your text. Usually you'll look at the white-space, and it will say 32 32 32 32, or for Unicode 32 00 32 00 32 00 32 00. You may find the problem this way, providing there isn't masses of code.
Download the Hex Plugin from here; http://sourceforge.net/projects/npp-plugins/files/Hex%20Editor/
Yes, it is called Short-circuit Evaluation.
If the validity of the boolean statement can be assured after part of the statement, the rest is not evaluated.
This is very important when some of the statements have side-effects.
Here is another way I figured it out:
const x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x < 9):
alert("between 5 and 8");
break;
case (x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}
The get_ddl procedure for a PACKAGE will return both spec AND body, so it will be better to change the query on the all_objects so the package bodies are not returned on the select.
So far I changed the query to this:
SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type, ' ', '_'), object_name, owner)
FROM all_OBJECTS
WHERE (OWNER = 'OWNER1')
and object_type not like '%PARTITION'
and object_type not like '%BODY'
order by object_type, object_name;
Although other changes might be needed depending on the object types you are getting...
$bucket = '$node->' . $fieldname . "['und'][0]['value'] = " . '$form_state' . "['values']['" . $fieldname . "']";
print $bucket;
yields:
$node->mindd_2_study_status['und'][0]['value'] = $form_state['values']
['mindd_2_study_status']
using (var connection = new SqlConnection("Enter Your Connection String"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Enter the First Command Here";
command.ExecuteNonQuery();
command.CommandText = "Enter Second Comand Here";
command.ExecuteNonQuery();
//Similarly You can Add Multiple
}
}
Include the port number with the IP address.
For example:
http://19.18.20.101:5566
where 5566 is the port number.
If you really want to use a Date instead for a Calendar for comparison, this is the shortest piece of code you could use:
Calendar c = Calendar.getInstance();
Date d = new GregorianCalendar(c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).getTime();
This way you make sure the hours/minute/second/millisecond values are blank.
You may also use the querySelector() method, assuming the 'myspan' id is unique as the method returns the first element with the specified selector:
document.querySelector('#myspan').textContent = 'newtext';
maybe there are some unmerged paths in your git repository that you have to resolve before stashing.
BH's answer of installing Java 6u45 was very close... still got the popup on reboot...BUT after uninstalling Java 6u45, rebooted, no warning! Thank you BH! Then installed the latest version, 8u151-i586, rebooted no warning.
I added lines in PATH as above, didn't do anything.
My system: Windows 7, 64 bit. Warning was for No JVM, 32 bit Java not found. Yes, I could have installed the 64 bit version, but 32bit is more compatible with all programs.
In short, use:
list
- if you require an ordered sequence of items.
dict
- if you require to relate values with keys
set
- if you require to keep unique elements.
A list is a mutable sequence, typically used to store collections of homogeneous items.
A list implements all of the common sequence operations:
x in l
and x not in l
l[i]
, l[i:j]
, l[i:j:k]
len(l)
, min(l)
, max(l)
l.count(x)
l.index(x[, i[, j]])
- index of the 1st occurrence of x
in l
(at or after i
and before j
indeces)A list also implements all of the mutable sequence operations:
l[i] = x
- item i
of l
is replaced by x
l[i:j] = t
- slice of l
from i
to j
is replaced by the contents of the iterable t
del l[i:j]
- same as l[i:j] = []
l[i:j:k] = t
- the elements of l[i:j:k]
are replaced by those of t
del l[i:j:k]
- removes the elements of s[i:j:k]
from the listl.append(x)
- appends x
to the end of the sequence l.clear()
- removes all items from l
(same as del l[:]
)l.copy()
- creates a shallow copy of l
(same as l[:]
)l.extend(t)
or l += t
- extends l
with the contents of t
l *= n
- updates l
with its contents repeated n
timesl.insert(i, x)
- inserts x
into l
at the index given by i
l.pop([i])
- retrieves the item at i
and also removes it from l
l.remove(x)
- remove the first item from l
where l[i]
is equal to xl.reverse()
- reverses the items of l
in placeA list could be used as stack by taking advantage of the methods append
and pop
.
A dictionary maps hashable values to arbitrary objects. A dictionary is a mutable object. The main operations on a dictionary are storing a value with some key and extracting the value given the key.
In a dictionary, you cannot use as keys values that are not hashable, that is, values containing lists, dictionaries or other mutable types.
A set is an unordered collection of distinct hashable objects. A set is commonly used to include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
Please Try to pass parameters in httpoptions
, you can follow function below
deleteAction(url, data) {
const authToken = sessionStorage.getItem('authtoken');
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Bearer ' + authToken,
}),
body: data,
};
return this.client.delete(url, options);
}
You shouldn't use ${varName}
when you're outside of strings, you should just use varName
. Inside strings you use it like this; echo "this is a string ${someVariable}";
. Infact you can place an general java expression inside of ${...}
; echo "this is a string ${func(arg1, arg2)}
.
you have to move the adb command to /bin/ folder
in my case:
sudo su
mv /root/Android/Sdk/platform-tools/adb /bin/
In addition to @ImportanceOfBeingErnest's post, I use the following line to add a legend at an absolute position in a plot.
plt.legend(bbox_to_anchor=(1.0,1.0),\
bbox_transform=plt.gcf().transFigure)
For unknown reasons, bbox_transform=fig.transFigure
does not work with me.
In cases where you want to remove something that is close to the end of a string (in case of variable sized strings) you can combine slice() and substr().
I had a string with markup, dynamically built, with a list of anchor tags separated by comma. The string was something like:
var str = "<a>text 1,</a><a>text 2,</a><a>text 2.3,</a><a>text abc,</a>";
To remove the last comma I did the following:
str = str.slice(0, -5) + str.substr(-4);
The following adds elements to a list in a loop.
l<-c()
i=1
while(i<100) {
b<-i
l<-c(l,b)
i=i+1
}
package com.ezeon.util.gen;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
/*** Encryption and Decryption of String data; PBE(Password Based Encryption and Decryption)
* @author Vikram
*/
public class CryptoUtil
{
Cipher ecipher;
Cipher dcipher;
// 8-byte Salt
byte[] salt = {
(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
(byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03
};
// Iteration count
int iterationCount = 19;
public CryptoUtil() {
}
/**
*
* @param secretKey Key used to encrypt data
* @param plainText Text input to be encrypted
* @return Returns encrypted text
* @throws java.security.NoSuchAlgorithmException
* @throws java.security.spec.InvalidKeySpecException
* @throws javax.crypto.NoSuchPaddingException
* @throws java.security.InvalidKeyException
* @throws java.security.InvalidAlgorithmParameterException
* @throws java.io.UnsupportedEncodingException
* @throws javax.crypto.IllegalBlockSizeException
* @throws javax.crypto.BadPaddingException
*
*/
public String encrypt(String secretKey, String plainText)
throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
UnsupportedEncodingException,
IllegalBlockSizeException,
BadPaddingException {
//Key generation for enc and desc
KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
//Enc process
ecipher = Cipher.getInstance(key.getAlgorithm());
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
String charSet = "UTF-8";
byte[] in = plainText.getBytes(charSet);
byte[] out = ecipher.doFinal(in);
String encStr = new String(Base64.getEncoder().encode(out));
return encStr;
}
/**
* @param secretKey Key used to decrypt data
* @param encryptedText encrypted text input to decrypt
* @return Returns plain text after decryption
* @throws java.security.NoSuchAlgorithmException
* @throws java.security.spec.InvalidKeySpecException
* @throws javax.crypto.NoSuchPaddingException
* @throws java.security.InvalidKeyException
* @throws java.security.InvalidAlgorithmParameterException
* @throws java.io.UnsupportedEncodingException
* @throws javax.crypto.IllegalBlockSizeException
* @throws javax.crypto.BadPaddingException
*/
public String decrypt(String secretKey, String encryptedText)
throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
UnsupportedEncodingException,
IllegalBlockSizeException,
BadPaddingException,
IOException {
//Key generation for enc and desc
KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
//Decryption process; same key will be used for decr
dcipher = Cipher.getInstance(key.getAlgorithm());
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
byte[] enc = Base64.getDecoder().decode(encryptedText);
byte[] utf8 = dcipher.doFinal(enc);
String charSet = "UTF-8";
String plainStr = new String(utf8, charSet);
return plainStr;
}
public static void main(String[] args) throws Exception {
CryptoUtil cryptoUtil=new CryptoUtil();
String key="ezeon8547";
String plain="This is an important message";
String enc=cryptoUtil.encrypt(key, plain);
System.out.println("Original text: "+plain);
System.out.println("Encrypted text: "+enc);
String plainAfter=cryptoUtil.decrypt(key, enc);
System.out.println("Original text after decryption: "+plainAfter);
}
}
You simply add another @font-face
rule:
@font-face {
font-family: CustomFont;
src: url('CustomFont.ttf');
}
@font-face {
font-family: CustomFont2;
src: url('CustomFont2.ttf');
}
If your second font still doesn't work, make sure you're spelling its typeface name and its file name correctly, your browser caches are behaving, your OS isn't messing around with a font of the same name, etc.
Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).
You can limit the whole search to one row by using Limit 0,1
SELECT COUNT(UserName)
FROM TableName
WHERE UserName = 'User' AND
Password = 'Pass'
LIMIT 0, 1
If you need a small and specific mechanism, you can search for DLL Triggers info.
use word-break
it can be used without styling table
to table-layout: fixed
table {_x000D_
width: 140px;_x000D_
border: 1px solid #bbb_x000D_
}_x000D_
_x000D_
.tdbreak {_x000D_
word-break: break-all_x000D_
}
_x000D_
<p>without word-break</p>_x000D_
<table>_x000D_
<tr>_x000D_
<td>LOOOOOOOOOOOOOOOOOOOOOOOOOOOOGGG</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<p>with word-break</p>_x000D_
<table>_x000D_
<tr>_x000D_
<td class="tdbreak">LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOGGG</td>_x000D_
</tr>_x000D_
</table>
_x000D_
I used a small hack to use the RecyclerView on older devices. I just went into my local m2 repository and picked up the RecyclerView source files and put them into my project.
You can find the sourcecode here:
<Android-SDK>\extras\android\m2repository\com\android\support\recyclerview-v7\21.0.0-rc1\recyclerview-v7-21.0.0-rc1-sources.jar
var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
if(searchEles[i].id.indexOf('q1_') == 0) {
matches.push(searchEles[i]);
}
}
}
Once again, I strongly suggest jQuery for such tasks:
$("#myDiv :input").hide(); // :input matches all input elements, including selects
This can also happen if you've recently upgraded Ant. I was using Ant 1.8.4 on a project, and upgraded Ant to 1.9.4, and started to get this error when building a fat jar using Ant.
The solution for me was to downgrade back to Ant 1.8.4 for the command line and Eclipse using the process detailed here
Note that neither DBCC DROPCLEANBUFFERS;
nor DBCC FREEPROCCACHE;
is supported in SQL Azure / SQL Data Warehouse.
However, if you need to reset the plan cache in SQL Azure, you can alter one of the tables in the query (for instance, just add then remove a column), this will have the side-effect of removing the plan from the cache.
I personally do this as a way of testing query performance without having to deal with cached plans.
Go ahead and use Lombok, you can if necessary "delombok" your code afterwards http://projectlombok.org/features/delombok.html
I believe you are looking for setInterval()
On your select use width: auto and no padding to see how long your text is. I'm using 100% available width on my select and all of my options have the same length, this allows me to use very simple css.
text-indent will move the text from left, similar to padding-left
120px is my text length - I want to center it so take half of that size and half of the select size, leaving me with 50% - 60px
select{
width: 100%;
text-indent: calc(50% - 60px);
}
What if I have different sizes of options?
It is possible, however, the solution will not be a pretty one.
The former solution might get you really close to being centered if the difference between options isn't like 5 characters.
If you still need to center it more precisely you can do this
Prepare this class:
.realWidth{
width: auto;
}
Apply onChange listener to select element
In that listener apply .realWidth to the select element with
const selectRef = document.getElementById("yourId");
selectRef.classList.add("realWidth");
Get access to the real width of the option.
const widthOfSelect = selectRef.getBoundingClientRect().width / 2;
widthOfSelect is the width you are looking for. Store it in global/component variable.
Remove the realWidth, you don't need it anymore.
selectRef.classList.remove("realWidth");
I am using react, I'm not sure this will work in vanilla, if not you have to find another solution.
<select style={`textIndent: calc(50% - ${widthOfSelect}) %`}> ... </select>
Another solution, however, that is a bad one could be creating the CSS classes with js and putting it to head.
PROS:
CONS:
#'re.IGNORECASE' for case insensitive results short form re.I
#'re.match' returns the first match located from the start of the string.
#'re.search' returns location of the where the match is found
#'re.compile' creates a regex object that can be used for multiple matches
>>> s = r'TeSt'
>>> print (re.match(s, r'test123', re.I))
<_sre.SRE_Match object; span=(0, 4), match='test'>
# OR
>>> pattern = re.compile(s, re.I)
>>> print(pattern.match(r'test123'))
<_sre.SRE_Match object; span=(0, 4), match='test'>
@Steve already gave a good answer to your question:
verts = [None] * 1000
Warning: As @Joachim Wuttke pointed out, the list must be initialized with an immutable element. [[]] * 1000
does not work as expected because you will get a list of 1000 identical lists (similar to a list of 1000 points to the same list in C). Immutable objects like int, str or tuple will do fine.
Resizing lists is slow. The following results are not very surprising:
>>> N = 10**6
>>> %timeit a = [None] * N
100 loops, best of 3: 7.41 ms per loop
>>> %timeit a = [None for x in xrange(N)]
10 loops, best of 3: 30 ms per loop
>>> %timeit a = [None for x in range(N)]
10 loops, best of 3: 67.7 ms per loop
>>> a = []
>>> %timeit for x in xrange(N): a.append(None)
10 loops, best of 3: 85.6 ms per loop
But resizing is not very slow if you don't have very large lists. Instead of initializing the list with a single element (e.g. None
) and a fixed length to avoid list resizing, you should consider using list comprehensions and directly fill the list with correct values. For example:
>>> %timeit a = [x**2 for x in xrange(N)]
10 loops, best of 3: 109 ms per loop
>>> def fill_list1():
"""Not too bad, but complicated code"""
a = [None] * N
for x in xrange(N):
a[x] = x**2
>>> %timeit fill_list1()
10 loops, best of 3: 126 ms per loop
>>> def fill_list2():
"""This is slow, use only for small lists"""
a = []
for x in xrange(N):
a.append(x**2)
>>> %timeit fill_list2()
10 loops, best of 3: 177 ms per loop
For huge data set numpy or other optimized libraries are much faster:
from numpy import ndarray, zeros
%timeit empty((N,))
1000000 loops, best of 3: 788 ns per loop
%timeit zeros((N,))
100 loops, best of 3: 3.56 ms per loop
A solution that do not require a lot of CSS, nor tweaking bootstrap default 12col layout:
http://jsfiddle.net/0ufdyeur/1/
HTML:
<div class="stretch">
<div class="col-lg-2"></div>
<div class="col-lg-2"></div>
<div class="col-lg-2"></div>
<div class="col-lg-2"></div>
<div class="col-lg-2"></div>
</div>
CSS:
@media (min-width: 1200px) { /*if not lg, change this criteria*/
.stretch{
width: 120%; /*the actual trick*/
}
}
HashMap
is implemented by Hash Table while TreeMap
is implemented by Red-Black tree
. The main difference between HashMap
and TreeMap
actually reflect the main difference between a Hash
and a Binary Tree
, that is, when iterating, TreeMap guarantee can the key order which is determined by either element's compareTo() method or a comparator set in the TreeMap's constructor.
Take a look at following diagram.
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
You can set your tint color and font as setTitleTextattribute:
UIFont *font= (kUIScreenHeight>KipadHeight)?[UIFont boldSystemFontOfSize:32.0f]:[UIFont boldSystemFontOfSize:16.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,
tintColorLight, NSForegroundColorAttributeName, nil];
[[UINavigationBar appearance] setTitleTextAttributes:attributes];
Update: created a js fiddle here to see it live: http://jsfiddle.net/HFMvX/
I went through tons of google searches and didn't find anything satisfying. i like how passpack have done it so essentially reverse-engineered their approach, here we go:
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /\d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /\W/.test(pass),
}
var variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
Good passwords start to score around 60 or so, here's function to translate that in words:
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "strong";
if (score > 60)
return "good";
if (score >= 30)
return "weak";
return "";
}
you might want to tune this a bit but i found it working for me nicely
can you try to run svn checkout
once manually to your URL https://yoururl/trunk C:\ant-1.8.1\Test_Checkout
using command line
and accept certificate.
Or as @AndrewSpear says below
Rather than checking out manually run svn list https://your.repository.url
from Terminal (Mac) / Command Line (Win) to get the option to accept the certificate permanently
svn will ask you for confirmation. accept it permanently.
After that this should work for subsequent requests from ant script.
DROP that table and again run Spring Project. That might help. Sometime you are overriding foreignKey.
With jQuery
you can use
$('#main-div .specific-class').length
otherwise in VanillaJS (from IE8
included) you may use
document.querySelectorAll('#main-div .specific-class').length;
I don't know if this is a faster alternative, but I have another solution -
from datetime import datetime
start=datetime.now()
#Statements
print datetime.now()-start
You need to add a a gesture recognizer (For tap use UITapGestureRecognizer, for tap and hold use UILongPressGestureRecognizer) to your UIImageView
.
let tap = UITapGestureRecognizer(target: self, action: #selector(YourClass.tappedMe))
imageView.addGestureRecognizer(tap)
imageView.isUserInteractionEnabled = true
And Implement the selector method like:
@objc func tappedMe()
{
println("Tapped on Image")
}
Or try user scripts: http://dev.chromium.org/developers/design-documents/user-scripts
Check the API Docs
Methods addOption(data)
and setValue(value)
might be what you are looking for.
Update: Seeing the popularity of this answer, here is some additional info based on comments/requests...
setValue(value, silent)
Resets the selected items to the given value.
If "silent" is truthy (ie:true
,1
), no change event will be fired on the original input.
addOption(data)
Adds an available option, or array of options. If it already exists, nothing will happen.
Note: this does not refresh the options list dropdown (userefreshOptions()
for that).
In response to options being overwritten:
This can happen by re-initializing the select without using the options you initially provided. If you are not intending to recreate the element, simply store the selectize object to a variable:
// 1. Only set the below variables once (ideally)
var $select = $('select').selectize(options); // This initializes the selectize control
var selectize = $select[0].selectize; // This stores the selectize object to a variable (with name 'selectize')
// 2. Access the selectize object with methods later, for ex:
selectize.addOption(data);
selectize.setValue('something', false);
// Side note:
// You can set a variable to the previous options with
var old_options = selectize.settings;
// If you intend on calling $('select').selectize(old_options) or something
The current top answer is not fully correct.
As others have pointed out here, https requires handshaking and therefore does more TCP/IP roundtrips.
In a WAN environment typically then the latency becomes the limiting factor and not the increased CPU usage on the server.
Just keep in mind that the latency from Europe to the US can be around 200 ms (torundtrip time).
You can easily measure this (for the single user case) with HTTPWatch.
Prerequisite:
Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control
Aria does not change anything visually. (Aria is scared of designers too).
aria-label
aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users
How To Use:
<input type="edit" aria-label="search" placeholder="search">
There is no visual change in application. But screen readers can understand the purpose of control
aria-labelledby
Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually
Approach 1:
<span id="sd">Search</span>
<input type="text" aria-labelledby="sd">
Approach 2:
aria-labelledby can also be used to combine two labels for screen reader users
<span id="de">Billing Address</span>
<span id="sd">First Name</span>
<input type="text" aria-labelledby="de sd">
Draw the include below to make it compile:
#include <ChuckNorris>
I hear he can compile syntax errors...
The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.
So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.
One way to convert a string to an integer is to use the int function. For example:
percent = (int(pyc) / int(tpy)) * 100
DB_CLOSE_DELAY=-1
hbm2ddl closes the connection after creating the table, so h2 discards it.
If you have your connection-url configured like this
jdbc:h2:mem:test
the content of the database is lost at the moment the last connection is closed.
If you want to keep your content you have to configure the url like this
jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
If doing so, h2 will keep its content as long as the vm lives.
Notice the semicolon (;
) rather than colon (:
).
See the In-Memory Databases section of the Features page. To quote:
By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add
;DB_CLOSE_DELAY=-1
to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, usejdbc:h2:mem:test;DB_CLOSE_DELAY=-1
.
As said by jensgram, IE6 does not support attribute selector. You could add a class="disabled" to select the disabled inputs so that this can work in IE6.
For the ROW_NUMBER
technique, if you do not have a sorting column to use, you can use the CURRENT_TIMESTAMP
as follows:
SELECT TOP 20
col1,
col2,
col3,
col4
FROM (
SELECT
tbl.col1 AS col1
,tbl.col2 AS col2
,tbl.col3 AS col3
,tbl.col4 AS col4
,ROW_NUMBER() OVER (
ORDER BY CURRENT_TIMESTAMP
) AS sort_row
FROM dbo.MyTable tbl
) AS query
WHERE query.sort_row > 10
ORDER BY query.sort_row
This has worked well for me for searches over table sizes of even up to 700,000.
This fetches records 11 to 30.
The idea is to check if the incoming request is made with https, if so simply don't redirect it again to https but continue as usual. Else, if it is http, redirect it with appending https.
app.use (function (req, res, next) {
if (req.secure) {
next();
} else {
res.redirect('https://' + req.headers.host + req.url);
}
});
For this html:
<div class="outer">
<div class="inner"></div>
</div>
This selector should work:
$('.outer > .inner')
Click the mse7.exe
installed along with Office typically at \Program Files\Microsoft Office\OFFICE11
.
This will open up the debugger, open the file and then run the debugger in the GUI mode.
It is surprisingly simple...
Code behind:
// Here's your object that you'll create a list of
private class Products
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductPrice { get; set; }
}
// Here you pass in the List of Products
private void BindItemsInCart(List<Products> ListOfSelectedProducts)
{
// The the LIST as the DataSource
this.rptItemsInCart.DataSource = ListOfSelectedProducts;
// Then bind the repeater
// The public properties become the columns of your repeater
this.rptItemsInCart.DataBind();
}
ASPX code:
<asp:Repeater ID="rptItemsInCart" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Product Description</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ProductName") %></td>
<td><%# Eval("ProductDescription")%></td>
<td><%# Eval("ProductPrice")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
I hope this helps!
Try insmod
instead of modprobe. Modprobe
looks in the module directory /lib/modules/uname -r
for all the modules and other
files