All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
Change <?php echo $proxy ?>
to ' . $proxy . '
.
You use <?php
when you're outputting HTML by leaving PHP mode with ?>
. When you using echo
, you have to use concatenation, or wrap your string in double quotes and use interpolation.
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.
your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms
Use like below:
yourFunc(input: any):Observable<string> {
var requestHeader = { headers: new HttpHeaders({ 'Content-Type': 'text/plain', 'No-Auth': 'False' })};
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post<string>(this.yourBaseApi+ '/do-api', input, { headers, responseType: 'text' as 'json' });
}
I think many people have problems with Post 'Content-type': 'application / json'
The problem here is parse data Map <String, dynamic>
to json
:
Hope the code below can help someone
Model:
class ConversationReq {
String name = '';
String description = '';
String privacy = '';
String type = '';
String status = '';
String role;
List<String> members;
String conversationType = '';
ConversationReq({this.type, this.name, this.status, this.description, this.privacy, this.conversationType, this.role, this.members});
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['description'] = this.description;
data['privacy'] = this.privacy;
data['type'] = this.type;
data['conversations'] = [
{
"members": members,
"conversationType": conversationType,
}
];
return data;
}
}
Request:
createNewConversation(ConversationReq param) async {
HeaderRequestAuth headerAuth = await getAuthHeader();
var headerRequest = headerAuth.toJson();
/*
{
'Content-type': 'application/json',
'x-credential-session-token': xSectionToken,
'x-user-org-uuid': xOrg,
}
*/
var bodyValue = param.toJson();
var bodydata = json.encode(bodyValue);// important
print(bodydata);
final response = await http.post(env.BASE_API_URL + "xxx", headers: headerRequest, body: bodydata);
print(json.decode(response.body));
if (response.statusCode == 200) {
// TODO
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load ConversationRepo');
}
}
I know this is a little late, nevertheless i'm answering this for anyone still experiencing this issue on windows (USING XAMPP).
Step 1. Verify that there is a mismatch in your PHP version. To do this, open routes/web.php and create a simple route to return the php information like so:
Route::get('/', function() {
return response()->json([
'stuff' => phpinfo()
]);
})
and compare this with output from your command line
As we can see, in my case there is a mismatch, this usually happens if you have multiple versions of php installed.
Step 2. Add the php version being used by your xampp to your system path
Step 3. Verify that you have the extension enabled in your php.ini file. NB. Make sure you are editing the php.ini file that is shown under the 'loaded configuration file' entry in the results of phpinfo() command.
For express, upgrade your express library to 4.17.1
which is the latest stable version. Then;
In CorsOption: Set origin
to your localhost url or your frontend production url and credentials
to true
e.g
const corsOptions = {
origin: config.get("origin"),
credentials: true,
};
I set my origin dynamically using config npm module.
Then , in res.cookie:
For localhost: you do not need to set sameSite and secure option at all, you can set httpOnly
to true
for http cookie to prevent XSS attack and other useful options depending on your use case.
For production environment, you need to set sameSite
to none
for cross-origin request and secure
to true
. Remember sameSite
works with express latest version only as at now and latest chrome version only set cookie over https
, thus the need for secure option.
Here is how I made mine dynamic
res
.cookie("access_token", token, {
httpOnly: true,
sameSite: app.get("env") === "development" ? true : "none",
secure: app.get("env") === "development" ? false : true,
})
As it turns out, one should not forget to include jacson dependency into the pom file. This solved the issue for me:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Give the same name in urls.py
path('detail/<int:id>', views.detail, name="detail"),
Angular 8 HttpClient Service example with Error Handling and Custom Header
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Student } from '../model/student';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiService {
// API path
base_path = 'http://localhost:3000/students';
constructor(private http: HttpClient) { }
// Http Options
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
// Handle API errors
handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
// Create a new item
createItem(item): Observable<Student> {
return this.http
.post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
.pipe(
retry(2),
catchError(this.handleError)
)
}
....
....
Check complete example tutorial here
Use a custom Action/Controller Attribute to set the CORS headers.
Example:
public class AllowMyRequestsAttribute : ControllerAttribute, IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
// check origin
var origin = context.HttpContext.Request.Headers["origin"].FirstOrDefault();
if (origin == someValidOrigin)
{
context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", origin);
context.HttpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
context.HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
context.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "*");
// Add whatever CORS Headers you need.
}
}
public void OnActionExecuting(ActionExecutingContext context)
{
// empty
}
}
Then on the Web API Controller / Action:
[ApiController]
[AllowMyRequests]
public class MyController : ApiController
{
[HttpGet]
public ActionResult<string> Get()
{
return "Hello World";
}
}
I was trying to use Feign, while I encounter same issue, As I understood HTTP message converter will help but wanted to understand how to achieve this.
@FeignClient(name = "mobilesearch", url = "${mobile.search.uri}" ,
fallbackFactory = MobileSearchFallbackFactory.class,
configuration = MobileSearchFeignConfig.class)
public interface MobileSearchClient {
@RequestMapping(method = RequestMethod.GET)
List<MobileSearchResponse> getPhones();
}
You have to use Customer Configuration for the decoder, MobileSearchFeignConfig,
public class MobileSearchFeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
@Bean
public Decoder feignDecoder() {
return new ResponseEntityDecoder(new SpringDecoder(feignHttpMessageConverter()));
}
public ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(new MappingJackson2HttpMessageConverter());
return new ObjectFactory<HttpMessageConverters>() {
@Override
public HttpMessageConverters getObject() throws BeansException {
return httpMessageConverters;
}
};
}
public class MappingJackson2HttpMessageConverter extends org.springframework.http.converter.json.MappingJackson2HttpMessageConverter {
MappingJackson2HttpMessageConverter() {
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.valueOf(MediaType.TEXT_HTML_VALUE + ";charset=UTF-8"));
setSupportedMediaTypes(mediaTypes);
}
}
}
My case was that i was using RDS (mysql db verion 8) of AWS and was connecting my application through EC2 (my php code 5.6 was in EC2).
Here in this case since it is RDS there is no my.cnf the parameters are maintained by PARAMETER Group of AWS. Refer: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html
so what i did was:
Created a new Parameter group and then edited them.
Searched all character-set parameters. These are blank by default. edit them individually and select utf8 from drop down list.
character_set_client, character_set_connection, character_set_database, character_set_server
And then most important, Rebooted RDS instance.
This has solved my problem and connection from php5.6 to mysql 8.x was working great.
hope this helps.
Please view this image for better understanding. enter image description here
You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).
Your code could be like:
const myArray = [
{
"id":25,
"name":"Anakin Skywalker",
"createdAt":"2017-04-12T12:48:55.000Z",
"updatedAt":"2017-04-12T12:48:55.000Z"
},
{
"id":1,
"name":"Luke Skywalker",
"createdAt":"2017-04-12T11:25:03.000Z",
"updatedAt":"2017-04-12T11:25:03.000Z"
}
]
const myOrderedArray = _.sortBy(myArray, o => o.name)
Laravel - htmlspecialchars() expects parameter 1 to be string, object given.
thank me latter.........................
when you send or get array from contrller or function but try to print as single value or single variable in laravel blade file so it throws an error
->use any think who convert array into string it work.
solution: 1)run the foreach loop and get single single value and print. 2)The implode() function returns a string from the elements of an array. {{ implode($your_variable,',') }}
implode is best way to do it and its 100% work.
First thing you need to do here is correct the hibernate dialect version like @JavaLearner has explained. Then you have make sure that all the versions of hibernate dependencies you are using are upto date. Typically you would need: database driver like mysql-connector-java
, hibernate dependency: hibernate-core
and hibernate entity manager: hibernate-entitymanager
. Lastly don't forget to check that the database tables you are using are not the reserved words like order
, group
, limit
, etc. It might save you a lot of headache.
I also got this error .I was using Text inside body after changing to XML(text/xml) , got result as expected.
If your request is XML Request use XML(text/xml).
If your request is JSON Request use JSON(application/json)
In my case I had to clear browser history/cookies to get rid of this error.
This worked for me
/* Portrait */
@media only screen
and (min-device-width: 834px)
and (max-device-width: 834px)
and (orientation: portrait)
and (-webkit-min-device-pixel-ratio: 2) {
}
/* Landscape */
@media only screen
and (min-width: 1112px)
and (max-width: 1112px)
and (orientation: landscape)
and (-webkit-min-device-pixel-ratio: 2)
{
}
I just wondered, why col-xs-6
did not work for me but then I found the answer in the Bootstrap 4 documentation. The class prefix for extra small devices is now col-
while in the previous versions it was col-xs
.
https://getbootstrap.com/docs/4.1/layout/grid/#grid-options
Bootstrap 4 dropped all col-xs-*
classes, so use col-*
instead. For example col-xs-6
replaced by col-6
.
For some reason the responsive table in particular doesn't behave as it should. You can patch it by getting rid of display:block;
.table-responsive {
display: table;
}
I may file a bug report.
Edit:
It's the @Neps' answer but with details.
Note: @Saurabh's answer is more suitable if you don't want to modify your component or don't have access to it.
Components are complicated. One component can be a small fancy button wrapper, and another one can be an entire table with bunch of logic inside. Vue doesn't know what exactly you expect when bind v-model
or use v-on
so all of that should be processed by component's creator.
According to Vue docs, $emit
passes events to parent. Example from docs:
Main file
<blog-post
@enlarge-text="onEnlargeText"
/>
Component
<button @click="$emit('enlarge-text')">
Enlarge text
</button>
(@
is the v-on
shorthand)
Component handles native click
event and emits parent's @enlarge-text="..."
enlarge-text
can be replaced with click
to make it look like we're handling a native click event:
<blog-post
@click="onEnlargeText"
></blog-post>
<button @click="$emit('click')">
Enlarge text
</button>
But that's not all. $emit
allows to pass a specific value with an event. In the case of native click
, the value is MouseEvent (JS event that has nothing to do with Vue).
Vue stores that event in a $event
variable. So, it'd the best to emit $event
with an event to create the impression of native event usage:
<button v-on:click="$emit('click', $event)">
Enlarge text
</button>
$about = DB::where('page', 'about-me')->first();
in stead of get()
.
It works on my project. Thanks.
You can just add style="min-height:100vh" to your page content conteiner and place footer in another conteiner
I solved this error using the bellow i get it from here
ionic cordova run browser
will load those native plugins that support browser
platform.
You can use default javascript cookies set method. this working perfect.
createCookieInHour: (cookieName, cookieValue, hourToExpire) => {
let date = new Date();
date.setTime(date.getTime()+(hourToExpire*60*60*1000));
document.cookie = cookieName + " = " + cookieValue + "; expires = " +date.toGMTString();
},
call java scripts funtion in react method as below,
createCookieInHour('cookieName', 'cookieValue', 5);
and you can use below way to view cookies.
let cookie = document.cookie.split(';');
console.log('cookie : ', cookie);
please refer below document for more information - URL
Using ngcWebpack Plugin I got this error when not specifying a mainPath or entryModule.
Keep the json file in Assets (parallel to app dir) directory
Note that if you would have generated with ng new YourAppname- this assets directory exists same line with 'app' directory, and services should be child directory of app directory. May look like as below:
::app/services/myservice.ts
getOrderSummary(): Observable {
// get users from api
return this.http.get('assets/ordersummary.json')//, options)
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
In case you are using node.js (with express)
If you want to serve static files in node.js, you need to use a function. Add the following code to your js file:
app.use(express.static("public"));
Where app is:
const express = require("express");
const app = express();
Then create a folder called public in you project folder. (You could call it something else, this is just good practice but remember to change it from the function as well.)
Then in this file create another folder named css (and/or images file under css if you want to serve static images as well.) then add your css files to this folder.
After you add them change the stylesheet accordingly. For example if it was:
href="cssFileName.css"
and
src="imgName.png"
Make them:
href="css/cssFileName.css"
src="css/images/imgName.png"
That should work
If you make an AJAX request with fetch
, the response isn't shown unless it's read with .text()
, .json()
, etc.
If you just do:
r = fetch("/some-path");
the response won't be shown in dev tools.
It shows up after you run:
r.then(r => r.text())
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"
You can disable need to run Internet Explorer's first launch configuration by running this PowerShell script, it will adjust corresponding registry property:
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer\Main" -Name "DisableFirstRunCustomize" -Value 2
After this, WebClient will work without problems
For the SpringBoot2 just add
httpResponse.setHeader("Access-Control-Expose-Headers", "custom-header1, custom-header2");
to your CORS filter implementation code to have whitelisted custom-header1
and custom-header2
etc
If you have a specific integer timestamp to insert/update, you can use PHP date() function with your timestamp as second arg :
date("Y-m-d H:i:s", $myTimestamp)
You need change url from https://android.googleapis.com/gcm/send to https://fcm.googleapis.com/fcm/send and change your app library too. this tutorial can help you https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol
Google recently changed the terms of use of its Google Maps APIs; if you were already using them on a website (different from localhost) prior to June 22nd, 2016, nothing will change for you; otherwise, you will get the aforementioned issue and need an API key in order to fix your error. The free API key is valid up to 25,000 map loads per day.
In this article you will find everything you may need to know regarding the topic, including a tutorial to fix your error:
Google Maps API error: MissingKeyMapError [SOLVED]
Also, remember to replace YOUR_API_KEY with your actual API key!
When you click the Button
if(isset($_POST['save'])){
$sql = "INSERT INTO `members`(`id`, `membership_id`, `email`, `first_name`)
VALUES ('".$_POST["id"]."','".$_POST["membership_id"]."','".$_POST["email"]."','".$_POST["firstname"]."')";
**if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}**
}
This will execute the Query in the variable $sql
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
I was having major problems with Axios, Spring Boot and Spring Security with authentication.
Please note the version of Spring Boot and the Spring Security you are using matters.
Spring Boot: 1.5.10 Spring: 4.3.14 Spring Security 4.2.4
To resolve this issue using Annotation Based Java Configuration I created the following class:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("youruser").password("yourpassword")
.authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().
authorizeRequests()
.requestMatchers(CorsUtils:: isPreFlightRequest).permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.realmName("Biometrix");
http.csrf().disable();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList("Authorization"));
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
One of the major gotchas with Axios is that when your API requires authentication it sends an Authorization header with the OPTIONS request. If you do not include Authorization in the allowed headers configuration setting our OPTIONS request (aka PreFlight request) will fail and Axios will report an error.
As you can see with a couple of simple and properly placed settings CORS configuration with SpringBoot is pretty easy.
It's been solved.
The losses only save to the History over the epochs. I was running iterations instead of using the Keras built in epochs option.
so instead of doing 4 iterations I now have
model.fit(......, nb_epoch = 4)
Now it returns the loss for each epoch run:
print(hist.history)
{'loss': [1.4358016599558268, 1.399221191623641, 1.381293383180471, h1.3758836857303727]}
Example for Slack.... (use your own web address you generate there)...
curl -X POST -H "Content-type:application/json" --data "{\"text\":\"A New Program Has Just Been Posted!!!\"}" https://hooks.slack.com/services/T7M0PFD42/BAA6NK48Y/123123123123123
I needed to add the script below to index.html inside the HEAD tag.
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
But in your case, since you don't have index.html, just add it to your HEAD tag instead.
So it's like:
<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
...
</body>
</html>
You just need to add three file and two css links. You can either cdn's as well. Links for the js files and css files are as such :-
They are valid if you are using bootstrap in your project.
I hope this will help you. Regards, Vivek Singla
Take a look at the FormData object: https://developer.mozilla.org/en/docs/Web/API/FormData
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
Assuming you already have a application created under google developer console, Follow the below steps
https://console.cloud.google.com/apis/dashboard?
you will be getting the below page Note: Please use a server to load the html
file
This is what I did to solve my problem. I tested in local MySQL 5.7 ubuntu 18.04.
set global sql_mode="NO_ENGINE_SUBSTITUTION";
Before running this query globally I added a cnf file in /etc/mysql/conf.d directory. The cnf file name is mysql.cnf and codes
[mysqld]
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ALLOW_INVALID_DATES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
Then I restart mysql
sudo service mysql restart
Hope this can help someone.
Even simpler:
body: new URLSearchParams({
'userName': '[email protected]',
'password': 'Password!',
'grant_type': 'password'
}),
Docs: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
I'm using Ubuntu 16.04 and PHP 5.6.20
After too many problems, the below steps solved this for me:
find php.ini
path via phpinfo()
uncomment
extension=php_pdo_mysql.dll
add this line
extension=pdo_mysql.so
then run
sudo apt-get install php-mysql
In my case it is Asp.Net Core 3.1 API. I changed the HTTP GET method from public ActionResult GetValidationRulesForField( GetValidationRulesForFieldDto getValidationRulesForFieldDto)
to public ActionResult GetValidationRulesForField([FromQuery] GetValidationRulesForFieldDto getValidationRulesForFieldDto)
and its working.
Access the field with array notation to avoid strict type checking on single field:
data['propertyName']; //will work even if data has not declared propertyName
Alternative way is (un)cast the variable for single access:
(<any>data).propertyName;//access propertyName like if data has no type
The first is shorter, the second is more explicit about type (un)casting
You can also totally disable type checking on all variable fields:
let untypedVariable:any= <any>{}; //disable type checking while declaring the variable
untypedVariable.propertyName = anyValue; //any field in untypedVariable is assignable and readable without type checking
Note: This would be more dangerous than avoid type checking just for a single field access, since all consecutive accesses on all fields are untyped
var theString = "TEST";
char[] myChar = theString.ToCharArray();
I tested this in the C# interactive window of Visual Studio 2019 and got:
char[4] { 'T', 'E', 'S', 'T' }
@PostMapping(path = "/my/endpoint", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE })
public ResponseEntity<Void> handleBrowserSubmissions(MyDTO dto) throws Exception {
...
}
That way works for me
you have many HTML and java script mistakes includes:
tag, using non UTF-8 encoding for form submission, no need,...
You must use document.forms.FORMNAME
or document.forms[0]
for first appear form in page
Corrected:
function validate_frm_new_user_request()_x000D_
{_x000D_
alert('test');_x000D_
var valid = true;_x000D_
_x000D_
if ( document.forms.frm_new_user_request.u_userid.value == "" )_x000D_
{_x000D_
alert ( "Please enter your valid ISID Information." );_x000D_
document.forms.frm_new_user_request.u_userid.focus();_x000D_
valid = false;_x000D_
console.log("FALSE::Empty Value ");_x000D_
}_x000D_
return valid;_x000D_
}
_x000D_
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title></title>_x000D_
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />_x000D_
_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<form method="post" action="" name="frm_new_user_request" id="frm_new_user_request" onsubmit="return validate_frm_new_user_request();">_x000D_
<center>_x000D_
<table>_x000D_
_x000D_
<tr align="left">_x000D_
<td><Label>ISID<em>*:</Label><input maxlength="15" id="u_userid" name="u_userid" size="20" type="text"/></td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td align="center" colspan="4">_x000D_
<input type="image" src="btn.png" border="0" ALT="Create New Request">_x000D_
_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
Using return;
will work just fine. It will not prevent the full loop from completing. It will only stop executing the current iteration of the forEach
loop.
Try the following little program:
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
stringList.stream().forEach(str -> {
if (str.equals("b")) return; // only skips this iteration.
System.out.println(str);
});
}
Output:
a
c
Notice how the return;
is executed for the b
iteration, but c
prints on the following iteration just fine.
The reason the behavior seems unintuitive at first is because we are used to the return
statement interrupting the execution of the whole method. So in this case, we expect the main
method execution as a whole to be halted.
However, what needs to be understood is that a lambda expression, such as:
str -> {
if (str.equals("b")) return;
System.out.println(str);
}
... really needs to be considered as its own distinct "method", completely separate from the main
method, despite it being conveniently located within it. So really, the return
statement only halts the execution of the lambda expression.
The second thing that needs to be understood is that:
stringList.stream().forEach()
... is really just a normal loop under the covers that executes the lambda expression for every iteration.
With these 2 points in mind, the above code can be rewritten in the following equivalent way (for educational purposes only):
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
for(String s : stringList) {
lambdaExpressionEquivalent(s);
}
}
private static void lambdaExpressionEquivalent(String str) {
if (str.equals("b")) {
return;
}
System.out.println(str);
}
With this "less magic" code equivalent, the scope of the return
statement becomes more apparent.
You can use MarkerWithLabel with SVG icons.
Update: The Google Maps Javascript API v3 now natively supports multiple characters in the MarkerLabel
proof of concept fiddle (you didn't provide your icon, so I made one up)
Note: there is an issue with labels on overlapping markers that is addressed by this fix, credit to robd who brought it up in the comments.
code snippet:
function initMap() {_x000D_
var latLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
var homeLatLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
zoom: 12,_x000D_
center: latLng,_x000D_
mapTypeId: google.maps.MapTypeId.ROADMAP_x000D_
});_x000D_
_x000D_
var marker = new MarkerWithLabel({_x000D_
position: homeLatLng,_x000D_
map: map,_x000D_
draggable: true,_x000D_
raiseOnDrag: true,_x000D_
labelContent: "ABCD",_x000D_
labelAnchor: new google.maps.Point(15, 65),_x000D_
labelClass: "labels", // the CSS class for the label_x000D_
labelInBackground: false,_x000D_
icon: pinSymbol('red')_x000D_
});_x000D_
_x000D_
var iw = new google.maps.InfoWindow({_x000D_
content: "Home For Sale"_x000D_
});_x000D_
google.maps.event.addListener(marker, "click", function(e) {_x000D_
iw.open(map, this);_x000D_
});_x000D_
}_x000D_
_x000D_
function pinSymbol(color) {_x000D_
return {_x000D_
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',_x000D_
fillColor: color,_x000D_
fillOpacity: 1,_x000D_
strokeColor: '#000',_x000D_
strokeWeight: 2,_x000D_
scale: 2_x000D_
};_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', initMap);
_x000D_
html,_x000D_
body,_x000D_
#map_canvas {_x000D_
height: 500px;_x000D_
width: 500px;_x000D_
margin: 0px;_x000D_
padding: 0px_x000D_
}_x000D_
.labels {_x000D_
color: white;_x000D_
background-color: red;_x000D_
font-family: "Lucida Grande", "Arial", sans-serif;_x000D_
font-size: 10px;_x000D_
text-align: center;_x000D_
width: 30px;_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>_x000D_
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerwithlabel/src/markerwithlabel.js"></script>_x000D_
<div id="map_canvas" style="height: 400px; width: 100%;"></div>
_x000D_
Remove the characters ^
(start of string) and $
(end of string) from the regular expression.
var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
index.html
should be inside templates
, as I know. So, your second attempt looks correct.
But, as the error message says, index.html
looks like having some errors. E.g. the in the third line, the meta
tag should be actually head
tag, I think.
I experienced this error with my WordPress site but I saw that there were two indexes showing in my developer tools sources.
Chrome Developer Tool Error So I had the thought that if there are two indexes starting at the first line of code then there's a replication and they're conflicting with each other. So I thought that then perhaps it's my HTML minification from my caching plugin tool.
So I turned off the HTML minify setting and deleted my cache. And poof! It worked!
I wrote this method to handle UTF8 arrays and JSON problems. It works fine with array (simple and multidimensional).
/**
* Encode array from latin1 to utf8 recursively
* @param $dat
* @return array|string
*/
public static function convert_from_latin1_to_utf8_recursively($dat)
{
if (is_string($dat)) {
return utf8_encode($dat);
} elseif (is_array($dat)) {
$ret = [];
foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d);
return $ret;
} elseif (is_object($dat)) {
foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d);
return $dat;
} else {
return $dat;
}
}
// Sample use
// Just pass your array or string and the UTF8 encode will be fixed
$data = convert_from_latin1_to_utf8_recursively($data);
I've just managed to setup new TabLayout, so here are the quick steps to do this (????)?*:???
Add dependencies inside your build.gradle file:
dependencies {
compile 'com.android.support:design:23.1.1'
}
Add TabLayout inside your layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"/>
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Setup your Activity like this:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class TabLayoutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pull_to_refresh);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FirstTabFragment();
case 1:
default:
return new SecondTabFragment();
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "First Tab";
case 1:
default:
return "Second Tab";
}
}
}
}
i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te
First line of the error message describes the error type: "PDOException". The next line displays PDO::errorInfo
, i.e:
- SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard).
- Driver-specific error code.
- Driver-specific error message.
The stack trace you attached, line 3, reveals that you did not specify the database connection parameters in the configuration file. The error show up when you test on local, right? You need to update /.env
with the actual database connection parameters.
sudo service mysql restart
Or
sudo restart mysql
MySQL added this utf8mb4 code after 5.5.3, Mb4 is the most bytes 4 meaning, specifically designed to be compatible with four-byte Unicode. Fortunately, UTF8MB4 is a superset of UTF8, except that there is no need to convert the encoding to UTF8MB4. Of course, in order to save space, the general use of UTF8 is enough.
The original UTF-8 format uses one to six bytes and can encode 31 characters maximum. The latest UTF-8 specification uses only one to four bytes and can encode up to 21 bits, just to represent all 17 Unicode planes. UTF8 is a character set in Mysql that supports only a maximum of three bytes of UTF-8 characters, which is the basic multi-text plane in Unicode.
To save 4-byte-long UTF-8 characters in Mysql, you need to use the UTF8MB4 character set, but only 5.5. After 3 versions are supported (View version: Select version ();). I think that in order to get better compatibility, you should always use UTF8MB4 instead of UTF8. For char type data, UTF8MB4 consumes more space and, according to Mysql's official recommendation, uses VARCHAR instead of char.
In MariaDB utf8mb4 as the default CHARSET when it not set explicitly in the server config, hence COLLATE utf8mb4_unicode_ci is used.
Refer MariaDB CHARSET & COLLATE Click
CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
You guys copied the wrong code.
Go into the "/build" folder and grab the jquery.datetimepicker.full.js or jquery.datetimepicker.full.min.js if you want the minified version. It should fix it! :)
As previous answers have solved for, but should be stated very explicitly: the php code needs to live in the php-fpm container, while the static files need to live in the nginx container. For simplicity, most people have just attached all the code to both, as I have also done below. If the future, I will likely separate out these different parts of the code in my own projects as to minimize which containers have access to which parts.
Updated my example files below with this latest revelation (thank you @alkaline )
This seems to be the minimum setup for docker 2.0 forward (because things got a lot easier in docker 2.0)
docker-compose.yml:
version: '2'
services:
php:
container_name: test-php
image: php:fpm
volumes:
- ./code:/var/www/html/site
nginx:
container_name: test-nginx
image: nginx:latest
volumes:
- ./code:/var/www/html/site
- ./site.conf:/etc/nginx/conf.d/site.conf:ro
ports:
- 80:80
(UPDATED the docker-compose.yml above: For sites that have css, javascript, static files, etc, you will need those files accessible to the nginx container. While still having all the php code accessible to the fpm container. Again, because my base code is a messy mix of css, js, and php, this example just attaches all the code to both containers)
In the same folder:
site.conf:
server
{
listen 80;
server_name site.local.[YOUR URL].com;
root /var/www/html/site;
index index.php;
location /
{
try_files $uri =404;
}
location ~ \.php$ {
fastcgi_pass test-php:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
In folder code:
./code/index.php:
<?php
phpinfo();
and don't forget to update your hosts file:
127.0.0.1 site.local.[YOUR URL].com
and run your docker-compose up
$docker-compose up -d
and try the URL from your favorite browser
site.local.[YOUR URL].com/index.php
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
<div class="prev">Prev</div>
<div class="next">Next</div>
$('.your_class').slick({
infinite: true,
speed: 300,
slidesToShow: 5,
slidesToScroll: 5,
arrows: true,
prevArrow: $('.prev'),
nextArrow: $('.next')
});
That meta tag basically specifies which character set a website is written with.
Here is a definition of UTF-8:
UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.
in my case (laravel 5+) i had to wrap my password in single quotation marks and clear config cache:
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=user_name
DB_PASSWORD='password'
and then run:
php artisan config:clear
Edit the file .env in your laravel root directory. make looks as in below :
DB_HOST=localhost
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=your-root-pas
Also create one database in phpmyadmin named, "laravel".
Run below commands :
php artisan cache:clear
php artisan config:cache
php artisan config:clear
php artisan migrate
It worked for me, XAMPP with Apache and MySQL.
@Nishit, JSONObject does not natively understand how to parse through a StringBuilder; instead you appear to be using the JSONObject(java.lang.Object bean) constructor to create the JSONObject, however passing it a StringBuilder.
See this link for more information on that particular constructor.
http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.Object%29
When a constructor calls for a java.lang.Object class, more than likely it's really telling you that you're expected to create your own class (since all Classes ultimately extend java.lang.Object) and that it will interface with that class in a specific way, albeit normally it will call for an interface instead (hence the name) OR it can accept any class and interface with it "abstractly" such as calling .toString() on it. Bottom line, you typically can't just pass it any class and expect it to work.
At any rate, this particular constructor is explained as such:
Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the "get" or "is" prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named "getName", and if the result of calling object.getName() is "Larry Fine", then the JSONObject will contain "name": "Larry Fine".
So, what this means is that it's expecting you to create your own class that implements get or is methods (i.e.
public String getName() {...}
or
public boolean isValid() {...}
So, to solve your problem, if you really want that higher level of control and want to do some manipulation (e.g. modify some values, etc.) but still use StringBuilder to dynamically generate the code, you can create a class that extends the StringBuilder class so that you can use the append feature, but implement get/is methods to allow JSONObject to pull the data out of it, however this is likely not what you want/need and depending on the JSON, you might spend a lot of time and energy creating the private fields and get/is methods (or use an IDE to do it for you) or it might be all for naught if you don't necessarily know the breakdown of the JSON string.
So, you can very simply call toString()
on the StringBuilder which will provide a String representation of the StringBuilder instance and passing that to the JSONObject constructor, such as below:
...
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = br.readLine()) != null){
jsonString.append(readAPIResponse);
}
JSONObject jsonObj = new JSONObject(jsonString.toString());
...
The new testing improvements that debuted in Spring Boot 1.4.M2
can help reduce the amount of code you need to write situation such as these.
The test would look like so:
import static org.springframework.test.web.servlet.request.MockMvcRequestB??uilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMat??chers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMat??chers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(HelloWorld.class)
public class UserVehicleControllerTests {
@Autowired
private MockMvc mockMvc;
@Test
public void testSayHelloWorld() throws Exception {
this.mockMvc.perform(get("/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"));
}
}
See this blog post for more details as well as the documentation
Your form is also missing '{{csrf_field()}}'
Updated based on Muhammad's answer...
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(headers()['Content-Range']);
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
you can implement your adapter's onClickListener:
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>implements View.OnClickListener
and use interface with method in it
public interface mClickListener {
public void mClick(View v, int position);
}
and in your onClick method call the method in the interface and pass it the view and position
in your main activity implement that interface
public class MainActivity extends ActionBarActivity implements AdapterClass.mClickListener
and override that method
@Override
public void onCommentsClick(View v, int position) {
final Intent intent = new Intent(this, OtherActivity.class);
}
as its better to manage your activity transition by the activity not other classes
the solution to this problem differs because each time you deploy the application will give you the same sentence or the problem is different, so you should see the tomcat server log for the exact problem.
The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.
For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.
static String getBase64EncodedCipherText(String cipherText) {
byte[] cText = cipherText.getBytes();
// return an ISO-8859-1 encoded String
return Base64.getEncoder().encodeToString(cText);
}
static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
return new String((Base64.getDecoder().decode(encodedCipherText)));
}
public static void main(String[] args) {
try {
String cText = getRawCipherText(null, "Hello World of Encryption...");
System.out.println("Text to encrypt/encode: Hello World of Encryption...");
// This output is a simple sanity check to display that the text
// has indeed been converted to a cipher text which
// is unreadable by all but the most intelligent of programmers.
// It is absolutely inhuman of me to do such a thing, but I am a
// rebel and cannot be trusted in any way. Please look away.
System.out.println("RAW CIPHER TEXT: " + cText);
cText = getBase64EncodedCipherText(cText);
System.out.println("BASE64 ENCODED: " + cText);
// There he goes again!!
System.out.println("BASE64 DECODED: " + getBase64DecodedCipherText(cText));
System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
} catch (Exception e) {
e.printStackTrace();
}
}
The output looks like:
Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;?C?l??<8??U???X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED: q$;?C?l??<8??U???X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...
I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.
Looking at the class in edit #2, I would make it look like this:
class XmlController extends Controller
{
public function index()
{
$content = Request::all();
return Response::json($content);
}
}
Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.
More information on Laravel responses here:
I had the same issue with a site which previously was running fine. I resolved the issue by deleting the temporary files from C:\WINDOWS\Microsoft.NET\Framework\v#.#.#####\Temporary ASP.NET Files\@projectName\###CC##C\###C#CC
var data = JSON.stringify
({
'StrContactDetails': Details,
'IsPrimary': true
})
Submit
is null
because it is not part of activity_main.xml
When you call findViewById
inside an Activity
, it is going to look for a View
inside your Activity's layout.
try this instead :
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Another thing : you use
android:layout_below="@+id/LoginTitle"
but what you want is probably
android:layout_below="@id/LoginTitle"
See this question about the difference between @id
and @+id
.
The problem is the tv.setText(text)
. The variable tv is probably null
and you call the setText
method on that null
, which you can't.
My guess that the problem is on the findViewById
method, but it's not here, so I can't tell more, without the code.
If you are using bootstrap then the below solution will work.
<div>
<button type="submit" class="btn btn-primary" >Invoke User Endpoint</button>
<button type="submit" class="btn btn-primary ml-3">Invoke Hello Endpoint</button>
</div>
_x000D_
In my case, there was no string on which i was calling appendChild
, the object i was passing on appendChild
argument was wrong, it was an array and i had pass an element object, so i used divel.appendChild(childel[0])
instead of divel.appendChild(childel)
and it worked. Hope it help someone.
In my case, the root cause of this exception comes from using an old version mysql-connector and I had this error :
unable to load authentication plugin 'caching_sha2_password'. mysql
Adding this line to the mysql server configuration file (my.cnf or my.ini) fix this issue :
default_authentication_plugin=mysql_native_password
Well, the problem is that Files.newBufferedReader(Path path)
is implemented like this :
public static BufferedReader newBufferedReader(Path path) throws IOException {
return newBufferedReader(path, StandardCharsets.UTF_8);
}
so basically there is no point in specifying UTF-8
unless you want to be descriptive in your code.
If you want to try a "broader" charset you could try with StandardCharsets.UTF_16
, but you can't be 100% sure to get every possible character anyway.
To use AUTO_INCREMENT
you need to deifne column as INT
or floating-point types, not CHAR
.
AUTO_INCREMENT
use only unsigned value, so it's good to use UNSIGNED
as well;
CREATE TABLE discussion_topics (
topic_id INT NOT NULL unsigned AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (topic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Yor $.post
has no data. You need to pass the form data. You can use serialize()
to post the form data. Try this
$("#post-btn").click(function(){
$.post("process.php", $('#reg-form').serialize() ,function(data){
alert(data);
});
});
The same error is produced in MariaDB (10.1.36-MariaDB) by using the combination of parenthesis and the COLLATE statement. My SQL was different, the error was the same, I had:
SELECT *
FROM table1
WHERE (field = 'STRING') COLLATE utf8_bin;
Omitting the parenthesis was solving it for me.
SELECT *
FROM table1
WHERE field = 'STRING' COLLATE utf8_bin;
In Controller, your method should be;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<SaveResponse> uploadAttachment(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
....
Further, you need to update application.yml (or application.properties) to support maximum file size and request size.
spring:
http:
multipart:
max-file-size: 5MB
max-request-size: 20MB
The question is a bit old but I just solved a very similar problem. We have several intranet sites here including the one I'm responsible for, and the others require compatibility mode or they break. For that reason, site rules default IE to compatibility mode on intranet sites. I am upgrading my own stuff and no longer need it; in fact, some of the features I'm trying to use don't look right in compat mode. I'm using the meta IE-Edge tag like you are.
IE assumes websites without the fully-qualified address are intranet, and acts accordingly. With that in mind I just altered the bindings in IIS to only listen to the fully-qualified address, then set up a dummy website that listened for the unqualified address. The second one redirects all traffic to the fully-qualified address, making IE believe it's an external site. The site renders correctly with or without the Compatibility Mode on Intranet Sites box checked.
My answer is WRT python 2.6.2.
import commands
status, output = commands.getstatusoutput("curl -H \"Content-Type:application/json\" -k -u (few other parameters required) -X GET https://example.org -s")
print output
I apologize for not providing the required parameters 'coz it's confidential.
Be sure to configure the 'default'
key in app/config/database.php
For postgres, this would be 'default' => 'postgres',
If you are receiving a [PDOException] could not find driver
error, check to see if you have the correct PHP extensions installed. You need pdo_pgsql.so
and pgsql.so
installed and enabled. Instructions on how to do this vary between operating systems.
For Windows, the pgsql
extensions should come pre-downloaded with the official PHP distribution. Just edit your php.ini
and uncomment the lines extension=pdo_pgsql.so
and extension=pgsql.so
Also, in php.ini
, make sure extension_dir
is set to the proper directory. It should be a folder called extensions
or ext
or similar inside your PHP install directory.
Finally, copy libpq.dll
from C:\wamp\bin\php\php5.*\
into C:\wamp\bin\apache*\bin
and restart all services through the WampServer interface.
If you still get the exception, you may need to add the postgres \bin
directory to your PATH
:
PATH
entry.This should hopefully resolve any problems. For more information see:
We see this a lot with OAuth2 integrations. We provide API services to our Customers, and they'll naively try to put their private key into an AJAX call. This is really poor security. And well-coded API Gateways, backends for frontend, and other such proxies, do not allow this. You should get this error.
I will quote @aspillers comment and change a single word: "Access-Control-Allow-Origin
is a header sent in a server response which indicates IF the client is allowed to see the contents of a result".
ISSUE: The problem is that a developer is trying to include their private key inside a client-side (browser) JavaScript request. They will get an error, and this is because they are exposing their client secret.
SOLUTION: Have the JavaScript web application talk to a backend service that holds the client secret securely. That backend service can authenticate the web app to the OAuth2 provider, and get an access token. Then the web application can make the AJAX call.
DataTables has functionality for this since v 1.10
https://datatables.net/reference/option/createdRow
Example:
$('#tid_css').DataTable({
// ...
"createdRow": function(row, data, dataIndex) {
if (data["column_index"] == "column_value") {
$(row).css("background-color", "Orange");
$(row).addClass("warning");
}
},
// ...
});
I figured out the answer to above problem. Below query will return rows which have even a signle occurrence of characters besides alphabets, numbers, square brackets, curly brackets,s pace and dot. Please note that position of closing bracket ']' in matching pattern is important.
Right ']' has the special meaning of ending a character set definition. It wouldn't make any sense to end the set before you specified any members, so the way to indicate a literal right ']' inside square brackets is to put it immediately after the left '[' that starts the set definition
SELECT * FROM test WHERE REGEXP_LIKE(sampletext, '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );
Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of
So you should prevent the default behaviour of the button click
$('#btnSave').click(function (e) {
// prevent the default event behaviour
e.preventDefault();
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
// perform your save call here
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
Building on what is mentioned in the comments, the simplest solution would be:
@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {
//whatever
}
class SomeDto {
private List<WhateverBudgerPerDateDTO> budgetPerDate;
//getters setters
}
The solution assumes that the HTTP request you are creating actually has
Content-Type:application/json
instead of text/plain
For seekers of missing font-awesome icons, I have collected a few ideas:
Assure you use a correct link to the CDN, such as:
<link
href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css"
rel="stylesheet" type='text/css'>
If your page uses HTTPS, do you link to the font-awesome CSS using HTTPS (replace http://
with https://
in the link above).
Double check that you don't have AdBlock Plus or uBlock enabled. They might be blocking some of the icons.
Reset your browsers cache. (On Chrome do a looong click on the reload button and select Hard Cache Reset)
Assure that the <span>
or <i>
element you use, uses the FontAwesome
font family. For example, it must not just
<i class="fa-pencil" title="Edit"></i>
but
<i class="fa fa-pencil" title="Edit"></i>
It won't work if you have something as the following in your CSS:
* {
font-family: 'Josefin Sans', sans-serif !important;
}
If you are using IE8, are you using a HTML5 Shim?
If this doesn't work, there are further Troubleshooting Ideas on the Font Awesome Wiki.
Just an addendum:
OnFragmentInteractionListener handle communication between Activity and Fragment using an interface (OnFragmentInteractionListener) and is created by default by Android Studio, but if you dont need to communicate with your activity, you can just get ride of it.
The goal is that you can attach your fragment to multiple activities and still reuse the same communication approach (Every activity could have its own OnFragmentInteractionListener for each fragment).
But and if im sure my fragment will be attached to only one type of activity and i want to communicate with that activity?
Then, if you dont want to use OnFragmentInteractionListener because of its verbosity, you can access your activity methods using:
((MyActivityClass) getActivity()).someMethod()
You can implement search filter in listview by two ways. 1. using searchview 2. using edittext.
If yo want to use searchview then read here : searchview filter.
If you want to use edittext, read below.
I have taken reference from : listview search filter android
Code snippets to make filter with edittext.
First create model class MovieNames.java:
public class MovieNames {
private String movieName;
public MovieNames(String movieName) {
this.movieName = movieName;
}
public String getMovieName() {
return this.movieName;
}
}
Create listview_item.xml file :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Make ListViewAdapter.java class :
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private ArrayList<MovieNames> arraylist;
public ListViewAdapter(Context context, ArrayList<MovieNames> arraylist) {
mContext = context;
inflater = LayoutInflater.from(mContext);
this.arraylist = arraylist;
}
public class ViewHolder {
TextView name;
}
@Override
public int getCount() {
return arraylist.size();
}
@Override
public MovieNames getItem(int position) {
return arraylist.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.name.setText(arraylist.get(position).getMovieName());
return view;
}
}
Prepare activity_main.xml file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.parsaniahardik.searchedit.MainActivity"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="enter query"
android:singleLine="true">
<requestFocus/>
</EditText>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:divider="#694fea"
android:dividerHeight="1dp" />
</LinearLayout>
Finally make MainActivity.java class :
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private EditText etsearch;
private ListView list;
private ListViewAdapter adapter;
private String[] moviewList;
public static ArrayList<MovieNames> movieNamesArrayList;
public static ArrayList<MovieNames> array_sort;
int textlength = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Generate sample data
moviewList = new String[]{"Xmen", "Titanic", "Captain America",
"Iron man", "Rocky", "Transporter", "Lord of the rings", "The jungle book",
"Tarzan","Cars","Shreck"};
list = (ListView) findViewById(R.id.listView);
movieNamesArrayList = new ArrayList<>();
array_sort = new ArrayList<>();
for (int i = 0; i < moviewList.length; i++) {
MovieNames movieNames = new MovieNames(moviewList[i]);
// Binds all strings into an array
movieNamesArrayList.add(movieNames);
array_sort.add(movieNames);
}
adapter = new ListViewAdapter(this,movieNamesArrayList);
list.setAdapter(adapter);
etsearch = (EditText) findViewById(R.id.editText);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, array_sort.get(position).getMovieName(), Toast.LENGTH_SHORT).show();
}
});
etsearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlength = etsearch.getText().length();
array_sort.clear();
for (int i = 0; i < movieNamesArrayList.size(); i++) {
if (textlength <= movieNamesArrayList.get(i).getMovieName().length()) {
Log.d("ertyyy",movieNamesArrayList.get(i).getMovieName().toLowerCase().trim());
if (movieNamesArrayList.get(i).getMovieName().toLowerCase().trim().contains(
etsearch.getText().toString().toLowerCase().trim())) {
array_sort.add(movieNamesArrayList.get(i));
}
}
}
adapter = new ListViewAdapter(MainActivity.this, array_sort);
list.setAdapter(adapter);
}
});
}
}
Since you return to the client just String
and its content type == 'text/plain'
, there is no any chance for default converters to determine how to convert String
response to the FFSampleResponseHttp
object.
The simple way to fix it:
expected-response-type
from <int-http:outbound-gateway>
replyChannel1
<json-to-object-transformer>
Otherwise you should write your own HttpMessageConverter
to convert the String to the appropriate object.
To make it work with MappingJackson2HttpMessageConverter
(one of default converters) and your expected-response-type
, you should send your reply with content type = 'application/json'
.
If there is a need, just add <header-enricher>
after your <service-activator>
and before sending a reply to the <int-http:inbound-gateway>
.
So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.
UPDATE
OK. Since you changed your server to return FfSampleResponseHttp
object as HTTP response, not String, just add contentType = 'application/json'
header before sending the response for the HTTP and MappingJackson2HttpMessageConverter
will do the stuff for you - your object will be converted to JSON and with correct contentType
header.
From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp"
and MappingJackson2HttpMessageConverter
should do the stuff for you again.
Of course you should remove <json-to-object-transformer>
from you message flow after <int-http:outbound-gateway>
.
It depends on when the self executing anonymous function is running. It is possible that it is running before window.document
is defined.
In that case, try adding a listener
window.addEventListener('load', yourFunction, false);
// ..... or
window.addEventListener('DOMContentLoaded', yourFunction, false);
yourFunction () {
// some ocde
}
Update: (after the update of the question and inclusion of the code)
Read the following about the issues in referencing DOM elements from a JavaScript inserted and run in head
element:
- “getElementsByTagName(…)[0]” is undefined?
- Traversing the DOM
FireFox is reporting that the response did not even specify the character encoding in the header, eg. Content-Type: text/html; charset=utf-8
and not just Content-Type: text/plain;
.
What web server are you using? Are you sure you are not requesting a non-existing page (404) that responds poorly?
"Java 8 support for Eclipse Kepler SR2", and the new "JavaSE-1.8" execution environment showed up automatically.
Download this one:- Eclipse kepler SR2
and then follow this link:- Eclipse_Java_8_Support_For_Kepler
Add this to your section:
<script> function resizeIframe(obj) { obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px'; } </script>
And change your iframe to this:
<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />
It is posted Here
It does however use javascript, but it is simple and easy to use code that will fix your problem.
write
php artisan config:cache
in your terminal and it will be fixed
You could implement a showfile function which takes in parameters of the data returned from the WEBApi, and a filename for the file you are trying to download. What I did was create a separate browser service identifies the user's browser and then handles the rendering of the file based on the browser. For instance if the target browser is chrome on an ipad, you have to use javascripts FileReader object.
FileService.showFile = function (data, fileName) {
var blob = new Blob([data], { type: 'application/pdf' });
if (BrowserService.isIE()) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
}
else if (BrowserService.isChromeIos()) {
loadFileBlobFileReader(window, blob, fileName);
}
else if (BrowserService.isIOS() || BrowserService.isAndroid()) {
var url = URL.createObjectURL(blob);
window.location.href = url;
window.document.title = fileName;
} else {
var url = URL.createObjectURL(blob);
loadReportBrowser(url, window,fileName);
}
}
function loadFileBrowser(url, window, fileName) {
var iframe = window.document.createElement('iframe');
iframe.src = url
iframe.width = '100%';
iframe.height = '100%';
iframe.style.border = 'none';
window.document.title = fileName;
window.document.body.appendChild(iframe)
window.document.body.style.margin = 0;
}
function loadFileBlobFileReader(window, blob,fileName) {
var reader = new FileReader();
reader.onload = function (e) {
var bdata = btoa(reader.result);
var datauri = 'data:application/pdf;base64,' + bdata;
window.location.href = datauri;
window.document.title = fileName;
}
reader.readAsBinaryString(blob);
}
Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.
If so, please update bootstrap, worked for me.
If you use AIX try this This will attach a text file and include a HTML body If this does not work catch the output in the /var/spool/mqueue
#!/usr/bin/kWh
if (( $# < 1 ))
then
echo "\n\tSyntax: $(basename) MAILTO SUBJECT BODY.html ATTACH.txt "
echo "\tmailzatt"
exit
fi
export MAILTO=${[email protected]}
MAILFROM=$(whoami)
SUBJECT=${2-"mailzatt"}
export BODY=${3-/apps/bin/attch.txt}
export ATTACH=${4-/apps/bin/attch.txt}
export HST=$(hostname)
#export BODY="/wrk/stocksum/report.html"
#export ATTACH="/wrk/stocksum/Report.txt"
#export MAILPART=`uuidgen` ## Generates Unique ID
#export MAILPART_BODY=`uuidgen` ## Generates Unique ID
export MAILPART="==".$(date +%d%S)."===" ## Generates Unique ID
export MAILPART_BODY="==".$(date +%d%Sbody)."===" ## Generates Unique ID
(
echo "To: $MAILTO"
echo "From: mailmate@$HST "
echo "Subject: $SUBJECT"
echo "MIME-Version: 1.0"
echo "Content-Type: multipart/mixed; boundary=\"$MAILPART\""
echo ""
echo "--$MAILPART"
echo "Content-Type: multipart/alternative; boundary=\"$MAILPART_BODY\""
echo ""
echo ""
echo "--$MAILPART_BODY"
echo "Content-Type: text/html"
echo "Content-Disposition: inline"
cat $BODY
echo ""
echo "--$MAILPART_BODY--"
echo ""
echo "--$MAILPART"
echo "Content-Type: text/plain"
echo "Content-Disposition: attachment; filename=\"$(basename $ATTACH)\""
echo ""
cat $ATTACH
echo ""
echo "--${MAILPART}--"
) | /usr/sbin/sendmail -t
replace operates on a specific string, so you need to call it like this
removeSpecialChars = z.replace("!@#$%^&*()[]{};:,./<>?\|`~-=_+", " ")
but this is probably not what you need, since this will look for a single string containing all that characters in the same order. you can do it with a regexp, as Danny Michaud pointed out.
as a side note, you might want to look for BeautifulSoup, which is a library for parsing messy HTML formatted text like what you usually get from scaping websites.
app.factory('getSettings', ['$http','$q' /*here!!!*/,function($http, $q) {
you need to declare ALL your dependencies OR none and you forgot to declare $q .
edit:
controller.js : login, dont return ""
The answer to your original question
How to read a string one char at the time, and stop when you reach end of line?
is, in C++, very simply, namely: use getline. The link shows a simple example:
#include <iostream>
#include <string>
int main () {
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
Do you really want to do this in C? I wouldn't! The thing is, in C, you have to allocate the memory in which to place the characters you read in? How many characters? You don't know ahead of time. If you allocate too few characters, you will have to allocate a new buffer every time to realize you reading more characters than you made room for. If you over-allocate, you are wasting space.
C is a language for low-level programming. If you are new to programming and writing simple applications for reading files line-by-line, just use C++. It does all that memory allocation for you.
Your later questions regarding "\0"
and end-of-lines in general were answered by others and do apply to C as well as C++. But if you are using C, please remember that it's not just the end-of-line that matters, but memory allocation as well. And you will have to be careful not to overrun your buffer.
I think your issue may be in the url pattern. Changing
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
and
<form action="/Register" method="post">
may fix your problem
Use this
<script>
$(document).ready(function(){
$( '.expand' ).click(function() {
$( '.img_display_content' ).show();
});
});
</script>
Event assigning always after Document Object Model loaded
You will have to define Serializer Formatter within WebApiConfig.cs available in App_Start Folder like
Adding config.Formatters.Remove(config.Formatters.XmlFormatter); // which will provide you data in JSON Format
Adding config.Formatters.Remove(config.Formatters.JsonFormatter); // which will provide you data in XML Format
use this code it is working
// index.jsp or login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In C the char type has a numeric value so the > operator will work just fine for example
#include <stdio.h>
main() {
char a='z';
char b='h';
if ( a > b ) {
printf("%c greater than %c\n",a,b);
}
}
BlobBuilder
is obsolete, use Blob
constructor instead:
URL.createObjectURL(new Blob([/*whatever content*/] , {type:'text/plain'}));
This returns a blob URL which you can then use in an anchor's href
. You can also modify an anchor's download
attribute to manipulate the file name:
<a href="/*assign url here*/" id="link" download="whatever.txt">download me</a>
Fiddled. If I recall correctly, there are arbitrary restrictions on trusted non-user initiated downloads; thus we'll stick with a link clicking which is seen as sufficiently user-initiated :)
Update: it's actually pretty trivial to save current document's html! Whenever our interactive link is clicked, we'll update its href
with a relevant blob. After executing the click-bound event, that's the download URL that will be navigated to!
$('#link').on('click', function(e){
this.href = URL.createObjectURL(
new Blob([document.documentElement.outerHTML] , {type:'text/html'})
);
});
If you are making jquery ajax request, dont forget to add
contentType:'application/json'
I had simillar issue with maven tests on x86 linux which i was using in terminal. I was logging in to linux by ssh. I started my java selenium tests by
mvn -DargLine="-Dbaseurl=http://http://127.0.0.1:8080/web/" install
Excepting my app, after running these tests I received error in logs:
unknown error: Chrome failed to start: exited abnormally
I was running these tests as root user. Before this error i received that ChromeDriver is nor present. I moved forward with this by installing ChromeDriver binary and adding it to PATH. But then i had to install google-chrome browser - ChromeDriver alone isn't enough to run tests. So the mistake is problem maybe with screen buffer in terminal window, but You can install Xvfb which is virtual screen buffer. What is important, that you should run your tests not as root, because you may receive another Chrome Browser error. So no as root i run:
export DISPLAY=:99
Xvfb :99 -ac -screen 0 1280x1024x24 &
What is important here, that in my case the number related to DISPLAY ought to be same as Xvfb :NN parameter. 99 in that case. I had another problem because i ran Xvfb with another DISPLAY value and I wanted it to stop. In order to restart Xvfb:
ps -aux | grep Xvfb
kill -9 PID
sudo rm /tmp/.X11-unix/X99
So find a process PID with grep. Kill Xvfb process. And then there is lock in /tmp/.X11-unix/XNN , so delete this lock and you can start server again. If You run not as root, set simillar displays, install google-chrome then with maven you can start selenium tests. My tests went fine with these rules and operations.
The fastest method is regex
#Try with regex first
t0 = timeit.timeit("""
s = r2.sub('', st)
""", setup = """
import re
r2 = re.compile(r'[^a-zA-Z0-9]', re.MULTILINE)
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""", number = 1000000)
print(t0)
#Try with join method on filter
t0 = timeit.timeit("""
s = ''.join(filter(str.isalnum, st))
""", setup = """
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""",
number = 1000000)
print(t0)
#Try with only join
t0 = timeit.timeit("""
s = ''.join(c for c in st if c.isalnum())
""", setup = """
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""", number = 1000000)
print(t0)
2.6002226710006653 Method 1 Regex
5.739747313000407 Method 2 Filter + Join
6.540099570000166 Method 3 Join
Had the same issue and just figured, website is running under MAMP's php, but when you call in command, it runs mac's(if no bash path modified). you will have issue when mac doesn't have those extensions.
run php -i to find out loaded extensions, and install those one you missed. or run '/Applications/MAMP/bin/php/php5.3.6/bin/php artisan {your command}' to use MAMP's
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
Use like this on dropdown change
$("#assetgroupSelect").change(function(){
$("#idValue").val($this.val());
})
you code is fine but never executed, cause of submit button [type="submit"] just replace it by type=button
<input value="Submit" type="button" onclick="submitform()">
inside your script; form is not declared.
let form = document.forms[0];
xhr.open(form.method, form.action, true);
It seems to be a browser bug.
10690: Reported a bug in Firefox for responsive images (those with max-width: 100%) in table cells. No other browsers are affected. See
.img-responsive
in <fieldset>
have the same behaviour.
In addition to all the answers, if you happen to receive in response text/html
while you've expected something else (i.e. application/json
), it may suggest that an error occurred on the server side (say 404) and the error page was returned instead of your data.
So it happened in my case. Hope it will save somebody's time.
You are sending a array of string
var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
So change model type accordingly
public ActionResult AddUser(List<string> model)
{
}
instead of receiving the json string a model binding is better. For example:
[HttpPost]
public ActionResult AddUser(UserAddModel model)
{
if (ModelState.IsValid) {
return Json(new { Response = "Success" });
}
return Json(new { Response = "Error" });
}
<script>
function submitForm() {
$.ajax({
type: 'POST',
url: "@Url.Action("AddUser")",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: $("form[name=UserAddForm]").serialize(),
success: function (data) {
console.log(data);
}
});
}
</script>
Check that doPost()
method of servlet is called from the jsp form and remove conn.commit
.
Make this changes in php file
<html>
<head>
<meta charset="utf-8">
<title>Answer</title>
</head>
<body>
<p>The answer is:
<?php
$first = $_POST['first'];
$second= $_POST['second'];
if($_POST['group1'] == 'add') {
echo $first + $second;
}
else if($_POST['group1'] == 'subtract') {
echo $first - $second;
}
else if($_POST['group1'] == 'times') {
echo $first * $second;
}
else if($_POST['group1'] == 'divide') {
echo $first / $second;
}
else {
echo "Enter the numbers properly";
}
?>
</p>
</body>
</html>
Just to complement m59's correct answer, here is a working jsfiddle:
<body ng-app='myApp'>
<div>
<button my-directive>Click Me!</button>
</div>
<h1>{{2+3}}</h1>
</body>
Use this code to pass arraylist<customobj>
to anthother Activity
firstly serialize our contact bean
public class ContactBean implements Serializable {
//do intialization here
}
Now pass your arraylist
Intent intent = new Intent(this,name of activity.class);
contactBean=(ConactBean)_arraylist.get(position);
intent.putExtra("contactBeanObj",conactBean);
_activity.startActivity(intent);
Adding certificates to Java\jdk\jre\lib\security folder worked for me. If you are using Chrome click on the green bulb [https://support.google.com/chrome/answer/95617?p=ui_security_indicator&rd=1] and save the certificate in security folder.
I had read yesterday that the issue was fixed for someone when that person cleared cookies. I had tried that but it did not work for me.
Checking the following section in DatabaseInterface.class.php,
define(
'PMA_MYSQL_INT_VERSION',
PMA_Util::cacheGet('PMA_MYSQL_INT_VERSION', true)
);
I figured that somehow cache is the problem. So, I remembered that I was restarting the service instead of doing a start
and stop
.
# restart the service
systemd restart php-fpm
# start and stop the service
systemd stop php-fpm
systemd start php-fpm
Doing a stop
followed by a start
fixed the issue for me.
Some answers already pointed out background-size: cover
is useful in the case, but none points out the browser support details. Here it is:
Add this CSS into your stylesheet:
body {
background: url(background.jpg) no-repeat center center fixed;
background-size: cover; /* for IE9+, Safari 4.1+, Chrome 3.0+, Firefox 3.6+ */
-webkit-background-size: cover; /* for Safari 3.0 - 4.0 , Chrome 1.0 - 3.0 */
-moz-background-size: cover; /* optional for Firefox 3.6 */
-o-background-size: cover; /* for Opera 9.5 */
margin: 0; /* to remove the default white margin of body */
padding: 0; /* to remove the default white margin of body */
}
-moz-background-size: cover;
is optional for Firefox, as Firefox starts supporting the value cover
since version 3.6. If you need to support Konqueror 3.5.4+ as well, add -khtml-background-size: cover;
.
As you're using CSS3, it's suggested to change your DOCTYPE to HTML5. Also, HTML5 CSS Reset stylesheet is suggested to be added BEFORE your our stylesheet to provide a consistent look & feel for modern browsers.
Reference: background-size at MDN
If you ever need to support old browsers like IE 8 or below, you can still go for Javascript way (scroll down to jQuery section)
Last, if you predict your users will use mobile phones to browse your website, do not use the same background image for mobile web, as your desktop image is probably large in file size, which will be a burden to mobile network usage. Use media query to branch CSS.
Looks to be the same question as:
When an ASP.NET System.Web.HttpResponse.End() is called, the current thread is aborted?
So it's by design. You need to add a catch for that exception and gracefully "ignore" it.
One way to achieve this is using a position:fixed
container for the background image and place it outside of the .jumbotron
. Make the bg
container the same height as the .jumbotron
and center the background image:
background: url('/assets/example/...jpg') no-repeat center center;
CSS
.bg {
background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
position: fixed;
width: 100%;
height: 350px; /*same height as jumbotron */
top:0;
left:0;
z-index: -1;
}
.jumbotron {
margin-bottom: 0px;
height: 350px;
color: white;
text-shadow: black 0.3em 0.3em 0.3em;
background:transparent;
}
Then use jQuery to decrease the height of the .jumbtron
as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.
JavaScript
var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
var scrolled = $(window).scrollTop();
$('.bg').css('height', (jumboHeight-scrolled) + 'px');
}
$(window).scroll(function(e){
parallax();
});
Demo
check String before set another EditText
to empty. if Field1
is empty then why need to change again to ( "" )? so you can check the size of Your String with s.lenght() or any other solution
another way that you can check lenght of String is:
String sUsername = Field1.getText().toString();
if (!sUsername.matches(""))
{
// do your job
}
Please set your form action attribute as below it will solve your problem.
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
jQuery code:
$(document).ready(function () {
$("#addProductForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});
Before teaching yourself Spring and Struts, you should probably learn Java. Output like this
org.classes.database.Employee@d9b02
is the result of the Object#toString()
method which all objects inherit from the Object
class, the superclass of all classes in Java.
The List
sub classes implement this by iterating over all the elements and calling toString()
on those. It seems, however, that you haven't implemented (overriden) the method in your Employee
class.
Your JSTL here
<c:forEach items="${eList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>
</tr>
</c:forEach>
is fine except for the fact that you don't have a page, request, session, or application scoped attribute named eList
.
You need to add it
<% List eList = (List)session.getAttribute("empList");
request.setAttribute("eList", eList);
%>
Or use the attribute empList
in the forEach
.
<c:forEach items="${empList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>
</tr>
</c:forEach>
Writing this middleware might help !
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
for details visit http://enable-cors.org/server_expressjs.html
In my case, I use nginx as reverse-proxy for an API Gateway URL. I got same error.
I resolved the issue when I added the following two lines to the Nginx config:
proxy_set_header Host "XXXXXX.execute-api.REGION.amazonaws.com";
proxy_ssl_server_name on;
Source is here: Setting up proxy_pass on nginx to make API calls to API Gateway
?php
/* Database config */
$db_host = 'localhost';
$db_user = '~';
$db_pass = '~';
$db_database = 'banners';
/* End config */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
These are all good answers, however many forget to close the cursor and database. If you don't close the cursor or database you may run in to memory leaks.
Additionally:
You can get an error when searching by String
that contains non alpha/numeric characters. For example: "1a5f9ea3-ec4b-406b-a567-e6927640db40
". Those dashes (-
) will cause an unrecognized token
error. You can overcome this by putting the string in an array. So make it a habit to query like this:
public boolean hasObject(String id) {
SQLiteDatabase db = getWritableDatabase();
String selectString = "SELECT * FROM " + _TABLE + " WHERE " + _ID + " =?";
// Add the String you are searching by here.
// Put it in an array to avoid an unrecognized token error
Cursor cursor = db.rawQuery(selectString, new String[] {id});
boolean hasObject = false;
if(cursor.moveToFirst()){
hasObject = true;
//region if you had multiple records to check for, use this region.
int count = 0;
while(cursor.moveToNext()){
count++;
}
//here, count is records found
Log.d(TAG, String.format("%d records found", count));
//endregion
}
cursor.close(); // Dont forget to close your cursor
db.close(); //AND your Database!
return hasObject;
}
According to the create table statement, the default charset of the table is already utf8mb4. It seems that you have a wrong connection charset.
In Java, set the datasource url like this: jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8.
"?useUnicode=true&characterEncoding=utf-8" is necessary for using utf8mb4.
It works for my application.
After years, I want to add another approach by using a view engine in Express.js
var fs = require('fs');
app.get('/test', function(req, res, next) {
var html = fs.readFileSync('./html/test.html', 'utf8')
res.render('test', { html: html })
// or res.send(html)
})
Then, do that in your views/test
if you choose res.render
method at the above code (I'm writing in EJS format):
<%- locals.html %>
That's all.
In this way, you don't need to break your View Engine arrangements.
EDIT : 31/10/2017
The same code/approach will work for Asp.Net Core 2.0 as well. The major difference is, In asp.net core, both web api controllers and Mvc controllers are merged together to single controller model. So your return type might be IActionResult
or one of it's implementation (Ex :OkObjectResult
)
Use
contentType:"application/json"
You need to use JSON.stringify
method to convert it to JSON string when you send it,
And the model binder will bind the json data to your class object.
The below code will work fine (tested)
$(function () {
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
});
Result
contentType
property tells the server that we are sending the data in JSON format. Since we sent a JSON data structure,model binding will happen properly.
If you inspect the ajax request's headers, you can see that the Content-Type
value is set as application/json
.
If you do not specify contentType explicitly, It will use the default content type which is application/x-www-form-urlencoded;
Edit on Nov 2015 to address other possible issues raised in comments
Let's say you have a complex view model class as your web api action method parameter like this
public class CreateUserViewModel
{
public int Id {set;get;}
public string Name {set;get;}
public List<TagViewModel> Tags {set;get;}
}
public class TagViewModel
{
public int Id {set;get;}
public string Code {set;get;}
}
and your web api end point is like
public class ProductController : Controller
{
[HttpPost]
public CreateUserViewModel Save([FromBody] CreateUserViewModel m)
{
// I am just returning the posted model as it is.
// You may do other stuff and return different response.
// Ex : missileService.LaunchMissile(m);
return m;
}
}
At the time of this writing, ASP.NET MVC 6 is the latest stable version and in MVC6, Both Web api controllers and MVC controllers are inheriting from Microsoft.AspNet.Mvc.Controller
base class.
To send data to the method from client side, the below code should work fine
//Build an object which matches the structure of our view model class
var model = {
Name: "Shyju",
Id: 123,
Tags: [{ Id: 12, Code: "C" }, { Id: 33, Code: "Swift" }]
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: "../product/save",
contentType: "application/json"
}).done(function(res) {
console.log('res', res);
// Do something with the result :)
});
If you do not decorate the web api method parameter with [FromBody]
attribute
[HttpPost]
public CreateUserViewModel Save(CreateUserViewModel m)
{
return m;
}
And send the model(raw javascript object, not in JSON format) without specifying the contentType property value
$.ajax({
type: "POST",
data: model,
url: "../product/save"
}).done(function (res) {
console.log('res', res);
});
Model binding will work for the flat properties on the model, not the properties where the type is complex/another type. In our case, Id
and Name
properties will be properly bound to the parameter m
, But the Tags
property will be an empty list.
The same problem will occur if you are using the short version, $.post
which will use the default Content-Type when sending the request.
$.post("../product/save", model, function (res) {
//res contains the markup returned by the partial view
console.log('res', res);
});
There are 2 easy ways
For Kotlin and bindings the code is:
binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
You should use this library for multi upload in CI https://github.com/stvnthomas/CodeIgniter-Multi-Upload
A very good solution to this can be found here:
Here's a class that serves as a wrapper to a pyserial object. It allows you to read lines without 100% CPU. It does not contain any timeout logic. If a timeout occurs,
self.s.read(i)
returns an empty string and you might want to throw an exception to indicate the timeout.
It is also supposed to be fast according to the author:
The code below gives me 790 kB/sec while replacing the code with pyserial's readline method gives me just 170kB/sec.
class ReadLine:
def __init__(self, s):
self.buf = bytearray()
self.s = s
def readline(self):
i = self.buf.find(b"\n")
if i >= 0:
r = self.buf[:i+1]
self.buf = self.buf[i+1:]
return r
while True:
i = max(1, min(2048, self.s.in_waiting))
data = self.s.read(i)
i = data.find(b"\n")
if i >= 0:
r = self.buf + data[:i+1]
self.buf[0:] = data[i+1:]
return r
else:
self.buf.extend(data)
ser = serial.Serial('COM7', 9600)
rl = ReadLine(ser)
while True:
print(rl.readline())
You have mentioned Wrong id
alert(document.getElementById("name").value);
if you want to use name
attribute then
alert(document.getElementsByName("username")[0].value);
Updates:
input type="text" id="name" name="username"
id is different from name
Use Flowplayer:
<link rel="stylesheet" href="//releases.flowplayer.org/7.0.4/commercial/skin/skin.css">
<style>
</style>
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="//releases.flowplayer.org/7.0.4/commercial/flowplayer.min.js"></script>
<script src="//releases.flowplayer.org/hlsjs/flowplayer.hlsjs.min.js"></script>
<script>
flowplayer(function (api) {
api.on("load", function (e, api, video) {
$("#vinfo").text(api.engine.engineName + " engine playing " + video.type);
}); });
</script>
<div class="flowplayer fixed-controls no-toggle no-time play-button obj"
style=" width: 85.5%;
height: 80%;
margin-left: 7.2%;
margin-top: 6%;
z-index: 1000;" data-key="$812975748999788" data-live="true" data-share="false" data-ratio="0.5625" data-logo="">
<video autoplay="true" stretch="true">
<source type="application/x-mpegurl" src="http://live.wmncdn.net/safaritv2/live2.stream/index.m3u8">
</video>
</div>
Different methods are available in flowplayer.org website.
you can add the 1px border to just the sides and bottom of each row. the first value is the top border, the second is the right border, the third is the bottom border, and the fourth is the left border.
div.row {
border: 0px 1px 1px 1px solid;
}
request.getContextPath()-
returns root path of your application, while
../
- returns parent directory of a file.
You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.
Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
PS- This is the one reason I can figure out. Don't know if there is any more significance to it.
The following worked for me:
/* function to save JSON to file from browser
* adapted from http://bgrins.github.io/devtools-snippets/#console-save
* @param {Object} data -- json object to save
* @param {String} file -- file name to save to
*/
function saveJSON(data, filename){
if(!data) {
console.error('No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
and then to call it like so
saveJSON(myJsonObject, "saved_data.json");
For the header half of the question, I'm gonna give a shout out to res.type
here:
res.type('json')
is equivalent to
res.setHeader('Content-Type', 'application/json')
Source: express docs:
Sets the Content-Type HTTP header to the MIME type as determined by mime.lookup() for the specified type. If type contains the “/” character, then it sets the Content-Type to type.
When autocomplete changes a value, it fires a autocompletechange event, not the change event
$(document).ready(function () {
$('#tags').on('autocompletechange change', function () {
$('#tagsname').html('You selected: ' + this.value);
}).change();
});
Demo: Fiddle
Another solution is to use select event, because the change event is triggered only when the input is blurred
$(document).ready(function () {
$('#tags').on('change', function () {
$('#tagsname').html('You selected: ' + this.value);
}).change();
$('#tags').on('autocompleteselect', function (e, ui) {
$('#tagsname').html('You selected: ' + ui.item.value);
});
});
Demo: Fiddle
It's due to you sending one object, and you're expecting two parameters.
Try this and you'll see:
public class UserDetails
{
public string username { get; set; }
public string password { get; set; }
}
public JsonResult Login(UserDetails data)
{
string error = "";
//the rest of your code
}
Below code is working on my live server as well as in my own Lapy.
Note:
Please Create data folder in WebContent and put in any single image or any file(jsp or html file).
Add jar files
commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
commons-logging-1.0.4.jar
upload.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
UploadServlet.java
package com.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String DATA_DIRECTORY = "data";
private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
private static final int MAX_REQUEST_SIZE = 1024 * 1024;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);
// Sets the directory used to temporarily store files that are larger
// than the configured size threshold. We use temporary directory for
// java
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("")
+ File.separator + DATA_DIRECTORY;
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println(filePath);
// saves the file to upload directory
item.write(uploadedFile);
}
}
// displays done.jsp page after upload finished
getServletContext().getRequestDispatcher("/done.jsp").forward(
request, response);
} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
web.xml
<servlet>
<description></description>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
done.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>
for (int i = 0; i < 5; i++){
int asciiVal = rand()%26 + 97;
char asciiChar = asciiVal;
cout << asciiChar << " and ";
}
public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter.add("aaaa")
}
}
Be aware also if you have declared getters and setters for attributes of the parameter which are not sent in the POST (event if they are not declared in the constructor), for example:
@RestController
public class TestController {
@RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(@RequestBody BeanTest beanTest) {
return "Hello " + beanTest.getName();
}
public static class BeanTest {
private Long id;
private String name;
public BeanTest() {
}
public BeanTest(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
A post request with the next structure: {"id":"1"} would not work, you must delete name get and set.
It looks like this issue has to do with the difference between the Content-Type
and Accept
headers. In HTTP, Content-Type
is used in request and response payloads to convey the media type of the current payload. Accept
is used in request payloads to say what media types the server may use in the response payload.
So, having a Content-Type
in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type
does matter.
If a server is not able to process the Content-Type
of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept
header, it will return a 406 error.)
In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.
You could fix this in one of two ways:
Include the DataServiceVersion header in the request and set it be less than v3. For example:
DataServiceVersion: 2.0;
(Option 2 assumes that you aren't using any v3 features in your request payload.)
This is for your reference only:
https://github.com/rajit/bootstrap3-datepicker/tree/master/locales/zh-CN
https://github.com/smalot/bootstrap-datetimepicker
https://bootstrap-datepicker.readthedocs.io/en/v1.4.1/i18n.html
The case is as follows:
<div class="input" id="event_period">
<input class="date" required="required" type="text">
</div>
$.fn.datepicker.dates['zh-CN'] = {
days:["???","???","???","???","???","???","???"],
daysShort:["??","??","??","??","??","??","??"],
daysMin:["?","?","?","?","?","?","?"],
months:["??","??","??","??","??","??","??","??","??","??","???","???"],
monthsShort:["1?","2?","3?","4?","5?","6?","7?","8?","9?","10?","11?","12?"],
today:"??",
clear:"??"
};
$('#event_period').datepicker({
inputs: $('input.date'),
todayBtn: "linked",
clearBtn: true,
format: "yyyy?mm?",
titleFormat: "yyyy?mm?",
language: 'zh-CN',
weekStart:1 // Available or not
});
I think you want like this, DEMO
var xmlDoc = $.parseXML( xml );
var $xml = $(xmlDoc);
var $person = $xml.find("person");
$person.each(function(){
var name = $(this).find('name').text(),
age = $(this).find('age').text();
$("#ProfileList" ).append('<li>' +name+ ' - ' +age+ '</li>');
});
The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts
svg.selectAll("rect")
.attr('x',function(d,i){
// get x coord
console.log(this.getBBox().x, 'or', d3.select(this).attr('x'))
})
.attr('y',function(d,i){
// get y coord
console.log(this.getBBox().y)
})
.attr('dx',function(d,i){
// get dx coord
console.log(parseInt(d3.select(this).attr('dx')))
})
On Windows 10, curl 7.28.1 within powershell, I found the following to work for me:
$filePath = "c:\temp\dir with spaces\myfile.wav"
$curlPath = ("myfilename=@" + $filePath)
curl -v -F $curlPath URL
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
I've had same problem, and this is how I fixed it:
Just throw this in your web.config:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE" />
<add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type" />
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
The problem here is very simple. If you want to display value in JSP, you have to use <%= %> tag instead of <% %>, here is the solved code:
<tr>
<td><%=rs.getInt("ID") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getString("SKILL") %></td>
</tr>
For me, the problem was passing in a larger than normally expected HTTP header. I resolved it by setting maxHttpHeaderSize="1048576" attribute on the Connector node in server.xml.
function nameInput(limitField)
{
//LimitFile here is a text input and this function is passed to the text
onInput
var inputString = limitField.value;
// here we capture all illegal chars by adding a ^ inside the class,
// And overwrite them with "".
var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
limitField.value = newStr;
}
This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.
Depending on what you want to accomplish, you might replace INSERT with INSERT IGNORE in your file. This will avoid generating an error for the rows that you are trying to insert and already exist.
May be this problem cause by Gmail account protection. Just click below link and disable security settings.It will work. https://www.google.com/settings/security/lesssecureapps
I Just put CSS in my <div>
now working in code
position: relative; top: -22px;
I would recommend you to make use of the $.post
or $.get
syntax of jQuery for simple cases:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
});
If you need to catch the fail cases, just do this:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
Additionally, if you always send a JSON string, you can use $.getJSON or $.post with one more parameter at the very end.
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}, 'json');
This example will help you:
<form>
<input type="button" value="Open Window" onclick="window.open('http://www.google.com')">
</form>
You can open next page on same page by:
<input type="button" value="Open Window" onclick="window.open('http://www.google.com','_self')">
dealing with dates, dateadd must be used for precision
declare @a DATE = getdate()
declare @b time(7) = getdate()
select @b, @A, GETDATE(), DATEADD(day, DATEDIFF(day, 0, @a), cast(@b as datetime2(0)))
I believe this is the best way of doing it, I've tried it and it works very well.
#img {
object-fit: cover;
}
This is where I found it. Good luck!
for ( i = 0; i < total.length; i++ );
^-- remove the semi-colon here
With this semi-colon, the loop loops until i == total.length
, doing nothing, and then what you thought was the body of the loop is executed.
You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.
In the Controller, you can use the javax.json to convert and manipulate this.
Download and add the .jar to the project libs and import the JsonObject.
To create an json object, you can use
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("header1", foo1);
job.add("header2", foo2);
JsonObject json = job.build();
To read it from String, you can use
JsonReader jr = Json.createReader(new StringReader(jsonString));
JsonObject json = jsonReader.readObject();
jsonReader.close();
I believe you have to reference bootstrap.js before bootstrap-datepicker.js
I just came up with the same problem since we still use bootstrap 2.3.2.
My solution for this: http://jsfiddle.net/KnuU6/281/
css:
.myCollapse {
display: none;
}
.myCollapse.in {
display: block;
}
javascript:
$("[data-toggle=myCollapse]").click(function( ev ) {
ev.preventDefault();
var target;
if (this.hasAttribute('data-target')) {
target = $(this.getAttribute('data-target'));
} else {
target = $(this.getAttribute('href'));
};
target.toggleClass("in");
});
html:
<table>
<tr><td><a href="#demo" data-toggle="myCollapse">Click me to toggle next row</a></td></tr>
<tr class="collapse" id="#demo"><td>You can collapse and expand me.</td></tr>
</table>
If you want to add a header to all Jersey responses, you could also use a ContainerResponseFilter
, from Jersey's filter documentation :
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response;
@Provider
public class PoweredByResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
responseContext.getHeaders().add("X-Powered-By", "Jersey :-)");
}
}
Make sure that you initialize it correctly in your project using the @Provider
annotation or through traditional ways with web.xml
.
For Microsoft IIS servers, you can enable this header via your web.config
file:
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Content-Type-Options"/>
<add name="X-Content-Type-Options" value="nosniff"/>
</customHeaders>
</httpProtocol>
</system.webServer>
And you are done.
You can get another validation on this tutorial : http://twitterbootstrap.org/bootstrap-form-validation
They use JQuery validation.
jquery.validate.js
jquery.validate.min.js
jquery-1.7.1.min.js
And you'll get the source code there.
<form id="registration-form" class="form-horizontal">
<h2>Sample Registration form <small>(Fill up the forms to get register)</small></h2>
<div class="form-control-group">
<label class="control-label" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="name" id="name"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="name">User Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="username" id="username"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="name">Password</label>
<div class="controls">
<input type="password" class="input-xlarge" name="password" id="password">
</div>
</div>
<div class="form-control-group">
<label class="control-label" for="name"> Retype Password</label>
<div class="controls">
<input type="password" class="input-xlarge" name="confirm_password" id="confirm_password"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" class="input-xlarge" name="email" id="email"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="message">Your Address</label>
<div class="controls">
<textarea class="input-xlarge" name="address" id="address" rows="3"></textarea></div>
</div>
<div class="form-control-group">
<label class="control-label" for="message"> Please agree to our policy</label>
<div class="controls">
<input id="agree" class="checkbox" type="checkbox" name="agree"></div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success btn-large">Register</button>
<button type="reset" class="btn">Cancel</button></div>
</form>
And The JQuery :
<script src="assets/js/jquery-1.7.1.min.js"></script>
<script src="assets/js/jquery.validate.js"></script>
<script src="script.js"></script>
<script>
addEventListener('load', prettyPrint, false);
$(document).ready(function(){
$('pre').addClass('prettyprint linenums');
});
Here is the live example of the code: http://twitterbootstrap.org/live/bootstrap-form-validation/
Check the full tutorial: http://twitterbootstrap.org/bootstrap-form-validation/
happy coding.
PHP - curl:
$username = 'myusername';
$password = 'mypassword';
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...
PHP - POST in WordPress:
$username = 'myusername';
$password = 'mypassword';
...
wp_remote_post('https://...some...api...endpoint...', array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode("$username:$password")
)
));
...
Try to use this , it works perfectly for me
//
varb = new List<object>();
// Example
varb.Add(new[] { float.Parse(GridView1.Rows[1].Cells[2].Text )});
// JSON + Serializ
public string Json()
{
return (new JavaScriptSerializer()).Serialize(varb);
}
// Jquery SIDE
var datasets = {
"Products": {
label: "Products",
data: <%= getJson() %>
}
You are almost certainly running your code before the DOM is constructed. Try running your code in a window.onload
handler function (but see note below):
window.onload = function() {
// all of your code goes in here
// it runs after the DOM is built
}
Another popular cross-browser solution is to put your <script>
block just before the closing </body>
tag. This could be the best solution for you, depending on your needs:
<html>
<body>
<!-- all of your HTML goes here... -->
<script>
// code in this final script element can use all of the DOM
</script>
</body>
</html>
window.onload
will wait until all images and subframes have loaded, which might be a long time after the DOM is built. You could also use document.addEventListener("DOMContentLoaded", function(){...})
to avoid this problem, but this is not supported cross-browser. The bottom-of-body trick is both cross-browser and runs as soon as the DOM is complete.Be careful with your tests. If you in your form you put the same email as the email address which must receive it will be directly in spam :)
Try this way.
In your css file change font-family: FontAwesome
into font-family: "FontAwesome";
or font-family: 'FontAwesome';
. I've solved the same problem using this method.
I've solved my problems, so I post here the correct code in case someone needs similar stuff.
Open Port
int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY );
Set parameters
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) {
std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}
Write
unsigned char cmd[] = "INIT \r";
int n_written = 0,
spot = 0;
do {
n_written = write( USB, &cmd[spot], 1 );
spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);
It was definitely not necessary to write byte per byte, also int n_written = write( USB, cmd, sizeof(cmd) -1)
worked fine.
At last, read:
int n = 0,
spot = 0;
char buf = '\0';
/* Whole response*/
char response[1024];
memset(response, '\0', sizeof response);
do {
n = read( USB, &buf, 1 );
sprintf( &response[spot], "%c", buf );
spot += n;
} while( buf != '\r' && n > 0);
if (n < 0) {
std::cout << "Error reading: " << strerror(errno) << std::endl;
}
else if (n == 0) {
std::cout << "Read nothing!" << std::endl;
}
else {
std::cout << "Response: " << response << std::endl;
}
This one worked for me. Thank you all!
If you are using ES6 you can:
var sample = [1, 2, 3]
var result = sample.filter(elem => elem !== 2)
/* output */
[1, 3]
Also take notice filter does not update the existing array it will return a new filtered array every time.
For anyone interested, this one worked for me in Ubuntu:
Go to .ssh directory.
$ cd ~/.ssh
Remove the known_hosts file.
$ rm known_hosts
Re-push your Git changes.
you can use the following to find the posted data.
data = json.loads(request.raw_post_data)
Java 8 variant for EJB in war file with maven project. Tested on EAP 7.0.
@Log4j // lombok annotation
@Startup
@Singleton
public class ApplicationLogic {
public static final String DEVELOPMENT_APPLICATION_NAME = "application";
public static final String DEVELOPMENT_GROUP_NAME = "com.group";
private static final String POM_PROPERTIES_LOCATION = "/META-INF/maven/" + DEVELOPMENT_GROUP_NAME + "/" + DEVELOPMENT_APPLICATION_NAME + "/pom.properties";
// In case no pom.properties file was generated or wrong location is configured, no pom.properties loading is done; otherwise VERSION will be assigned later
public static String VERSION = "No pom.properties file present in folder " + POM_PROPERTIES_LOCATION;
private static final String VERSION_ERROR = "Version could not be determinated";
{
Optional.ofNullable(getClass().getResourceAsStream(POM_PROPERTIES_LOCATION)).ifPresent(p -> {
Properties properties = new Properties();
try {
properties.load(p);
VERSION = properties.getProperty("version", VERSION_ERROR);
} catch (Exception e) {
VERSION = VERSION_ERROR;
log.fatal("Unexpected error occured during loading process of pom.properties file in META-INF folder!");
}
});
}
}
On windows use the name of the table in quotes:
TABLE "user";
or SELECT * FROM "user";
Post to the UI thread works for me.
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
iv.post(new Runnable() {
@Override
public void run() {
int width = iv.getMeasuredWidth();
int height = iv.getMeasuredHeight();
}
});
I got this error when I had a filename and class exported mismatch:
filename: list.component.ts
class exported: ListStudentsComponent
Changing from ListStudentsComponent to ListComponent fixed my issue.
Seems bundler can't use .gem files out of the box. Pointing the :path to a directory containing .gem files doesn't work. Some people suggested to setup a local gem server (geminabox, stickler) for that purpose.
However, what I found to be much simpler is to use a local gem "server" from file system: Just put your .gem files in a local directory, then use "gem generate_index" to make it a Gem repository
mkdir repo
mkdir repo/gems
cp *.gem repo/gems
cd repo
gem generate_index
Finally point bundler to this location by adding the following line to your Gemfile
source "file://path/to/repo"
If you update the gems in the repository, make sure to regenerate the index.
Or this:
$(document).ready(function(){
$(".header").click(function(){
$(this).children(".children").toggle();
});
$(".header a").click(function(e) {
return false;
});
});
session_destroy()
is effective after the page load is complete. So in the second upload, the session is terminated. But with unset()
you can also log out from within the page.
It may work with any character from the HTML Escape character list, but I had the same problem with a Java project. I used StringEscapeUtils.escapeHTML("Testing \" <br> <p>")
and the title was <a href=".." title="Test" <br> <p>">Testing</a>
.
It only worked for me when I changed the StringEscapeUtils to StringEscapeUtils.escapeJavascript("Testing \" <br> <p>")
and it worked in every browser.
Completing the answer from @xanblax
private static string getUserName()
{
SelectQuery query = new SelectQuery(@"Select * from Win32_Process");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (System.Management.ManagementObject Process in searcher.Get())
{
if (Process["ExecutablePath"] != null &&
string.Equals(Path.GetFileName(Process["ExecutablePath"].ToString()), "explorer.exe", StringComparison.OrdinalIgnoreCase))
{
string[] OwnerInfo = new string[2];
Process.InvokeMethod("GetOwner", (object[])OwnerInfo);
return OwnerInfo[0];
}
}
}
return "";
}
If you run into this issue when running an IIS 8.5 web server you can use the following method.
First, find the "Request Filtering" module in the IIS site you are working on, then double click it...
Next, you need to right click in the white area shown below then click the context menu option called "Edit Feature Settings".
Then the last thing to do is change the "Maximum query string (Bytes)" value from 2048 to something more appropriate such as 5000 for your needs.
This is how we can join two Dataframes on same column names in PySpark.
df = df1.join(df2, ['col1','col2','col3'])
If you do printSchema()
after this then you can see that duplicate columns have been removed.
Note: this answer applies only to Angular components and directives, NOT services.
I had this same issue when ngOnInit
(and other lifecycle hooks) were not firing for my components, and most searches led me here.
The issue is that I was using the arrow function syntax (=>
) like this:
class MyComponent implements OnInit {
// Bad: do not use arrow function
public ngOnInit = () => {
console.log("ngOnInit");
}
}
Apparently that does not work in Angular 6. Using non-arrow function syntax fixes the issue:
class MyComponent implements OnInit {
public ngOnInit() {
console.log("ngOnInit");
}
}
String-Builder :
int one = 1;
String color = "red";
StringBuilder sb = new StringBuilder();
sb.append("One=").append(one).append(", Color=").append(color).append('\n');
System.out.print(sb);
// Prints "One=1, Colour=red" followed by an ASCII newline.
String-Buffer
StringBuffer sBuffer = new StringBuffer("test");
sBuffer.append(" String Buffer");
System.out.println(sBuffer);
It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However, if the thread safety is necessary, the best option is StringBuffer objects.
Create an xml file any name (say progressBar.xml) in drawable
and add <color name="silverGrey">#C0C0C0</color>
in color.xml.
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="720" >
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="6"
android:useLevel="false" >
<size
android:height="200dip"
android:width="300dip" />
<gradient
android:angle="0"
android:endColor="@color/silverGrey"
android:startColor="@android:color/transparent"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Now in your xml file where you have your listView add this code:
<ListView
android:id="@+id/list_form_statusMain"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
<ProgressBar
android:id="@+id/progressBar"
style="@style/CustomAlertDialogStyle"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"
android:indeterminate="true"
android:indeterminateDrawable="@drawable/circularprogress"
android:visibility="gone"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
In AsyncTask in the method:
@Override
protected void onPreExecute()
{
progressbar_view.setVisibility(View.VISIBLE);
// your code
}
And in onPostExecute:
@Override
protected void onPostExecute(String s)
{
progressbar_view.setVisibility(View.GONE);
//your code
}
select t.* from table t
join (
select C2, C3, C4
from table
group by C2, C3, C4
having count(*) > 1
) t2
using (C2, C3, C4);
You need to concatenate your string.
document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';
The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.
I would even suggest creating the string separate:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
var urlString = 'url(buttons/' + imagePrefix + '.png)';
document.getElementById(tabName).style.backgroundImage = urlString;
}
As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html
The link here solved my problem.
http://brainof-dave.blogspot.com.au/2008/08/remote-certificate-is-invalid-according.html
I went to url of the web service (on the server that had the issue), clicked on the little security icon in IE, which brought up the certificate. I then clicked on the Details tab, clicked the Copy To File button, which allowed me to export the certifcate as a .cer file. Once I had the certificate locally, I was able to import it into the certificate store on the server using the below instructions.
Start a new MMC. File --> Add/Remove Snap-In... Click Add... Choose Certificates and click Add. Check the "Computer Account" radio button. Click Next.
Choose the client computer in the next screen. Click Finish. Click Close. Click OK. NOW install the certificate into the Trusted Root Certification Authorities certificate store. This will allow all users to trust the certificate.
To detect your controller is pushed or not just use below code in anywhere you want:
if ([[[self.parentViewController childViewControllers] firstObject] isKindOfClass:[self class]]) {
// Not pushed
}
else {
// Pushed
}
I hope this code can help anyone...
Based on some comments above below is the code how to remove an object based on a key name and key value
var items = [
{ "id": 3.1, "name": "test 3.1"},
{ "id": 22, "name": "test 3.1" },
{ "id": 23, "name": "changed test 23" }
]
function removeByKey(array, params){
array.some(function(item, index) {
return (array[index][params.key] === params.value) ? !!(array.splice(index, 1)) : false;
});
return array;
}
var removed = removeByKey(items, {
key: 'id',
value: 23
});
console.log(removed);
What I do on my cloud instances is I redirect port 80 to port 3000 with this command:
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000
Then I launch my Node.js on port 3000. Requests to port 80 will get mapped to port 3000.
You should also edit your /etc/rc.local
file and add that line minus the sudo
. That will add the redirect when the machine boots up. You don't need sudo
in /etc/rc.local
because the commands there are run as root
when the system boots.
Use the forever module to launch your Node.js with. It will make sure that it restarts if it ever crashes and it will redirect console logs to a file.
Add your Node.js start script to the file you edited for port redirection, /etc/rc.local
. That will run your Node.js launch script when the system starts.
This not only applies to Linode, but Digital Ocean, AWS EC2 and other VPS providers as well. However, on RedHat based systems /etc/rc.local
is /ect/rc.d/local
.
If you really want to create an array rather than a list use either
String[] names = ["lucas", "Fred", "Mary"]
or
def names = ["lucas", "Fred", "Mary"].toArray()
After the blog post How Can I Use Windows PowerShell to Delete All the .TMP Files on a Drive?, you can use something like this to delete all .tmp for example from a folder and all subfolders in PowerShell:
get-childitem [your path/ or leave empty for current path] -include
*.tmp -recurse | foreach ($_) {remove-item $_.fullname}
#read file lines and edit specific item
file=open("pythonmydemo.txt",'r')
a=file.readlines()
print(a[0][6:11])
a[0]=a[0][0:5]+' Ericsson\n'
print(a[0])
file=open("pythonmydemo.txt",'w')
file.writelines(a)
file.close()
print(a)
You can use $anchorScroll
.
Just inject $anchorScroll
as a dependency, and call $anchorScroll()
whenever you want to scroll to top.
Simply throw Exception if input is invalid
Scanner sc=new Scanner(System.in);
try
{
System.out.println("Please input an integer");
//nextInt will throw InputMismatchException
//if the next token does not match the Integer
//regular expression, or is out of range
int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
//Print "This is not an integer"
//when user put other than integer
System.out.println("This is not an integer");
}
Try doing it like this.
User::where('email', $userEmail)
->update([
'member_type' => $plan
]);
In order for a percentage value to work for height, the parent's height must be determined. The only exception is the root element <html>
, which can be a percentage height. .
So, you've given all of your elements height, except for the <html>
, so what you should do is add this:
html {
height: 100%;
}
And your code should work fine.
* { padding: 0; margin: 0; }_x000D_
html, body, #fullheight {_x000D_
min-height: 100% !important;_x000D_
height: 100%;_x000D_
}_x000D_
#fullheight {_x000D_
width: 250px;_x000D_
background: blue;_x000D_
}
_x000D_
<div id=fullheight>_x000D_
Lorem Ipsum _x000D_
</div>
_x000D_
A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters.
public void MyMethod(string myParam) { }
...
string myArg1 = "this is my argument";
myClass.MyMethod(myArg1);
You have to click on query window just below the phpMyAdmin logo, a new window will open. Just click on SQL History tab. There you can see history of SQL Queries.
I open the project,.csproj, using a notepad and delete that missing file reference.
If you are only looking for a refresh rate for the GOOGLEFINANCE
function, keep in mind that data delays can be up to 20 minutes (per Google Finance Disclaimer).
GoogleClock
)Here is a modified version of the refresh action, taking the data delay into consideration, to save on unproductive refresh cycles.
=GoogleClock(GOOGLEFINANCE(symbol,"datadelay"))
For example, with:
then
=GoogleClock(GOOGLEFINANCE("GOOG","datadelay"))
Results in a dynamic data-based refresh rate of:
=GoogleClock(15)
GoogleClock
)If your sheet contains a number of rows of symbols, you could add a datadelay
column for each symbol and use the lowest value, for example:
=GoogleClock(MIN(dataDelayValuesNamedRange))
Where dataDelayValuesNamedRange
is the absolute reference or named reference of the range of cells that contain the data delay values for each symbol (assuming these values are different).
GoogleClock()
The GoogleClock()
function was removed in 2014 and replaced with settings setup for refreshing sheets. At present, I have confirmed that replacement settings is only on available in Sheets from when accessed from a desktop browser, not the mobile app (I'm using Google's mobile Sheets app updated 2016-03-14).
(This part of the answer is based on, and portions copied from, Google Docs Help)
To change how often "some" Google Sheets functions update:
NOTE External data functions recalculate at the following intervals:
The references in earlier sections to the display and use of the datadelay
attribute still apply, as well as the concepts for more efficient coding of sheets.
On a positive note, the new refresh option continues to be refreshed by Google servers regardless of whether you have the sheet loaded or not. That's a positive for shared sheets for sure; even more so for Google Apps Scripts (GAS), where GAS is used in workflow code or referenced data is used as a trigger for an event.
[*] in my understanding so far (I am currently testing this)
A workaround may be to try to use -ve
values for margins like following:
<Button
android:id="@+id/button_back"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="CloseActivity"
android:padding="0dp"
android:layout_marginLeft="-5dip"
android:layout_marginRight="-5dip"
android:layout_marginTop="-5dip"
android:layout_marginBottom="-5dip"
android:text="@string/back" />
It will make that space vanish. I mean you can choose the appropriate dip
value, which makes it go away. It worked for me. Hope it works for you.
try to change the size of the image by changing the pixel size from the url in each json object as follows :
for example I change s480x480 to be s720x720
With regard to Brent.Longborough's answer (appering only on page 2 onward), perhaps you need to set the \thispagestyle{} after \begin{document}. I wonder if the letter class is setting the first page style to empty.
I found the datetime.isoformat in the documentation. It seems to do what you want:
datetime.isoformat([sep])
Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS
If utcoffset() does not return None, a 6-character string is appended, giving the UTC offset in (signed) hours and minutes: YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if microsecond is 0 YYYY-MM-DDTHH:MM:SS+HH:MM
The optional argument sep (default 'T') is a one-character separator, placed between the date and time portions of the result. For example,
>>>
>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
... def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
I fixed it like this example.
$scope.myCalendar = new Date(myUnixDate*1000);
<input date-time ng-model="myCalendar" format="DD/MM/YYYY" />
I had a similar problem with a new ASP.NET Core application a while ago. Turns out one of the referenced libraries used a version of Newtonsoft.Json that was lower than 9.0.0.0. So I upgraded the version for that library and the problem was solved. Not sure if you'll be able to do the same here
The process for timing out an operations is described in the documentation for signal.
The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.
Note that this will only work on UNIX.
Here's an implementation that creates a decorator (save the following code as timeout.py
).
from functools import wraps
import errno
import os
import signal
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorator
This creates a decorator called @timeout
that can be applied to any long running functions.
So, in your application code, you can use the decorator like so:
from timeout import timeout
# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
...
# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
...
# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
...
Here is what I'm doing:
git clone repo /tmp/folder
cp -rf /tmp/folder/.git /dest/folder/
cd /dest/folder
git checkout -f master
You can use Cell.Interior.Color
, I've used it to count the number of cells in a range that have a given background color (ie. matching my legend).
In modern browsers you can use the Map
data structure instead of a object.
A Map object can iterate its elements in insertion order...
It is very simple to adding an image into project and view the image. First create a folder into in your project which can contain any type of images.
Then Right click on Project ->>
Go to Build Path ->>
configure Build Path ->>
add Class folder ->>
choose your folder (which you just created for store the images) under the project name.
class Surface extends JPanel {
private BufferedImage slate;
private BufferedImage java;
private BufferedImage pane;
private TexturePaint slatetp;
private TexturePaint javatp;
private TexturePaint panetp;
public Surface() {
loadImages();
}
private void loadImages() {
try {
slate = ImageIO.read(new File("images\\slate.png"));
java = ImageIO.read(new File("images\\java.png"));
pane = ImageIO.read(new File("images\\pane.png"));
} catch (IOException ex) {
Logger.`enter code here`getLogger(Surface.class.getName()).log(
Level.SEVERE, null, ex);
}
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60));
javatp = new TexturePaint(java, new Rectangle(0, 0, 90, 60));
panetp = new TexturePaint(pane, new Rectangle(0, 0, 90, 60));
g2d.setPaint(slatetp);
g2d.fillRect(10, 15, 90, 60);
g2d.setPaint(javatp);
g2d.fillRect(130, 15, 90, 60);
g2d.setPaint(panetp);
g2d.fillRect(250, 15, 90, 60);
g2d.dispose();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
public class TexturesEx extends JFrame {
public TexturesEx() {
initUI();
}
private void initUI() {
add(new Surface());
setTitle("Textures");
setSize(360, 120);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
TexturesEx ex = new TexturesEx();
ex.setVisible(true);
}
});
}
}
I had the same problem as the OP except I remembered to declare the ReadOnlyVariables.
After some playing around, I discovered it was the name of my variable that was the issue. "File_Path" in SSIS somehow got converted to "FilePath". C# does not play nicely with underscores in variable names.
So to access the variable, I type
string fp = Variables.FilePath;
In the PreExecute() method of the Script Component.
Here is a simple program that displays the camera feed in a cv2.namedWindow
and will take a snapshot when you hit SPACE
. It will also quit if you hit ESC
.
import cv2
cam = cv2.VideoCapture(0)
cv2.namedWindow("test")
img_counter = 0
while True:
ret, frame = cam.read()
if not ret:
print("failed to grab frame")
break
cv2.imshow("test", frame)
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
elif k%256 == 32:
# SPACE pressed
img_name = "opencv_frame_{}.png".format(img_counter)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()
I think this should answer your question for the most part. If there is any line of it that you don't understand let me know and I'll add comments.
If you need to grab multiple images per press of the SPACE
key, you will need an inner loop or perhaps just make a function that grabs a certain number of images.
Note that the key events are from the cv2.namedWindow
so it has to have focus.
In postgresql you can use regular expressions in WHERE clause. Check http://www.postgresql.org/docs/8.4/static/functions-matching.html
MySQL has something simmilar: http://dev.mysql.com/doc/refman/5.5/en/regexp.html
See below example its working
C:/Program Files/PostgreSQL/9.4/bin\pg_restore.exe --host localhost --port 5432 --username "postgres" --dbname "newDatabase" --no-password --verbose
"C:\Users\Yogesh\Downloads\new Download\DB.backup"
If your column is of type DATE (as you say), then you don't need to convert it into a string first (in fact you would convert it implicitly to a string first, then explicitly to a date and again explicitly to a string):
SELECT TO_CHAR(COL1, 'mm/dd/yyyy') FROM TABLE1
The date format your seeing for your column is an artifact of the tool your using (TOAD, SQL Developer etc.) and it's language settings.
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
count = rs3.getInt("count");
@petah and Acrylic DNS Proxy is the best answer, and at the end he references the ability to do multi-site using an Apache which @jeremyasnyder describes a little further down...
... however, in our case we're testing a multi-tenant hosting system and so most domains we want to test go to the same virtualhost
, while a couple others are directed elsewhere.
So in our case, you simply use regex wildcards in the ServerAlias
directive, like so...
ServerAlias *.foo.local
Ok, first launch an ipython shell
from the terminal and import
TensorFlow:
$ ipython --pylab
Python 3.6.5 |Anaconda custom (64-bit)| (default, Apr 29 2018, 16:14:56)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
Using matplotlib backend: Qt5Agg
In [1]: import tensorflow as tf
Now, we can watch the GPU memory usage in a console using the following command:
# realtime update for every 2s
$ watch -n 2 nvidia-smi
Since we've only import
ed TensorFlow but have not used any GPU yet, the usage stats will be:
Notice how the GPU memory usage is very less (~ 700MB); Sometimes the GPU memory usage might even be as low as 0 MB.
Now, let's load the GPU in our code. As indicated in tf documentation
, do:
In [2]: sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
Now, the watch stats should show an updated GPU usage memory as below:
Observe now how our Python process from the ipython shell is using ~ 7 GB of the GPU memory.
P.S. You can continue watching these stats as the code is running, to see how intense the GPU usage is over time.
I use http://wiltgen.net/objecty/, it helps to embed media content and avoid the IE "click to activate" problem.
Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.
The value will get reflected when using in the blocks of parent class
if the variable is static then change the value during initialization itself with static block,
class Son extends Dad {
static {
me = "son";
}
}
or else change in constructor.
You can also change the value later in any blocks. It will get reflected in super class
setState(updater, callback)
for useState
Following implementation comes really close to the original setState
callback from classes.
Additions made to Robin's solution:
setState
invocation, like with classesconst App = () => {
const [state, setState] = useStateCallback(0); // same API as useState + setState with cb
const handleClick = () => {
setState(
prev => prev + 1,
// 2nd argument is callback , `s` is *updated* state
s => console.log("I am called after setState, state:", s)
);
};
return <button onClick={handleClick}>Increment</button>;
}
useStateCallback
function useStateCallback(initialState) {
const [state, setState] = useState(initialState);
const cbRef = useRef(null); // mutable ref to store current callback
const setStateCallback = useCallback((state, cb) => {
cbRef.current = cb; // store passed callback to ref
setState(state);
}, []);
useEffect(() => {
// cb.current is `null` on initial render, so we only execute cb on state *updates*
if (cbRef.current) {
cbRef.current(state);
cbRef.current = null; // reset callback after execution
}
}, [state]);
return [state, setStateCallback];
}
Further info: React Hooks FAQ: Is there something like instance variables?
const App = () => {
const [state, setState] = useStateCallback(0);
const handleClick = () =>
setState(
prev => prev + 1,
// important: use `s`, not the stale/old closure value `state`
s => console.log("I am called after setState, state:", s)
);
return (
<div>
<p>Hello Comp. State: {state} </p>
<button onClick={handleClick}>Click me</button>
</div>
);
}
function useStateCallback(initialState) {
const [state, setState] = useState(initialState);
const cbRef = useRef(null);
const setStateCallback = useCallback((state, cb) => {
cbRef.current = cb;
setState(state);
}, []);
useEffect(() => {
if (cbRef.current) {
cbRef.current(state);
cbRef.current = null;
}
}, [state]);
return [state, setStateCallback];
}
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<script>var { useReducer, useEffect, useState, useRef, useCallback } = React</script>
<div id="root"></div>
_x000D_
Try this one
UPDATE employee
set EMPLOYEE.MAIDEN_NAME =
(SELECT ADD1
FROM EMPS
WHERE EMP_CODE=EMPLOYEE.EMP_CODE);
WHERE EMPLOYEE.EMP_CODE >='00'
AND EMPLOYEE.EMP_CODE <='ZZ';
The method takes a regular expression, not a string, and the dot has a special meaning in regular expressions. Escape it like so split("\\.")
. You need a double backslash, the second one escapes the first.
PRIMARY KEY CONSTRAINT
cannot be altered, you may only drop it and create again. For big datasets it can cause a long run time and thus - table inavailability.
By Java class, I am assuming you mean a Servlet class as setting session attribute in arbitrary Java class does not make sense.You can do something like this in your servlet's doGet/doPost methods
public void doGet(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
String username = (String)request.getAttribute("un");
session.setAttribute("UserName", username);
}
the data object is a buffer of bytes. Simply call .toString()
to get human-readable code:
console.log( data.toString() );
reference: Node.js buffers
The spring data JPA query needs the "%" chars as well as a space char following like
in your query, as in
@Query("Select c from Registration c where c.place like %:place%")
.
Cf. http://docs.spring.io/spring-data/jpa/docs/current/reference/html.
You may want to get rid of the @Query
annotation alltogether, as it seems to resemble the standard query (automatically implemented by the spring data proxies); i.e. using the single line
List<Registration> findByPlaceContaining(String place);
is sufficient.
you can simply identify all changers in the form, like this
//when form change, show aleart
$("#FormId").change(function () {
aleart('Done some change on form');
});
phpmyadmin doesn't follow the MySQL connection because it defines its proper collation in phpmyadmin config file.
So if we don't want or if we can't access server parameters, we should just force it to send results in a different format (encoding) compatible with client i.e. phpmyadmin
for example if both the MySQL connection collation and the MySQL charset are utf8 but phpmyadmin is ISO, we should just add this one before any select query sent to the MYSQL via phpmyadmin :
SET SESSION CHARACTER_SET_RESULTS =latin1;
I had exactly this issue in a recent project which really is a pain in the rear. I finally found it's because the Python we used in Docker has encoding "ansi_x3.4-1968" instead of "utf-8". So if anyone out there using Docker and got this error, following these steps may thoroughly solve your problem.
create a file and name it default_locale in the same directory of your Dockerfile, put this line in it,
environment=LANG="es_ES.utf8", LC_ALL="es_ES.UTF-8", LC_LANG="es_ES.UTF-8"
add these to your Dockerfile,
RUN apt-get clean && apt-get update && apt-get install -y locales
RUN locale-gen en_CA.UTF-8
COPY ./default_locale /etc/default/locale
RUN chmod 0755 /etc/default/locale
ENV LC_ALL=en_CA.UTF-8
ENV LANG=en_CA.UTF-8
ENV LANGUAGE=en_CA.UTF-8
This thoroughly solved my issue when I built and run my Docker again, hopefully this solve your issue also.
to_char(to_date(V_MONTH_NUM,'MM'),'MONTH')
where V_MONTH_NUM
is the month number
SELECT to_char(to_date(V_MONTH_NUM,'MM'),'MONTH') from dual;
Jar mismatch comes when you use library projects in your application and both projects are using same jar with different version so just check all library projects attached in your application. if some mismatch exist then remove it.
if above process is not working then just do remove project dependency from build path and again add library projects and build the application.
Maybe the following helps you.
arraylistname.get(position);
In the Controller:
public class YourControllerNameController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public YourControllerNameController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<IActionResult> YourMethodName()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier) // will give the user's userId
var userName = User.FindFirstValue(ClaimTypes.Name) // will give the user's userName
// For ASP.NET Core <= 3.1
ApplicationUser applicationUser = await _userManager.GetUserAsync(User);
string userEmail = applicationUser?.Email; // will give the user's Email
// For ASP.NET Core >= 5.0
var userEmail = User.FindFirstValue(ClaimTypes.Email) // will give the user's Email
}
}
In some other class:
public class OtherClass
{
private readonly IHttpContextAccessor _httpContextAccessor;
public OtherClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void YourMethodName()
{
var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
}
}
Then you should register IHttpContextAccessor
in the Startup
class as follows:
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Or you can also register as follows
services.AddHttpContextAccessor();
}
For more readability write extension methods as follows:
public static class ClaimsPrincipalExtensions
{
public static T GetLoggedInUserId<T>(this ClaimsPrincipal principal)
{
if (principal == null)
throw new ArgumentNullException(nameof(principal));
var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (typeof(T) == typeof(string))
{
return (T)Convert.ChangeType(loggedInUserId, typeof(T));
}
else if (typeof(T) == typeof(int) || typeof(T) == typeof(long))
{
return loggedInUserId != null ? (T)Convert.ChangeType(loggedInUserId, typeof(T)) : (T)Convert.ChangeType(0, typeof(T));
}
else
{
throw new Exception("Invalid type provided");
}
}
public static string GetLoggedInUserName(this ClaimsPrincipal principal)
{
if (principal == null)
throw new ArgumentNullException(nameof(principal));
return principal.FindFirstValue(ClaimTypes.Name);
}
public static string GetLoggedInUserEmail(this ClaimsPrincipal principal)
{
if (principal == null)
throw new ArgumentNullException(nameof(principal));
return principal.FindFirstValue(ClaimTypes.Email);
}
}
Then use as follows:
public class YourControllerNameController : Controller
{
public IActionResult YourMethodName()
{
var userId = User.GetLoggedInUserId<string>(); // Specify the type of your UserId;
var userName = User.GetLoggedInUserName();
var userEmail = User.GetLoggedInUserEmail();
}
}
public class OtherClass
{
private readonly IHttpContextAccessor _httpContextAccessor;
public OtherClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void YourMethodName()
{
var userId = _httpContextAccessor.HttpContext.User.GetLoggedInUserId<string>(); // Specify the type of your UserId;
}
}
You're trying to use key functions with lambda functions.
Python and other languages like C# or F# use lambda functions.
Also, when it comes to key functions and according to the documentation
Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.
...
The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
So, key functions have a parameter key and it can indeed receive a lambda function.
In Real Python there's a nice example of its usage. Let's say you have the following list
ids = ['id1', 'id100', 'id2', 'id22', 'id3', 'id30']
and want to sort through its "integers". Then, you'd do something like
sorted_ids = sorted(ids, key=lambda x: int(x[2:])) # Integer sort
and printing it would give
['id1', 'id2', 'id3', 'id22', 'id30', 'id100']
In your particular case, you're only missing to write key=
before lambda. So, you'd want to use the following
a = sorted(a, key=lambda x: x.modified, reverse=True)
you need to download and install jdk
from here
Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.
import UIKit
// MARK: Local Constants
private let changeSegueId = "MasterToChange"
private let bookSegueId = "MasterToBook"
According to this post, it's much better now:
// pick out one album
JObject jalbum = albums[0] as JObject;
// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();
Documentation: Convert JSON to a Type
I use this trick, pretty sure I already posted it to a duplicate of this question:
-(void)tableViewDidLoadRows:(UITableView *)tableView{
// do something after loading, e.g. select a cell.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// trick to detect when table view has finished loading.
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tableViewDidLoadRows:) object:tableView];
[self performSelector:@selector(tableViewDidLoadRows:) withObject:tableView afterDelay:0];
// specific to your controller
return self.objects.count;
}
package main
import "fmt"
import "strconv"
func FloatToString(input_num float64) string {
// to convert a float number to a string
return strconv.FormatFloat(input_num, 'f', 6, 64)
}
func main() {
fmt.Println(FloatToString(21312421.213123))
}
If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg
strconv.FormatFloat(input_num, 'f', -1, 64)
Personally I find fmt
easier to use. (Playground link)
fmt.Printf("x = %.6f\n", 21312421.213123)
Or if you just want to convert the string
fmt.Sprintf("%.6f", 21312421.213123)
In swift 3 use this -
object?.addTarget(objectWhichHasMethod, action: #selector(classWhichHasMethod.yourMethod), for: someUIControlEvents)
For example(from my code) -
self.datePicker?.addTarget(self, action:#selector(InfoTableViewCell.datePickerValueChanged), for: .valueChanged)
Just give a :
after method name if you want the sender as parameter.
Turn this:
DbCommand command = connection.CreateCommand();
command.CommandText = "SELECT @param";
DbParameter param = command.CreateParameter();
param.ParameterName = "@param";
param.Value = "Hello World";
command.Parameters.Add(param);
... into this:
DbCommand command = connection.CreateCommand("SELECT {0}", "Hello World");
... using this extension method:
using System;
using System.Data.Common;
using System.Globalization;
using System.Reflection;
namespace DbExtensions {
public static class Db {
static readonly Func<DbConnection, DbProviderFactory> getDbProviderFactory;
static readonly Func<DbCommandBuilder, int, string> getParameterName;
static readonly Func<DbCommandBuilder, int, string> getParameterPlaceholder;
static Db() {
getDbProviderFactory = (Func<DbConnection, DbProviderFactory>)Delegate.CreateDelegate(typeof(Func<DbConnection, DbProviderFactory>), typeof(DbConnection).GetProperty("DbProviderFactory", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true));
getParameterName = (Func<DbCommandBuilder, int, string>)Delegate.CreateDelegate(typeof(Func<DbCommandBuilder, int, string>), typeof(DbCommandBuilder).GetMethod("GetParameterName", BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(Int32) }, null));
getParameterPlaceholder = (Func<DbCommandBuilder, int, string>)Delegate.CreateDelegate(typeof(Func<DbCommandBuilder, int, string>), typeof(DbCommandBuilder).GetMethod("GetParameterPlaceholder", BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(Int32) }, null));
}
public static DbProviderFactory GetProviderFactory(this DbConnection connection) {
return getDbProviderFactory(connection);
}
public static DbCommand CreateCommand(this DbConnection connection, string commandText, params object[] parameters) {
if (connection == null) throw new ArgumentNullException("connection");
return CreateCommandImpl(GetProviderFactory(connection).CreateCommandBuilder(), connection.CreateCommand(), commandText, parameters);
}
private static DbCommand CreateCommandImpl(DbCommandBuilder commandBuilder, DbCommand command, string commandText, params object[] parameters) {
if (commandBuilder == null) throw new ArgumentNullException("commandBuilder");
if (command == null) throw new ArgumentNullException("command");
if (commandText == null) throw new ArgumentNullException("commandText");
if (parameters == null || parameters.Length == 0) {
command.CommandText = commandText;
return command;
}
object[] paramPlaceholders = new object[parameters.Length];
for (int i = 0; i < paramPlaceholders.Length; i++) {
DbParameter dbParam = command.CreateParameter();
dbParam.ParameterName = getParameterName(commandBuilder, i);
dbParam.Value = parameters[i] ?? DBNull.Value;
command.Parameters.Add(dbParam);
paramPlaceholders[i] = getParameterPlaceholder(commandBuilder, i);
}
command.CommandText = String.Format(CultureInfo.InvariantCulture, commandText, paramPlaceholders);
return command;
}
}
}
More ADO.NET extension methods: DbExtensions
if (typeof($('#container .prateleira')[0]) === 'undefined') {
$('#ctl00_Conteudo_ctrPaginaSistemaAreaWrapper').css('display','none');
}
What about this:
var txt="";
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for (var x in nyc){
txt += nyc[x];
}
Answers that claim Django model's Meta
and metaclasses are "completely different" are misleading answers.
The construction of Django model class objects, that is to say the object that stands for the class definition itself (yes, classes are also objects), are indeed controlled by a metaclass called ModelBase
, and you can see that code here.
And one of the things that ModelBase
does is to create the _meta
attribute on every Django model which contains validation machinery, field details, save logic and so forth. During this operation, the stuff that is specified in the model's inner Meta
class is read and used within that process.
So, while yes, in a sense Meta
and metaclasses are different 'things', within the mechanics of Django model construction they are intimately related; understanding how they work together will deepen your insight into both at once.
This might be a helpful source of information to better understand how Django models employ metaclasses.
https://code.djangoproject.com/wiki/DevModelCreation
And this might help too if you want to better understand how objects work in general.
I think this suits perfect for any color you have:
a {
color: inherit;
}
You can use inner divs to set the margin.
<div style="display: table-cell;">
<div style="margin:5px;background-color: red;">1</div>
</div>
<div style="display: table-cell; ">
<div style="margin:5px;background-color: green;">1</div>
</div>
Not 100% sure as the question is missing some details but if you are using JAX-WS RI, then have a look at Adding SOAP headers when sending requests:
The portable way of doing this is that you create a
SOAPHandler
and mess with SAAJ, but the RI provides a better way of doing this.When you create a proxy or dispatch object, they implement
BindingProvider
interface. When you use the JAX-WS RI, you can downcast toWSBindingProvider
which defines a few more methods provided only by the JAX-WS RI.This interface lets you set an arbitrary number of Header object, each representing a SOAP header. You can implement it on your own if you want, but most likely you'd use one of the factory methods defined on
Headers
class to create one.import com.sun.xml.ws.developer.WSBindingProvider; HelloPort port = helloService.getHelloPort(); // or something like that... WSBindingProvider bp = (WSBindingProvider)port; bp.setOutboundHeader( // simple string value as a header, like <simpleHeader>stringValue</simpleHeader> Headers.create(new QName("simpleHeader"),"stringValue"), // create a header from JAXB object Headers.create(jaxbContext,myJaxbObject) );
Update your code accordingly and try again. And if you're not using JAX-WS RI, please update your question and provide more context information.
Update: It appears that the web service you want to call is secured with WS-Security/UsernameTokens. This is a bit different from your initial question. Anyway, to configure your client to send usernames and passwords, I suggest to check the great post Implementing the WS-Security UsernameToken Profile for Metro-based web services (jump to step 4). Using NetBeans for this step might ease things a lot.
This is a guaranteed way to get it done in Vanilla (or simply Pure) JavaScript:
var picurl = 'pictures/apple.png';
document.getElementById("image_id").src=picurl;
Say this is the column that contains the datetime
value, table data
.
+--------------------+
| date_created |
+--------------------+
| 2018-06-02 15:50:30|
+--------------------+
mysql> select DATE(date_created) from data;
+--------------------+
| DATE(date_created) |
+--------------------+
| 2018-06-02 |
+--------------------+
mysql> select YEAR(date_created) from data;
+--------------------+
| YEAR(date_created) |
+--------------------+
| 2018 |
+--------------------+
mysql> select MONTH(date_created) from data;
+---------------------+
| MONTH(date_created) |
+---------------------+
| 6 |
+---------------------+
mysql> select DAY(date_created) from data;
+-------------------+
| DAY(date_created) |
+-------------------+
| 2 |
+-------------------+
mysql> select HOUR(date_created) from data;
+--------------------+
| HOUR(date_created) |
+--------------------+
| 15 |
+--------------------+
mysql> select MINUTE(date_created) from data;
+----------------------+
| MINUTE(date_created) |
+----------------------+
| 50 |
+----------------------+
mysql> select SECOND(date_created) from data;
+----------------------+
| SECOND(date_created) |
+----------------------+
| 31 |
+----------------------+
There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).
Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.
Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.
Adding my bit as this is a popular question.
I couldn't place .history directory inside .gitignore because no matter what combo I tried, it just didn't work. Windows keeps generating new files upon every save and I don't want to see these at all.
But then I realized, this is just my personal development environment on my machine. Things like .history or .vscode are specific for me so it would be weird if everyone included their own .gitignore entries based on what IDE or OS they are using.
So this worked for me, just append ".history" to .git/info/exclude
echo ".history" >> .git/info/exclude
Is there a step missing?
Yes. You need to create the directory:
mkdir ${HOME}/.ssh
Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:
% chmod 700 ~/.ssh
Should the
.ssh
dir be generated when I use thessh-keygen
command?
No. This command generates an SSH key pair but will fail if it cannot write to the required directory:
% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.
Once you've created your keys, you should also restrict who can read those key files to just yourself:
% chmod -R go-wrx ~/.ssh/*
You can try a simple kernel and the filter2D function, e.g. in Python:
kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
im = cv2.filter2D(im, -1, kernel)
Wikipedia has a good overview of kernels with some more examples here - https://en.wikipedia.org/wiki/Kernel_(image_processing)
In image processing, a kernel, convolution matrix, or mask is a small matrix. It is used for blurring, sharpening, embossing, edge detection, and more. This is accomplished by doing a convolution between a kernel and an image.
to accomplish what you want, you must getPaths from the polygon. Paths will be an array of LatLng points. you get the elements of the array and split the LatLng pairs with the methods .lat and .lng in the function below, i have a redundant array corresponding to a polyline that marks the perimeter around the polygon.
saving is another story. you can then opt for many methods. you may save your list of points as a csv formatted string and export that to a file (easiest solution, by far). i highly recommend GPS TXT formats, like the ones (there are 2) readable by GPS TRACKMAKER (great free version software). if you are competent to save them to a database, that is a great solution (i do both, for redundancy).
function areaPerimeterParse(areaPerimeterPath) {
var flag1stLoop = true;
var areaPerimeterPathArray = areaPerimeterPath.getPath();
var markerListParsedTXT = "Datum,WGS84,WGS84,0,0,0,0,0\r\n";
var counter01 = 0;
var jSpy = "";
for (var j = 0;j<areaPerimeterPathArray.length;j++) {
counter01++;
jSpy += j+" ";
if (flag1stLoop) {
markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(j).lat(), areaPerimeterPathArray.getAt(j).lng()].join(',')+',00/00/00,00:00:00,1'+'\r\n';
flag1stLoop = false;
} else {
markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(j).lat(), areaPerimeterPathArray.getAt(j).lng()].join(',')+',00/00/00,00:00:00,0'+'\r\n';
}
}
// last point repeats first point
markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(0).lat(), areaPerimeterPathArray.getAt(0).lng()].join(',')+',00/00/00,00:00:00,0'+'\r\n';
return markerListParsedTXT;
}
attention, the line that ends with ",1" (as opposed to ",0") starts a new polygon (this format allows you to save multiple polygons in the same file). i find TXT more human readable than the XML based formats GPX and KML.
You could use jQuery's grep method:
$.grep(carBrands, function(obj) { return obj.name == "ford"; });
But as you specify no jQuery, you could just make a derivative of the function. From the source code:
function grepArray( elems, callback, inv ) {
var ret = [];
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
if ( !inv !== !callback( elems[ i ], i ) ) {
ret.push( elems[ i ] );
}
}
return ret;
}
grepArray(carBrands, function(obj) { return obj.name == "ford"; });
Complete Multipart Request with Upload Progress
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.CharsetUtils;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.beusoft.app.AppContext;
public class MultipartRequest extends Request<String> {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private String FILE_PART_NAME = "files";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
private Map<String, String> headerParams;
private final MultipartProgressListener multipartProgressListener;
private long fileLength = 0L;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, File file, long fileLength,
Map<String, String> mStringPart,
final Map<String, String> headerParams, String partName,
MultipartProgressListener progLitener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mFilePart = file;
this.fileLength = fileLength;
this.mStringPart = mStringPart;
this.headerParams = headerParams;
this.FILE_PART_NAME = partName;
this.multipartProgressListener = progLitener;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
entity.setCharset(CharsetUtils.get("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
buildMultipartEntity();
httpentity = entity.build();
}
// public void addStringBody(String param, String value) {
// if (mStringPart != null) {
// mStringPart.put(param, value);
// }
// }
private void buildMultipartEntity() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart, ContentType.create("image/gif"), mFilePart.getName()));
if (mStringPart != null) {
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
}
@Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity.writeTo(new CountingOutputStream(bos, fileLength,
multipartProgressListener));
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
// System.out.println("Network Response "+ new String(response.data, "UTF-8"));
return Response.success(new String(response.data, "UTF-8"),
getCacheEntry());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// fuck it, it should never happen though
return Response.success(new String(response.data), getCacheEntry());
}
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
//Override getHeaders() if you want to put anything in header
public static interface MultipartProgressListener {
void transferred(long transfered, int progress);
}
public static class CountingOutputStream extends FilterOutputStream {
private final MultipartProgressListener progListener;
private long transferred;
private long fileLength;
public CountingOutputStream(final OutputStream out, long fileLength,
final MultipartProgressListener listener) {
super(out);
this.fileLength = fileLength;
this.progListener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
if (progListener != null) {
this.transferred += len;
int prog = (int) (transferred * 100 / fileLength);
this.progListener.transferred(this.transferred, prog);
}
}
public void write(int b) throws IOException {
out.write(b);
if (progListener != null) {
this.transferred++;
int prog = (int) (transferred * 100 / fileLength);
this.progListener.transferred(this.transferred, prog);
}
}
}
}
Sample Usage
protected <T> void uploadFile(final String tag, final String url,
final File file, final String partName,
final Map<String, String> headerParams,
final Response.Listener<String> resultDelivery,
final Response.ErrorListener errorListener,
MultipartProgressListener progListener) {
AZNetworkRetryPolicy retryPolicy = new AZNetworkRetryPolicy();
MultipartRequest mr = new MultipartRequest(url, errorListener,
resultDelivery, file, file.length(), null, headerParams,
partName, progListener);
mr.setRetryPolicy(retryPolicy);
mr.setTag(tag);
Volley.newRequestQueue(this).add(mr);
}
You can't, but... If you own both pages then...
1) You can send the data via query params (http://siteB.com/?key=value)
2) You can create an iframe of Site B inside site A and you can send post messages from one place to the other. As Site B is the owner of site B cookies it will be able to set whatever value you need by processing the correct post message. (You should prevent other unwanted senders to send messages to you! that is up to you and the mechanism you decide to use to prevent that from happening)
Here is a nice tutorial, it is what you need. (Source: coursesweb.net/php-mysql)
In this tutorial you can learn how to register, to count, and display in your webpage the number of online users and visitors. The principle is this: each user / visitor is registered in a text file or database. Every time a page of the website is accessed, the php script deletes all records older than a certain time (eg 2 minutes), adds the current user / visitor and takes the number of records left to display.
You can store the online users and visitors in a file on the server, or in a MySQL table. In this case, I think that using a text file to add and read the records is faster than storing them into a MySQL table, which requires more requests.
First it's presented the method with recording in a text file on the server, than the method with MySQL table.
To download the files with the scripts presented in this tutorial, click -> Count Online Users and Visitors.
• Both scripts can be included in ".php" files (with include()
), or in ".html" files (with <script>
), as you can see in the examples presented at the bottom of this page; but the server must run PHP.
To add records in a file on the server with PHP you must set CHMOD 0766 (or CHMOD 0777) permissions to that file, so the PHP can write data in it.
userson.txt
) and give it CHMOD 0777
permissions (in your FTP application, right click on that file, choose Properties, then select Read
, Write
, and Execute
options).usersontxt.php
) having the code below, then copy this php file in the same directory as userson.txt
.The code for usersontxt.php
;
<?php
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start(); // start Session, if not already started
$filetxt = 'userson.txt'; // the file in which the online users /visitors are stored
$timeon = 120; // number of secconds to keep a user online
$sep = '^^'; // characters used to separate the user name and date-time
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
You can get a free registration script from: http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the line with visitors
$nrvst = 0; // to store the number of visitors
// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)
$addrow[] = $uvon. $sep. time();
// check if the file from $filetxt exists and is writable
if(is_writable($filetxt)) {
// get into an array the lines added in $filetxt
$ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrrows = count($ar_rows);
// number of rows
// if there is at least one line, parse the $ar_rows array
if($nrrows>0) {
for($i=0; $i<$nrrows; $i++) {
// get each line and separate the user /visitor and the timestamp
$ar_line = explode($sep, $ar_rows[$i]);
// add in $addrow array the records in last $timeon seconds
if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
$addrow[] = $ar_rows[$i];
}
}
}
}
$nruvon = count($addrow); // total online
$usron = ''; // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
if(preg_match($rgxvst, $addrow[$i])) $nrvst++; // increment the visitors
else {
// gets and stores the user's name
$ar_usron = explode($sep, $addrow[$i]);
$usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
}
}
$nrusr = $nruvon - $nrvst; // gets the users (total - visitors)
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
?>
4.To show the number of online visitors /users in a ".html" file, use this code:
<script type="text/javascript" src="usersontxt.php?uvon=showon"></script>
This script (and the other presented below) works with $_SESSION. At the beginning of the PHP file in which you use it, you must add: session_start();. Count Online users and visitors using a MySQL table
To register, count and show the number of online visitors and users in a MySQL table, require to perform three SQL queries: Delete the records older than a certain time. Insert a row with the new user /visitor, or, if it is already inserted, Update the timestamp in its column. Select the remaining rows. Here's the code for a script that uses a MySQL table (named "userson") to store and display the Online Users and Visitors.
The code for create_userson.php
:
<?php
header('Content-type: text/html; charset=utf-8');
// HERE add your data for connecting to MySQ database
$host = 'localhost'; // MySQL server address
$user = 'root'; // User name
$pass = 'password'; // User`s password
$dbname = 'database'; // Database name
// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);
// check connection
if (mysqli_connect_errno()) exit('Connect failed: '. mysqli_connect_error());
// sql query for CREATE "userson" TABLE
$sql = "CREATE TABLE `userson` (
`uvon` VARCHAR(32) PRIMARY KEY,
`dt` INT(10) UNSIGNED NOT NULL
) CHARACTER SET utf8 COLLATE utf8_general_ci";
// Performs the $sql query on the server to create the table
if ($conn->query($sql) === TRUE) echo 'Table "userson" successfully created';
else echo 'Error: '. $conn->error;
$conn->close();
?>
userson
table (For explanations about the code, see the comments in script).usersmysql.php
):
In both file you must add your personal data for connecting to MySQL database, in the variables: $host
, $user
, $pass
, and $dbname
.The code for usersmysql.php:
<?php
// Script Online Users and Visitors - coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start(); // start Session, if not already started
// HERE add your data for connecting to MySQ database
$host = 'localhost'; // MySQL server address
$user = 'root'; // User name
$pass = 'password'; // User`s password
$dbname = 'database'; // Database name
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
You can get a free registration script from: http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the rows with visitors
$dt = time(); // current timestamp
$timeon = 120; // number of secconds to keep a user online
$nrvst = 0; // to store the number of visitors
$nrusr = 0; // to store the number of usersrs
$usron = ''; // to store the name of logged users
// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);
// Define and execute the Delete, Insert/Update, and Select queries
$sqldel = "DELETE FROM `userson` WHERE `dt`<". ($dt - $timeon);
$sqliu = "INSERT INTO `userson` (`uvon`, `dt`) VALUES ('$uvon', $dt) ON DUPLICATE KEY UPDATE `dt`=$dt";
$sqlsel = "SELECT * FROM `userson`";
// Execute each query
if(!$conn->query($sqldel)) echo 'Error: '. $conn->error;
if(!$conn->query($sqliu)) echo 'Error: '. $conn->error;
$result = $conn->query($sqlsel);
// if the $result contains at least one row
if ($result->num_rows > 0) {
// traverse the sets of results and set the number of online visitors and users ($nrvst, $nrusr)
while($row = $result->fetch_assoc()) {
if(preg_match($rgxvst, $row['uvon'])) $nrvst++; // increment the visitors
else {
$nrusr++; // increment the users
$usron .= '<br/> - <i>'.$row['uvon']. '</i>'; // stores the user's name
}
}
}
$conn->close(); // close the MySQL connection
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. ($nrusr+$nrvst). '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
?>
After you have created these two php files on your server, run the "create_userson.php" on your browser to create the "userson" table.
Include the usersmysql.php
file in the php file in which you want to display the number of online users and visitors.
Or, if you want to insert it in a ".html" file, add this code:
Examples using these scripts
• Including the "usersontxt.php` in a php file:
<!doctype html>
Counter Online Users and Visitors• Including the "usersmysql.php" in a html file:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Counter Online Users and Visitors</title>
<meta name="description" content="PHP script to count and show the number of online users and visitors" />
<meta name="keywords" content="online users, online visitors" />
</head>
<body>
<!-- Includes the script ("usersontxt.php", or "usersmysql.php") -->
<script type="text/javascript" src="usersmysql.php?uvon=showon"></script>
</body>
</html>
Both scripts (with storing data in a text file on the server, or into a MySQL table) will display a result like this: Online: 5
Visitors: 3 Users: 2
Presumably you have it in a variable and are using JSON.parse(data);
. In which case, use:
JSON.parse(data.replace(/"/g,'"'));
You might want to fix your JSON-writing script though, because "
is not valid in a JSON object.
All of the above seem to assume you know the URL for the latest Java RPM...
Oracle provide persistent links to the latest updates of each Java version as documented at https://support.oracle.com/epmos/faces/DocumentDisplay?_afrLoop=397248601136938&id=1414485.1 - though you need to create/log in to an Oracle Support account. *Otherwise you can only access the last "public" update of each Java version, e.g. 1.6_u45 (Mar 2013; Latest update is u65, Oct 2013)*
Once you know the persistent link, you should be able to resolve it to the real download; The following works for me, though I don't yet know if the "aru" reference changes.
ME=<myOracleID>
PW=<myOraclePW>
PATCH_FILE=p13079846_17000_Linux-x86-64.zip
echo "Get real URL from the persistent link"
wget -o getrealurl.out --no-cookies --no-check-certificate --user=$ME \
--password=$PW --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com" \
https://updates.oracle.com/Orion/Services/download/$PATCH_FILE?aru=16884382&\
patch_file=$PATCH_FILE
wait # wget appears to go into background, so "wait" waits
# until all background processes complete
REALURL=`grep "^--" getrealurl.out |tail -1 |sed -e 's/.*http/http/'`
wget -O $PATCH_FILE $REALURL
#These last steps must be done quickly, as the REALURL seems to have a short-lived
#cookie on it and I've had no success with --keep-session-cookies etc.
Make the area with your data and formulas a Table:
Then adding new information in the next line will copy all formulas in that table for the new line. Data validation will also be applied for the new row as it was for the whole column. This is indeed Excel being smarter with your data.
NO VBA required...
ResponseEntity
is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.
@ResponseBody
is a marker for the HTTP response body and @ResponseStatus
declares the status code of the HTTP response.
@ResponseStatus
isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse
or a HttpHeaders
parameter.
Basically, ResponseEntity
lets you do more.
For the folks that like me got here because they're trying to host aspnet.core mvc in a console application: The ONLY way I was able to solve this was by converting the .csproj to the new format and add the Sdk property to the Project tag on the very first line.
<Project Sdk="Microsoft.NET.Sdk.Razor">
Go into Tools -> Options -> Designers-> Uncheck "Prevent saving changes that require table re-creation". Voila.
That happens because sometimes it is necessary to drop and recreate a table in order to change something. This can take a while, since all data must be copied to a temp table and then re-inserted in the new table. Since SQL Server by default doesn't trust you, you need to say "OK, I know what I'm doing, now let me do my work."
PATH
is an environment variable, and can be displayed with the echo command:
echo $PATH
It's a list of paths separated by the colon character ':
'
The which
command tells you which file gets executed when you run a command:
which lshw
sometimes what you get is a path to a symlink; if you want to trace that link to where the actual executable lives, you can use readlink
and feed it the output of which
:
readlink -f $(which lshw)
The -f
parameter instructs readlink
to keep following the symlink recursively.
Here's an example from my machine:
$ which firefox
/usr/bin/firefox
$ readlink -f $(which firefox)
/usr/lib/firefox-3.6.3/firefox.sh
attributes are in your HTML text document/file (== imagine this is the result of your html markup parsed), whereas
properties are in HTML DOM tree (== basically an actual property of some object in JS sense).
Importantly, many of them are synced (if you update class
property, class
attribute in html will also be updated; and otherwise). But some attributes may be synced to unexpected properties - eg, attribute checked
corresponds to property defaultChecked
, so that
.prop('checked')
value, but will not change .attr('checked')
and .prop('defaultChecked')
values$('#input').prop('defaultChecked', true)
will also change .attr('checked')
, but this will not be visible on an element.Rule of thumb is:
.prop()
method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the.attr()
method. (http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/)
And here is a table that shows where .prop()
is preferred (even though .attr()
can still be used).
.prop()
can return any type - string, integer, boolean; while .attr()
always returns a string..prop()
is said to be about 2.5 times faster than .attr()
.inet_ntoa()
converts a in_addr
to string:
The inet_ntoa function converts an (Ipv4) Internet network address into an ASCII string in Internet standard dotted-decimal format.
inet_addr()
does the reverse job
The inet_addr function converts a string containing an IPv4 dotted-decimal address into a proper address for the IN_ADDR structure
PS this the first result googling "in_addr to string"!
They are not doing the same job: $emit
dispatches an event upwards through the scope hierarchy, while $broadcast
dispatches an event downwards to all child scopes.
When you download tomcat from their official website (of today that's tomcat version 9.0.26), all the apps you installed to tomcat can handle HTTP requests of unlimited size, given that the apps themselves do not have any limits on request size.
However, when you try to upload an app in tomcat's manager app, that app has a default war file limit of 50MB. If you're trying to install Jenkins for example which is 77 MB as ot today, it will fail.
Tomcat itself has size limit for each port, and this is defined in conf\server.xml
. This is controlled by maxPostSize
attribute of each Connector
(port). If this attribute does not exist, which it is by default, there is no limit on the request size.
To add a limit to a specific port, set a byte size for the attribute. For example, the below config for the default 8080 port limits request size to 200 MB. This means that all the apps installed under port 8080 now has the size limit of 200MB
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxPostSize="209715200" />
After passing the port level size limit, you can still configure app level limit. This also means that app level limit should be less than port level limit. The limit can be done through annotation within each servlet, or in the web.xml file. Again, if this is not set at all, there is no limit on request size.
To set limit through java annotation
@WebServlet("/uploadFiles")
@MultipartConfig( fileSizeThreshold = 0, maxFileSize = 209715200, maxRequestSize = 209715200)
public class FileUploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// ...
}
}
To set limit through web.xml
<web-app>
...
<servlet>
...
<multipart-config>
<file-size-threshold>0</file-size-threshold>
<max-file-size>209715200</max-file-size>
<max-request-size>209715200</max-request-size>
</multipart-config>
...
</servlet>
...
</web-app>
Tomcat's Manager app (by default localhost:8080/manager) is nothing but a default web app. By default that app has a web.xml
configuration of request limit of 50MB. To install (upload) app with size greater than 50MB through this manager app, you have to change the limit. Open the manager app's web.xml file from webapps\manager\WEB-INF\web.xml
and follow the above guide to change the size limit and finally restart tomcat.
For example string s="(U+007c)"
To remove only the parentheses from s, try the below one:
import re
a=re.sub("\\(","",s)
b=re.sub("\\)","",a)
print(b)
try this
json = $.grep(newcurrPayment.paymentTypeInsert, function (el, idx) { return el.FirstName == "Test1" }, true)
you need to make county_ID
as index for the right frame:
frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
on=[ 'countyid' ], how='left' )
for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.
so you need to verify integrity before joining by , verify_integrity=True
For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.
If you want both attachment and text try this based on the accepted answer :
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "yourHost");
props.put("mail.smtp.port", "yourHostPort");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password");
}
});
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(mailFrom));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
msg.setSubject("your subject");
Multipart multipart = new MimeMultipart();
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText("your text");
MimeBodyPart attachmentBodyPart= new MimeBodyPart();
DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"
multipart.addBodyPart(textBodyPart); // add the text part
multipart.addBodyPart(attachmentBodyPart); // add the attachement part
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
LOGGER.log(Level.SEVERE,"Error while sending email",e);
}
Update :
If you want to send a mail as an html content formated you have to do
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(content, "text/html");
So basically setText
is for raw text and will be well display on every server email including gmail, setContent
is more for an html template and if you content is formatted as html it will maybe also works in gmail
If you don't mind leaving pure C# and going for WinApi calls, then you might want to consider the PathIsDirectoryEmpty() function. According to the MSDN, the function:
Returns TRUE if pszPath is an empty directory. Returns FALSE if pszPath is not a directory, or if it contains at least one file other than "." or "..".
That seems to be a function which does exactly what you want, so it is probably well optimised for that task (although I haven't tested that).
To call it from C#, the pinvoke.net site should help you. (Unfortunately, it doesn't describe this certain function yet, but you should be able to find some functions with similar arguments and return type there and use them as the basis for your call. If you look again into the MSDN, it says that the DLL to import from is shlwapi.dll
)
One pitfall I ran into was a parent element having the 'overflow' attribute set to 'auto'. This negates child div elements with the page-break-inside attribute in the print version. Otherwise, page-break-inside: avoid
works fine on Chrome for me.
In javascript you can do something like this
<input
ref="fileInput"
multiple
type="file"
style="display: none"
@change="trySubmitFile"
>
and the function can be something like this.
trySubmitFile(e) {
if (this.disabled) return;
const files = e.target.files || e.dataTransfer.files;
if (files.length > 5) {
alert('You are only allowed to upload a maximum of 2 files at a time');
}
if (!files.length) return;
for (let i = 0; i < Math.min(files.length, 2); i++) {
this.fileCallback(files[i]);
}
}
I am also searching for a solution where this can be limited at the time of selecting files but until now I could not find anything like that.
Would the following Macro help you?
Sub activateSheet(sheetname As String)
'activates sheet of specific name
Worksheets(sheetname).Activate
End Sub
Basically you want to make use of the .Activate function. Or you can use the .Select function like so:
Sub activateSheet(sheetname As String)
'selects sheet of specific name
Sheets(sheetname).Select
End Sub
I have similar requirement where I need a MySQL client but not server (running in a virtual machine and don't want any additional overhead) and for me the easiest thing was to install MySQL community server taking typical installation options but NOT configure the server, so it never starts, never runs. Added C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin to system path environment variable and I'm able to use the MySQL command line client mssql.exe and mysqladmin.exe programs.
Try this. The following considers checkbox and label as a unique element:
<style>
.item {white-space: nowrap;display:inline }
</style>
<fieldset>
<div class="item">
<input type="checkbox" id="a">
<label for="a">aaaaaaaaaaaa aaaa a a a a a a aaaaaaaaaaaaa</label>
</div>
<div class="item">
<input type="checkbox" id="b">
<!-- depending on width, a linebreak NEVER occurs here. -->
<label for="b">bbbbbbbbbbbb bbbbbbbbbbbbbbbbb b b b b bb</label>
</div>
<div class="item">
<input type="checkbox" id="c">
<label for="c">ccccc c c c c ccccccccccccccc cccc</label>
</div>
</fieldset>
This is how you Delete From a slice the idiomatic way. You don't need to build a function it is built into the append. Try it here https://play.golang.org/p/QMXn9-6gU5P
z := []int{9, 8, 7, 6, 5, 3, 2, 1, 0}
fmt.Println(z) //will print Answer [9 8 7 6 5 3 2 1 0]
z = append(z[:2], z[4:]...)
fmt.Println(z) //will print Answer [9 8 5 3 2 1 0]
If you know the group id of X
, you can use this command to redownload all of X
and it's dependencies
mvn clean dependency:purge-local-repository -DresolutionFuzziness=org.id.of.x
It does the same thing as the other answers that propose using dependency:purge-local-repository
, but it only deletes and redownloads everything related to X
.
My solution is:
-vm
D:/work/Java/jdk1.6.0_13/bin/javaw.exe
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-framework
plugins\org.eclipse.osgi_3.4.3.R34x_v20081215-1030.jar
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
I had the same issue as above and I am using PostgreSQL 10.5. I tried everything as above but nothing seems to be working.
Then I closed the pgadmin and opened a session for the PSQL terminal. Logged into the PSQL and connected to the database and schema respectively :
\c <DATABASE_NAME>;
set search_path to <SCHEMA_NAME>;
Then, restarted the pgadmin console and then I was able to work without issue in the query-tool of the pagadmin.
please Find below one it helps me a lot to set data function
$('#datepicker').datepicker({dateFormat: 'yy-mm-dd'}).datepicker('setDate', '2010-07-25');
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
That's what ln
is documented to do when the target already exists and is a directory. If you want /etc/nginx
to be a symlink rather than contain a symlink, you had better not create it as a directory first!
@RequestParam annotation used for accessing the query parameter values from the request. Look at the following request URL:
http://localhost:8080/springmvc/hello/101?param1=10¶m2=20
In the above URL request, the values for param1 and param2 can be accessed as below:
public String getDetails(
@RequestParam(value="param1", required=true) String param1,
@RequestParam(value="param2", required=false) String param2){
...
}
The following are the list of parameters supported by the @RequestParam annotation:
@PathVariable
@PathVariable identifies the pattern that is used in the URI for the incoming request. Let’s look at the below request URL:
http://localhost:8080/springmvc/hello/101?param1=10¶m2=20
The above URL request can be written in your Spring MVC as below:
@RequestMapping("/hello/{id}") public String getDetails(@PathVariable(value="id") String id,
@RequestParam(value="param1", required=true) String param1,
@RequestParam(value="param2", required=false) String param2){
.......
}
The @PathVariable annotation has only one attribute value for binding the request URI template. It is allowed to use the multiple @PathVariable annotation in the single method. But, ensure that no more than one method has the same pattern.
Also there is one more interesting annotation: @MatrixVariable
And the Controller method for it
@RequestMapping(value = "/{stocks}", method = RequestMethod.GET)
public String showPortfolioValues(@MatrixVariable Map<String, List<String>> matrixVars, Model model) {
logger.info("Storing {} Values which are: {}", new Object[] { matrixVars.size(), matrixVars });
List<List<String>> outlist = map2List(matrixVars);
model.addAttribute("stocks", outlist);
return "stocks";
}
But you must enable:
<mvc:annotation-driven enableMatrixVariables="true" >
It seems that the original test case is wrong.
I can confirm that the selector #my_parent_element *
works with unbind()
.
Let's take the following html as an example:
<div id="#my_parent_element">
<div class="div1">
<div class="div2">hello</div>
<div class="div3">my</div>
</div>
<div class="div4">name</div>
<div class="div5">
<div class="div6">is</div>
<div class="div7">
<div class="div8">marco</div>
<div class="div9">(try and click on any word)!</div>
</div>
</div>
</div>
<button class="unbind">Now, click me and try again</button>
And the jquery bit:
$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
alert('hi!');
})
$('button.unbind').click(function() {
$('#my_parent_element *').unbind('click');
})
You can try it here: http://jsfiddle.net/fLvwbazk/7/
With personal experience of using the following code within a Stored Procedure which Hashed a SP Variable I can confirm, although undocumented, this combination works 100% as per my example:
@var=SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_512', @SPvar)), 3, 128)
RaisedButton(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [Text('Submit')],
)
)
It works for me.
Honestly, I like the other answers. Easy and no need to get into JS. But I noticed that you were asking about jQuery. So for the sake of completeness, in jQuery if you return false with the .click() handler, it will negate the default action of the widget.
See here for an example (and more goodies, too). Here's the documentation, too.
in a nutshell, with your sample code, do this:
<script type="text/javascript">
$('button[type!=submit]').click(function(){
// code to cancel changes
return false;
});
</script>
<a href="index.html"><button>Cancel changes</button></a>
<button type="submit">Submit</button>
As an added benefit, with this, you can get rid of the anchor tag and just use the button.
Here is an easy way to get the file name from a path:
echo "$PATH" | rev | cut -d"/" -f1 | rev
To remove the extension you can use, assuming the file name has only ONE dot (the extension dot):
cut -d"." -f1
Check out this link for more details.
To find files which are created in last one hour in current directory, you can use -amin
find . -amin -60 -type f
This will find files which are created with in last 1 hour.
I don't know why
cfg_name_unique NOT LIKE '%categories%'
still returns those two values, but maybe exclude them explicit:
SELECT *
FROM developer_configurations_cms
WHERE developer_configurations_cms.cat_id = '1'
AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
AND developer_configurations_cms.cfg_name_unique NOT LIKE '%categories%'
AND developer_configurations_cms.cfg_name_unique NOT IN ('categories_posts', 'categories_news')
shell_exec
returns all of the output stream as a string. exec
returns the last line of the output by default, but can provide all output as an array specifed as the second parameter.
See
Yegor256's answer worked for me, but I thought I would just add some comments to help out those who are not so good at mounting drives(like me!):
Amazon gives you a choice of what you want to name the volume when you attach it. You have use a name in the range from /dev/sda - /dev/sdp The newer versions of Ubuntu will then rename what you put in there to /dev/xvd(x) or something to that effect.
So for me, I chose /dev/sdp as name the mount name in AWS, then I logged into the server, and discovered that Ubuntu had renamed my volume to /dev/xvdp1). I then had to mount the drive - for me I had to do it like this:
mount -t ext4 xvdp1 /mnt/tmp
After jumping through all those hoops I could access my files at /mnt/tmp
Updating this (9 years after it was asked) as the answer I was looking for wasn't mentioned:
Firefox also has presets for throttling connection speeds. Find them in the Network Monitor tab of the developer tools. Default is 'No throttling'.
Slowest is GPRS (Download speed: 50 Kbps, Upload speed: 20 Kbps, Minimum latency (ms): 500), ranging through 'good' and 'regular' 2G, 3G and 4G to DSL and WiFi (Download speed: 30Mbps, Upload speed: 15Mbps, Minimum latency (ms): 2).
More in the Dev Tools docs.
If you only want to animate the height of a view (from say 0 to a certain number) you could implement your own animation:
final View v = getTheViewToAnimateHere();
Animation anim=new Animation(){
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
// Do relevant calculations here using the interpolatedTime that runs from 0 to 1
v.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, (int)(30*interpolatedTime)));
}};
anim.setDuration(500);
v.startAnimation(anim);
you can also use andSelf()
method to get wrapper DOM contain then find()
can be work around as your idea
$(function() {_x000D_
$('.slide-link').andSelf().find('[data-slide="0"]').addClass('active');_x000D_
})
_x000D_
.active {_x000D_
background: green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<a class="slide-link" href="#" data-slide="0">1</a>_x000D_
<a class="slide-link" href="#" data-slide="1">2</a>_x000D_
<a class="slide-link" href="#" data-slide="2">3</a>
_x000D_
I made a node module to automate this task: mddir
node mddir "../relative/path/"
To install: npm install mddir -g
To generate markdown for current directory: mddir
To generate for any absolute path: mddir /absolute/path
To generate for a relative path: mddir ~/Documents/whatever.
The md file gets generated in your working directory.
Currently ignores node_modules, and .git folders.
If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.
Get npm bin folder path with:
npm config get prefix
Cd into that folder
brew install dos2unix
dos2unix lib/node_modules/mddir/src/mddir.js
This converts line endings to Unix instead of Dos
Then run as normal with: node mddir "../relative/path/".
|-- .bowerrc
|-- .jshintrc
|-- .jshintrc2
|-- Gruntfile.js
|-- README.md
|-- bower.json
|-- karma.conf.js
|-- package.json
|-- app
|-- app.js
|-- db.js
|-- directoryList.md
|-- index.html
|-- mddir.js
|-- routing.js
|-- server.js
|-- _api
|-- api.groups.js
|-- api.posts.js
|-- api.users.js
|-- api.widgets.js
|-- _components
|-- directives
|-- directives.module.js
|-- vendor
|-- directive.draganddrop.js
|-- helpers
|-- helpers.module.js
|-- proprietary
|-- factory.actionDispatcher.js
|-- services
|-- services.cardTemplates.js
|-- services.cards.js
|-- services.groups.js
|-- services.posts.js
|-- services.users.js
|-- services.widgets.js
|-- _mocks
|-- mocks.groups.js
|-- mocks.posts.js
|-- mocks.users.js
|-- mocks.widgets.js
I know this is quite late to answer this question but I resolved this problem by myself and thought worth sharing it with everyone.`
public void replaceFragment(BaseFragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
final FragmentManager fManager = getSupportFragmentManager();
BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
if (fragm == null) { //here fragment is not available in the stack
transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
transaction.addToBackStack(fragment.getFragmentTag());
} else {
//fragment was found in the stack , now we can reuse the fragment
// please do not add in back stack else it will add transaction in back stack
transaction.replace(R.id.container, fragm, fragm.getFragmentTag());
}
transaction.commit();
}
And in the onBackPressed()
@Override
public void onBackPressed() {
if(getSupportFragmentManager().getBackStackEntryCount()>1){
super.onBackPressed();
}else{
finish();
}
}
Marco's answer above is correct, but just to expand on the question of "under what context"...
frame - this is the property you most often use for normal iPhone applications. most controls will be laid out relative to the "containing" control so the frame.origin will directly correspond to where the control needs to display, and frame.size will determine how big to make the control.
center - this is the property you will likely focus on for sprite based games and animations where movement or scaling may occur. By default animation and rotation will be based on the center of the UIView. It rarely makes sense to try and manage such objects by the frame property.
bounds - this property is not a positioning property, but defines the drawable area of the UIView "relative" to the frame. By default this property is usually (0, 0, width, height). Changing this property will allow you to draw outside of the frame or restrict drawing to a smaller area within the frame. A good discussion of this can be found at the link below. It is uncommon for this property to be manipulated unless there is specific need to adjust the drawing region. The only exception is that most programs will use the [[UIScreen mainScreen] bounds]
on startup to determine the visible area for the application and setup their initial UIView's frame accordingly.
Why is there an frame rectangle and an bounds rectangle in an UIView?
Hopefully this helps clarify the circumstances where each property might get used.
If you have a UITabController with Screens with Embeded Navigation Controllers, you have to set the UITabController Presentation to FullScreen as shown in pic below
To get the behavior you want you need to wait for the process to finish before you exit Main()
. To be able to tell when your process is done you need to return a Task
instead of a void
from your function, you should never return void
from a async
function unless you are working with events.
A re-written version of your program that works correctly would be
class Program { static void Main(string[] args) { Debug.WriteLine("Calling DoDownload"); var downloadTask = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); downloadTask.Wait(); //Waits for the background task to complete before finishing. } private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); } }
Because you can not await
in Main()
I had to do the Wait()
function instead. If this was a application that had a SynchronizationContext I would do await downloadTask;
instead and make the function this was being called from async
.
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
It would match any element p
that's immediately adjacent to an element 'p'. See: http://www.w3.org/TR/CSS2/selector.html
A char
doesn't have any methods - it's a Java primitive. You're looking for the Character wrapper class.
The usage would be:
if(Character.isLetter(ch)) { //... }
I tried using a CLR function and it was more than twice as fast as BCP. Here's my code.
Original Method:
SET @bcpCommand = 'bcp "SELECT blobcolumn FROM blobtable WHERE ID = ' + CAST(@FileID AS VARCHAR(20)) + '" queryout "' + @FileName + '" -T -c'
EXEC master..xp_cmdshell @bcpCommand
CLR Method:
declare @file varbinary(max) = (select blobcolumn from blobtable WHERE ID = @fileid)
declare @filepath nvarchar(4000) = N'c:\temp\' + @FileName
SELECT Master.dbo.WriteToFile(@file, @filepath, 0)
C# Code for the CLR function
using System;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;
namespace BlobExport
{
public class Functions
{
[SqlFunction]
public static SqlString WriteToFile(SqlBytes binary, SqlString path, SqlBoolean append)
{
try
{
if (!binary.IsNull && !path.IsNull && !append.IsNull)
{
var dir = Path.GetDirectoryName(path.Value);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (var fs = new FileStream(path.Value, append ? FileMode.Append : FileMode.OpenOrCreate))
{
byte[] byteArr = binary.Value;
for (int i = 0; i < byteArr.Length; i++)
{
fs.WriteByte(byteArr[i]);
};
}
return "SUCCESS";
}
else
"NULL INPUT";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}
To elaborate on the other answers provided, this is my solution (placed in an Activity):
@Override
public void onBackPressed(){
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE
would have been too narrow in its meaning.
The fundamental difference in most programming languages is that unless the unexpected happens a for
loop will always repeat n
times or until a break statement, (which may be conditional), is met then finish with a while
loop it may repeat 0 times, 1, more or even forever
, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while
loop, (or repeat until
), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).
It is worth noting that in Python a for
or while
statement can have break
, continue
and else
statements where:
break
- terminates the loopcontinue
- moves on to the next time around the loop without executing following code this time aroundelse
- is executed if the loop completed without any break
statements being executed.N.B. In the now unsupported Python 2 range
produced a list of integers but you could use xrange
to use an iterator. In Python 3 range
returns an iterator.
So the answer to your question is 'it all depends on what you are trying to do'!
volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:
int i1; int geti1() {return i1;} volatile int i2; int geti2() {return i2;} int i3; synchronized int geti3() {return i3;}
geti1()
accesses the value currently stored ini1
in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads.In particular, another thread may have updatedi1
in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 fori1
, for thread1 to have a value of 2 fori1
and for thread2 to have a value of 3 fori1
if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.On the other hand,
geti2()
effectively accesses the value ofi2
from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally volatile variables have a higher access and update overhead than "plain" variables. Generally threads are allowed to have their own copy of data is for better efficiency.There are two differences between volitile and synchronized.
Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block. That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing
geti3()
does the following:
- The thread acquires the lock on the monitor for object this .
- The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory .
- The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
- (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
- The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
http://javaexp.blogspot.com/2007/12/difference-between-volatile-and.html
Somewhere in your initialisation put this code.
Array.prototype.contains = function contains(obj) {
for (var i = 0; i < this.length; i++) {
if (this[i] === obj) {
return true;
}
}
return false;
};
Then, you can use it this way:
<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>
You need to use the val()
function to get the textbox value. text
does not exist as a property only as a function and even then its not the correct function to use in this situation.
var from = $("input#fromAddress").val()
val()
is the standard function for getting the value of an input.
I was having almost the same problem as this but slightly different on Server 2012 R2. I have a powershell script in Task Scheduler that copies 3 files from one location to another. If I run the script manually from powershell, it works like a charm. But when run from Task Scheduler, it only copies the first 2 small files, then hang on the 3rd (large file). And I was also getting a result of "The operator or administrator has refused the request". And I have done almost everything in this forum.
Here is the scenario and how I fixed it for me. May not work for others, but just in case it will:
Scenario: 1. Powershell script in Task Scheduler 2. Ran using a domain account which is a local admin on the server 3. Selected 'Run whether user is logged on or not" 4. Run with highest priviledges
Fix: 1. I had to login to the server using the domain account so that it created a local profile in C:\Users. 2. Checked and made user that the user has access to all the drives I referred to on my script
I believe #1 is the main fix for me. I hope this works for others out there.
What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!
As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you set — Official Documentation
Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!
How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.
Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.
Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…
First Approach: Are your files gzipped?
Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.
How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.
const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())
Second Approach:: Analyze your Angular bundle
If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.
It’s super easy to get this graph.
npm install -g webpack-bundle-analyzer
ng build --stats-json
(don’t use flag --prod
). By enabling --stats-json
you will get an additional file stats.jsonwebpack-bundle-analyzer ./dist/stats.json
and your browser will pop up the page at localhost:8888. Have fun with it.ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours
the rdl file content:
<Visibility><Hidden>=Parameters!casetype.Value=300</Hidden></Visibility>
so the text box will hidden, if your expression is true.
Add width:100px, margin:50%.
Now the left side of the button is set to the center.
Finally add half of the width of the button in our case 50px.
The middle of the button is in the center.
<input type='submit' style='width:100px;margin:0 50%;position:relative;left:-50px;'>
Try this:
i = 5
ii = 10
if i == 5 and ii == 10:
print "i is 5 and ii is 10"
Edit: Oh, and you dont need that semicolon on the last line (edit to remove it from my code).
You Can Show Facebook Share/Like Count Like This: ( Tested and Verified)
$url = http://www.yourdomainname.com // You can use inner pages
$rest_url = "http://api.facebook.com/restserver.php?format=json&method=links.getStats&urls=".urlencode($url);
$json = json_decode(file_get_contents($rest_url),true);
echo Facebook Shares = '.$json[0][share_count];
echo Facebook Likes = '.$json[0][like_count];
echo Facebook Comments = '.$json[0][comment_count];
Simple prevent the default behavior of click
, dblclick
or touchend
events will disable the zoom functionality.
If you have already a callback on one of this events just call a event.preventDefault()
.
I was having similar problem and
var dataObj = JSON.parse(data);
console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie
This solved my problem. Thanks Selvakumar Arumugam
Java only knows about the platform it is currently running on, so it can only give you a platform-dependent output on that platform (using bw.newLine()
) . The fact that you open it on a windows system means that you either have to convert the file before using it (using something you have written, or using a program like unix2dos), or you have to output the file with windows format carriage returns in it originally in your Java program. So if you know the file will always be opened on a windows machine, you will have to output
bw.write(rs.getString(1)==null? "":rs.getString(1));
bw.write("\r\n");
It's worth noting that you aren't going to be able to output a file that will look correct on both platforms if it is just plain text you are using, you may want to consider using html if it is an email, or xml if it is data. Alternatively, you may need some kind of client that reads the data and then formats it for the platform that the viewer is using.
Here are two methods to get more than 1 column in a scalar subquery (or inline subquery) and querying the lookup table only once. This is a bit convoluted but can be the very efficient in some special cases.
You can use concatenation to get several columns at once:
SELECT x,
regexp_substr(yz, '[^^]+', 1, 1) y,
regexp_substr(yz, '[^^]+', 1, 2) z
FROM (SELECT a.x,
(SELECT b.y || '^' || b.z yz
FROM b
WHERE b.v = a.v)
yz
FROM a)
You would need to make sure that no column in the list contain the separator character.
You could also use SQL objects:
CREATE OR REPLACE TYPE b_obj AS OBJECT (y number, z number);
SELECT x,
v.yz.y y,
v.yz.z z
FROM (SELECT a.x,
(SELECT b_obj(y, z) yz
FROM b
WHERE b.v = a.v)
yz
FROM a) v
I had a ClassNotFoundException pointing to my Application class.
I found that I missed Java builder in my .project
If something is missing in your buildSpec, close Eclipse, make sure everything is in place and start Eclipse again
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
In my case I had Java 7 and 8 (both x64) installed and I want to redirect to java 7 but everything is set to use Java 8. Java uses the PATH environment variable:
C:\ProgramData\Oracle\Java\javapath
as the first option to look for its folder runtime (is a hidden folder). This path contains 3 symlinks that can't be edited.
In my pc, the PATH environment variable looks like this:
C:\ProgramData\Oracle\Java\javapath;C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;
In my case, It should look like this:
C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;
I had to cut and paste the symlinks to somewhere else so java can't find them, and I can restore them later.
After setting the JAVA_HOME and JRE_HOME environment variables to the desired java folders' runtimes (in my case it is Java 7), the command java -version
should show your desired java runtime. I remark there's no need to mess with the registry.
Tested on Win7 x64.
Answer to use "/I" is working but with little trick - in target you must end with character \ to tell xcopy that target is directory and not file!
Example:
xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)_DropFolder" /F /R /Y /I
does not work and return code 2, but this one:
xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)_DropFolder\" /F /R /Y /I
Command line arguments used in my sample:
/F - Displays full source & target file names
/R - This will overwrite read-only files
/Y - Suppresses prompting to overwrite an existing file(s)
/I - Assumes that destination is directory (but must ends with \)
I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.
Just putting it in src/main/resources
will bundle it inside the artifact. E.g. if your artifact is a JAR, you will have the log4j.properties
file inside it, losing its initial point of making logging configurable.
I usually put it in src/main/resources
, and set it to be output to target like so:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<targetPath>${project.build.directory}</targetPath>
<includes>
<include>log4j.properties</include>
</includes>
</resource>
</resources>
</build>
Additionally, in order for log4j to actually see it, you have to add the output directory to the class path.
If your artifact is an executable JAR, you probably used the maven-assembly-plugin to create it. Inside that plugin, you can add the current folder of the JAR to the class path by adding a Class-Path
manifest entry like so:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.your-package.Main</mainClass>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
Now the log4j.properties file will be right next to your JAR file, independently configurable.
To run your application directly from Eclipse, add the resources
directory to your classpath in your run configuration: Run->Run Configurations...->Java Application->New
select the Classpath
tab, select Advanced
and browse to your src/resources
directory.
The behaviour is not really that strange. Looking into the implementation of the classes, it is caused by:
Charset.defaultCharset()
is not caching the determined character set in Java 5.Charset.defaultCharset()
again causes a second evaluation of the system property, no character set with the name "Latin-1" is found, so Charset.defaultCharset()
defaults to "UTF-8".OutputStreamWriter
is however caching the default character set and is probably used already during VM initialization, so that its default character set diverts from Charset.defaultCharset()
if the system property "file.encoding" has been changed at runtime.As already pointed out, it is not documented how the VM must behave in such a situation. The Charset.defaultCharset()
API documentation is not very precise on how the default character set is determined, only mentioning that it is usually done on VM startup, based on factors like the OS default character set or default locale.
I am quite benefited with http://stackoverflow.com. I was wandering from hours for automatic login and submit from vb application to another web site. Due to help of this site I am able to complete my task
I have to login following web php page.
<HTML>
<body>
<div align="center"><img src="banner.png" height="80px" /></div>
<script type="text/javascript">
$(document).ready(function(){
$("#login").validate();
$("#login_container").css({'position': 'absolute',
'top' : (($(window).height()/2) - $("#login_container").height()/2)+'px'});
$("#login_container").css({'left' : (($(window).width()/2) - $("#login_container").width()/2)+'px'});
});
</script>
<div id="login_container">
<form name="login" id="login" action="?q=login" method="post">
<table>
<tr><td>Username</td><td><input type="text" name="name" class="required"/></td></tr>
<tr><td>Password</td><td><input type="password" name="password" class="required"/></td></tr>
<tr><td></td><td><input type="submit" name="subimt" value="Login" /></td></tr>
</table>
</form>
</div>
</body>
</html>
For automatic Login and clicking I wrote following VB.Net Code. In form1
I placed a button and a Webbrowser control
Imports System.IO
Imports System.Windows.Forms
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
WebBrowser1.Navigate("http://xyz.com")
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
WebBrowser1.Document.GetElementById("name").SetAttribute("Value", "bharatlal")
WebBrowser1.Document.GetElementById("password").SetAttribute("Value", "mahato")
WebBrowser1.Document.GetElementById("subimt").Focus()
WebBrowser1.Document.GetElementById("subimt").InvokeMember("click")
End Sub
End Class
Perfectly worked for me
jQuery('#datetimepicker1').datetimepicker({
use24hours: true,
format: "YYYY-MM-DD HH:mm ",
defaultDate: new Date(),
});
mvn clean package -DpropEnv=PROD
Then using like this in POM.xml
<properties>
<myproperty>${propEnv}</myproperty>
</properties>
in which element is currently the class '.bar' ? Here is another solution but it's up to you.
var reg = /Image/g, // regexp for an image element
query = document.querySelector('.bar'); // returns [object HTMLImageElement]
query += this.toString(); // turns object into a string
if (query.match(reg)) { // checks if it matches
alert('the class .bar is attached to the following Element:\n' + query);
}
Of course this is only a lookup for 1 simple element <img>
(/Image/g
) but you can put all in an array like <li>
is /LI/g
, <ul>
= /UL/g
etc.
On Version 1.9.6.1. For UnPushed commit.
Go File -> New Project.
Select Web under Visual C#.
Select ASP.NET Web Application
Click OK.
Select MVC.
Click OK.
JSON is essentially a String in PHP or JAVA context. That means string which is valid JSON can be returned in response. Following should work.
@RequestMapping(value="/user/addUser", method=RequestMethod.POST)
@ResponseBody
public String addUser(@ModelAttribute("user") User user) {
if (user != null) {
logger.info("Inside addIssuer, adding: " + user.toString());
} else {
logger.info("Inside addIssuer...");
}
users.put(user.getUsername(), user);
return "{\"success\":1}";
}
This is okay for simple string response. But for complex JSON response you should use wrapper class as described by Shaun.
var element = document.getElementById('element');
alert(element.offsetHeight);
The pageContext
is an implicit object available in JSPs. The EL documentation says
The context for the JSP page. Provides access to various objects including:
servletContext: ...
session: ...
request: ...
response: ...
Thus this expression will get the current HttpServletRequest
object and get the context path for the current request and append /JSPAddress.jsp
to it to create a link (that will work even if the context-path this resource is accessed at changes).
The primary purpose of this expression would be to keep your links 'relative' to the application context and insulate them from changes to the application path.
For example, if your JSP (named thisJSP.jsp
) is accessed at http://myhost.com/myWebApp/thisJSP.jsp
, thecontext path will be myWebApp
. Thus, the link href generated will be /myWebApp/JSPAddress.jsp
.
If someday, you decide to deploy the JSP on another server with the context-path of corpWebApp
, the href generated for the link will automatically change to /corpWebApp/JSPAddress.jsp
without any work on your part.
For those who are looking to sort whether or not there are optgroup :
/**
* Sorting options
* and optgroups
*
* @param selElem select element
* @param optionBeforeGroup ?bool if null ignores, if true option appear before group else option appear after group
*/
function sortSelect(selElem, optionBeforeGroup = null) {
let initialValue = selElem.tagName === "SELECT" ? selElem.value : null;
let allChildrens = Array.prototype.slice.call(selElem.childNodes);
let childrens = [];
for (let i = 0; i < allChildrens.length; i++) {
if (allChildrens[i].parentNode === selElem && ["OPTGROUP", "OPTION"].includes(allChildrens[i].tagName||"")) {
if (allChildrens[i].tagName == "OPTGROUP") {
sortSelect(allChildrens[i]);
}
childrens.push(allChildrens[i]);
}
}
childrens.sort(function(a, b){
let x = a.tagName == "OPTGROUP" ? a.getAttribute("label") : a.innerHTML;
let y = b.tagName == "OPTGROUP" ? b.getAttribute("label") : b.innerHTML;
x = typeof x === "undefined" || x === null ? "" : (x+"");
y = typeof y === "undefined" || y === null ? "" : (y+"");
if (optionBeforeGroup === null) {
if (x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}
if (x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}
} else if (optionBeforeGroup === true) {
if ((a.tagName == "OPTION" && b.tagName == "OPTGROUP") || x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}
if ((a.tagName == "OPTGROUP" && b.tagName == "OPTION") || x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}
} else if (optionBeforeGroup === false) {
if ((a.tagName == "OPTGROUP" && b.tagName == "OPTION") || x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}
if ((a.tagName == "OPTION" && b.tagName == "OPTGROUP") || x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}
}
return 0;
});
if (optionBeforeGroup !== null) {
childrens.sort(function(a, b){
if (optionBeforeGroup === true) {
if (a.tagName == "OPTION" && b.tagName == "OPTGROUP") {return -1;}
if (a.tagName == "OPTGROUP" && b.tagName == "OPTION") {return 1;}
} else {
if (a.tagName == "OPTGROUP" && b.tagName == "OPTION") {return -1;}
if (a.tagName == "OPTION" && b.tagName == "OPTGROUP") {return 1;}
}
return 0;
});
}
selElem.innerHTML = "";
for (let i = 0; i < childrens.length; i++) {
selElem.appendChild(childrens[i]);
}
if (selElem.tagName === "SELECT") {
selElem.value = initialValue;
}
}
The method exposed by sykora is the best option in this case. But sometimes is not the easiest and it's not a general method. For a general method use git cherry-pick:
To achieve what OP wants, its a 2-step process:
newbranch
Execute
git checkout master
git log
Note the hashes of (say 3) commits you want on newbranch
. Here I shall use:
C commit: 9aa1233
D commit: 453ac3d
E commit: 612ecb3
Note: You can use the first seven characters or the whole commit hash
newbranch
git checkout newbranch
git cherry-pick 612ecb3
git cherry-pick 453ac3d
git cherry-pick 9aa1233
git checkout newbranch
git cherry-pick 612ecb3~1..9aa1233
git cherry-pick applies those three commits to newbranch.
Put empty value if the value does not exist or null.
value={ this.state.value || "" }
Let's just say you have 3 buttons:
<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">
To style the disabled button you can use the following css:
input[type="button"]:disabled{
color:#000;
}
This will only affect the button which is disabled.
To stop the color changing when hovering you can use this too:
input[type="button"]:disabled:hover{
color:#000;
}
You can also avoid this by using a css-reset.
Here is an example JSFiddle - http://jsfiddle.net/6yL6t/
And the code:
function hashCode(str) {
var hash = 0, i, chr, len;
if (str.length == 0) return hash;
for (i = 0, len = str.length; i < len; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
var onceHashes = {};
function once(func) {
var unique = hashCode(func.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1]);
if (!onceHashes[unique]) {
onceHashes[unique] = true;
func();
}
}
You could do:
for (var i=0; i<10; i++) {
once(function() {
alert(i);
});
}
And it will run only once :)
You can also use the command line, Change directory where your folder is located then type the following :
git init
git add <folder1> <folder2> <etc.>
git commit -m "Your message about the commit"
git remote add origin https://github.com/yourUsername/yourRepository.git
git push -u origin master
git push origin master
ulimit -c unlimited
is a system variable, wich will allow to create a core dump after your application crashes. In this case an unlimited amount. Look for a file called core in the very same directory. Make sure you compiled your code with debugging informations enabled!
regards
Found the answer. What I did was was first
sudo apt-get install aptitude
sudo aptitude install libglib2.0-0
sudo aptitude install gcc-4.7 make linux-headers-`uname -r` -y
and tried it but it didn't work so I continued and did
sudo apt-get install build-essential
sudo apt-get install gcc-4.7 linux-headers-`uname -r`
after doing these two steps and trying again, it worked.
It sounds less like a Java synchronization issue and more like a database locking problem.
I don't know if adding a version to all your persistent classes will sort it out, but that's one way that Hibernate can provide exclusive access to rows in a table.
Could be that isolation level needs to be higher. If you allow "dirty reads", maybe you need to bump up to serializable.
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
});
Since tr:not(:first-child)
is not supported by IE 6, 7, 8. You can use the help of jQuery.
You may find it here
Cast the dtype
of the col to str
and you can perform vectorised slicing calling str
:
In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df
Out[29]:
First Second new_col
0 123 234 1
1 22 4353 2
2 32 355 3
3 453 453 4
4 45 345 4
5 453 453 4
6 56 56 5
if you need to you can cast the dtype
back again calling astype(int)
on the column
LDAP stands for Lightweight Directory Access Protocol. As the name suggests, it is a lightweight protocol for accessing directory services, specifically X.500-based directory services. LDAP runs over TCP/IP or other connection oriented transfer services. The nitty-gritty details of LDAP are defined in RFC2251 "The Lightweight Directory Access Protocol (v3)" and other documents comprising the technical specification RFC3377. This section gives an overview of LDAP from a user's perspective.
What kind of information can be stored in the directory? The LDAP information model is based on entries. An entry is a collection of attributes that has a globally-unique Distinguished Name (DN). The DN is used to refer to the entry unambiguously. Each of the entry's attributes has a type and one or more values. The types are typically mnemonic strings, like cn
for common name, or mail
for email address. The syntax of values depend on the attribute type. For example, a cn
attribute might contain the value Babs Jensen
. A mail attribute might contain the value [email protected]
. A jpegPhoto
attribute would contain a photograph in the JPEG (binary) format.
How is the information arranged? In LDAP, directory entries are arranged in a hierarchical tree-like structure.
len(each) == max(len(x) for x in myList)
or just each == max(myList, key=len)
For Autodidacts:
function BaseClass(toBePrivate){
var morePrivates;
this.isNotPrivate = 'I know';
// add your stuff
}
var o = BaseClass.prototype;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';
// MiddleClass extends BaseClass
function MiddleClass(toBePrivate){
BaseClass.call(this);
// add your stuff
var morePrivates;
this.isNotPrivate = 'I know';
}
var o = MiddleClass.prototype = Object.create(BaseClass.prototype);
MiddleClass.prototype.constructor = MiddleClass;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';
// TopClass extends MiddleClass
function TopClass(toBePrivate){
MiddleClass.call(this);
// add your stuff
var morePrivates;
this.isNotPrivate = 'I know';
}
var o = TopClass.prototype = Object.create(MiddleClass.prototype);
TopClass.prototype.constructor = TopClass;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';
// to be continued...
Create "instance" with getter and setter:
function doNotExtendMe(toBePrivate){
var morePrivates;
return {
// add getters, setters and any stuff you want
}
}
If you want to see what you you have inside an object in your web app, then use the json pipe in a component HTML template, for example:
<li *ngFor="let obj of myArray">{{obj | json}}</li>
Tested and valid using Angular 4.3.2.
The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes()
call directly or create a vector for that instead.
This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.
level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses
ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()
or
level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))
ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()
or
directly in the aes()
call without a pre-created vector:
ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()
As also noted by John Szakmeister and VasiliNovikov, the shortest command to get the full diff from master's perspective on your branch is:
git diff master...
This uses your local copy of master.
To compare a specific file use:
git diff master... filepath
Output example:
Another possible solution: create an object containing the group names and indexes.
var regex = new RegExp("(.*) (.*)");
var regexGroups = { FirstName: 1, LastName: 2 };
Then, use the object keys to reference the groups:
var m = regex.exec("John Smith");
var f = m[regexGroups.FirstName];
This improves the readability/quality of the code using the results of the regex, but not the readability of the regex itself.
Try this...
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
It's like this:
$('.tag.clickedTag').click(function (){
// this will catch with two classes
}
$('.tag.clickedTag.otherclass').click(function (){
// this will catch with three classes
}
$('.tag:not(.clickedTag)').click(function (){
// this will catch tag without clickedTag
}
No one has mentioned using negative inset
values for legend
. Here is an example, where the legend is to the right of the plot, aligned to the top (using keyword "topright"
).
# Random data to plot:
A <- data.frame(x=rnorm(100, 20, 2), y=rnorm(100, 20, 2))
B <- data.frame(x=rnorm(100, 21, 1), y=rnorm(100, 21, 1))
# Add extra space to right of plot area; change clipping to figure
par(mar=c(5.1, 4.1, 4.1, 8.1), xpd=TRUE)
# Plot both groups
plot(y ~ x, A, ylim=range(c(A$y, B$y)), xlim=range(c(A$x, B$x)), pch=1,
main="Scatter plot of two groups")
points(y ~ x, B, pch=3)
# Add legend to top right, outside plot region
legend("topright", inset=c(-0.2,0), legend=c("A","B"), pch=c(1,3), title="Group")
The first value of inset=c(-0.2,0)
might need adjusting based on the width of the legend.
I am beginning Angular and in my case, the issue was that I hadn't saved the file after adding the 'import' statement.