The only problem with threads is accessing the same object from different threads without synchronization.
If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.
I got this error when I made the bonehead mistake of importing MatSnackBar
instead of MatSnackBarModule
in app.module.ts
.
If you see this immediately after adding a new Vendor class, be sure to run the VScode command (control-shift-P) Index Workspace
I was having this problem after I installed the dotnet-ef tool using Ansible with sudo escalated previllage on Ubuntu. I had to add become: no for the Playbook task, then the dotnet-ef tool became available to the current user.
- name: install dotnet tool dotnet-ef
command: dotnet tool install --global dotnet-ef --version {{dotnetef_version}}
become: no
As mentioned in Scott Kuhl's answer this issue is mentioned in https://github.com/madskristensen/WebCompiler/issues/413
For me, running the command npm i caniuse-lite- browserslist
only worked for about 1/2 a day before it was an issue again.
The following solution, mentioned in the post, works much better. This updates the node.js file so that it uses console.log
instead of console.warn
when returning these errors.
You can manually update this file located at C:\Users\[Username]\AppData\Local\Temp\WebCompiler[VersionNumber]\node_modules\browserslist
Or, so that it is done automatically, add the following to your .csproj file by:
</Project>
end tag and before the build web compiler package was imported. <ItemGroup>
<PackageReference Include="MSBuildTasks" Version="1.5.0.235">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
<PropertyGroup>
<TempFolder>$([System.IO.Path]::GetTempPath())</TempFolder>
</PropertyGroup>
<ItemGroup>
<BrowsersListNodeJsFiles Include="$(TempFolder)\WebCompiler*\node_modules\browserslist\node.js" />
</ItemGroup>
<Target Name="BrowsersListWarningsAsInfo" BeforeTargets="WebCompile">
<FileUpdate Files="@(BrowsersListNodeJsFiles)"
Regex="console.warn"
ReplacementText="console.log" />
</Target>
Steps:
Try to install angular-devkit for building angular projects
npm install --save-dev @angular-devkit/build-angular
In my case, the issue is, because of missing dependencies. The dependencies are missing, because I've forgotten to call:
npm install
After calling the above command, all required dependencies are loaded in node_modules
, and that is no more issue
The best and most effective solution is just adding theme in your main class and add input decoration like these.
theme: ThemeData(
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.pink)
)
),
)
Spring Boot 2.0.*
or aboveIf you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary
, because various auto-configurations down the road expect to be able to get one by type.
If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:
@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
return firstDataSourceProperties().initializeDataSourceBuilder().build();
}
@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
return DataSourceBuilder.create().type(BasicDataSource.class).build();
}
firstDataSourceProperties
has to be flagged as@Primary
so that the database initializer feature uses your copy (if you use the initializer).
And your application.propoerties
will look something like this:
app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver
app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver
The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.
In my case, I was using a service in a sub module (NOT the root AppModule), and the HttpClientModule was imported only in the module.
So I have to modify the default scope of the service, by changing 'providedIn' to 'any' in the @Injectable decorator.
By default, if you using angular-cli to generate the service, the 'providedIn' was set to 'root'.
Hope this helps.
I also had the same issue though am using MacOS. The issue is kind of bug. I solved this issue by repeatedly running the commands,
sudo npm cache clean --force
sudo npm uninstall
sudo npm install
One time it did not work but when I repeatedly cleaned the cache and after uninstalling npm, reinstalling npm, the error went off. I am using Angular 8 and this issue is common
in ubuntu or windows
Remove the ; from ;extension=pdo_mysql or extension=php_pdo_mysql.dll and add extension=pdo_mysql.so
restart xampp or wampp
install sudo apt-get install php-mysql
and
php artisan migrate
This reply may be late but it may help users having similar problem. The opencv-contrib (available at https://github.com/opencv/opencv_contrib/releases) contains extra modules but the build procedure has to be done from core opencv (available at from https://github.com/opencv/opencv/releases) modules.
Follow below steps (assuming you are building it using CMake GUI)
Download openCV (from https://github.com/opencv/opencv/releases) and unzip it somewhere on your computer. Create build folder inside it
Download exra modules from OpenCV. (from https://github.com/opencv/opencv_contrib/releases). Ensure you download the same version.
Unzip the folder.
Open CMake
Click Browse Source and navigate to your openCV folder.
Click Browse Build and navigate to your build Folder.
Click the configure button. You will be asked how you would like to generate the files. Choose Unix-Makefile from the drop down menu and Click OK. CMake will perform some tests and return a set of red boxes appear in the CMake Window.
Search for "OPENCV_EXTRA_MODULES_PATH" and provide the path to modules folder (e.g. /Users/purushottam_d/Programs/OpenCV3_4_5_contrib/modules)
Click Configure again, then Click Generate.
Go to build folder
# cd build
# make
# sudo make install
The answer has been given by Faisal Khurshid and Michael_B already.
This is just an attempt to make a possible solution more obvious.
For IE11 and below you need to enable grid's older specification in the parent div e.g. body or like here "grid" like so:
.grid-parent{display:-ms-grid;}
then define the amount and width of the columns and rows like e.g. so:
.grid-parent{
-ms-grid-columns: 1fr 3fr;
-ms-grid-rows: 4fr;
}
finally you need to explicitly tell the browser where your element (item) should be placed in e.g. like so:
.grid-item-1{
-ms-grid-column: 1;
-ms-grid-row: 1;
}
.grid-item-2{
-ms-grid-column: 2;
-ms-grid-row: 1;
}
{% url namespace:url_name %}
. So, check if you have added the app_name
in urls.py.path('<int:question_id>/', views.detail, name='question_detail')
whereas the index.html file had the following entry <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
. Notice the incorrect name.In case of springboot app on tomcat, I needed to create an additional class as below and this worked:
@SpringBootApplication
public class SpringBootTomcatApplication extends SpringBootServletInitializer {
}
I am also facing the same issue and i resolve it by putting web.xml file and the applicationcontext.xml file in WEB-INF folder.
Hope this helps :)
first install fontawsome using npm
npm install --save @fortawesome/fontawesome-free
add to resources\sass\app.scss
// Fonts
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
and add to resources\js\app.js
require('@fortawesome/fontawesome-free/js/all.js');
then run
npm run dev
or
npm run production
I moved the tsconfig.json
file into a new folder to restructure my project.
So it wasn't able to resolve the path to node_modules/@types folder inside typeRoots
property of tsconfig.json
So just update the path from
"typeRoots": [
"../node_modules/@types"
]
to
"typeRoots": [
"../../node_modules/@types"
]
To just ensure that the path to node_modules is resolved from the new location of the tsconfig.json
I solved this issue by removing empty string from my resolve array. Check out resolve documentation on webpack's site.
//Doesn't work
module.exports = {
resolve: {
extensions: ['', '.js', '.jsx']
}
...
};
//Works!
module.exports = {
resolve: {
extensions: ['.js', '.jsx']
}
...
};
I got it done by only encoding the output using utf-8. Here is the code example
new_tweets = api.GetUserTimeline(screen_name = user,count=200)
result = new_tweets[0]
try: text = result.text
except: text = ''
with open(file_name, 'a', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(text)
i.e: do not encode when collecting data from api, encode the output (print or write) only.
conda activate myEnv
conda list --explicit > myEnvBkp.txt
conda create --name myEnvRestored --file myEnvBkp.txt
Heres a more generic implementation:
This technique still uses index
to keep with Swift's standards, and imply a full Character.
extension String
{
func subString <R> (_ range: R) -> String? where R : RangeExpression, String.Index == R.Bound
{
return String(self[range])
}
func index(at: Int) -> Index
{
return self.index(self.startIndex, offsetBy: at)
}
}
To sub string from the 3rd character:
let item = "Fred looks funny"
item.subString(item.index(at: 2)...) // "ed looks funny"
I've used camel subString
to indicate it returns a String
and not a Substring
.
Create a UITextView inside of a tableViewController. I used function: textViewDidChange and then checked for return-key-input. then if it detected return-key-input, delete the input of return key and dismiss keyboard.
func textViewDidChange(_ textView: UITextView) {
tableView.beginUpdates()
if textView.text.contains("\n"){
textView.text.remove(at: textView.text.index(before: textView.text.endIndex))
textView.resignFirstResponder()
}
tableView.endUpdates()
}
Sometimes this error comes because it's simply the wrong folder. :-(
It shall be the folder which contains the pom.xml
.
For me, upgrading eslint-plugin-react to the latest version 7.21.5 fixed this
In my case just changing the permissions of anaconda folder worked:
sudo chmod -R u=rwx,g=rx,o=rx /path/to/anaconda
If your goal is only to take the files and not the folder, the approach I made was to use the file size
as a filter. This property is the current size of the file hosted by AWS. All the folders return 0 in that property.
The following is a C# code using linq but it shouldn't be hard to translate to Java.
var amazonClient = new AmazonS3Client(key, secretKey, region);
var listObjectsRequest= new ListObjectsRequest
{
BucketName = 'someBucketName',
Delimiter = 'someDelimiter',
Prefix = 'somePrefix'
};
var objects = amazonClient.ListObjects(listObjectsRequest);
var objectsInFolder = objects.S3Objects.Where(file => file.Size > 0).ToList();
You can just "call" your model with an array of the correct shape:
model(np.array([[6.7, 3.3, 5.7, 2.5]]))
Full example:
from sklearn.datasets import load_iris
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import numpy as np
X, y = load_iris(return_X_y=True)
model = Sequential([
Dense(16, activation='relu'),
Dense(32, activation='relu'),
Dense(1)])
model.compile(loss='mean_absolute_error', optimizer='adam')
history = model.fit(X, y, epochs=10, verbose=0)
print(model(np.array([[6.7, 3.3, 5.7, 2.5]])))
<tf.Tensor: shape=(1, 1), dtype=float64, numpy=array([[1.92517677]])>
Your test requires a ServletContext: add @WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT
...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
UPDATE
In Spring Boot 1.4.x and above @WebIntegrationTest
is no longer preferred. @SpringBootTest
or @WebMvcTest
If you are using ubantu then try to run MVN with sudo. I got same error for
mvn -Dtest=PerfLatency#latencyTest test -X
But
sudo mvn -Dtest=PerfLatency#latencyTest test -X
Solved my problem
You could use componentDidMount and componentWillUnmount methods:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class MovieItem extends Component
{
_handleNVEvent = event => {
...
};
componentDidMount() {
ReactDOM.findDOMNode(this).addEventListener('nv-event', this._handleNVEvent);
}
componentWillUnmount() {
ReactDOM.findDOMNode(this).removeEventListener('nv-event', this._handleNVEvent);
}
[...]
}
export default MovieItem;
The problem is already in the language:
the idea to differentiate the output based on limited placeholder like '[name]' defines limitations.
I like the core functionality of webpack, but the usage requires a rewrite with abstract definitions which are based on logic and simplicity... the hardest thing in software-development... logic and simplicity.
All this could be solved by just providing a list of input/output definitions... A LIST INPUT/OUTPUT DEFINITIONS.
Although this comment doesn't help much but we can learn from our mistakes by pointing at them.
Vinod Kumar: Good workaround, its:
module.exports = {
plugins: [
new FileManagerPlugin({
events: {
onEnd: {
copy: [
{source: 'www', destination: './vinod test 1/'},
{source: 'www', destination: './vinod testing 2/'},
{source: 'www', destination: './vinod testing 3/'},
],
},
}
}),
],
};
BTW. this is my first comment on stackoverflow (after 10 years as a programmer) and stackoverflow sucks in usability, like why is there so much text everywhere ? my eyes are bleeding.
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);
Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});
It will depend of your php version. Check it running:
php -version
Now, according to your current version, run:
sudo apt-get install php7.2-mysql
Upgrade your Gradle Plugin
classpath 'com.android.tools.build:gradle:3.2.1'
If you are now getting this error:
Could not find com.android.tools.build:gradle:3.2.1.
just add google() to your repositories, like this:
repositories {
google()
jcenter()
}
Happy Coding -:)
I had this issue after moving my home folder to a new drive on linux. It was fixed by removing .nvm folder and reinstalling nvm
I solved the problem by changing windows user access for the project folder:
Here is a screenshot: http://prntscr.com/djdn0g
A bit late to the party but I decided to create my own one after looking at @Alex Macmillan answers and that was by passing two extra parameters; the position in which to place the scripts such as or and setting up the async to true/false, here it is:
import { useEffect } from 'react';
const useScript = (url, position, async) => {
useEffect(() => {
const placement = document.querySelector(position);
const script = document.createElement('script');
script.src = url;
script.async = typeof async === 'undefined' ? true : async;
placement.appendChild(script);
return () => {
placement.removeChild(script);
};
}, [url]);
};
export default useScript;
The way to call it is exactly the same as shown in the accepted answer of this post but with two extra(again) parameters:
// First string is your URL
// Second string can be head or body
// Third parameter is true or false.
useScript("string", "string", bool);
The best and easiest method is to base64 encode the font file. And use it in font-face. For encoding, go to the folder having the font-file and use the command in terminal:
base64 Roboto.ttf > basecodedtext.txt
You will get an output file named basecodedtext.txt. Open that file. Remove any white spaces in that.
Copy that code and add the following line to the CSS file:
@font-face {
font-family: "font-name";
src: url(data:application/x-font-woff;charset=utf-8;base64,<<paste your code here>>) format('woff');
}
Then you can use the font-family: "font-name"
in your CSS.
You don't need JSON loader. Node provides ECMAScript Modules (ES6 Module support) with the --experimental-modules
flag, you can use it like this
node --experimental-modules myfile.mjs
Then it's very simple
import myJSON from './myJsonFile.json';
console.log(myJSON);
Then you'll have it bound to the variable myJSON
.
Seems your resource POST
method won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).
Since in you already add Access-Control-Allow-Origin
headers to your Response, you can add new OPTIONS
method to your resource class.
@OPTIONS
@Path("{path : .*}")
public Response options() {
return Response.ok("")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "2000")
.build();
}
As the other answers have described, lit
and typedLit
are how to add constant columns to DataFrames. lit
is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.
You'll commonly be using lit
to create org.apache.spark.sql.Column
objects because that's the column type required by most of the org.apache.spark.sql.functions
.
Suppose you have a DataFrame with a some_date
DateType column and would like to add a column with the days between December 31, 2020 and some_date
.
Here's your DataFrame:
+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+
Here's how to calculate the days till the year end:
val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
.withColumn("days_till_yearend", diff)
.show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23| 99|
|2020-01-05| 361|
|2020-04-12| 263|
+----------+-----------------+
You could also use lit
to create a year_end
column and compute the days_till_yearend
like so:
import java.sql.Date
df
.withColumn("yearend", lit(Date.valueOf("2020-12-31")))
.withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
.show()
+----------+----------+-----------------+
| some_date| yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31| 99|
|2020-01-05|2020-12-31| 361|
|2020-04-12|2020-12-31| 263|
+----------+----------+-----------------+
Most of the time, you don't need to use lit
to append a constant column to a DataFrame. You just need to use lit
to convert a Scala type to a org.apache.spark.sql.Column
object because that's what's required by the function.
See the datediff
function signature:
As you can see, datediff
requires two Column arguments.
I had the same its because of version incompatibility check for version or remove version if using spring boot
Eugene's answer uses the correct function to get the data, but for posterity I'd like to spell out exactly how to use it in React v0.14+ (according to this answer):
import ReactDOM from 'react-dom';
//...
componentDidMount() {
var rect = ReactDOM.findDOMNode(this)
.getBoundingClientRect()
}
Is working for me perfectly, and I'm using the data to scroll to the top of the new component that just mounted.
I tried 2 solutions, both work.
Solution_1
.yml
available-users-list:
configurations:
-
username: eXvn817zDinHun2QLQ==
password: IP2qP+BQfWKJMVeY7Q==
-
username: uwJlOl/jP6/fZLMm0w==
password: IP2qP+BQKJLIMVeY7Q==
LoginInfos.java
@ConfigurationProperties(prefix = "available-users-list")
@Configuration
@Component
@Data
public class LoginInfos {
private List<LoginInfo> configurations;
@Data
public static class LoginInfo {
private String username;
private String password;
}
}
List<LoginInfos.LoginInfo> list = loginInfos.getConfigurations();
Solution_2
.yml
available-users-list: '[{"username":"eXvn817zHBVn2QLQ==","password":"IfWKJLIMVeY7Q=="}, {"username":"uwJlOl/g9jP6/0w==","password":"IP2qWKJLIMVeY7Q=="}]'
Java
@Value("${available-users-listt}")
String testList;
ObjectMapper mapper = new ObjectMapper();
LoginInfos.LoginInfo[] array = mapper.readValue(testList, LoginInfos.LoginInfo[].class);
The important part is this:
Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml];
due to:
nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
According to this log, Spring could not find your MemberPointSummaryDAOImpl
class.
I had the same error code when I used @Transaction
on a wrong method/actionlevel.
methodWithANumberOfDatabaseActions() {
methodA( ...)
methodA( ...)
}
@Transactional
void methodA( ...) {
... ERROR message
}
I had to place the @Transactional
just above the method methodWithANumberOfDatabaseActions()
, of course.
That solved the error message in my case.
It May be due to some exceptions like (Parsing NUMERIC to String or vise versa).
Please verify cell values either are null or do handle Exception and see.
Best, Shahid
setting aria-hidden to false and toggling it on element.show() worked for me.
e.g
<span aria-hidden="true">aria text</span>
$(span).attr('aria-hidden', 'false');
$(span).show();
and when hiding back
$(span).attr('aria-hidden', 'true');
$(span).hide();
Make sure pom.xml exist in the directory, when using the mvn spring-boot:run command. No need to add any thing in the pom.xml file.
You need to close the input element with a />
at the end.
<input id="icon_prefix" type="text" class="validate" />
When working with Docker Compose, you can use command: postgres -c option=value
in your docker-compose.yml
to configure Postgres.
For example, this makes Postgres log to a file:
command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs
Adapting Vojtech Vitek's answer, you can use
command: postgres -c config_file=/etc/postgresql.conf
to change the config file Postgres will use. You'd mount your custom config file with a volume:
volumes:
- ./customPostgresql.conf:/etc/postgresql.conf
Here's the docker-compose.yml
of my application, showing how to configure Postgres:
# Start the app using docker-compose pull && docker-compose up to make sure you have the latest image
version: '2.1'
services:
myApp:
image: registry.gitlab.com/bullbytes/myApp:latest
networks:
- myApp-network
db:
image: postgres:9.6.1
# Make Postgres log to a file.
# More on logging with Postgres: https://www.postgresql.org/docs/current/static/runtime-config-logging.html
command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs
environment:
# Provide the password via an environment variable. If the variable is unset or empty, use a default password
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-4WXUms893U6j4GE&Hvk3S*hqcqebFgo!vZi}
# If on a non-Linux OS, make sure you share the drive used here. Go to Docker's settings -> Shared Drives
volumes:
# Persist the data between container invocations
- postgresVolume:/var/lib/postgresql/data
- ./logs:/logs
networks:
myApp-network:
# Our application can communicate with the database using this hostname
aliases:
- postgresForMyApp
networks:
myApp-network:
driver: bridge
# Creates a named volume to persist our data. When on a non-Linux OS, the volume's data will be in the Docker VM
# (e.g., MobyLinuxVM) in /var/lib/docker/volumes/
volumes:
postgresVolume:
Note that when on Linux, the log directory on the host must have the right permissions. Otherwise you'll get the slightly misleading error
FATAL: could not open log file "/logs/postgresql-2017-02-04_115222.log": Permission denied
I say misleading, since the error message suggests that the directory in the container has the wrong permission, when in reality the directory on the host doesn't permit writing.
To fix this, I set the correct permissions on the host using
chgroup ./logs docker && chmod 770 ./logs
As other people have commented, because the return type of your method is String
Spring won't feel need to do anything with the result.
If you change your signature so that the return type is something that needs marshalling, that should help:
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Map<String, Object> bar() {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("test", "jsonRestExample");
return map;
}
In a local directory that contains the file ./docs/specs/openapi.yml
that you want to view, you can run the following to start a container and access the spec at http://127.0.0.1:8246
.
docker run -t -i -p 8246:8080 -e SWAGGER_JSON=/var/specs/openapi.yml -v $PWD/docs/specs:/var/specs swaggerapi/swagger-ui
I was having the same problem and everyone was talking about this is related to DNS configuration, which make sense, since your container maybe isn't knowing how to resolve the name of the domain where your database is.
I guess your can configure that at the moment you start your container, but I think it's better to config this once and for all.
I'm using Windows 10 and in this case docker's gui give us some facilities.
Just right click on docker's icon in the tray bar and select "Settings" item.
Then, on the Docker's window, select the "Network" section and change the DNS option from "Automatic" to "Fixed" and hit "Apply". Docker will restart itself after that. I putted the Google's DNS (8.8.8.8) and it worked fine to me.
Hope it helps.
const style1 = {
backgroundColor: "#2196F3",
}
const style2 = {
color: "white",
}
const someComponent = () => {
return <div style={{ ...style1, ...style2 }}>This has 2 separate styles</div>
}
Note the double curly brackets. The spread operator is your friend.
Check your ".env" file in the root folder. is it correct?
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
None of these worked for me when I deployed my website online on shared hosting, below is what I did that worked.
In the .env
file, I changed
DB_HOST=127.0.0.1
to
DB_HOST=localhost
and viola, it worked well as expected.
There is another cause for this type of problem what I would like to share, because I struggle in this problem for some time and I could't find any answer on SO.
In a repository like:
@Repository
public interface UserEntityDao extends CrudRepository<UserEntity, Long>{
}
If your entity UserEntity
does not have the @Entity
annotation on the class, you will have the same error.
This error is confusing for this case, because you focus on trying to resolve the problem about Spring not found the Repository but the problem is the entity. And if you came to this answer trying to test your Repository, this answer may help you.
Here is more functional example with some ES6 features:
'use strict';
const React = require('react');
function renderArticles(articles) {
if (articles.length > 0) {
return articles.map((article, index) => (
<Article key={index} article={article} />
));
}
else return [];
}
const Article = ({article}) => {
return (
<article key={article.id}>
<a href={article.link}>{article.title}</a>
<p>{article.description}</p>
</article>
);
};
const Articles = React.createClass({
render() {
const articles = renderArticles(this.props.articles);
return (
<section>
{ articles }
</section>
);
}
});
module.exports = Articles;
In my case, i faced the problem while creating table from phpmyadmin. For id column i choose the primary option from index dropdown and filled the size 10.
If you're using phpmyadmin, to solve this problem change the index dropdown option again, after reselecting the primary option again it'll ask you the size, leave it blank and you're done.
For me these steps worked
stop-all.sh
hadoop namenode -format
start-all.sh
You don't have to necessarily provide name and Qualifier. If you set a name, that's the name with which the bean is registered in the context. If you don't provide a name for your service it will be registered as uncapitalized non-qualified class name based on BeanNameGenerator
. So in your case the Implementation will be registered as employeeServiceImpl
. So if you try to autowire with that name, it should resolve directly.
private EmployeeService employeeServiceImpl;
@RequestMapping("/employee")
public String employee() {
this.employeeService.fetchAll();
return "employee";
}
@Autowired(required = true)
public void setEmployeeService(EmployeeService employeeServiceImpl) {
this.employeeServiceImpl = employeeServiceImpl;
}
@Qualifier
is used in case if there are more than one bean exists of same type and you want to autowire different implementation beans for various purposes.
@littleguy23 That is correct, but you don't want to do it to multi select. So just a small change to the code:
$(document).ready(function() {
// Select - Single
$('select:not([multiple])').material_select();
});
The /P
switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
Two ways I've used it... first:
SET /P variable=
When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.
And second:
SET /P variable=<%temp%\filename.txt
Will set variable to contents (the first line) of the txt file. This method won't work unless the /P
is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.
MySqlBDConfig.java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "mysqlEmFactory" ,transactionManagerRef = "mysqlTransactionManager")
public class MySqlBDConfig{
@Autowired
private Environment env;
@Bean(name="mysqlProperities")
@ConfigurationProperties(prefix="spring.mysql")
public DataSourceProperties mysqlProperities(){
return new DataSourceProperties();
}
@Bean(name="mysqlDataSource")
public DataSource interfaceDS(@Qualifier("mysqlProperities")DataSourceProperties dataSourceProperties){
return dataSourceProperties.initializeDataSourceBuilder().build();
}
@Primary
@Bean(name="mysqlEmFactory")
public LocalContainerEntityManagerFactoryBean mysqlEmFactory(@Qualifier("mysqlDataSource")DataSource mysqlDataSource,EntityManagerFactoryBuilder builder){
return builder.dataSource(mysqlDataSource).packages("PACKAGE OF YOUR MODELS").build();
}
@Bean(name="mysqlTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("mysqlEmFactory")EntityManagerFactory factory){
return new JpaTransactionManager(factory);
}
}
H2DBConfig.java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "dsEmFactory" ,transactionManagerRef = "dsTransactionManager")
public class H2DBConfig{
@Autowired
private Environment env;
@Bean(name="dsProperities")
@ConfigurationProperties(prefix="spring.h2")
public DataSourceProperties dsProperities(){
return new DataSourceProperties();
}
@Bean(name="dsDataSource")
public DataSource dsDataSource(@Qualifier("dsProperities")DataSourceProperties dataSourceProperties){
return dataSourceProperties.initializeDataSourceBuilder().build();
}
@Bean(name="dsEmFactory")
public LocalContainerEntityManagerFactoryBean dsEmFactory(@Qualifier("dsDataSource")DataSource dsDataSource,EntityManagerFactoryBuilder builder){
LocalContainerEntityManagerFactoryBean em = builder.dataSource(dsDataSource).packages("PACKAGE OF YOUR MODELS").build();
HibernateJpaVendorAdapter ven = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(ven);
HashMap<String, Object> prop = new HashMap<>();
prop.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
prop.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));
em.setJpaPropertyMap(prop);
em.afterPropertiesSet();
return em;
}
@Bean(name="dsTransactionManager")
public PlatformTransactionManager dsTransactionManager(@Qualifier("dsEmFactory")EntityManagerFactory factory){
return new JpaTransactionManager(factory);
}
}
application.properties
#---mysql DATASOURCE---
spring.mysql.driverClassName = com.mysql.jdbc.Driver
spring.mysql.url = jdbc:mysql://127.0.0.1:3306/test
spring.mysql.username = root
spring.mysql.password = root
#----------------------
#---H2 DATASOURCE----
spring.h2.driverClassName = org.h2.Driver
spring.h2.url = jdbc:h2:file:~/test
spring.h2.username = root
spring.h2.password = root
#---------------------------
#------JPA-----
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext ac=SpringApplication.run(KeopsSageInvoiceApplication.class, args);
UserMysqlDao userRepository = ac.getBean(UserMysqlDao.class)
//for exemple save a new user using your repository
userRepository.save(new UserMysql());
}
}
I had tried everything I could find on the net including the methods that have been given on this answer. After almost trying to solve the problem for whole day I have found the solution that have worked for me like a charm.
in the file WebApiConfig in folder App_Start, comment all the lines of code and add the following code:
`public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
var enableCorsAttribute = new EnableCorsAttribute("*",
"Origin, Content-Type, Accept",
"GET, PUT, POST, DELETE, OPTIONS");
config.EnableCors(enableCorsAttribute);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
//routeTemplate: "api/{controller}/{id}",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.Add(new BrowserJsonFormatter());
}
public class BrowserJsonFormatter : JsonMediaTypeFormatter
{
public BrowserJsonFormatter()
{
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
this.SerializerSettings.Formatting = Formatting.Indented;
}
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
base.SetDefaultContentHeaders(type, headers, mediaType);
headers.ContentType = new MediaTypeHeaderValue("application/json");
}
}`
On Java 9 or later, Map.entry
can be used, so long as you know that neither the key nor value will be null. If either value could legitimately be null, AbstractMap.SimpleEntry
(as suggested in another answer) or AbstractMap.SimpleImmutableEntry
would be the way to go.
private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
int subLength = prefix.length();
return input.entrySet().stream().map(e ->
Map.entry(e.getKey().substring(subLength), AttributeType.GetByName(e.getValue())));
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
This is discouraged (if you want to create/distribute a clean Docker image), since the PATH
variable is set by /etc/profile
script, the value can be overridden.
head /etc/profile
:
if [ "`id -u`" -eq 0 ]; then
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else
PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
fi
export PATH
At the end of the Dockerfile, you could add:
RUN echo "export PATH=$PATH" > /etc/environment
So PATH is set for all users.
Add a runtime first and select project properties. Then check the server name from the 'Runtimes' tab as shown in the image.
If you using java-based annotation you can do this:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
Where static folder
src
¦
+---main
+---java
+---resources
+---webapp
+---static
+---css
+---....
ymptom: After configuring Nexus to serve SSL maven builds fail with "peer not authenticated" or "PKIX path building failed".
This is usually caused by using a self signed SSL certificate on Nexus. Java does not consider these to be a valid certificates, and will not allow connecting to server's running them by default.
You have a few choices here to fix this:
For option 1 you can use the keytool command and follow the steps in the below article.
Explicitly Trusting a Self-Signed or Private Certificate in a Java Based Client
For option 3, invoke Maven with "-Dmaven.wagon.http.ssl.insecure=true". If the host name configured in the certificate doesn't match the host name Nexus is running on you may also need to add "-Dmaven.wagon.http.ssl.allowall=true".
Note: These additional parameters are initialized in static initializers, so they have to be passed in via the MAVEN_OPTS environment variable. Passing them on the command line to Maven will not work.
See here for more information:
Maybe you should reset frame of the button, I had some problem too, and nslog the view of keyboard like this:
ios8:
"<UIInputSetContainerView: 0x7fef0364b0d0; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0x7fef0364b1e0>>"
before8:
"<UIPeripheralHostView: 0x11393c860; frame = (0 352; 320 216); autoresizesSubviews = NO; layer = <CALayer: 0x11393ca10>>"
Using @PersistenceContext with @Modifying as below fixes error while using createNativeQuery
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
@PersistenceContext
private EntityManager entityManager;
@Override
@Transactional
@Modifying
public <S extends T> S save(S entity) {
Query q = entityManager.createNativeQuery(...);
q.setParameter...
q.executeUpdate();
return entity;
}
Simplest solution would be -
$('.selectpicker').trigger('change');
I had the same error on PHP 7.3.7 docker with laravel:
This works for me
apt-get update && apt-get install -y libpq-dev && docker-php-ext-install pdo pgsql pdo_pgsql
This will install the pgsql and pdo_pgsql drivers.
Now run this command to uncomment the lines extension=pdo_pgsql.so and extension=pgsql.so from php.ini
sed -ri -e 's!;extension=pdo_pgsql!extension=pdo_pgsql!' $PHP_INI_DIR/php.ini
sed -ri -e 's!;extension=pgsql!extension=pgsql!' $PHP_INI_DIR/php.ini
Use apt to uninstall and remove all MySQL packages:
$ sudo apt-get remove --purge mysql-server mysql-client mysql-common -y
$ sudo apt-get autoremove -y
$ sudo apt-get autoclean
Remove the MySQL folder:
$ rm -rf /etc/mysql
Delete all MySQL files on your server:
$ sudo find / -iname 'mysql*' -exec rm -rf {} \;
Your system should no longer contain default MySQL related files.
Maybe this would be useful
-webkit-justify-content: space-around;
In my case I removed the server logon credentials for central from my setting.
<server>
<id>central</id>
<username>admin</username>
<password>******</password>
</server>
<mirror>
<id>central</id>
<mirrorOf>central</mirrorOf>
<name>maven-central</name>
<url>http://www.localhost:8081/repository/maven-central/</url>
</mirror>
I don't know why I did that, but its completely wrong since the central maven repo can be accessed anonymously. See my debug output that led to my error identification and resolution.
[DEBUG] Using connector BasicRepositoryConnector with priority 0.0 for http://www.localhost:8081/repository/maven-central/ with username=admin, password=***
Try nvm alias default
. For example:
$ nvm alias default 0.12.7
This sets the default node version in your shell. Then verify that the change persists by closing the shell window, opening a new one, then:
node --version
In swift 3 use:
let url = URL(string: "Whatever url you have(eg: https://google.com)")
I'll show you with a pic!
Add a new File
Go to Project/Build Setting/APPl LLVM 6.0-Language
You have to clear the cache like that (because your old configuration is in you cache file) :
php artisan cache:clear
The pdo error comes from the fact Laravel use the pdo driver to connect to mysql
To rename files, you can use the rename
utility:
brew install rename
For example, to change a search string in all filenames in current directory:
rename -nvs searchword replaceword *
Remove the 'n' parameter to apply the changes.
More info: man rename
example given below
protocol NameOfProtocol: class {
// member of protocol
}
class ClassName: UIViewController {
weak var delegate: NameOfProtocol?
}
For those of you who are using pipenv and want to install specific version:
pipenv install --python 3.6
Exception clearly indicates the problem.
CompteDAOHib: No default constructor found
For spring to instantiate your bean, you need to provide a empty constructor for your class CompteDAOHib
.
The res.render stuff will throw an error if you're not using a view engine.
If you just want to serve json replace the res.render('error', { error: err });
lines in your code with:
res.json({ error: err })
PS: People usually also have message in the returned object:
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
The other answers have pointed out the solution for the majority of cases involving PropertySources
, but none have mentioned that certain property sources are unable to be casted into useful types.
One such example is the property source for command line arguments. The class that is used is SimpleCommandLinePropertySource
. This private class is returned by a public method, thus making it extremely tricky to access the data inside the object. I had to use reflection in order to read the data and eventually replace the property source.
If anyone out there has a better solution, I would really like to see it; however, this is the only hack I have gotten to work.
And if you are using typescript (gulpfile.ts
) then do this for yargs
(building on @Caio Cunha's excellent answer https://stackoverflow.com/a/23038290/1019307 and other comments above):
npm install --save-dev yargs
typings install dt~yargs --global --save
.ts
filesAdd this to the .ts files:
import { argv } from 'yargs';
...
let debug: boolean = argv.debug;
This has to be done in each .ts file individually (even the tools/tasks/project
files that are imported into the gulpfile.ts/js
).
gulp build.dev --debug
Or under npm
pass the arg through to gulp:
npm run build.dev -- --debug
The following worked for me, nothing else -:
SET GLOBAL innodb_log_buffer_size = 80*1024*1024*1024;
and
SET GLOBAL innodb_strict_mode = 0;
Hope this helps someone because it wasted couple of days of my time as I was trying to do this in my.cnf with no joy.
I installed php-soap to CentOS Linux release 7.1.1503 (Core) using following way.
1) yum install php-soap
================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
php-soap x86_64 5.4.16-36.el7_1 base 157 k
Updating for dependencies:
php x86_64 5.4.16-36.el7_1 base 1.4 M
php-cli x86_64 5.4.16-36.el7_1 base 2.7 M
php-common x86_64 5.4.16-36.el7_1 base 563 k
php-devel x86_64 5.4.16-36.el7_1 base 600 k
php-gd x86_64 5.4.16-36.el7_1 base 126 k
php-mbstring x86_64 5.4.16-36.el7_1 base 503 k
php-mysql x86_64 5.4.16-36.el7_1 base 99 k
php-pdo x86_64 5.4.16-36.el7_1 base 97 k
php-xml x86_64 5.4.16-36.el7_1 base 124 k
Transaction Summary
================================================================================
Install 1 Package
Upgrade ( 9 Dependent packages)
Total download size: 6.3 M
Is this ok [y/d/N]: y
Downloading packages:
------
------
------
Installed:
php-soap.x86_64 0:5.4.16-36.el7_1
Dependency Updated:
php.x86_64 0:5.4.16-36.el7_1 php-cli.x86_64 0:5.4.16-36.el7_1
php-common.x86_64 0:5.4.16-36.el7_1 php-devel.x86_64 0:5.4.16-36.el7_1
php-gd.x86_64 0:5.4.16-36.el7_1 php-mbstring.x86_64 0:5.4.16-36.el7_1
php-mysql.x86_64 0:5.4.16-36.el7_1 php-pdo.x86_64 0:5.4.16-36.el7_1
php-xml.x86_64 0:5.4.16-36.el7_1
Complete!
2) yum search php-soap
============================ N/S matched: php-soap =============================
php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
3) service httpd restart
To verify run following
4) php -m | grep -i soap
soap
For those who use Tomcat with Bitronix, this will fix the problem:
The error indicates that no handler could be found for your datasource 'jdbc/mydb', so you'll need to make sure your tomcat server refers to your bitronix configuration files as needed.
In case you're using btm-config.properties and resources.properties files to configure the datasource, specify these two JVM arguments in tomcat:
(if you already used them, make sure your references are correct):
e.g.
-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59"
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties"
Now, restart your server and check the log.
Xampp
I guess you're using MySQL
.
mysql_fetch_array($result);
And make sure $result
is not empty.
You are missing a PDO driver.
First install the driver
For ubuntu: For mysql database.
sudo apt-get install php5.6-mysql/php7.2-mysql
You also can search for other database systems.
You also can search for the driver:
sudo apt-cache search drivername
Then Run the cmd php artisan migrate
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
You probably have seen the tilde (~) and caret (^) in the package.json. What is the difference between them?
When you do npm install moment --save, It saves the entry in the package.json with the caret (^) prefix.
In the simplest terms, the tilde (~) matches the most recent minor version (the middle number). ~1.2.3 will match all 1.2.x versions but will miss 1.3.0.
The caret (^), on the other hand, is more relaxed. It will update you to the most recent major version (the first number). ^1.2.3 will match any 1.x.x release including 1.3.0, but will hold off on 2.0.0.
Reference: https://medium.com/@Hardy2151/caret-and-tilde-in-package-json-57f1cbbe347b
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.
For Postgres:
SELECT column
FROM table
WHERE char_length(column) = (SELECT max(char_length(column)) FROM table )
This will give you the string itself,modified for postgres from @Thorsten Kettner answer
if it is IIS 8 go to control panel, turn windows features on/off and enable Bad "Named pipe activation" then restart IIS. Hope the same works with IIS 7
Based on @ofer.sheffer answer this command will mass rename and append the current date to the filename. ie "file.txt" becomes "20180329 - file.txt" for all files in the current folder
for %a in (*.*) do ren "%a" "%date:~-4,4%%date:~-7,2%%date:~-10,2% - %a"
For structuring an app, this is one of the best guides that I've found:
Note that the structure recommended by Google is different than what you'll find in a lot of seed projects, but for large apps it's a lot saner.
Google also has a style guide that makes sense to use only if you also use Closure.
...this answer is incomplete, but I hope that the limited information above will be helpful to someone.
another example with just scriplets, when iterating through an ArrayList that contains Maps.
<%
java.util.List<java.util.Map<String,String>> employees=(java.util.List<java.util.Map<String, String>>)request.getAttribute("employees");
for (java.util.Map employee: employees) {
%>
<tr>
<td><input value="<%=employee.get("fullName") %>"/></td>
</tr>
...
<%}%>
When you generate a JAXB model from an XML Schema, global elements that correspond to named complex types will have that metadata captured as an @XmlElementDecl
annotation on a create method in the ObjectFactory
class. Since you are creating the JAXBContext
on just the DocumentType
class this metadata isn't being processed. If you generated your JAXB model from an XML Schema then you should create the JAXBContext
on the generated package name or ObjectFactory
class to ensure all the necessary metadata is processed.
Example solution:
JAXBContext jaxbContext = JAXBContext.newInstance(my.generatedschema.dir.ObjectFactory.class);
DocumentType documentType = ((JAXBElement<DocumentType>) jaxbContext.createUnmarshaller().unmarshal(inputStream)).getValue();
<div className='btn' onClick={(e) =>
console.log(e.currentTarget.attributes['tag'].value)}
tag='bold'>
<i className='fa fa-bold' />
</div>
so e.currentTarget.attributes['tag'].value
works for me
I had this happen because my tests were not in the same package as my components. (I had renamed my component package, but not my test package.) And I was using @ComponentScan
in my test @Configuration
class, so my tests weren't finding the components on which they relied.
So, double check that if you get this error.
If you load you table file with dtype=str
or convert column type to string df['a'] = df['a'].astype(str)
then you can use such approach:
df['a']= 'col' + df['a'].str[:]
This approach allows prepend, append, and subset string of df
.
Works on Pandas v0.23.4, v0.24.1. Don't know about earlier versions.
I ran into this when trying to run spring boot from the command line...
mvn spring-boot:run
I accidentally mis-typed the command as...
mvn spring-boot run
So it was looking for the commands... run, build etc...
Issue :
configure: error: no acceptable C compiler found in $PATH
Fixed the issue by executing the following command:
yum install gcc
to install gcc.
Two main reasons:
1) mysql-server isn't installed! You have to install it (mysql-server and not mysql-client) and run it.
2) It's installed by default and running. So, it's not possible to run it again through Xampp or Lampp. You have to stop it: sudo service mysql stop
then you can start it through Xampp. It's possible to check if it's running or not with this code: sudo netstat -tap | grep mysql
If you see a result like this: tcp 0 0 localhost:mysql : LISTEN 1043/mysqld
It means that it's running properly.
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
I had this issue while using Python installed with sudo make altinstall
on Opensuse linux. It seems that the compiled libraries are installed in /usr/local/lib64
but Python is looking for them in /usr/local/lib
.
I solved it by creating a dynamic link to the relevant directory in /usr/local/lib
sudo ln -s /usr/local/lib64/python3.8/lib-dynload/ /usr/local/lib/python3.8/lib-dynload
I suspect the better thing to do would be to specify libdir
as an argument to configure
(at the start of the build process) but I haven't tested it that way.
The class format of JDK8 has changed and thats the reason why Tomcat is not able to compile JSPs. Try to get a newer version of Tomcat.
I recently had the same problem. This is a bug in Tomcat, or rather, JDK 8 has a slightly different class file format than what prior-JDK8 versions had. This causes inconsistency and Tomcat is not able to compile JSPs in JDK8.
See following references:
You may use clang as well. It used to be faster than GCC, and now it is quite a stable thing. It is much easier to build clang from sources (you can really drink cup of coffee during build process).
In short:
Compile your code:
path/to/clang --target=arm-linux-gnueabihf --sysroot=/some/path/arm-linux-gnueabihf/sysroot my-happy-program.c -fuse-ld=lld
Optionally you may use legacy arm-linux-gnueabihf binutils. Then you may remove "-fuse-ld=lld" flag at the end.
Below is my cmake toolchain file.
toolchain.cmake
set(CMAKE_SYSTEM_VERSION 1)
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
# Custom toolchain-specific definitions for your project
set(PLATFORM_ARM "1")
set(PLATFORM_COMPILE_DEFS "COMPILE_GLES")
# There we go!
# Below, we specify toolchain itself!
set(TARGET_TRIPLE arm-linux-gnueabihf)
# Specify your target rootfs mount point on your compiler host machine
set(TARGET_ROOTFS /Volumes/rootfs-${TARGET_TRIPLE})
# Specify clang paths
set(LLVM_DIR /Users/stepan/projects/shared/toolchains/llvm-7.0.darwin-release-x86_64/install)
set(CLANG ${LLVM_DIR}/bin/clang)
set(CLANGXX ${LLVM_DIR}/bin/clang++)
# Specify compiler (which is clang)
set(CMAKE_C_COMPILER ${CLANG})
set(CMAKE_CXX_COMPILER ${CLANGXX})
# Specify binutils
set (CMAKE_AR "${LLVM_DIR}/bin/llvm-ar" CACHE FILEPATH "Archiver")
set (CMAKE_LINKER "${LLVM_DIR}/bin/llvm-ld" CACHE FILEPATH "Linker")
set (CMAKE_NM "${LLVM_DIR}/bin/llvm-nm" CACHE FILEPATH "NM")
set (CMAKE_OBJDUMP "${LLVM_DIR}/bin/llvm-objdump" CACHE FILEPATH "Objdump")
set (CMAKE_RANLIB "${LLVM_DIR}/bin/llvm-ranlib" CACHE FILEPATH "ranlib")
# You may use legacy binutils though.
#set(BINUTILS /usr/local/Cellar/arm-linux-gnueabihf-binutils/2.31.1)
#set (CMAKE_AR "${BINUTILS}/bin/${TARGET_TRIPLE}-ar" CACHE FILEPATH "Archiver")
#set (CMAKE_LINKER "${BINUTILS}/bin/${TARGET_TRIPLE}-ld" CACHE FILEPATH "Linker")
#set (CMAKE_NM "${BINUTILS}/bin/${TARGET_TRIPLE}-nm" CACHE FILEPATH "NM")
#set (CMAKE_OBJDUMP "${BINUTILS}/bin/${TARGET_TRIPLE}-objdump" CACHE FILEPATH "Objdump")
#set (CMAKE_RANLIB "${BINUTILS}/bin/${TARGET_TRIPLE}-ranlib" CACHE FILEPATH "ranlib")
# Specify sysroot (almost same as rootfs)
set(CMAKE_SYSROOT ${TARGET_ROOTFS})
set(CMAKE_FIND_ROOT_PATH ${TARGET_ROOTFS})
# Specify lookup methods for cmake
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
# Sometimes you also need this:
# set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
# Specify raspberry triple
set(CROSS_FLAGS "--target=${TARGET_TRIPLE}")
# Specify other raspberry related flags
set(RASP_FLAGS "-D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS")
# Gather and distribute flags specified at prev steps.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CROSS_FLAGS} ${RASP_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CROSS_FLAGS} ${RASP_FLAGS}")
# Use clang linker. Why?
# Well, you may install custom arm-linux-gnueabihf binutils,
# but then, you also need to recompile clang, with customized triple;
# otherwise clang will try to use host 'ld' for linking,
# so... use clang linker.
set(CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} -fuse-ld=lld)
Import base.py in
__init__.py
alone. make sure you won't repeat the same configuration again!.set environment variable
SET DJANGO_DEVELOPMENT =dev
settings/
__init__.py
base.py
local.py
production.py
In
__init__.py
from .base import *
if os.environ.get('DJANGO_DEVELOPMENT')=='prod':
from .production import *
else:
from .local import *
In
base.py
configured the global configurations. except for Database. like
SECRET_KEY, ALLOWED_HOSTS,INSTALLED_APPS,MIDDLEWARE .. etc....
In
local.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'database',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
}
}
"The project works on the laptop, but now having copied the updated source code onto the desktop ..."
I did something similar, creating two versions of a project and copying files between them. It gave me the same error.
My solution was to go into the project file, where I discovered that what had looked like this:
<Compile Include="App_Code\Common\Pair.cs" />
<Compile Include="App_Code\Common\QueryCommand.cs" />
Now looked like this:
<Content Include="App_Code\Common\Pair.cs">
<SubType>Code</SubType>
</Content>
<Content Include="App_Code\Common\QueryCommand.cs">
<SubType>Code</SubType>
</Content>
When I changed them back, Visual Studio was happy again.
Whenever a TypeInitializationException
is thrown, check all initialization logic of the type you are referring to for the first time in the statement where the exception is thrown - in your case: Logger
.
Initialization logic includes: the type's static constructor (which - if I didn't miss it - you do not have for Logger
) and field initialization.
Field initialization is pretty much "uncritical" in Logger
except for the following lines:
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
s_commonAppData
is null
at the point where Path.Combine(s_commonAppData, "XXXX");
is called. As far as I'm concerned, these initializations happen in the exact order you wrote them - so put s_commonAppData
up by at least two lines ;)
Take a look at this article: CSS: User Agent Selectors
Basically, when you use this script:
var b = document.documentElement;
b.setAttribute('data-useragent', navigator.userAgent);
b.setAttribute('data-platform', navigator.platform );
b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');
You can now use CSS to target any browser / version.
So for IE11 we could do this:
html[data-useragent*='rv:11.0']
{
color: green;
}
For Thymeleaf:
I just began using spring 4 and thymeleaf, when I encountered this error it was resolved by adding:
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="order" value="0" />
</bean>
You might just have to install the packages.
yum install php-pdo php-mysqli
After they're installed, restart Apache.
httpd restart
or
apachectl restart
If you want to serve .html files, you must add this <mvc:default-servlet-handler />
in your spring config file. .html files are static.
Hope that this can help someone.
From what I know, the correct syntax is:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
document.getElementById(tabName).style.backgroundImage = "url('buttons/" + imagePrefix + ".png')";
}
So basically, getElementById(tabName).backgroundImage
and split the string like:
"cssInHere('and" + javascriptOutHere + "/cssAgain')";
Square brackets are meant for character class, and you're actually trying to match any one of: s
, |
, s
(again), e
, a
, s
(again), o
and n
.
Use parentheses instead for grouping:
(s|season)
or non-capturing group:
(?:s|season)
Note: Non-capture groups tell the engine that it doesn't need to store the match, while the other one (capturing group does). For small stuff, either works, for 'heavy duty' stuff, you might want to see first if you need the match or not. If you don't, better use the non-capture group to allocate more memory for calculation instead of storing something you will never need to use.
sample code:
<em><b>
<h2>Upload,Save and Download video </h2>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="video"/>
<input type="submit" name="submit" value="Upload"/></b>
</form></em>
<?php>
include("connect.php");
$errors=1;
//Targeting Folder
$target="videos/";
if(isset($_POST['submit'])){
//Targeting Folder
$target=$target.basename($_FILES['video']['name']);
//Getting Selected video Type
$type=pathinfo($target,PATHINFO_EXTENSION);
//Allow Certain File Format To Upload
if($type!='mp4' && $type!='3gp' && $type!='avi'){
echo "Only mp4,3gp,avi file format are allowed to Upload";
$errors=0;
}
//checking for Exsisting video Files
if(file_exists($target)){
echo "File Exist";
$errors=0;
}
$filesize=$_FILES['video']['size'];
if($filesize>250*2000000){
echo 'You Can not Upload Large File(more than 500MB) by Default ini setting..<a href="http://www.codenair.com/2018/03/how-to-upload-large-file-in-php.html">How to upload large file in php</a>';
$errors=0;
}
if($errors == 0){
echo ' Your File Not Uploaded';
}else{
//Moving The video file to Desired Directory
$uplaod_success=move_uploaded_file($_FILES['video']['tmp_name'],$target);
if($uplaod_success){
//Getting Selected video Information
$name=$_FILES['video']['name'];
$size=$_FILES['video']['size'];
$result=mysqli_query($con,"INSERT INTO VIdeos (name,size,type)VALUES('".$name."','".$size."','".$type."')");
if($result==TRUE){
echo "Your video '$name' Successfully Upload and Information Saved Our Database";
}
}
}
}
?>
My problem solved with these :
1- Add this to your head :
<base href="/" />
2- Use this in app.config
$locationProvider.html5Mode(true);
Sometime gcc had created as /usr/bin/gcc32
. so please create a ln -s /usr/bin/gcc32 /usr/bin/gcc
and then compile that ./configure
.
This might be possible that your view is present even though it shows the error. So to solve this issue you need to stop the server and run this command on the terminal.
php artisan config:cache
then restart the server
I added META-INF folder with context.xml contain
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/SpringGradleDemo"/>
SpringGradleDemo is my project name and it work. My servlet-mapping is "/" I read it here https://tomcat.apache.org/tomcat-5.5-doc/config/context.html
If you really need this you can achieve your goal with help of separate table for sequencing (if you don't mind) and a trigger.
Tables
CREATE TABLE table1_seq
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0', name VARCHAR(30)
);
Now the trigger
DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO table1_seq VALUES (NULL);
SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;
Then you just insert rows to table1
INSERT INTO Table1 (name)
VALUES ('Jhon'), ('Mark');
And you'll have
| ID | NAME | ------------------ | LHPL001 | Jhon | | LHPL002 | Mark |
Here is SQLFiddle demo
My problem was the lack of BindingResult
parameter after my model attribute.
@RequestMapping(method = RequestMethod.POST, value = "/sign-up", consumes = "application/x-www-form-urlencoded")
public ModelAndView registerUser(@Valid @ModelAttribute UserRegistrationInfo userRegistrationInfo
HttpServletRequest httpRequest,
HttpSession httpSession) { ... }
After I added BindingResult
my controller became
@RequestMapping(method = RequestMethod.POST, value = "/sign-up", consumes = "application/x-www-form-urlencoded")
public ModelAndView registerUser(@Valid @ModelAttribute UserRegistrationInfo userRegistrationInfo, BindingResult bindingResult,
HttpServletRequest httpRequest,
HttpSession httpSession) { ..}
Check answer @sashok_bg @sashko_bg Mersi mnogo
Try this one -
CREATE PROC [dbo].[getVoucherNo]
AS BEGIN
DECLARE
@Prefix VARCHAR(10) = 'J'
, @startFrom INT = 1
, @maxCode VARCHAR(100)
, @sCode INT
IF EXISTS(
SELECT 1
FROM dbo.Journal_Entry
) BEGIN
SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,ABS(LEN(Voucher_No)- LEN(@Prefix))) AS INT)) AS varchar(100))
FROM dbo.Journal_Entry;
SELECT @Prefix +
CAST(LEN(LEFT(@maxCode, 10) + 1) AS VARCHAR(10)) + -- !!! possible problem here
CAST(@maxCode AS VARCHAR(100))
END
ELSE BEGIN
SELECT (@Prefix + CAST(@startFrom AS VARCHAR))
END
END
Try http://www.sql-server-helper.com/tips/date-formats.aspx. Lists all formats needed. In this case select Convert(varchar(10),CONVERT(date,YourDateColumn,106),103) change 103 to 104 id you need dd.mm.yyyy
I wasn't using Azure, but I got the same error locally. Using <customErrors mode="Off" />
seemed to have no effect, but checking the Application logs in Event Viewer revealed a warning from ASP.NET which contained all the detail I needed to resolve the issue.
If you are like me and need to change color of text itself also while in the same time filling the background color check my solution.
Steps to create:
Good thing about this solution:
Not so good thing about this solution:
Check the pen ---> https://codepen.io/nikolamitic/pen/vpNoNq
<button class="btn btn--animation-from-right">
<span class="btn__text-static">Cover left</span>
<div class="btn__text-dynamic">
<span class="btn__text-dynamic-inner">Cover left</span>
</div>
</button>
.btn {
padding: 10px 20px;
position: relative;
border: 2px solid #222;
color: #fff;
background-color: #222;
position: relative;
overflow: hidden;
cursor: pointer;
text-transform: uppercase;
font-family: monospace;
letter-spacing: -1px;
[class^="btn__text"] {
font-size: 24px;
}
.btn__text-dynamic,
.btn__text-dynamic-inner {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
z-index: 2;
transition: all ease 0.5s;
}
.btn__text-dynamic {
background-color: #fff;
color: #222;
overflow: hidden;
}
&:hover {
.btn__text-dynamic {
transform: translateX(-100%);
}
.btn__text-dynamic-inner {
transform: translateX(100%);
}
}
}
.btn--animation-from-right {
&:hover {
.btn__text-dynamic {
transform: translateX(100%);
}
.btn__text-dynamic-inner {
transform: translateX(-100%);
}
}
}
You can remove .btn--animation-from-right modifier if you want to animate to the left.
I think you can use methods of the str
type to do this. There's no need for regular expressions:
def remove_prefix(text, prefix):
if text.startswith(prefix): # only modify the text if it starts with the prefix
text = text.replace(prefix, "", 1) # remove one instance of prefix
return text
I'm using SourceTree along with TortoiseMerge/Diff, which is very easy and convinient diff/merge tool.
If you'd like to use it as well, then:
Get standalone version of TortoiseMerge/Diff (quite old, since it doesn't ship standalone since version 1.6.7 of TortosieSVN, that is since July 2011). Links and details in this answer.
Unzip TortoiseIDiff.exe
and TortoiseMerge.exe
to any folder (c:\Program Files (x86)\Atlassian\SourceTree\extras\
in my case).
In SourceTree open Tools > Options > Diff > External Diff / Merge
. Select TortoiseMerge
in both dropdown lists.
Hit OK
and point SourceTree to your location of TortoiseIDiff.exe
and TortoiseMerge.exe
.
After that, you can select Resolve Conflicts > Launch External Merge Tool
from context menu on each conflicted file in your local repository. This will open up TortoiseMerge, where you can easily deal with all the conflicts, you have. Once finished, simply close TortoiseMerge (you don't even need to save changes, this will probably be done automatically) and after few seconds SourceTree should handle that gracefully.
The only problem is, that it automatically creates backup copy, even though proper option is unchecked.
If the data is in an UTF-8 compatible format, you can convert the bytes to a string.
>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2
Optionally convert to hex first, if the data is not already UTF-8 compatible. E.g. when the data are actual raw bytes.
from binascii import hexlify
from codecs import encode # alternative
>>> print(hexlify(b"\x13\x37"))
b'1337'
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
1337
>>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
1337
I think this one will answer your question :P
$url="https://.../api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=??desc&limit=1&grab_content&content_limit=1";
Using cURL
// Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
Using file_get_contents
$result = file_get_contents($url);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
Accessing
$array["threads"][13/* thread id */]["title"/* thread key */]
And
$array["threads"][13/* thread id */]["content"/* thread key */]["content"][23/* post id */]["message" /* content key */];
Using @Adrian Frühwirth answer:
function strip {
local STRING=${1#$"$2"}
echo ${STRING%$"$2"}
}
use it like this
HELLO=":hello:"
HELLO=$(strip "$HELLO" ":")
echo $HELLO # hello
I had a similar problem and I solved it by:
Using <base href="/index.html">
in the index page
Using a catch all route middleware in my node/Express server as follows (put it after the router):
app.use(function(req, res) {
res.sendfile(__dirname + '/Public/index.html');
});
I think that should get you up and running.
If you use an apache server, you might want to mod_rewrite your links. It is not difficult to do. Just a few changes in the config files.
All that is assuming you have html5mode enabled on angularjs. Now. note that in angular 1.2, declaring a base url is not recommended anymore actually.
Thanks to the way you can index and subset a pandas dataframe, a very easy way to extract a single column from a csv file into a variable is:
myVar = pd.read_csv('YourPath', sep = ",")['ColumnName']
A few things to consider:
The snippet above will produce a pandas Series
and not dataframe
.
The suggestion from ayhan with usecols
will also be faster if speed is an issue.
Testing the two different approaches using %timeit
on a 2122 KB sized csv file yields 22.8 ms
for the usecols approach and 53 ms
for my suggested approach.
And don't forget import pandas as pd
See the problem is with the extension. Depending upon the extension, spring could figure out the content-type. If your url ends with .com then it sends text/html as the content-type header. If you want to change this behavior of Spring, please use the below code:
@Configuration
@Import(HibernateConfig.class)
@EnableWebMvc
// @EnableAsync()
// @EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.azim.web.service.*", basePackageClasses = { WebSecurityConfig.class }, excludeFilters = { @ComponentScan.Filter(Configuration.class) })
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useJaf(false)
.defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
}
@Bean(name = "validator")
public Validator validator() {
return new LocalValidatorFactoryBean();
}
}
Here, we are setting favorPathExtension to false and Default Content-type to Application/json. Note: HibernateConfig class contains all the beans.
For information i removed the action attribute and i got this error when i call an ajax post..Even though my action attribute in the form looks like this action="javascript://;"
I thought I had it from the ajax call and serializing the form but I added the dummy action attribute to the form back again and it worked.
The maximum row size for an InnoDB table, which applies to data stored locally within a database page, is slightly less than half a page for 4KB, 8KB, 16KB, and 32KB
For 16kb pages (default), we can calculate:
Slightly less than half a page 8126 / Number of bytes to threshold for overflow 767 = 10.59 fields of 767 bytes maximum
Basically, you could max out a row with:
Remember, it will only overflow to an overflow page if the field is > 767 bytes. If there are too many fields of 767 bytes, it will bust (passing beyond max row_size). Not usual with latin1 but very possible with utf-8 if the developers aren’t careful.
For this case, I think you could possibly bump the innodb_page_size to 32kb.
in my.cnf:
innodb_page_size=32K
References:
Refer django docs on static files.
In settings.py:
import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = 'static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(CURRENT_PATH, 'static'),
)
Then place your js and css files static folder in your project. Not in media folder.
In views.py:
from django.shortcuts import render_to_response, RequestContext
def view_name(request):
#your stuff goes here
return render_to_response('template.html', locals(), context_instance = RequestContext(request))
In template.html:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.8.3.min.js"></script>
In urls.py:
from django.conf import settings
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
Project file structure can be found here in imgbin.
You can still continue to use the same View resolver but set the suffix to empty.
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix="" />
Now your code can choose to return either index.html or index.jsp as shown in below sample -
@RequestMapping(value="jsp", method = RequestMethod.GET )
public String startJsp(){
return "/test.jsp";
}
@RequestMapping(value="html", method = RequestMethod.GET )
public String startHtml(){
return "/test.html";
}
Saxon will do this not only for XPath 2.0, but also for XQuery 1.0 and (in the commercial version) 3.0. It doesn't come as a Linux package, but as a jar file. Syntax (which you can easily wrap in a simple script) is
java net.sf.saxon.Query -s:source.xml -qs://element/attribute
2020 UPDATE
Saxon 10.0 includes the Gizmo tool, which can be used interactively or in batch from the command line. For example
java net.sf.saxon.Gizmo -s:source.xml
/>show //element/@attribute
/>quit
Deleting package-lock.json
and installing the desired package again solved the issue for me.
From your question I guess you are using Ubuntu (or a derivate). If you use:
apt-file search opencv.pc
then you see that you have to install libopencv-dev
.
After you do so, pkg-config --cflags opencv
and pkg-config --libs opencv
should work as expected.
try this
$.getJSON(url, function(data){
$.each(data.response.venue.tips.groups.items, function (index, value) {
console.log(this.text);
});
});
In my case event.stopPropagation();
was making my page refresh each time I pressed on a link so I had to find another solution.
So what I did was to catch the event on the parent and block the trigger if it was actually coming from his child using event.target
.
Here is the solution:
if (!angular.element($event.target).hasClass('some-unique-class-from-your-child')) ...
So basically your ng-click from your parent component works only if you clicked on the parent. If you clicked on the child it won't pass this condition and it won't continue it's flow.
I think you're mixing up two different paradigms here.
As you noted, the highly flexible ExternalProject
module runs its commands at build time, so you can't make direct use of Project A's import file since it's only created once Project A has been installed.
If you want to include
Project A's import file, you'll have to install Project A manually before invoking Project B's CMakeLists.txt - just like any other third-party dependency added this way or via find_file
/ find_library
/ find_package
.
If you want to make use of ExternalProject_Add
, you'll need to add something like the following to your CMakeLists.txt:
ExternalProject_Add(project_a
URL ...project_a.tar.gz
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/project_a
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
)
include(${CMAKE_CURRENT_BINARY_DIR}/lib/project_a/project_a-targets.cmake)
ExternalProject_Get_Property(project_a install_dir)
include_directories(${install_dir}/include)
add_dependencies(project_b_exe project_a)
target_link_libraries(project_b_exe ${install_dir}/lib/alib.lib)
I know that this is a super old question, but maybe I could help some one else. If you are having a 500 error after setting DEBUG=False, you can always run the manage.py runserver in the command line to see any errors that wont appear in any web error logs.
Use BOOST_BINARY (Yes, you can use it in C).
#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);
This macro is expanded to an octal literal during preprocessing.
ElementTree is not too smart about namespaces. You need to give the .find()
, findall()
and iterfind()
methods an explicit namespace dictionary. This is not documented very well:
namespaces = {'owl': 'http://www.w3.org/2002/07/owl#'} # add more as needed
root.findall('owl:Class', namespaces)
Prefixes are only looked up in the namespaces
parameter you pass in. This means you can use any namespace prefix you like; the API splits off the owl:
part, looks up the corresponding namespace URL in the namespaces
dictionary, then changes the search to look for the XPath expression {http://www.w3.org/2002/07/owl}Class
instead. You can use the same syntax yourself too of course:
root.findall('{http://www.w3.org/2002/07/owl#}Class')
If you can switch to the lxml
library things are better; that library supports the same ElementTree API, but collects namespaces for you in a .nsmap
attribute on elements.
Simple solution is ...
Just put below command :
sudo npm config get prefix
if it's not something like these /usr/local
, than you need to fix it using below command.
sudo npm config set prefix /usr/local
...
Now it's 100% working fine
I had this error too on the Windows machine.
My solution.
1) Download your language files from https://github.com/tesseract-ocr/tessdata/tree/3.04.00
For example, for eng, I downloaded all files with eng prefix.
2) Put them into tessdata directory inside of some folder. Add this folder into System Path variables as TESSDATA_PREFIX.
Result will be System env var: TESSDATA_PREFIX=D:/Java/OCR And OCR folder has tessdata with languages files.
This is a screenshot of the directory:
Very old question here, but I ran into the same error and none of the provided answers solved the issue.
My issue occurred because I manually changed the namespace and assembly names of the project after initial creation. Took me a little bit to notice that the namespace in the Inherits
attribute didn't match the updated namespace.
Updating that namespace in the Global.asax markup to match the apps namespace fixed the error for me.
There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.
While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
I've found this the easy fix, simply add this to the css:
cursor: pointer;
Another solution is:
>>> "".join(list(hex(255))[2:])
'ff'
Probably an archaic answer, but functional.
All three template options - <%@include>
, <jsp:include>
and <%@tag>
are valid, and all three cover different use cases.
With <@include>
, the JSP parser in-lines the content of the included file into the JSP before compilation (similar to a C #include
). You'd use this option with simple, static content: for example, if you wanted to include header, footer, or navigation elements into every page in your web-app. The included content becomes part of the compiled JSP and there's no extra cost at runtime.
<jsp:include>
(and JSTL's <c:import>
, which is similar and even more powerful) are best suited to dynamic content. Use these when you need to include content from another URL, local or remote; when the resource you're including is itself dynamic; or when the included content uses variables or bean definitions that conflict with the including page. <c:import>
also allows you to store the included text in a variable, which you can further manipulate or reuse. Both these incur an additional runtime cost for the dispatch: this is minimal, but you need to be aware that the dynamic include is not "free".
Use tag files when you want to create reusable user interface components. If you have a List of Widgets, say, and you want to iterate over the Widgets and display properties of each (in a table, or in a form), you'd create a tag. Tags can take arguments, using <%@tag attribute>
and these arguments can be either mandatory or optional - somewhat like method parameters.
Tag files are a simpler, JSP-based mechanism of writing tag libraries, which (pre JSP 2.0) you had to write using Java code. It's a lot cleaner to write JSP tag files when there's a lot of rendering to do in the tag: you don't need to mix Java and HTML code as you'd have to do if you wrote your tags in Java.
The reason that you get the 404 File Not Found
error, is that your path to CSS given as a value to the href
attribute is missing context path.
An HTTP request URL contains the following parts:
http://[host]:[port][request-path]?[query-string]
The request path is further composed of the following elements:
Context path: A concatenation of a forward slash (/) with the context
root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]
Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).
Path info: The part of the request path that is not part of the context path or the servlet path.
Read more here.
There are several solutions to your problem, here are some of them:
<c:url>
tag from JSTLIn my Java web applications I usually used <c:url>
tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).
If you say, that your CSS is located inside WebContent folder, then this should work:
<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />
The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):
7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.
NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.
An alternative solution is using Expression Language (EL) to add application context:
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />
Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.
<c:set>
tag from JSTLDISCLAIMER
The idea of this solution was taken from here.
To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set>
tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.
<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />
IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />
), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.
The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.
We need a class that implements ServletContextListener interface. Here is an example of such class:
package com.example.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
sc.setAttribute("ctx", sc.getContextPath());
}
@Override
public void contextDestroyed(ServletContextEvent event) {}
}
Now in a JSP we can access this global variable using EL:
<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />
NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
...
<listener>
<listener-class>com.example.listener.AppContextListener</listener-class>
</listener>
...
</webapp>
As suggested by user @gavenkoa you can also use scriptlets like this:
<%= request.getContextPath() %>
For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.
I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.
You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.
You can do this, you just need to circumvent the launcher.
In %appdata%\.minecraft\bin
(or ~/.minecraft/bin
on unixy systems), there is a minecraft.jar file. This is the actual game - the launcher runs this.
Invoke it like so:
java -Xms512m -Xmx1g -Djava.library.path=natives/ -cp "minecraft.jar;lwjgl.jar;lwjgl_util.jar" net.minecraft.client.Minecraft <username> <sessionID>
Set the working directory to .minecraft/bin
.
To get the session ID, POST (request this page):
https://login.minecraft.net?user=<username>&password=<password>&version=13
You'll get a response like this:
1343825972000:deprecated:SirCmpwn:7ae9007b9909de05ea58e94199a33b30c310c69c:dba0c48e1c584963b9e93a038a66bb98
The fourth field is the session ID. More details here. Read those details, this answer is outdated
Here's an example of logging in to minecraft.net in C#.
Unicode is an appropriate type here. The JSONDecoder docs describe the conversion table and state that json string objects are decoded into Unicode objects
https://docs.python.org/2/library/json.html#encoders-and-decoders
JSON Python
==================================
object dict
array list
string unicode
number (int) int, long
number (real) float
true True
false False
null None
"encoding determines the encoding used to interpret any str objects decoded by this instance (UTF-8 by default)."
Try paste in console this:
$ mkdir /var/pgsql_socket/
$ ln -s /private/tmp/.s.PGSQL.5432 /var/pgsql_socket/
If 'localhost' doesn't work but 127.0.0.1 does. Make sure your local hosts file points to the correct location. (/etc/hosts for linux/mac, C:\Windows\System32\drivers\etc\hosts for windows).
Also, make sure your user is allowed to connect to whatever database you're trying to select.
<context:component-scan base-package="" />
tells Spring to scan those packages for Annotations.
<mvc:annotation-driven>
registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.
This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.
You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.
Check out the 3.1 documentation to learn more.
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config
This is a fix for people who are not using maven. You also need to add standard.jar
to your lib folder for the core tag library to work. Works for jstl version 1.1.
<%@taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
It is common practice in C++. This is because in C++ you can't have same name for the member function and member variable, and getter functions are often named without "get" prefix.
class Person
{
public:
std::string name() const;
private:
std::string name; // This would lead to a compilation error.
std::string m_name; // OK.
};
main.cpp:9:19: error: duplicate member 'name' std::string name; ^ main.cpp:6:19: note: previous declaration is here std::string name() const; ^ 1 error generated.
"m_" states for the "member". Prefix "_" is also common.
You shouldn't use it in programming languages that solve this problem by using different conventions/grammar.
If you are using more animation attributes the shorthand is:
animation: bubble 2s linear 0.5s 1 normal forwards;
This gives:
bubble
animation name2s
durationlinear
timing-function0.5s
delay1
iteration-count (can be 'infinite
')normal
directionforwards
fill-mode (set 'backwards' if you want to have compatibility to use the end position as the final state[this is to support browsers that has animations turned off]{and to answer only the title, and not your specific case})Add the following parameter debug-enabled="true" to this line in the glassfish configuration. Example:
<java-config debug-options="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9009" debug-enabled="true"
system-classpath="" native-library-path-prefix="D:\Project\lib\windows\64bit" classpath-suffix="">
Start and stop the glassfish domain or service which was using this configuration.
Since Jackson 2.0 you can use JsonInclude
@JsonInclude(Include.NON_NULL)
public class Shop {
//...
}
I write out a rule in web.config after $locationProvider.html5Mode(true)
is set in app.js
.
Hope, helps someone out.
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
In my index.html I added this to <head>
<base href="/">
Don't forget to install IIS URL Rewrite on server.
Also if you use Web API and IIS, this will work if your API is at www.yourdomain.com/api
because of the third input (third line of condition).
My problem had a slightly different solution. The directory in which brew wanted to create the symlinks were not owned by the current user.
ls -la /usr/local/bin/lib/node | grep node
yielded:
drwxr-xr-x 3 24561 wheel 102 May 4 2012 node
drwxr-xr-x 7 24561 wheel 238 Sep 18 16:37 node_modules
For me, the following fixed it:
sudo chown $(users) /usr/local/bin/lib/node_modules
sudo chown $(users) /usr/local/bin/lib/node
ps. $(users)
will get expanded to your username, went a little out of my way to help out lazy copy pasters ;)
Here is how we solved it
a Users table looked like this
Users
-------------------------------------------------
id | name | address | phone | email | created_on | updated_on
And the business requirement changed and we were in a need to check all previous addresses and phone numbers a user ever had. new schema looks like this
Users (the data that won't change over time)
-------------
id | name
UserData (the data that can change over time and needs to be tracked)
-------------------------------------------------
id | id_user | revision | city | address | phone | email | created_on
1 | 1 | 0 | NY | lake st | 9809 | @long | 2015-10-24 10:24:20
2 | 1 | 2 | Tokyo| lake st | 9809 | @long | 2015-10-24 10:24:20
3 | 1 | 3 | Sdny | lake st | 9809 | @long | 2015-10-24 10:24:20
4 | 2 | 0 | Ankr | lake st | 9809 | @long | 2015-10-24 10:24:20
5 | 2 | 1 | Lond | lake st | 9809 | @long | 2015-10-24 10:24:20
To find the current address of any user, we search for UserData with revision DESC and LIMIT 1
To get the address of a user between a certain period of time we can use created_on bewteen (date1 , date 2)
If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?
In version 2, instead of
from module import attribute1
you can do
attribute1 = module.attribute1
I saw that two people put that question to their favorites so I will try to answer the solution which works for me: Instead of using find modules I'm writing configuration files for all libraries which are installed. Those files are extremly simple and can also be used to set non-standard variables. CMake will (at least on windows) search for those configuration files in
CMAKE_PREFIX_PATH/<<package_name>>-<<version>>/<<package_name>>-config.cmake
(which can be set through an environment variable). So for example the boost configuration is in the path
CMAKE_PREFIX_PATH/boost-1_50/boost-config.cmake
In that configuration you can set variables. My config file for boost looks like that:
set(boost_INCLUDE_DIRS ${boost_DIR}/include)
set(boost_LIBRARY_DIR ${boost_DIR}/lib)
foreach(component ${boost_FIND_COMPONENTS})
set(boost_LIBRARIES ${boost_LIBRARIES} debug ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-gd-1_50.lib)
set(boost_LIBRARIES ${boost_LIBRARIES} optimized ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-1_50.lib)
endforeach()
add_definitions( -D_WIN32_WINNT=0x0501 )
Pretty straight forward + it's possible to shrink the size of the config files even more when you write some helper functions. The only issue I have with this setup is that I havn't found a way to give config files a priority over find modules - so you need to remove the find modules.
Hope this this is helpful for other people.
select column1 as xyz,
column2 as pqr,
.....
from TableName;
In spring servlet .xml :
<context:component-scan base-package="net.controller" />
(I assumed that the service impl is in the same package as the service interface "net.service")
I think you have to add the package net.service (or all of net) to the component scan. Currently spring only searches in net.controller for components and as your service impl is in net.service, it will not be instantiated by spring.
Syntax
print_r(variable, return);
variable Required. Specifies the variable to return information about
return Optional. When set to true, this function will return the information (not print it). Default is false
Example
error_log( print_r(<array Variable>, TRUE) );
I found this answer to the question:
http://padcom13.blogspot.co.uk/2011/10/creating-standalone-applications-with.html
Not only do you get the dependent lib files in a lib folder, you also get a bin director with both a unix and a dos executable.
The executable ultimately calls java with a -cp argument that lists all of your dependent libs too.
The whole lot sits in an appasembly folder inside the target folder. Epic.
============= Yes I know this is an old thread, but it's still coming high on search results so I thought it might help someone like me.
The best way to handle the LazyInitializationException
is to fetch it upon query time, like this:
select t
from Topic t
left join fetch t.comments
You should ALWAYS avoid the following anti-patterns:
FetchType.EAGER
hibernate.enable_lazy_load_no_trans
Hibernate configuration propertyTherefore, make sure that your FetchType.LAZY
associations are initialized at query time or within the original @Transactional
scope using Hibernate.initialize
for secondary collections.
Here is slightly modified version. Changes are noted as code commentary.
BEGIN TRANSACTION
declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500)
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'pct%'
AND TABLE_NAME LIKE 'TestData%'
open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
-- And then fetch
fetch next from Tests into @test, @tableName
-- And then, if no row is fetched, exit the loop
if @@fetch_status <> 0
begin
break
end
-- Quotename is needed if you ever use special characters
-- in table/column names. Spaces, reserved words etc.
-- Other changes add apostrophes at right places.
set @cmd = N'exec sp_rename '''
+ quotename(@tableName)
+ '.'
+ quotename(@test)
+ N''','''
+ RIGHT(@test,LEN(@test)-3)
+ '_Pct'''
+ N', ''column'''
print @cmd
EXEC sp_executeSQL @cmd
END
close Tests
deallocate Tests
ROLLBACK TRANSACTION
--COMMIT TRANSACTION
Here is a list of python packages that implement Trie:
It can be done through "Import/Export Data..." in SQL Server Management Studio
You know that Maven is based on the Convention over Configuration pardigm? so you shouldn't configure things which are the defaults.
All that stuff represents the default in Maven. So best practice is don't define it it's already done.
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
By reading your exception , It's sure that you forgot to autowire customerService
You should autowire your customerservice .
make following changes in your controller class
@Controller
public class CustomerController{
@Autowired
private Customerservice customerservice;
......other code......
}
Again your service implementation class
write
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerDAO customerDAO;
......other code......
.....add transactional methods
}
If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).
you should autowire sessionFactory set method in your DAO mplementation
please find samle application context :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<context:component-scan base-package="com.sparkle" />
<!-- Configures the @Controller programming model -->
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!-- <bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" /> -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
</beans>
note that i am using jdbc.properties file for jdbc url and driver specification
It looks like your Spring component scan Base is missing UserServiceImpl
<context:component-scan base-package="org.assessme.com.controller." />
First get the gcc path using
Command: which gcc
Output: /usr/bin/gcc
I had the same issue, Please set the gcc path in below command and install
CC=/usr/bin/gcc rvm install 1.9.3
Later if you get "Ruby was built without documentation" run below command
rvm docs generate-ri
Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.
But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.
static {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
// ip address of the service URL(like.23.28.244.244)
if (hostname.equals("23.28.244.244"))
return true;
return false;
}
});
}
If you happen to be using Java 8, there is a much slicker way of achieving the same result:
static {
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}
DO it like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");
Do not forget the %
at the end
NOTE FOR PHP 7
To update on this answer as it has gained some popularity: This answer no longer applies as of PHP 7. As explained in the "Backward incompatible changes", in PHP 7 foreach works on copy of the array, so any changes on the array itself are not reflected on foreach loop. More details at the link.
Explanation (quote from php.net):
The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).
So, in your first example you only have one element in the array, and when the pointer is moved the next element does not exist, so after you add new element foreach ends because it already "decided" that it it as the last element.
In your second example, you start with two elements, and foreach loop is not at the last element so it evaluates the array on the next iteration and thus realises that there is new element in the array.
I believe that this is all consequence of On each iteration part of the explanation in the documentation, which probably means that foreach
does all logic before it calls the code in {}
.
Test case
If you run this:
<?
$array = Array(
'foo' => 1,
'bar' => 2
);
foreach($array as $k=>&$v) {
$array['baz']=3;
echo $v." ";
}
print_r($array);
?>
You will get this output:
1 2 3 Array
(
[foo] => 1
[bar] => 2
[baz] => 3
)
Which means that it accepted the modification and went through it because it was modified "in time". But if you do this:
<?
$array = Array(
'foo' => 1,
'bar' => 2
);
foreach($array as $k=>&$v) {
if ($k=='bar') {
$array['baz']=3;
}
echo $v." ";
}
print_r($array);
?>
You will get:
1 2 Array
(
[foo] => 1
[bar] => 2
[baz] => 3
)
Which means that array was modified, but since we modified it when the foreach
already was at the last element of the array, it "decided" not to loop anymore, and even though we added new element, we added it "too late" and it was not looped through.
Detailed explanation can be read at How does PHP 'foreach' actually work? which explains the internals behind this behaviour.
1. Performance:
Assume your where clause is like this:
WHERE NAME='JON'
If the NAME column is of any type other than nvarchar or nchar, then you should not specify the N prefix. However, if the NAME column is of type nvarchar or nchar, then if you do not specify the N prefix, then 'JON' is treated as non-unicode. This means the data type of NAME column and string 'JON' are different and so SQL Server implicitly converts one operand’s type to the other. If the SQL Server converts the literal’s type to the column’s type then there is no issue, but if it does the other way then performance will get hurt because the column's index (if available) wont be used.
2. Character set:
If the column is of type nvarchar or nchar, then always use the prefix N while specifying the character string in the WHERE criteria/UPDATE/INSERT clause. If you do not do this and one of the characters in your string is unicode (like international characters - example - a) then it will fail or suffer data corruption.
Try setting these values, it solves problem in fast-cgi
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
Well finally I have solved the problem. And surprise, surprise It was the freaking UPPERCASE letter in my table prefix. I had it this way in my wp-config file wp_C5n but for some reason most of the tables got a prefix wp_c5n. But not all. So what id did was I changed my table prefix in wp_config file to all lowercase and then went through all the tables by hand via phpMyadmin to see If there's any uppercase tables left. There where about 3. They were inside usermeta table and inside options table. Now finally everything is working. Did a quick search through wordpress codex but did not find anything mentioning not to use uppercase characters.
When you say you tried to use OR, how exactly did you try and use it? In your case, what you will need to do would be something like so:
String newStr4 = strr.split("2012")[0];
if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues")...)
str4.add(newStr4);
Run apt-get install build-essential
on your system.
This package depends on other packages considered to be essential for builds and will install them. If you find you have to build packages, this can be helpful to avoid piecemeal resolution of dependencies.
See this page for more info.
By having the .5s delay on transitioning the opacity property, the element will be completely transparent (and thus invisible) the whole time its height is transitioning. So the only thing you will actually see is the opacity changing. So you will get the same effect as leaving the height property out of the transition :
"transition: opacity .5s .5s;"
Is that what you're wanting? If not, and you're wanting to see the height transition, you can't have an opacity of zero during the whole time that it's transitioning.
Just weighing in here with a nice solution I have been using. This is similar to Lucky Soni's solution above in that it supports aggregation, but doesn't require hard coding of the field names.
cursor = db.<collection_name>.<my_query_with_aggregation>;
headerPrinted = false;
while (cursor.hasNext()) {
item = cursor.next();
if (!headerPrinted) {
print(Object.keys(item).join(','));
headerPrinted = true;
}
line = Object
.keys(item)
.map(function(prop) {
return '"' + item[prop] + '"';
})
.join(',');
print(line);
}
Save this as a .js
file, in this case we'll call it example.js
and run it with the mongo command line like so:
mongo <database_name> example.js --quiet > example.csv
In my case
android studio suddenly stop seeing my device
I fix it by change USB option to Media device (MTP)
how to get USB option from storage USB Computer Connection
check Debugging from developer options
try re-run on device , it should work
issue
USB option was charge only
UPDATE ANSWER 26/7/2016
there many reasons like not enabling developer mode --> USB debugging(if you dont see developer option click 7 times at build number )
but I face another issue every thing was works just fine suddenly android studio cant see my device
to fix this issue you need to restart adb , from terminal
adb kill-server
adb start-server
or from ddms
in devices section --> click at small arrow down --> restart adb
Just use simple disabled tag like this below.
<input type="checkbox" name="email" disabled>
Setting Activity
’s title from a Fragment
messes up responsibility levels. Fragment
is contained within an Activity
, so this is the Activity
, which should set its own title according to the type of the Fragment
for example.
Suppose you have an interface:
interface TopLevelFragment
{
String getTitle();
}
The Fragment
s which can influence the Activity
’s title then implement this interface. While in the hosting activity you write:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().add(0, new LoginFragment(), "login").commit();
}
@Override
public void onAttachFragment(Fragment fragment)
{
super.onAttachFragment(fragment);
if (fragment instanceof TopLevelFragment)
setTitle(((TopLevelFragment) fragment).getTitle());
}
In this manner Activity
is always in control what title to use, even if several TopLevelFragment
s are combined, which is quite possible on a tablet.
First of all, try the 32 Bit Version of the Import Wizard. This shows a lot more supported import formats.
Background: All depends on your Office (Runtimes Engines) installation.
If you dont't have Office 2007 or greater installed, the Import Wizard (32 Bit) only allows you to import Excel 97-2003 (.xls) files.
If you have the Office 2010 and geater (comes also in 64 Bit, not recommended) installed, the Import Wizard also supports Excel 2007+ (.xlsx) files.
To get an overview on the runtimes see 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine
If you have a look at the W3C specification, it would seem like the obvious thing to try is to mark your button elements with type='button'
when you don't want them to submit.
The thing to note in particular is where it says
A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"
What huge codes for something so simple:
In C#, create an extension method and use LINQ.
public static int CountOccurences(this string s, char c)
{
return s.Count(t => t == c);
}
Usage:
int count = "toto is the best".CountOccurences('t');
Result: 4.
The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n
, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n
on input, and conversely on output.
From the C99 standard (the N869 draft document), §7.19.2/2,
A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.
And in §7.19.3/2
Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.
About use of fseek
, in §7.19.9.2/4:
For a text stream, either
offset
shall be zero, oroffset
shall be a value returned by an earlier successful call to theftell
function on a stream associated with the same file andwhence
shall beSEEK_SET
.
About use of ftell
, in §17.19.9.4:
The
ftell
function obtains the current value of the file position indicator for the stream pointed to bystream
. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by thefseek
function for returning the file position indicator for the stream to its position at the time of theftell
call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.
I think that’s the most important, but there are some more details.
According to http://help.encoding.com/knowledge-base/article/correct-mime-types-for-serving-video-files/, the correct mime type for .mp4
is video/mp4
0 */6 * * * command
This will be the perfect way to say 6 hours a day.
Your command puts in for six minutes!
The easiest way to remove any link from the My Account panel in Magento is to first copy:
app/design/frontend/base/default/template/customer/account/navigation.phtml
to
app/design/frontend/enterprise/YOURSITE/template/customer/account/navigation.phtml
Open the file and fine this line, it should be around line 34:
<?php $_index = 1; ?>
Right below it add this:
<?php $_count = count($_links); /* Add or Remove Account Left Navigation Links Here -*/
unset($_links['tags']); /* My Tags */
unset($_links['invitations']); /* My Invitations */
unset($_links['enterprise_customerbalance']); /* Store Credit */
unset($_links['OAuth Customer Tokens']); /* My Applications */
unset($_links['enterprise_reward']); /* Reward Points */
unset($_links['giftregistry']); /* Gift Registry */
unset($_links['downloadable_products']); /* My Downloadable Products */
unset($_links['recurring_profiles']); /* Recurring Profiles */
unset($_links['billing_agreements']); /* Billing Agreements */
unset($_links['enterprise_giftcardaccount']); /* Gift Card Link */
?>
Just remove any of the links here that you DO want to appear.
Sometimes using
instead of spaces will work. Clearly it has drawbacks, though.
SQL Logins are defined at the server level, and must be mapped to Users in specific databases.
In SSMS object explorer, under the server you want to modify, expand Security > Logins, then double-click the appropriate user which will bring up the "Login Properties" dialog.
Select User Mapping, which will show all databases on the server, with the ones having an existing mapping selected. From here you can select additional databases (and be sure to select which roles in each database that user should belong to), then click OK to add the mappings.
These mappings can become disconnected after a restore or similar operation. In this case, the user may still exist in the database but is not actually mapped to a login. If that happens, you can run the following to restore the login:
USE {database};
ALTER USER {user} WITH login = {login}
You can also delete the DB user and recreate it from the Login Properties dialog, but any role memberships or other settings would need to be recreated.
The best way to force a specific JVM for MAVEN is to create a system wide file loaded by the mvn script.
This file is /etc/mavenrc
and it must declare a JAVA_HOME
environment variable pointing to your specific JVM.
Example:
export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64
If the file exists, it's loaded.
Here is an extract of the mvn
script in order to understand :
if [ -f /etc/mavenrc ] ; then . /etc/mavenrc fi if [ -f "$HOME/.mavenrc" ] ; then . "$HOME/.mavenrc" fi
Alternately, the same content can be written in ~/.mavenrc
For this use below code in your app gradle file under android closure.
dexOptions { javaMaxHeapSize "4g" }
Here is one way of doing it:
<%
Dim message
message = "This is my message"
Response.Write("<script language=VBScript>MsgBox """ + message + """</script>")
%>
For python 3.7:
Change directory, if you didn't add the following as your PATH: cd C:\Users{user_name}\AppData\Local\Programs\Python\Python37-32\Scripts To know where your package/application has been installed/located, type: "where program_name" like> where jupyter If you didn't find a location, you need to add the location in PATH.
Type: pip-autoremove jupyter It will ask to type y/n to confirm the action.
If any one of you are getting error like following after following answer given by Afwe Wef
Warning: mail() [<a href='function.mail'>function.mail</a>]: SMTP server response:
550 The address is not valid. in c:\wamp\www\email.php
Go to php.ini
; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = [email protected]
Enter [email protected] as your email id which you used to configure the hMailserver in front of sendmail_from .
your problem will be solved.
Tested on Wamp server2.2(Apache 2.2.22, php 5.3.13) on windows 8
If you are also getting following error
"APPLICATION" 6364 "2014-03-24 13:13:33.979" "SMTPDeliverer - Message 2: Relaying to host smtp.gmail.com."
"APPLICATION" 6364 "2014-03-24 13:13:34.415" "SMTPDeliverer - Message 2: Message could not be delivered. Scheduling it for later delivery in 60 minutes."
"APPLICATION" 6364 "2014-03-24 13:13:34.430" "SMTPDeliverer - Message 2: Message delivery thread completed."
You might have forgot to change the port from 25 to 465
If you have a project reference, it should work immediately.
If it is a file (dll) reference, you need the debugging symbols (the "pdb" file) to be in the same folder as the dll. Check that your projects are generating debug symbols (project properties => Build => Advanced => Output / Debug Info = full); and if you have copied the dll, put the pdb with it.
You can also load symbols directly in the IDE if you don't want to copy any files, but it is more work.
The easiest option is to use project references!
Diff has an option -r
which is meant to do just that.
diff -r dir1 dir2
yes, you can have associative arrays also in javascript:
var obj =
{
name:'some name',
otherProperty:'prop value',
date: new Date()
};
for(i in obj)
{
var propVal = obj[i]; // i is the key, and obj[i] is the value ...
}
I have removed the scope and then used a maven update to solve this problem.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
**<!-- <scope>provided</scope> -->**
</dependency>
The jstl lib is not present in the tomcat lib folder.So we have to include it. I don't understand why we are told to keep both servlet-api and jstl's scope as provided.
Apache Tomcat is used to deploy your Java Servlets and JSPs. So in your Java project you can build your WAR (short for Web ARchive) file, and just drop it in the deploy directory in Tomcat.
So basically Apache is an HTTP Server, serving HTTP. Tomcat is a Servlet and JSP Server serving Java technologies.
Tomcat includes Catalina, which is a servlet container. A servlet, at the end, is a Java class. JSP files (which are similar to PHP, and older ASP files) are generated into Java code (HttpServlet), which is then compiled to .class files by the server and executed by the Java virtual machine.
You can use the init files. Check the MySQL official documentation on How to Reset the Root Password (including comments for alternative solutions).
So basically using init files, you can add any SQL queries that you need for fixing your access (such as GRAND
, CREATE
, FLUSH PRIVILEGES
, etc.) into init file (any file).
Here is my example of recovering root account:
echo "CREATE USER 'root'@'localhost' IDENTIFIED BY 'root';" > your_init_file.sql
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;" >> your_init_file.sql
echo "FLUSH PRIVILEGES;" >> your_init_file.sql
and after you've created your file, you can run:
killall mysqld
mysqld_safe --init-file=$PWD/your_init_file.sql
then to check if this worked, press Ctrl+Z and type: bg
to run the process from the foreground into the background, then verify your access by:
mysql -u root -proot
mysql> show grants;
+-------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost |
+-------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' |
See also:
I had this similar issue. I wanted to set a class after looking at multiple expressions. ngClass can evaluate a method inside the component code and tell you what to do.
So inside an *ngFor:
<div [ngClass]="{'shrink': shouldShrink(a.category1, a.category2), 'showAll': section == 'allwork' }">{{a.listing}}</div>
And inside the component:
section = 'allwork';
shouldShrink(cat1, cat2) {
return this.section === cat1 || this.section === cat2 ? false : true;
}
Here I need to calculate if i should shrink a div based on if a 2 different categories have matched what the selected category is. And it works. So from there you can computer a true/false for the [ngClass] based on what your method returns given the inputs.
I have experienced this exact problem and found, on the users machine, one of the libraries I depended on was marked as "MISSING" in the references dialog. In that case it was some office font library that was available in my version of Office 2007, but not on the client desktop.
The error you get is a complete red herring (as pointed out by divo).
Fortunately I wasn't using anything from the library, so I was able to remove it from the XLA references entirely. I guess, an extension of divo' suggested best practice would be for testing to check the XLA on all the target Office versions (not a bad idea in any case).
For my console program the answers with tkinter above did not quite work for me because the .destroy() always gave an error,:
can't invoke "event" command: application has been destroyed while executing...
or when using .withdraw() the console window did not get the focus back.
To solve this you also have to call .update() before the .destroy(). Example:
# Python 3
import tkinter
r = tkinter.Tk()
text = r.clipboard_get()
r.withdraw()
r.update()
r.destroy()
The r.withdraw() prevents the frame from showing for a milisecond, and then it will be destroyed giving the focus back to the console.
This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.
There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.
The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like
1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host
EDIT
Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
you have parse that Json
string using JSON.parse()
..
}).done(function(data){
obj = JSON.parse(data);
alert(obj.jobtitel);
});
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *tomorrowDate = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE, dd MMM yyyy"];
NSLog(@"%@", [dateFormatter stringFromDate:tomorrowDate]);
In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:
<body onload="parent.alertsize(document.body.scrollHeight);">
In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.
To that JavaScript function it sends how many pixels its (iframe) height is.
The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.
That's it, nothing else is needed.
But if you like to know some more small tricks keep on reading...
DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
}
</script>
to that script just add:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>
How you use the above script is easy:
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)
Complete holding page code:
<!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>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>
<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>
Complete iframe code: (this iframe named "theiframe.htm")
<!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>IFRAME CONTENT</title>
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight);
}
</script>
</head>
<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END
</body>
</html>
I don't think desc
takes an na.rm
argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NA
s, use na.omit
(base) or tidyr::drop_na
:
outcome.df %>%
na.omit() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
library(tidyr)
outcome.df %>%
drop_na() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
If you only want to remove NA
s from the HeartAttackDeath column, filter with is.na
, or use tidyr::drop_na
:
outcome.df %>%
filter(!is.na(HeartAttackDeath)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
outcome.df %>%
drop_na(HeartAttackDeath) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
As pointed out at the dupe, complete.cases
can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:
outcome.df %>%
filter(complete.cases(.)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
Require script loads respect http caching headers. (Scripts are loaded with a dynamically inserted <script>
, which means the request looks just like any old asset getting loaded.)
Serve your javascript assets with the proper HTTP headers to disable caching during development.
Using require's urlArgs means any breakpoints you set will not be preserved across refreshes; you end up needing to put debugger
statements everywhere in your code. Bad. I use urlArgs
for cache-busting assets during production upgrades with the git sha; then I can set my assets to be cached forever and be guaranteed to never have stale assets.
In development, I mock all ajax requests with a complex mockjax configuration, then I can serve my app in javascript-only mode with a 10 line python http server with all caching turned off. This has scaled up for me to a quite large "enterprisey" application with hundreds of restful webservice endpoints. We even have a contracted designer who can work with our real production codebase without giving him access to our backend code.
I have done this in the past.
SELECT column_name
FROM information_schema.columns
WHERE table_name='insert table name here';
Change in the my.ini
or ~/.my.cnf
file by including the single line under [mysqld]
or [client]
section in your file:
max_allowed_packet=500M
then restart the MySQL service and you are done.
See the documentation for further information.
You can set an Image in UIImage object eiter of the following way:
UIImage *imageObject = [UIImage imageNamed:@"imageFileName"];
but by initializing UIImage
Object like this, the image is always stored in cache memory even you make it nil
like imageObject=nil;
Its better to follow this:
NSString *imageFilePath = [[NSBundle mainBundle] pathForResource:@"imageFilename" ofType:@"imageFile_Extension"];
UIImage *imageObject = [UIImage imageWithContentsOfFile:imageFilePath];
EXAMPLE: NSString *imageFilePath = [[NSBundle mainBundle] pathForResource:@"abc" ofType:@"png"];
UIImage *imageObject = [UIImage imageWithContentsOfFile:imageFilePath];
Another thing that can cause this error is creating a model with the centering/scaling standardize function from the arm package -- m <- standardize(lm(y ~ x, data = train))
If you then try predict(m)
, you get the same error as in this question.
try this
string htmlBody = ParseHmlBody(dtViewDetails.Rows[0]["Body"].ToString());
private string ParseHmlBody(string html)
{
string body = string.Empty;
try
{
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
body = htmlBody.OuterHtml;
}
catch (Exception ex)
{
dalPendingOrders.LogMessage("Error in ParseHmlBody" + ex.Message);
}
return body;
}
I found 2 things worth mentioning while uploading files using webdav and http web request. First, for the provider I was using, I had to append the filename at the end of the provider url. Ihad to append the port number in the url. And I also set the Request method to PUT instead of POST.
example:
string webdavUrl = "https://localhost:443/downloads/test.pdf";
request.Method = "PUT";
java [ options ] -jar file.jar [ argument ... ]
and
... Non-option arguments after the class name or JAR file name are passed to the main function...
Maybe you have to put the arguments in single quotes.
elec_and_weather['DEMAND_t-%i'% k] = np.zeros(len(elec_and_weather['DEMAND']))'
The error comes at the end of the line where you have the (') sign; this error always means that you have a syntax error.
I don't think you can do this with CSS. Instead, at regular 'word lengths' along the string, insert an HTML soft-hyphen:
ACTGATCG­AGCTGAAG­CGCAGTGC­GATGCTTC­GATGATGC­TGACGATG
This will display a hyphen at the end of the line, where it wraps, which may or may not be what you want.
Note Safari seems to wrap the long string in a <textarea>
anyway, unlike Firefox.
public int getMax(ArrayList list){
int max = Integer.MIN_VALUE;
for(int i=0; i<list.size(); i++){
if(list.get(i) > max){
max = list.get(i);
}
}
return max;
}
From my understanding, this is basically what Collections.max() does, though they use a comparator since lists are generic.
Here is example of using separated parallel
and for
here. In short it can be used for dynamic allocation of OpenMP thread-private arrays before executing for
cycle in several threads.
It is impossible to do the same initializing in parallel for
case.
UPD: In the question example there is no difference between single pragma and two pragmas. But in practice you can make more thread aware behavior with separated parallel and for directives. Some code for example:
#pragma omp parallel
{
double *data = (double*)malloc(...); // this data is thread private
#pragma omp for
for(1...100) // first parallelized cycle
{
}
#pragma omp single
{} // make some single thread processing
#pragma omp for // second parallelized cycle
for(1...100)
{
}
#pragma omp single
{} // make some single thread processing again
free(data); // free thread private data
}
###################################################
###################################################
###################################################
AVOID THIS
###################################################
###################################################
###################################################
/*for (Song s: songList){
System.out.println(s + "," + songList.indexOf(s);
}*/
it is possible in linked list.
you have to make toString() in song class. if you don't it will print out reference of the song.
probably irrelevant for you by now. ^_^
If you're doing some sort of math with the numbers you might also want to know the units. Given your input restrictions (that the input string contains unit and value only), this should correctly return both (you'll just need to figure out how to convert units into common units for your math).
def unit_value(str):
m = re.match(r'([^\d]*)(\d*\.?\d+)([^\d]*)', str)
if m:
g = m.groups()
return ' '.join((g[0], g[2])).strip(), float(g[1])
else:
return int(str)
You can try this...
<div class="image">
<img src="" alt="" />
<h2>Text you want to display over the image</h2>
</div>
CSS
.image {
position: relative;
width: 100%; /* for IE 6 */
}
h2 {
position: absolute;
top: 200px;
left: 0;
width: 100%;
}
You can append a queryString to your src and change it only when you will release an updated version:
<script src="test.js?v=1"></script>
In this way the browser will use the cached version until a new version will be specified (v=2, v=3...)
There's no reason to use setRawInputType()
, just use setInputType()
. However, you have to combine the class and flags with the OR operator:
edit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
Paxdiablo's answer is absolutely correct.
To avoid writing the return value 1
twice, I would use this instead:
=IF(OR(ISBLANK(A1),TRIM(A1)=""),1,0)
from PIL import Image
background = Image.open("test1.png")
foreground = Image.open("test2.png")
background.paste(foreground, (0, 0), foreground)
background.show()
First parameter to .paste()
is the image to paste. Second are coordinates, and the secret sauce is the third parameter. It indicates a mask that will be used to paste the image. If you pass a image with transparency, then the alpha channel is used as mask.
Check the docs.
How about this? (jsFiddle link)
CSS
ul {
background: #CCC;
height: 1000%;
width: 100%;
list-style-position: outside;
margin: 0; padding: 0;
position: absolute;
}
li {
background-color: #EBEBEB;
border-bottom: 1px solid #CCCCCC;
border-right: 1px solid #CCCCCC;
display: table;
height: 180px;
overflow: hidden;
width: 200px;
}
.divone{
display: table-cell;
margin: 0 auto;
text-align: center;
vertical-align: middle;
width: 100%;
}
img {
width: 100%;
height: 410px;
}
.wrapper {
position: absolute;
}
The exception message says you're trying to connect to the same host (127.0.0.1), while you're stating that your server is running on a different host. Besides the obvious bugs like having "localhost" in the url, or maybe some you might want to check your DNS settings.
Engine must be before select:
CREATE TEMPORARY TABLE temp1 ENGINE=MEMORY
as (select * from table1)
I have a sheet that is made to used by others and I have quite a few indirect() references around, so I need to formulaically handle a changed sheet tab name.
I used the formula from JohnP2 (below) but was having trouble because it didn't update automatically when a sheet name was changed. You need to go to the actual formula, make an arbitrary change and refresh to run it again.
=REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1")
I solved this by using info found in this solution on how to force a function to refresh. It may not be the most elegant solution, but it forced Sheets to pay attention to this cell and update it regularly, so that it catches an updated sheet title.
=IF(TODAY()=TODAY(), REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1"), "")
Using this, Sheets know to refresh this cell every time you make a change, which results in the address being updated whenever it gets renamed by a user.
Try something like that:
if (Request.Cookies["userId"] != null)
{
Response.Cookies["userId"].Expires = DateTime.Now.AddDays(-1);
}
But it also makes sense to use
Session.Abandon();
besides in many scenarios.
I've been looking into this problem further, and you simply need to grab all the appropriate DLL's from the same downloaded version of ODP.Net and put them in the same folder as your Exe file, because ODP.Net is fussy about not mixing version numbers.
I've explained how to do this here: http://splinter.com.au/using-the-new-odpnet-to-access-oracle-from-c Here's the gist of it though:
There's also xmlstarlet (which is available for Windows as well).
This
PRIMARY KEY (
id
(11))
is generated automatically by phpmyadmin, change to
PRIMARY KEY (
id
)
.
Seen from a non-PHP guru perspective, this should do exactly what us desired to:
<style>
[name$='pdf'] { width:100%; height: auto;}
</style>
The primary issue is that underlying hardware, the CPU, only has instructions to compare two signed values or compare two unsigned values. If you pass the unsigned comparison instruction a signed, negative value, it will treat it as a large positive number. So, -1, the bit pattern with all bits on (twos complement), becomes the maximum unsigned value for the same number of bits.
8-bits: -1 signed is the same bits as 255 unsigned 16-bits: -1 signed is the same bits as 65535 unsigned etc.
So, if you have the following code:
int fd;
fd = open( .... );
int cnt;
SomeType buf;
cnt = read( fd, &buf, sizeof(buf) );
if( cnt < sizeof(buf) ) {
perror("read error");
}
you will find that if the read(2) call fails due to the file descriptor becoming invalid (or some other error), that cnt will be set to -1. When comparing to sizeof(buf), an unsigned value, the if() statement will be false because 0xffffffff is not less than sizeof() some (reasonable, not concocted to be max size) data structure.
Thus, you have to write the above if, to remove the signed/unsigned warning as:
if( cnt < 0 || (size_t)cnt < sizeof(buf) ) {
perror("read error");
}
This just speaks loudly to the problems.
1. Introduction of size_t and other datatypes was crafted to mostly work,
not engineered, with language changes, to be explicitly robust and
fool proof.
2. Overall, C/C++ data types should just be signed, as Java correctly
implemented.
If you have values so large that you can't find a signed value type that works, you are using too small of a processor or too large of a magnitude of values in your language of choice. If, like with money, every digit counts, there are systems to use in most languages which provide you infinite digits of precision. C/C++ just doesn't do this well, and you have to be very explicit about everything around types as mentioned in many of the other answers here.
you can use solutions without adding "Access-Control-Allow-Origin": "*", if your server is already using Proxy gateway this issue will not happen because the front and backend will be route in the same IP and port in client side but for development, you need one of this three solution if you don't need extra code 1- simulate the real environment by using a proxy server and configure the front and backend in the same port
2- if you using Chrome you can use the extension called Allow-Control-Allow-Origin: * it will help you to avoid this problem
3- you can use the code but some browsers versions may not support that so try to use one of the previous solutions
the best solution is using a proxy like ngnix its easy to configure and it will simulate the real situation of the production deployment
You can make a multiple messages and with different types. Follow these steps below:
app/Components/FlashMessages.php
"namespace App\Components; trait FlashMessages { protected static function message($level = 'info', $message = null) { if (session()->has('messages')) { $messages = session()->pull('messages'); } $messages[] = $message = ['level' => $level, 'message' => $message]; session()->flash('messages', $messages); return $message; } protected static function messages() { return self::hasMessages() ? session()->pull('messages') : []; } protected static function hasMessages() { return session()->has('messages'); } protected static function success($message) { return self::message('success', $message); } protected static function info($message) { return self::message('info', $message); } protected static function warning($message) { return self::message('warning', $message); } protected static function danger($message) { return self::message('danger', $message); } }
app/Http/Controllers/Controller.php
".namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesResources; use App\Components\FlashMessages; class Controller extends BaseController { use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests; use FlashMessages; }
This will make the FlashMessages
trait available to all controllers that extending this class.
views/partials/messages.blade.php
"@if (count($messages)) <div class="row"> <div class="col-md-12"> @foreach ($messages as $message) <div class="alert alert-{{ $message['level'] }}">{!! $message['message'] !!}</div> @endforeach </div> </div> @endif
boot()
" method of "app/Providers/AppServiceProvider.php
":namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Components\FlashMessages; class AppServiceProvider extends ServiceProvider { use FlashMessages; public function boot() { view()->composer('partials.messages', function ($view) { $messages = self::messages(); return $view->with('messages', $messages); }); } ... }
This will make the $messages
variable available to "views/partials/message.blade.php
" template whenever it is called.
views/partials/messages.blade.php
"<div class="row"> <p>Page title goes here</p> </div> @include ('partials.messages') <div class="row"> <div class="col-md-12"> Page content goes here </div> </div>
You only need to include the messages template wherever you want to display the messages on your page.
use App\Components\FlashMessages; class ProductsController { use FlashMessages; public function store(Request $request) { self::message('info', 'Just a plain message.'); self::message('success', 'Item has been added.'); self::message('warning', 'Service is currently under maintenance.'); self::message('danger', 'An unknown error occured.'); //or self::info('Just a plain message.'); self::success('Item has been added.'); self::warning('Service is currently under maintenance.'); self::danger('An unknown error occured.'); } ...
Hope it'l help you.
There is no way that you can do it in PHP when HTML is already generated. What you can do is to use JavaScript or jQuery:
document.getElementById('//ID//').innerHTML="HTML CODE";
If you have to do it when your URI changes you can get the URI and then split it and then insert the HTML in script dynamically:
var url = document.URL;
// to get url and then use split() to check the parameter
None of the examples above create 8-bit (8bpp) bitmap images. Some software, such as image processing, only supports 8bpp. Unfortunately the MS .NET libraries do not have a solution. The PixelFormat.Format8bppIndexed format looks promising but after a lot of attempts I couldn't get it working.
To create a true 8-bit bitmap file you need to create the proper headers. Ultimately I found the Grayscale library solution for creating 8-bit bitmap (BMP) files. The code is very simple:
Image image = Image.FromFile("c:/path/to/image.jpg");
GrayBMP_File.CreateGrayBitmapFile(image, "c:/path/to/8bpp/image.bmp");
The code for this project is far from pretty but it works, with one little simple-to-fix problem. The author hard-coded the image resolution to 10x10. Image processing programs do not like this. The fix is open GrayBMP_File.cs (yeah, funky file naming, I know) and replace lines 50 and 51 with the code below. The example sets the resolution to 200x200 but you should change it to the proper number.
int resX = 200;
int resY = 200;
// horizontal resolution
Copy_to_Index(DIB_header, BitConverter.GetBytes(resX * 100), 24);
// vertical resolution
Copy_to_Index(DIB_header, BitConverter.GetBytes(resY * 100), 28);
if you use div and span it will occupy more code size when the datagrid-table row are more in volume. This below code is checked in all browsers
HTML:
<div id="gridheading">
<h4>Sl.No</h4><h4 class="big">Name</h4><h4>Location</h4><h4>column</h4><h4>column</h4><h4>column</h4><h4>Amount(Rs)</h4><h4>View</h4><h4>Edit</h4><h4>Delete</h4>
</div>
<div class="data">
<h4>01</h4><h4 class="big">test</h4><h4>TVM</h4><h4>A</h4><h4>I</h4><h4>4575</h4><h4>4575</h4></div>
<div class="data">
<h4>01</h4><h4 class="big">test</h4><h4>TVM</h4><h4>A</h4><h4>I</h4><h4>4575</h4><h4>4575</h4></div>
CSS:
#gridheading {
background: #ccc;
border-bottom: 1px dotted #BBBBBB;
font-size: 12px;
line-height: 30px;
text-transform: capitalize;
}
.data {
border-bottom: 1px dotted #BBBBBB;
display: block;
font-weight: normal;
line-height: 20px;
text-align: left;
word-wrap: break-word;
}
h4 {
border-right: thin dotted #000000;
display: table-cell;
margin-right: 100px;
text-align: center;
width: 100px;
word-wrap: break-word;
}
.data .big {
margin-right: 150px;
width: 200px;
}
Error jet 4 oledb It Can be possible upgrade kb4041678 kb4041681
If you have spaces in the filename, try these:
[file](./file%20with%20spaces.md)
[file](<./file with spaces.md>)
First one seems more reliable
Use the enumerate()
function to generate the index along with the elements of the sequence you are looping over:
for index, w in enumerate(loopme):
print "CURRENT WORD IS", w, "AT CHARACTER", index
window.load = function(){}
Its fully supported by all browsers, and it will fire an event when all images are fully loaded.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
If you using RadAjaxManager then here is the code which helps:
RadAjaxManager1.ResponseScripts.Add("window.opener.location.href = '../CaseManagement/LCCase.aspx?" + caseId + "';
window.close();");
Searching for created_at <= '2011-12-06'
will search for any records that where created at or before midnight on 2011-12-06
. You want to search for created_at < '2011-12-07'
.
this answers not working for new updated intelliJ... for new intelliJ..
Go to --> file --> Project Structure --> Global Libraries ==> set to JDK 1.8 or higher version.
also File -- > project Structure ---> projects ===> set "project language manual" to 8
also File -- > project Structure ---> project sdk ==> 1.8
This should enable lambda expression for your project.
If you want an integer, try this code:
import datetime
print(datetime.datetime.now().strftime("%s%f")[:13])
Output:
1545474382803
As documented in ?legend
you do this like so:
plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)
Line breaks are achieved with the new line character \n
. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.
Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).
The best way to get the text value from a <label>
element is as follows.
if you will be getting element ids frequently it's best to have a function to return the ids:
function id(e){return document.getElementById(e)}
Assume the following structure:
<label for='phone'>Phone number</label>
<input type='text' id='phone' placeholder='Mobile or landline numbers...'>
This code will extract the text value 'Phone number' from the<label>:
var text = id('phone').previousElementSibling.innerHTML;
This code works on all browsers, and you don't have to give each<label>
element a unique id.
For macOS Mojave , additional configuration was required, for compilers to find openssl you may need to set:
export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
Make sure your body has a height, f.ex:
body {
background: url(/img/debut_dark.png) repeat;
min-height: 100%;
}
Balanced tree is a tree whose height is of order of log(number of elements in the tree).
height = O(log(n))
O, as in asymptotic notation i.e. height should have same or lower asymptotic
growth rate than log(n)
n: number of elements in the tree
The definition given "a tree is balanced of each sub-tree is balanced and the height of the two sub-trees differ by at most one" is followed by AVL trees.
Since, AVL trees are balanced but not all balanced trees are AVL trees, balanced trees don't hold this definition and internal nodes can be unbalanced in them. However, AVL trees require all internal nodes to be balanced.
You can combine the check and cast into one statement:
let touch = object.anyObject() as UITouch
if let picker = touch.view as? UIPickerView {
...
}
Then you can use picker
within the if
block.
I was curious how fast would be the obvious raw rotation.
On my machine (i7@2600), the average for 1,500,150,000 iterations was 27.28 ns
(over a a random set of 131,071 64-bit integers).
Advantages: the amount of memory needed is little and the code is simple. I would say it is not that large, either. The time required is predictable and constant for any input (128 arithmetic SHIFT operations + 64 logical AND operations + 64 logical OR operations).
I compared to the best time obtained by @Matt J - who has the accepted answer. If I read his answer correctly, the best he has got was 0.631739
seconds for 1,000,000
iterations, which leads to an average of 631 ns
per rotation.
The code snippet I used is this one below:
unsigned long long reverse_long(unsigned long long x)
{
return (((x >> 0) & 1) << 63) |
(((x >> 1) & 1) << 62) |
(((x >> 2) & 1) << 61) |
(((x >> 3) & 1) << 60) |
(((x >> 4) & 1) << 59) |
(((x >> 5) & 1) << 58) |
(((x >> 6) & 1) << 57) |
(((x >> 7) & 1) << 56) |
(((x >> 8) & 1) << 55) |
(((x >> 9) & 1) << 54) |
(((x >> 10) & 1) << 53) |
(((x >> 11) & 1) << 52) |
(((x >> 12) & 1) << 51) |
(((x >> 13) & 1) << 50) |
(((x >> 14) & 1) << 49) |
(((x >> 15) & 1) << 48) |
(((x >> 16) & 1) << 47) |
(((x >> 17) & 1) << 46) |
(((x >> 18) & 1) << 45) |
(((x >> 19) & 1) << 44) |
(((x >> 20) & 1) << 43) |
(((x >> 21) & 1) << 42) |
(((x >> 22) & 1) << 41) |
(((x >> 23) & 1) << 40) |
(((x >> 24) & 1) << 39) |
(((x >> 25) & 1) << 38) |
(((x >> 26) & 1) << 37) |
(((x >> 27) & 1) << 36) |
(((x >> 28) & 1) << 35) |
(((x >> 29) & 1) << 34) |
(((x >> 30) & 1) << 33) |
(((x >> 31) & 1) << 32) |
(((x >> 32) & 1) << 31) |
(((x >> 33) & 1) << 30) |
(((x >> 34) & 1) << 29) |
(((x >> 35) & 1) << 28) |
(((x >> 36) & 1) << 27) |
(((x >> 37) & 1) << 26) |
(((x >> 38) & 1) << 25) |
(((x >> 39) & 1) << 24) |
(((x >> 40) & 1) << 23) |
(((x >> 41) & 1) << 22) |
(((x >> 42) & 1) << 21) |
(((x >> 43) & 1) << 20) |
(((x >> 44) & 1) << 19) |
(((x >> 45) & 1) << 18) |
(((x >> 46) & 1) << 17) |
(((x >> 47) & 1) << 16) |
(((x >> 48) & 1) << 15) |
(((x >> 49) & 1) << 14) |
(((x >> 50) & 1) << 13) |
(((x >> 51) & 1) << 12) |
(((x >> 52) & 1) << 11) |
(((x >> 53) & 1) << 10) |
(((x >> 54) & 1) << 9) |
(((x >> 55) & 1) << 8) |
(((x >> 56) & 1) << 7) |
(((x >> 57) & 1) << 6) |
(((x >> 58) & 1) << 5) |
(((x >> 59) & 1) << 4) |
(((x >> 60) & 1) << 3) |
(((x >> 61) & 1) << 2) |
(((x >> 62) & 1) << 1) |
(((x >> 63) & 1) << 0);
}
Assuming you don't want to eject and you just want to look at the config you will find them in /node_modules/react-scripts/config
webpack.config.dev.js. //used by `npm start`
webpack.config.prod.js //used by `npm run build`
This worked for me in Angular 2:
var img = new Image()
img.src = 'assets/sample.png'
pdf.addImage(img, 'png', 10, 78, 12, 15)
jsPDF version 1.5.3
assets directory is in src directory of the Angular project root
Install qt using:
sudo apt install qt5-qmake
Open ~/.bashrc
file:
vim ~/.bashrc
Added the path below to the ~/.bashrc
file:
export PATH="/opt/Qt/5.15.1/gcc_64/bin/:$PATH"
Execute/load a ~/.bashrc
file in your current shell
source ~/.bashrc`
Try now qmake
by using the version command below:
qmake --version
This should work:
$("#datepicker").datepicker("setDate", new Date());
And for autoclose (fiddle):
$('#datepicker').datepicker({
"setDate": new Date(),
"autoclose": true
});
To fit to the visible markers only, I've this method.
fitMapBounds() {
// Get all visible Markers
const visibleMarkers = [];
this.map.eachLayer(function (layer) {
if (layer instanceof L.Marker) {
visibleMarkers.push(layer);
}
});
// Ensure there's at least one visible Marker
if (visibleMarkers.length > 0) {
// Create bounds from first Marker then extend it with the rest
const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
visibleMarkers.forEach((marker) => {
markersBounds.extend(marker.getLatLng());
});
// Fit the map with the visible markers bounds
this.map.flyToBounds(markersBounds, {
padding: L.point(36, 36), animate: true,
});
}
}
I've written a simple wrapper around git-checkout-index
that you can use like this:
git export ~/the/destination/dir
If the destination directory already exists, you'll need to add -f
or --force
.
Installation is simple; just drop the script somewhere in your PATH
, and make sure it's executable.
JDK (Java Development Kit) :
JRE (Java Runtime Environment)
Java Runtime Environment contains JVM, class libraries, and other supporting files. JRE is targeted for execution of Java files.
JVM (Java Virtual Machine)
The JVM interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… Java Virtual Machine provides a platform-independent way of executing code.
You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.
I am a beginner in iPhone apps and I still have an issue although I followed the above advices. It looks like POST variables are not received by my server - not sure if it comes from php or objective-c code ...
the objective-c part (coded following Chris' protocol methodo)
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.php"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
// This is how we set header fields
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:@"user_name=%@&password=%@", self.userNameField.text , self.passwordTextField.text];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(@"Response: %@",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
Below the php part :
if (isset($_POST['user_name'],$_POST['password']))
{
// Create connection
$con2=mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// retrieve POST vars
$username = $_POST['user_name'];
$password = $_POST['password'];
$sql = "INSERT INTO myTable (user_name, password) VALUES ('$username', '$password')";
$retval = mysqli_query( $sql, $con2 );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysqli_close($con2);
}
}
else
{
echo "No data input in php";
}
I have been stuck the last days on this one.
const arr = JSON.parse(json);
obj.id = obj._id;
delete obj._id;
All together:
function renameKey ( obj, oldKey, newKey ) {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
}
const json = `
[
{
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
},
{
"_id":"5078c3a803ff4197dc81fbfc",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 2"
}
]
`;
const arr = JSON.parse(json);
arr.forEach( obj => renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );
console.log( updatedJson );
_x000D_
select * from SHOW VARIABLES WHERE Variable_name = 'hostname';
Updated February 2021
Just go to the official Node.js site (nodejs.org), download and execute the installer program.
It will take care of everything and with a few clicks of 'Next' you'll get the latest Node.js version running on your machine. Since 2020 it's the recommended way to update NodeJS. It's the easiest and least frustrating solution.
Pro tips
NodeJS installation includes NPM (Node package manager).
To check your NPM version use npm version
or node --version
.
If you prefer CLI, to update NPM use npm install -g npm
and then npm install -g node
.
For more details, see the docs for install
command.
Keep an eye on NodeJS blog - Vulnerabilities so you don't miss important security releases. Keep your NodeJS up-to-date.
Operating systems supported by Node.js: Windows, Linux, MacOS, SunOS, IBM AIX.
For Docker users, here's the official Node.js image.
Troubleshooting for Windows:
If anyone gets file error 2502/2503 like myself during install, run the .msi via Administrator command prompt with command
msiexec /package [node msi]
If my answer is helpful, don't forget to upvote it
(here is the original answer by Anmol Saraf, upvote it too)
I think the best way to do this with basic R is:
for( i in rownames(df) )
print(df[i, "column1"])
The advantage over the for( i in 1:nrow(df))
-approach is that you do not get into trouble if df
is empty and nrow(df)=0
.
decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(".ToString(\"C\") Formates With Currency $ Sign");
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450
Console.WriteLine();
Console.WriteLine(".ToString(\"F\") Formates With out Currency Sign");
Console.WriteLine(value.ToString("F"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F1"));
//OutPut : 12345.1
Console.WriteLine(value.ToString("F2"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F3"));
//OutPut : 12345.123
Console.WriteLine(value.ToString("F4"));
//OutPut : 12345.1234
Console.WriteLine(value.ToString("F5"));
//OutPut : 12345.12345
Console.WriteLine(value.ToString("F6"));
//OutPut : 12345.123450
Console.Read();
Tim Storer wrote a more flexible and nicer looking timeline.sty
(Internet Archive Wayback Machine link, as original is gone). In addition, the line is horizontal rather than vertical. So for instance:
\begin{timeline}{2008}{2010}{50}{250}
\MonthAndYearEvent{4}{2008}{First Podcast}
\MonthAndYearEvent{7}{2008}{Private Beta}
\MonthAndYearEvent{9}{2008}{Public Beta}
\YearEvent{2009}{IPO?}
\end{timeline}
produces a timeline that looks like this:
2008 2010
· · April, 2008 First Podcast ·
· July, 2008 Private Beta
· September, 2008 Public Beta
· 2009 IPO?
Personally, I find this a more pleasing solution than the other answers. But I also find myself modifying the code to get something closer to what I think a timeline should look like. So there's not definitive solution in my opinion.
I profiled a few methods to move an item within the same list with timeit. Here are the ones to use if j>i:
+---------------------------------+ ¦ 14.4usec ¦ x[i:i]=x.pop(j), ¦ ¦ 14.5usec ¦ x[i:i]=[x.pop(j)] ¦ ¦ 15.2usec ¦ x.insert(i,x.pop(j)) ¦ +---------------------------------+
and here the ones to use if j<=i:
+--------------------------------------+ ¦ 14.4usec ¦ x[i:i]=x[j],;del x[j] ¦ ¦ 14.4usec ¦ x[i:i]=[x[j]];del x[j] ¦ ¦ 15.4usec ¦ x.insert(i,x[j]);del x[j] ¦ +--------------------------------------+
Not a huge difference if you only use it a few times, but if you do heavy stuff like manual sorting, it's important to take the fastest one. Otherwise, I'd recommend just taking the one that you think is most readable.
This is how its looks
Inside your Adapter
private int selectedPosition = -1;
And onBindViewHolder
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
if (selectedPosition == position) {
holder.itemView.setSelected(true); //using selector drawable
holder.tvText.setTextColor(ContextCompat.getColor(holder.tvText.getContext(),R.color.white));
} else {
holder.itemView.setSelected(false);
holder.tvText.setTextColor(ContextCompat.getColor(holder.tvText.getContext(),R.color.black));
}
holder.itemView.setOnClickListener(v -> {
if (selectedPosition >= 0)
notifyItemChanged(selectedPosition);
selectedPosition = holder.getAdapterPosition();
notifyItemChanged(selectedPosition);
});
}
Thats it! As you can see i am just Notifying(updating) previous selected item and newly selected item
My Drawable set it as a background for recyclerview child views
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:state_selected="true">
<shape android:shape="rectangle">
<solid android:color="@color/blue" />
</shape>
</item>
A little late to the game, but I've written a class setlist
as part of collections-extended
that fully implements both Sequence
and Set
>>> from collections_extended import setlist
>>> sl = setlist('abracadabra')
>>> sl
setlist(('a', 'b', 'r', 'c', 'd'))
>>> sl[3]
'c'
>>> sl[-1]
'd'
>>> 'r' in sl # testing for inclusion is fast
True
>>> sl.index('d') # so is finding the index of an element
4
>>> sl.insert(1, 'd') # inserting an element already in raises a ValueError
ValueError
>>> sl.index('d')
4
GitHub: https://github.com/mlenzen/collections-extended
Documentation: http://collections-extended.lenzm.net/en/latest/
Get this error at the time of adding Node in my Angular project -
TSError: ? Unable to compile TypeScript: (path)/base.api.ts:19:13 - error TS2564: Property 'apiRoot Path' has no initializer and is not definitely assigned in the constructor.
private apiRootPath: string;
Solution -
Added "strictPropertyInitialization": false
in 'compilerOptions' of tsconfig.json.
my package.json -
"dependencies": {
...
"@angular/common": "~10.1.3",
"@types/express": "^4.17.9",
"express": "^4.17.1",
...
}
This is most likely not an answer to the issue itself but this question pops up as first result when searching for Sql declare scalar variable
hence i share a possible solution to this error.
In my case this error was caused by the use of ;
after a SQL statement. Just remove it and the error will be gone.
I guess the cause is the same as @IronSean already posted in an comment above:
it's worth noting that using GO (or in this case ;) causes a new branch where declared variables aren't visible past the statement.
For example:
DECLARE @id int
SET @id = 78
SELECT * FROM MyTable WHERE Id = @var; <-- remove this character to avoid the error message
SELECT * FROM AnotherTable WHERE MyTableId = @var
I know this thread is too old but recently I was wondering how to delete eclipse
app on my MacBook Pro
running macOS High Sierra
.
Bellow are the steps which I followed to delete it from my system. Added screenshots for more clear understanding.
Open the eclipse app and it will show an app icon in dock. If it is not already present in dock then please try to run the app from Spotlight Search
by pressing ?
+ space
.
Now right click on that eclipse logo from dock and click Show in Finder
under Options
.
eclipse
app in an external finder window.eclipse
) by pressing ?
+ delete
.Trash
as well if you are removing it from system completely.Thanks. Hope this helped.
Presumably you're passing the arguments in on the command line as follows:
php /path/to/wwwpublic/path/to/script.php arg1 arg2
... and then accessing them in the script thusly:
<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>
What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:
Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2
... and access:
<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>
If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:
EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:
<?php
if (PHP_SAPI === 'cli') {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
else {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
}
?>
You can also use:
import socket
socket.gethostname()
This is working fine for me,
I'm not entirely sure how it works. I believe this is a bit more low level and will return your server hostname, which might be different than the hostname used by your user to get to your page.
Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)
Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);
Is's better because getOne(ID id)
gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save()
it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find()
like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.
It is like
<?php
use yii\helpers\ArrayHelper;
use backend\models\Standard;
?>
<?= Html::activeDropDownList($model, 's_id',
ArrayHelper::map(Standard::find()->all(), 's_id', 'name')) ?>
ArrayHelper in Yii2 replaces the CHtml list data in Yii 1.1.[Please load array data from your controller]
EDIT
Load data from your controller.
Controller
$items = ArrayHelper::map(Standard::find()->all(), 's_id', 'name');
...
return $this->render('your_view',['model'=>$model, 'items'=>$items]);
In View
<?= Html::activeDropDownList($model, 's_id',$items) ?>
'SET' is forgotten
ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';
call: getStackTraceAsString(sqlEx)
public String getStackTraceAsString(Exception exc)
{
String stackTrace = "*** Error in getStackTraceAsString()";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream( baos );
exc.printStackTrace(ps);
try {
stackTrace = baos.toString( "UTF8" ); // charsetName e.g. ISO-8859-1
}
catch( UnsupportedEncodingException ex )
{
Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
}
ps.close();
try {
baos.close();
}
catch( IOException ex )
{
Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
}
return stackTrace;
}
The following syntax fixes it for you:
curl -v -F key1=value1 -F upload=@localfilename URL
Th easiest way to this is var id = $(this).val(); from inside an event like on change.
Along with forEach
method that accepts a lambda expression we have also got stream APIs, in Java 8.
Iterate over entries (Using forEach and Streams):
sample.forEach((k,v) -> System.out.println(k + "=" + v));
sample.entrySet().stream().forEachOrdered((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
System.out.println(currentKey + "=" + currentValue);
});
sample.entrySet().parallelStream().forEach((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
System.out.println(currentKey + "=" + currentValue);
});
The advantage with streams is they can be parallelized easily and can be useful when we have multiple CPUs at disposal. We simply need to use parallelStream()
in place of stream()
above. With parallel streams it makes more sense to use forEach
as forEachOrdered
would make no difference in performance. If we want to iterate over keys we can use sample.keySet()
and for values sample.values()
.
Why forEachOrdered
and not forEach
with streams ?
Streams also provide forEach
method but the behaviour of forEach
is explicitly nondeterministic where as the forEachOrdered
performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach
does not guarantee that the order would be kept. Also check this for more.
$('input[type="button"]').click(function (e) {
if (e.target) {
alert(e.target.id + ' clicked');
}
});
you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.
Giving write permissions to all IIS_USRS group is a bad idea from the security point of view. You dont need to do that and you can go with giving permissions only to system user running the application pool.
If you are using II7 (and I guess you do) do the following.
Note #1: if you see ApplicationPoolIdentity in #3 you need to reference this system user like this IIS AppPool{application_pool_name} . For example IIS AppPool\DefaultAppPool
Note #2: when adding this user make sure to set correct locations in the Select Users or Groups dialog. This needs to be set to local machine because this is local account.
It's worth noting that your code does insert a space
h2::after {
content: " ";
}
However, it's immediately removed.
From Anonymous inline boxes,
White space content that would subsequently be collapsed away according to the 'white-space' property does not generate any anonymous inline boxes.
And from The 'white-space' processing model,
If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.
So if you don't want the space to be removed, set white-space
to pre
or pre-wrap
.
h2 {_x000D_
text-decoration: underline;_x000D_
}_x000D_
h2.space::after {_x000D_
content: " ";_x000D_
white-space: pre;_x000D_
}
_x000D_
<h2>I don't have space:</h2>_x000D_
<h2 class="space">I have space:</h2>
_x000D_
Do not use non-breaking spaces (U+00a0). They are supposed to prevent line breaks between words. They are not supposed to be used as non-collapsible space, that wouldn't be semantic.
It's an old post but I none of this solution worked for me so I'm posting my solution if anyone find this helpful.
I just had the same problem.
In my case the control I needed to disable was a user control with child dropdowns which I could disable in IE but not in chrome.
my solution was to disable each child object, not just the usercontrol, with that code:
$('#controlName').find('*').each(function () { $(this).attr("disabled", true); })
It's working for me in chrome now.
Here's an answer, based on (and I think an improvement on) Tester101's answer, expressed as a subroutine, with the CopyFile line once instead of three times, and prepared to handle changing the file name as the copy is made (no hard-coded destination directory). I also found I had to delete the target file before copying to get this to work, but that might be a Windows 7 thing. The WScript.Echo statements are because I didn't have a debugger and can of course be removed if desired.
Sub CopyFile(SourceFile, DestinationFile)
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file already exists in the destination folder
Dim wasReadOnly
wasReadOnly = False
If fso.FileExists(DestinationFile) Then
'Check to see if the file is read-only
If fso.GetFile(DestinationFile).Attributes And 1 Then
'The file exists and is read-only.
WScript.Echo "Removing the read-only attribute"
'Remove the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
wasReadOnly = True
End If
WScript.Echo "Deleting the file"
fso.DeleteFile DestinationFile, True
End If
'Copy the file
WScript.Echo "Copying " & SourceFile & " to " & DestinationFile
fso.CopyFile SourceFile, DestinationFile, True
If wasReadOnly Then
'Reapply the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
Set fso = Nothing
End Sub
For me it only fetched new dependencies from Docker Hub with both --no-cache
and --pull
(which are available for docker-compose build
.
# other steps before rebuild
docker-compose build --no-cache --pull nginx # rebuild nginx
# other steps after rebuild, e.g. up (see other answers)
You can Use KeyPress instead of KeyUp or KeyDown its more efficient and here's how to handle
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
button1.PerformClick();
}
}
hope it works
Other option, for similar example but with anidated selects, think that you have two select, the name of the first is "ea_pub_dest" and the name of the second is "ea_pub_dest_2", ok, now take the event click of the first and display the second.
<script>
function test()
{
value = document.getElementById("ea_pub_dest").value;
if ( valor == "value_1" )
document.getElementById("ea_pub_dest_nivel").style.display = "block";
}
</script>
Try to use this.$router.go(0);
to manually reload the current page.
You can use regular expressions. Here is the function with @janm's suggestions.
class String
def is_i?
!!(self =~ /\A[-+]?[0-9]+\z/)
end
end
An edited version according to comment from @wich:
class String
def is_i?
/\A[-+]?\d+\z/ === self
end
end
In case you only need to check positive numbers
if !/\A\d+\z/.match(string_to_check)
#Is not a positive number
else
#Is all good ..continue
end
In Kotlin, an E-mail address you can validate by the simple method without writing a lot of code and bother yourself with a regular expression like "^[_A-Za-z0-9-\+]....".
Look how is simple:
fun validateEmail(emailForValidation: String): Boolean{
return Patterns.EMAIL_ADDRESS.matcher(emailForValidation).matches()
}
After you write this method for e-mail validation you just need to input your e-mail which you want to validate. If validateEmail() method returns true e-mail is valid and if false then e-mail is not valid.
Here is example how you can use this method:
val eMail: String = emailEditText.text.toString().trim()
if (!validateEmail(eMail)){ //IF NOT TRUE
Toast.makeText(context, "Please enter valid E-mail address", Toast.LENGTH_LONG).show()
return //RETURNS BACK TO IF STATEMENT
}
Replace @Restcontroller
with @controller
. @Restcontroller
returns only content not html and jsp pages.
Lists of bytes are subscriptable (at least in Python 3.6). This way you can retrieve the decimal value of each byte individually.
>>> intlist = [64, 4, 26, 163, 255]
>>> bytelist = bytes(intlist) # b'@x04\x1a\xa3\xff'
>>> for b in bytelist:
... print(b) # 64 4 26 163 255
>>> [b for b in bytelist] # [64, 4, 26, 163, 255]
>>> bytelist[2] # 26
For older versions of jQuery
jQuery().jquery (or)
jQuery().fn.jquery
For newer versions of jQuery
$().jquery (or)
$().fn.jquery
Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.
An alternative option is to set it in the machine level web.config, so its not even in the web site folder.
To generate it do it just like the linked article in David's answer.
Computer Management->Shared Folders->Open Files
cp -r /home/server/folder/test /home/server/
I was having this problem with sort in cygwin in a bash shell when using 'general-numeric-sort'. If I specified -t$'\t' -kFg
, where F is the field number, it didn't work, but when I specified both -t$'\t'
and -kF,Fg
(e.g -k7,7g
for the 7th field) it did work. -kF,Fg
without the -t$'\t'
did not work.
You could also use a graphic image one pixel wide as the gradient, and set the view property to expand the graphic to fill the view (assuming you are thinking of a simple linear gradient and not some kind of radial graphic).
You can use css and the :hover pseudo-property. Here is a simple demo. It uses the following css:
a span.tooltip {display:none;}
a:hover span.tooltip {position:absolute;top:30px;left:20px;display:inline;border:2px solid green;}
Note that older browsers have limited support for :hover.
A convenient string builder for c++
Like many people answered before, std::stringstream is the method of choice. It works good and has a lot of conversion and formatting options. IMO it has one pretty inconvenient flaw though: You can not use it as a one liner or as an expression. You always have to write:
std::stringstream ss;
ss << "my data " << 42;
std::string myString( ss.str() );
which is pretty annoying, especially when you want to initialize strings in the constructor.
The reason is, that a) std::stringstream has no conversion operator to std::string and b) the operator << ()'s of the stringstream don't return a stringstream reference, but a std::ostream reference instead - which can not be further computed as a string stream.
The solution is to override std::stringstream and to give it better matching operators:
namespace NsStringBuilder {
template<typename T> class basic_stringstream : public std::basic_stringstream<T>
{
public:
basic_stringstream() {}
operator const std::basic_string<T> () const { return std::basic_stringstream<T>::str(); }
basic_stringstream<T>& operator<< (bool _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (char _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (signed char _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (unsigned char _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (short _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (unsigned short _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (int _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (unsigned int _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (long _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (unsigned long _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (long long _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (unsigned long long _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (float _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (double _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (long double _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (void* _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (std::streambuf* _val) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (std::ostream& (*_val)(std::ostream&)) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (std::ios& (*_val)(std::ios&)) { std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (std::ios_base& (*_val)(std::ios_base&)){ std::basic_stringstream<T>::operator << (_val); return *this; }
basic_stringstream<T>& operator<< (const T* _val) { return static_cast<basic_stringstream<T>&>(std::operator << (*this,_val)); }
basic_stringstream<T>& operator<< (const std::basic_string<T>& _val) { return static_cast<basic_stringstream<T>&>(std::operator << (*this,_val.c_str())); }
};
typedef basic_stringstream<char> stringstream;
typedef basic_stringstream<wchar_t> wstringstream;
}
With this, you can write things like
std::string myString( NsStringBuilder::stringstream() << "my data " << 42 )
even in the constructor.
I have to confess I didn't measure the performance, since I have not used it in an environment which makes heavy use of string building yet, but I assume it won't be much worse than std::stringstream, since everything is done via references (except the conversion to string, but thats a copy operation in std::stringstream as well)
My Xcode Version 6.1.1 (6A2008a)
In playground, test like this:
// I'm in East Timezone 8
let x = NSDate() //Output:"Dec 29, 2014, 11:37 AM"
let y = NSDate.init() //Output:"Dec 29, 2014, 11:37 AM"
println(x) //Output:"2014-12-29 03:37:24 +0000"
// seconds since 2001
x.hash //Output:441,517,044
x.hashValue //Output:441,517,044
x.timeIntervalSinceReferenceDate //Output:441,517,044.875367
// seconds since 1970
x.timeIntervalSince1970 //Output:1,419,824,244.87537
The data container is a superfluous workaround. Data-volumes would do the trick for you. Alter your docker-compose.yml
to:
version: '2'
services:
mysql:
container_name: flask_mysql
restart: always
image: mysql:latest
environment:
MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this
MYSQL_USER: 'test'
MYSQL_PASS: 'pass'
volumes:
- my-datavolume:/var/lib/mysql
volumes:
my-datavolume:
Docker will create the volume for you in the /var/lib/docker/volumes
folder. This volume persist as long as you are not typing docker-compose down -v
For Ubuntu, you can try:
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
For Cent OS/RHEL try :
sudo yum install zlib.i686 ncurses-libs.i686 bzip2-libs.i686
Then, re-install the Android Studio and get success.
For Visual Studio 2019: I have done the following things to solve the problem
Backup the following Folder. After Taking backup and Delete This Folder C:\Users\munirul2537\AppData\Roaming\Microsoft\VisualStudio\16.0_add0ca51
Go to the installation panel of visual studio and do the following things
1.Go to install 2.Modify 3.Go to "Installation location" tab 4. Check "keep download cache after the installation" 5. Modify
Another thing it does is it makes it more obvious when reading the code that it is changing the behavior of the parent class. Than can help in debugging.
Also, in Joshua Block's book Effective Java (2nd edition), item 36 gives more details on the benefits of the annotation.
You can run the following, which will generate a set of ALTER sCHEMA statements for all your talbes:
SELECT 'ALTER SCHEMA dbo TRANSFER ' + TABLE_SCHEMA + '.' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'jonathan'
You then have to copy and run the statements in query analyzer.
Here's an older script that will do that for you, too, I think by changing the object owner. Haven't tried it on 2008, though.
DECLARE @old sysname, @new sysname, @sql varchar(1000)
SELECT
@old = 'jonathan'
, @new = 'dbo'
, @sql = '
IF EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLES
WHERE
QUOTENAME(TABLE_SCHEMA)+''.''+QUOTENAME(TABLE_NAME) = ''?''
AND TABLE_SCHEMA = ''' + @old + '''
)
EXECUTE sp_changeobjectowner ''?'', ''' + @new + ''''
EXECUTE sp_MSforeachtable @sql
Got it from this site.
It also talks about doing the same for stored procs if you need to.
You can simply use the return;
example
$(document).ready(function () {
alert(1);
return;
alert(2);
alert(3);
alert(4);
});
The return will return to the main caller function test1(); and continue from there to test3();
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script type="text/javascript">
function test1(){
test2();
test3();
}
function test2(){
alert(2);
return;
test4();
test5();
}
function test3(){
alert(3);
}
function test4(){
alert(4);
}
function test5(){
alert(5);
}
test1();
</script>
</body>
</html>
but if you just add throw ''; this will completely stop the execution without causing any errors.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script type="text/javascript">
function test1(){
test2();
test3();
}
function test2(){
alert(2);
throw '';
test4();
test5();
}
function test3(){
alert(3);
}
function test4(){
alert(4);
}
function test5(){
alert(5);
}
test1();
</script>
</body>
</html>
This is tested with firefox and chrome. I don't know how this is handled by IE or Safari
From the API (http://msdn.microsoft.com/en-us/library/system.datetime_members(VS.71).aspx) it does not seem it can show the name of the time zone used.
So before MySQL 8.0 there is no ROW_NUMBER() function. Accpted answer rewritten to support older versions of MySQL:
SET @row_number = 0;
SELECT t.A, t.B, t.C, (@row_number:=@row_number + 1) AS number
FROM dbo.tableZ AS t ORDER BY t.A;
This will do it:
window.history.pushState(null,null,'https://www.google.com');
So what's the problem,
It's a ’
(RIGHT SINGLE QUOTATION MARK
- U+2019) character which is being decoded as CP-1252 instead of UTF-8. If you check the encodings table, then you see that this character is in UTF-8 composed of bytes 0xE2
, 0x80
and 0x99
. If you check the CP-1252 code page layout, then you'll see that each of those bytes stand for the individual characters â
, €
and ™
.
and how can I fix it?
Use UTF-8 instead of CP-1252 to read, write, store, and display the characters.
I have the Content-Type set to UTF-8 in both my
<head>
tag and my HTTP headers:<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
This only instructs the client which encoding to use to interpret and display the characters. This doesn't instruct your own program which encoding to use to read, write, store, and display the characters in. The exact answer depends on the server side platform / database / programming language used. Do note that the one set in HTTP response header has precedence over the HTML meta tag. The HTML meta tag would only be used when the page is opened from local disk file system instead of from HTTP.
In addition, my browser is set to
Unicode (UTF-8)
:
This only forces the client which encoding to use to interpret and display the characters. But the actual problem is that you're already sending ’
(encoded in UTF-8) to the client instead of ’
. The client is correctly displaying ’
using the UTF-8 encoding. If the client was misinstructed to use, for example ISO-8859-1, you would likely have seen ââ¬â¢
instead.
I am using ASP.NET 2.0 with a database.
This is most likely where your problem lies. You need to verify with an independent database tool what the data looks like.
If the ’
character is there, then you aren't connecting to the database correctly. You need to tell the database connector to use UTF-8.
If your database contains ’
, then it's your database that's messed up. Most probably the tables aren't configured to use UTF-8
. Instead, they use the database's default encoding, which varies depending on the configuration. If this is your issue, then usually just altering the table to use UTF-8 is sufficient. If your database doesn't support that, you'll need to recreate the tables. It is good practice to set the encoding of the table when you create it.
You're most likely using SQL Server, but here is some MySQL code (copied from this article):
CREATE DATABASE db_name CHARACTER SET utf8;
CREATE TABLE tbl_name (...) CHARACTER SET utf8;
If your table is however already UTF-8, then you need to take a step back. Who or what put the data there. That's where the problem is. One example would be HTML form submitted values which are incorrectly encoded/decoded.
Here are some more links to learn more about the problem:
public static void main(String[] args) {
try {
String keystorePass = "20174";
String keyPass = "rav@789";
String alias = "TyaGi!";
InputStream keystoreStream = new FileInputStream("D:/keyFile.jks");
KeyStore keystore = KeyStore.getInstance("JCEKS");
keystore.load(keystoreStream, keystorePass.toCharArray());
Key key = keystore.getKey(alias, keyPass.toCharArray());
byte[] bt = key.getEncoded();
String s = new String(bt);
System.out.println("------>"+s);
String str12 = Base64.encodeBase64String(bt);
System.out.println("Fetched Key From JKS : " + str12);
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
System.out.println(ex);
}
}
I've never had a good memory for exact wording, but in my database class I think the professor always said something like:
The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF].
**multiple delete not working**
function delete_selection()
{
$id_array = array();
$selection = $this->input->post("selection", TRUE);
$id_array = explode("|", $selection);
foreach ($id_array as $item):
if ($item != ''):
//DELETE ROW
$this->db->where('entry_id', $item);
$this->db->delete('helpline_entry');
endif;
endforeach;
}
Simply add this to your css :-
.navbar-inner {
background:transparent;
}
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
For vector initialisation -
vector<int> v = {10,20,30}
can be done if you have C++11 compiler.
Else, you can have an array of the data and then use a for loop.
int array[] = {10,20,30}
for(unsigned int i=0; i<sizeof(array)/sizeof(array[0]); i++)
{
v.push_back(array[i]);
}
Apart from these, there are various other ways described above using some code. In my opinion, these ways are easy to remember and quick to write.
In some cases you may want the Rails root without having to load Rails.
For example, you get a quicker feedback cycle when TDD'ing models that do not depend on Rails by requiring spec_helper
instead of rails_helper
.
# spec/spec_helper.rb
require 'pathname'
rails_root = Pathname.new('..').expand_path(File.dirname(__FILE__))
[
rails_root.join('app', 'models'),
# Add your decorators, services, etc.
].each do |path|
$LOAD_PATH.unshift path.to_s
end
Which allows you to easily load Plain Old Ruby Objects from their spec files.
# spec/models/poro_spec.rb
require 'spec_helper'
require 'poro'
RSpec.describe ...
You miss the class declaration.
public class DerivativeQuiz{
public static void derivativeQuiz(String args[]){ ... }
}
Gradle looks for gradle.properties
files in these places:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradle
)Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).
Reference: https://gradle.org/docs/current/userguide/build_environment.html
You can use slice() for this:
>> foo = [1,2,3,4,5,6]
=> [1, 2, 3, 4, 5, 6]
>> bar = [10,20,30,40,50,60]
=> [10, 20, 30, 40, 50, 60]
>> half = foo.length / 2
=> 3
>> foobar = foo.slice(0, half) + bar.slice(half, foo.length)
=> [1, 2, 3, 40, 50, 60]
By the way, to the best of my knowledge, Python "lists" are just efficiently implemented dynamically growing arrays. Insertion at the beginning is in O(n), insertion at the end is amortized O(1), random access is O(1).
You can add this as an external tool to Visual Studio like so:
Title:
Get PublicKeyToken
Command:
c:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\sn.exe
(Path may differ between versions)
Arguments:
-T "$(TargetPath)"
And check the "Use Output window" option.
I was hoping to add this as a comment to Marcus Westin's reply, but I can't find a link - maybe I need more reputation?
Anyway, thanks, I found this code snippet useful for quick debugging in IE. I have made some quick tweaks to fix a problem that stopped it working for me, also to scroll down automatically and use fixed positioning so it will appear in the viewport. Here's my version in case anyone finds it useful:
myLog = function() {
var _div = null;
this.toJson = function(obj) {
if (typeof window.uneval == 'function') { return uneval(obj); }
if (typeof obj == 'object') {
if (!obj) { return 'null'; }
var list = [];
if (obj instanceof Array) {
for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
return '[' + list.join(',') + ']';
} else {
for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
return '{' + list.join(',') + '}';
}
} else if (typeof obj == 'string') {
return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
} else {
return new String(obj);
}
};
this.createDiv = function() {
myLog._div = document.body.appendChild(document.createElement('div'));
var props = {
position:'fixed', top:'10px', right:'10px', background:'#333', border:'5px solid #333',
color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
fontSize: '11px', whiteSpace: 'nowrap'
}
for (var key in props) { myLog._div.style[key] = props[key]; }
};
if (!myLog._div) { this.createDiv(); }
var logEntry = document.createElement('span');
for (var i=0; i < arguments.length; i++) {
logEntry.innerHTML += this.toJson(arguments[i]) + '<br />';
}
logEntry.innerHTML += '<br />';
myLog._div.appendChild(logEntry);
// Scroll automatically to the bottom
myLog._div.scrollTop = myLog._div.scrollHeight;
}
You have to use operating system calls (e.g. the Win32 API) or a wrapper around them. I tend to use Boost.Filesystem as it is superior interface compared to the mess that is the Win32 API (as well as being cross platform).
If you are looking to use the Win32 API, Microsoft has a list of functions and examples on msdn.
I made this method based on a comment from Tony Lâmpada's answer. It works very well.
def scroll_to(element)
page.execute_script("window.scrollTo(#{element.native.location.x}, #{element.native.location.y})")
end
With
def person = new Person("Kumar", 12)
you are defining a function/lazy variable which always returns a new Person instance with name "Kumar" and age 12. This is totally valid and the compiler has no reason to complain. Calling person.age will return the age of this newly created Person instance, which is always 12.
When writing
person.age = 45
you assign a new value to the age property in class Person, which is valid since age is declared as var
. The compiler will complain if you try to reassign person
with a new Person object like
person = new Person("Steve", 13) // Error
this works with "NA"
not for NA
comments = c("no","yes","NA")
for (l in 1:length(comments)) {
#if (!is.na(comments[l])) print(comments[l])
if (comments[l] != "NA") print(comments[l])
}
It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment
as you can see above).
Try checking to see if Hibernate core is put in as dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.11.Final</version>
<scope>compile</scope>
</dependency>
String str = "1234.56";
float num = 0.0f;
int digits = str.length()- str.indexOf('.') - 1;
float factor = 1f;
for(int i=0;i<digits;i++) factor /= 10;
for(int i=str.length()-1;i>=0;i--){
if(str.charAt(i) == '.'){
factor = 1;
System.out.println("Reset, value="+num);
continue;
}
num += (str.charAt(i) - '0') * factor;
factor *= 10;
}
System.out.println(num);
Just add 'unsigned' for the FOREIGN constraint
`FK` int(11) unsigned DEFAULT NULL,
After adding an item to a list, you can replace it by writing
list[someIndex] = new MyClass();
You can modify an existing item in the list by writing
list[someIndex].SomeProperty = someValue;
EDIT: You can write
var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);
I suppose better would be to use re.match() function. here is an example which may help you.
import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]
sentences
I would like to explain the concepts from the perspective of JavaScript prototype inheritance. Hopefully help to understand.
There are three options to define the scope of a directive:
scope: false
: Angular default. The directive's scope is exactly the one of its parent scope (parentScope
).scope: true
: Angular creates a scope for this directive. The scope prototypically inherits from parentScope
.scope: {...}
: isolated scope is explained below. Specifying scope: {...}
defines an isolatedScope
. An isolatedScope
does not inherit properties from parentScope
, although isolatedScope.$parent === parentScope
. It is defined through:
app.directive("myDirective", function() {
return {
scope: {
... // defining scope means that 'no inheritance from parent'.
},
}
})
isolatedScope
does not have direct access to parentScope
. But sometimes the directive needs to communicate with the parentScope
. They communicate through @
, =
and &
. The topic about using symbols @
, =
and &
are talking about scenarios using isolatedScope
.
It is usually used for some common components shared by different pages, like Modals. An isolated scope prevents polluting the global scope and is easy to share among pages.
Here is a basic directive: http://jsfiddle.net/7t984sf9/5/. An image to illustrate is:
@
: one-way binding@
simply passes the property from parentScope
to isolatedScope
. It is called one-way binding
, which means you cannot modify the value of parentScope
properties. If you are familiar with JavaScript inheritance, you can understand these two scenarios easily:
If the binding property is a primitive type, like interpolatedProp
in the example: you can modify interpolatedProp
, but parentProp1
would not be changed. However, if you change the value of parentProp1
, interpolatedProp
will be overwritten with the new value (when angular $digest).
If the binding property is some object, like parentObj
: since the one passed to isolatedScope
is a reference, modifying the value will trigger this error:
TypeError: Cannot assign to read only property 'x' of {"x":1,"y":2}
=
: two-way binding=
is called two-way binding
, which means any modification in childScope
will also update the value in parentScope
, and vice versa. This rule works for both primitives and objects. If you change the binding type of parentObj
to be =
, you will find that you can modify the value of parentObj.x
. A typical example is ngModel
.
&
: function binding&
allows the directive to call some parentScope
function and pass in some value from the directive. For example, check JSFiddle: & in directive scope.
Define a clickable template in the directive like:
<div ng-click="vm.onCheck({valueFromDirective: vm.value + ' is from the directive'})">
And use the directive like:
<div my-checkbox value="vm.myValue" on-check="vm.myFunction(valueFromDirective)"></div>
The variable valueFromDirective
is passed from the directive to the parent controller through {valueFromDirective: ...
.
Reference: Understanding Scopes
You cannot use the Directory directive in .htaccess. However if you create a .htaccess file in the /system directory and place the following in it, you will get the same result
#place this in /system/.htaccess as you had before
deny from all
To your question whether the map was like a bucket: no.
It's like a list with name=value
pairs whereas name
doesn't need to be a String (it can, though).
To get an element, you pass your key to the get()-method which gives you the assigned object in return.
And a Hashmap means that if you're trying to retrieve your object using the get-method, it won't compare the real object to the one you provided, because it would need to iterate through its list and compare() the key you provided with the current element.
This would be inefficient. Instead, no matter what your object consists of, it calculates a so called hashcode from both objects and compares those. It's easier to compare two int
s instead of two entire (possibly deeply complex) objects. You can imagine the hashcode like a summary having a predefined length (int), therefore it's not unique and has collisions. You find the rules for the hashcode in the documentation to which I've inserted the link.
If you want to know more about this, you might wanna take a look at articles on javapractices.com and technofundo.com
regards
XHTML solution:
<input type="radio" name="imgsel" value="" checked="checked" />
Please note, that the actual value of checked
attribute does not actually matter; it's just a convention to assign "checked"
. Most importantly, strings like "true"
or "false"
don't have any special meaning.
If you don't aim for XHTML conformance, you can simplify the code to:
<input type="radio" name="imgsel" value="" checked>
An even easier and more shorthand version would be:
if (!x) {
//Undefined
}
OR
if (typeof x !== "undefined") {
//Do something since x is defined.
}
You can use
set define off
Using this it won't prompt for the input
RESTORE DATABASE {DatabaseName}
FROM DISK = '{databasename}.bak'
WITH REPLACE, RECOVERY
I have came across with this error while I was playing with Ansible. I have changed the permissions of the private key to 600 in order to solve this problem. And it worked!
chmod 600 .vagrant/machines/default/virtualbox/private_key
Play around this piece of code. Focus on the concept, edit where necessary so that it can
<html>
<head>
<title> Delegate edit form</title>
</head>
<body>
Delegate update form </p>
<meta name="viewport" content="width=device-width; initial-scale=1.0">
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<link href='http://fonts.googleapis.com/css?family=Droid+Serif|Ubuntu' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="js/flexslider/flexslider.css" />
<link rel="stylesheet" href="css/basic-style.css">
<script src="js/libs/modernizr-2.6.2.min.js"></script>
</head>
<body id="home">
<header class="wrapper clearfix">
<nav id="topnav" role="navigation">
<div class="menu-toggle">Menu</div>
<ul class="srt-menu" id="menu-main-navigation">
<li><a href="Swift_Landing.html">Home page</a></li>
</header>
</section>
<style>
form label {
display: inline-block;
width: 100px;
font-weight: bold;
}
</style>
</ul>
<?php
session_start();
$usernm="root";
$passwd="";
$host="localhost";
$database="swift";
$Username=$_SESSION['myssession'];
mysql_connect($host,$usernm,$passwd);
mysql_select_db($database);
$sql = "SELECT * FROM usermaster WHERE User_name='$Username'";
$result = mysql_query ($sql) or die (mysql_error ());
while ($row = mysql_fetch_array ($result)){
?>
<form action="Delegate_update.php" method="post">
Name
<input type="text" name="Namex" value="<?php echo $row ['Name']; ?> " size=10>
Username
<input type="text" name="Username" value="<?php echo $row ['User_name']; ?> " size=10>
Password
<input type="text" name="Password" value="<?php echo $row ['User_password']; ?>" size=17>
<input type="submit" name="submit" value="Update">
</form>
<?php
}
?>
</p>
</body>
</html>
You could also do it with a Func like this
@{
var getStyle = new Func<int, int, string>((width, margin) => string.Format("width: {0}px; margin: {1}px;", width, margin));
}
<div style="@getStyle(50, 2)"></div>
objdump
+ gdb
minimal runnable example
TL;DR:
objdump -s core
can be used to dump memory in bulkNow for the full educational test setup:
main.c
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int myfunc(int i) {
*(int*)(NULL) = i; /* line 7 */
return i - 1;
}
int main(int argc, char **argv) {
/* Setup some memory. */
char data_ptr[] = "string in data segment";
char *mmap_ptr;
char *text_ptr = "string in text segment";
(void)argv;
mmap_ptr = (char *)malloc(sizeof(data_ptr) + 1);
strcpy(mmap_ptr, data_ptr);
mmap_ptr[10] = 'm';
mmap_ptr[11] = 'm';
mmap_ptr[12] = 'a';
mmap_ptr[13] = 'p';
printf("text addr: %p\n", text_ptr);
printf("data addr: %p\n", data_ptr);
printf("mmap addr: %p\n", mmap_ptr);
/* Call a function to prepare a stack trace. */
return myfunc(argc);
}
Compile, and run to generate core:
gcc -ggdb3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
ulimit -c unlimited
rm -f core
./main.out
Output:
text addr: 0x4007d4
data addr: 0x7ffec6739220
mmap addr: 0x1612010
Segmentation fault (core dumped)
GDB points us to the exact line where the segmentation fault happened, which is what most users want while debugging:
gdb -q -nh main.out core
then:
Reading symbols from main.out...done.
[New LWP 27479]
Core was generated by `./main.out'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x0000000000400635 in myfunc (i=1) at main.c:7
7 *(int*)(NULL) = i;
(gdb) bt
#0 0x0000000000400635 in myfunc (i=1) at main.c:7
#1 0x000000000040072b in main (argc=1, argv=0x7ffec6739328) at main.c:28
which points us directly to the buggy line 7.
CLI arguments are stored in the core file and don't need to be passed again
To answer the specific CLI argument questions, we see that if we change the cli arguments e.g. with:
rm -f core
./main.out 1 2
then this does get reflected in the previous bactrace without any changes in our commands:
Reading symbols from main.out...done.
[New LWP 21838]
Core was generated by `./main.out 1 2'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x0000564583cf2759 in myfunc (i=3) at main.c:7
7 *(int*)(NULL) = i; /* line 7 */
(gdb) bt
#0 0x0000564583cf2759 in myfunc (i=3) at main.c:7
#1 0x0000564583cf2858 in main (argc=3, argv=0x7ffcca4effa8) at main.c:2
So note how now argc=3
. Therefore this must mean that the core file stores that information. I'm guessing it just stores it as the arguments of main
, just like it stores the arguments of any other functions.
This makes sense if you consider that the core dump must be storing the entire memory and register state of the program, and so it has all the information needed to determine the value of function arguments on the current stack.
Less obvious is how to inspect the environment variables: How to get environment variable from a core dump Environment variables are also present in memory so the objdump does contain that information, but I'm not sure how to list all of them in one go conveniently, one by one as follows did work on my tests though:
p __environ[0]
Binutils analysis
By using binutils tools like readelf
and objdump
, we can bulk dump information contained in the core
file such as the memory state.
Most/all of it must also be visible through GDB, but those binutils tools offer a more bulk approach which is convenient for certain use cases, while GDB is more convenient for a more interactive exploration.
First:
file core
tells us that the core
file is actually an ELF file:
core: ELF 64-bit LSB core file x86-64, version 1 (SYSV), SVR4-style, from './main.out'
which is why we are able to inspect it more directly with usual binutils tools.
A quick look at the ELF standard shows that there is actually an ELF type dedicated to it:
Elf32_Ehd.e_type == ET_CORE
Further format information can be found at:
man 5 core
Then:
readelf -Wa core
gives some hints about the file structure. Memory appears to be contained in regular program headers:
Program Headers:
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
NOTE 0x000468 0x0000000000000000 0x0000000000000000 0x000b9c 0x000000 0
LOAD 0x002000 0x0000000000400000 0x0000000000000000 0x001000 0x001000 R E 0x1000
LOAD 0x003000 0x0000000000600000 0x0000000000000000 0x001000 0x001000 R 0x1000
LOAD 0x004000 0x0000000000601000 0x0000000000000000 0x001000 0x001000 RW 0x1000
and there is some more metadata present in a notes area, notably prstatus
contains the PC:
Displaying notes found at file offset 0x00000468 with length 0x00000b9c:
Owner Data size Description
CORE 0x00000150 NT_PRSTATUS (prstatus structure)
CORE 0x00000088 NT_PRPSINFO (prpsinfo structure)
CORE 0x00000080 NT_SIGINFO (siginfo_t data)
CORE 0x00000130 NT_AUXV (auxiliary vector)
CORE 0x00000246 NT_FILE (mapped files)
Page size: 4096
Start End Page Offset
0x0000000000400000 0x0000000000401000 0x0000000000000000
/home/ciro/test/main.out
0x0000000000600000 0x0000000000601000 0x0000000000000000
/home/ciro/test/main.out
0x0000000000601000 0x0000000000602000 0x0000000000000001
/home/ciro/test/main.out
0x00007f8d939ee000 0x00007f8d93bae000 0x0000000000000000
/lib/x86_64-linux-gnu/libc-2.23.so
0x00007f8d93bae000 0x00007f8d93dae000 0x00000000000001c0
/lib/x86_64-linux-gnu/libc-2.23.so
0x00007f8d93dae000 0x00007f8d93db2000 0x00000000000001c0
/lib/x86_64-linux-gnu/libc-2.23.so
0x00007f8d93db2000 0x00007f8d93db4000 0x00000000000001c4
/lib/x86_64-linux-gnu/libc-2.23.so
0x00007f8d93db8000 0x00007f8d93dde000 0x0000000000000000
/lib/x86_64-linux-gnu/ld-2.23.so
0x00007f8d93fdd000 0x00007f8d93fde000 0x0000000000000025
/lib/x86_64-linux-gnu/ld-2.23.so
0x00007f8d93fde000 0x00007f8d93fdf000 0x0000000000000026
/lib/x86_64-linux-gnu/ld-2.23.so
CORE 0x00000200 NT_FPREGSET (floating point registers)
LINUX 0x00000340 NT_X86_XSTATE (x86 XSAVE extended state)
objdump
can easily dump all memory with:
objdump -s core
which contains:
Contents of section load1:
4007d0 01000200 73747269 6e672069 6e207465 ....string in te
4007e0 78742073 65676d65 6e740074 65787420 xt segment.text
Contents of section load15:
7ffec6739220 73747269 6e672069 6e206461 74612073 string in data s
7ffec6739230 65676d65 6e740000 00a8677b 9c6778cd egment....g{.gx.
Contents of section load4:
1612010 73747269 6e672069 6e206d6d 61702073 string in mmap s
1612020 65676d65 6e740000 11040000 00000000 egment..........
which matches exactly with the stdout value in our run.
This was tested on Ubuntu 16.04 amd64, GCC 6.4.0, and binutils 2.26.1.
SELECT * FROM (SELECT *,(((acos(sin((43.6980168*pi()/180)) *
sin((latitude*pi()/180))+cos((43.6980168*pi()/180)) *
cos((latitude*pi()/180)) * cos(((7.266903899999988- longitude)*
pi()/180))))*180/pi())*60*1.1515 ) as distance
FROM wp_users WHERE 1 GROUP BY ID limit 0,10) as X
ORDER BY ID DESC
This is the distance calculation query between to points in MySQL, I have used it in a long database, it it working perfect! Note: do the changes (database name, table name, column etc) as per your requirements.
In general, it is considered best-practice to use relative URLs, so that your website will not be bound to the base URL of where it is currently deployed. For example, it will be able to work on localhost, as well as on your public domain, without modifications.
Other persons that are using mapping classes for Hibernate, make sure that have addressed correctly to model package in sessionFactory bean declaration in the following part:
public List<Book> list() {
List<Book> list=SessionFactory.getCurrentSession().createQuery("from book").list();
return list;
}
The mistake I did in the above snippet is that I have used the table name foo inside createQuery. Instead, I got to use Foo, the actual class name.
public List<Book> list() {
List<Book> list=SessionFactory.getCurrentSession().createQuery("from Book").list();
return list;
}
If you use visual studio, Team Explorer built-in tool is a very nice tool to resolve git merge conflicts.
First checkout to the branch which you want to rename:
git branch -m old_branch new_branch
git push -u origin new_branch
To remove an old branch from remote
:
git push origin :old_branch
Try:
sub2['income'].fillna((sub2['income'].mean()), inplace=True)
After looking for an answer for myself for some time, i could find something. in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML Below is generated HTML for example, when i want to display only Name property for my class
<td>
myClassNameProperty
</td>
<td>
myClassNameProperty, This is direct from Item
</td>
This is the generated HTML from below code
<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)
</td>
<td>
@item.Genre.Name, This is direct from Item
</td>
At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least
i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below
@item.Genre.Name
@item.Genre.Id
@item.Genre.Description
and so on depending on number of properties.
Replace the rule you have with the following:
div:not(#a) { // add your bg image here //}
If you are using CentOS, then you need to use
yum install python34-devel.x86_64
yum groupinstall -y 'development tools'
pip3 install mysql-connector
pip install mysqlclient
hi body very late but i am writing
if(mylist.contains(value)){}
I started down this path because ESXi's wget is not compiled with SSL and I wanted to download an OVA from a vendor's website directly onto the ESXi host which is on the other side of the world.
I had to disable the firewall(lazy)/enable https out by editing the rules(proper)
created the python script:
import ssl
import shutil
import tempfile
import urllib.request
context = ssl._create_unverified_context()
dlurl='https://somesite/path/whatever'
with urllib.request.urlopen(durl, context=context) as response:
with open("file.ova", 'wb') as tmp_file:
shutil.copyfileobj(response, tmp_file)
ESXi libraries are kind of paired down but the open source weasel installer seemed to use urllib for https... so it inspired me to go down this path
If you really want to force-download all dependencies, you can try to re-initialise the entire maven repository. Like in this article already described, you could use:
mvn -Dmaven.repo.local=$HOME/.my/other/repository clean install
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
The first parameter of Html.RadioButtonFor() should be the property name you're using, and the second parameter should be the value of that specific radio button. Then they'll have the same name attribute value and the helper will select the given radio button when/if it matches the property value.
Example:
<div class="editor-field">
<%= Html.RadioButtonFor(m => m.Gender, "M" ) %> Male
<%= Html.RadioButtonFor(m => m.Gender, "F" ) %> Female
</div>
Here's a more specific example:
I made a quick MVC project named "DeleteMeQuestion" (DeleteMe prefix so I know that I can remove it later after I forget about it).
I made the following model:
namespace DeleteMeQuestion.Models
{
public class QuizModel
{
public int ParentQuestionId { get; set; }
public int QuestionId { get; set; }
public string QuestionDisplayText { get; set; }
public List<Response> Responses { get; set; }
[Range(1,999, ErrorMessage = "Please choose a response.")]
public int SelectedResponse { get; set; }
}
public class Response
{
public int ResponseId { get; set; }
public int ChildQuestionId { get; set; }
public string ResponseDisplayText { get; set; }
}
}
There's a simple range validator in the model, just for fun. Next up, I made the following controller:
namespace DeleteMeQuestion.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index(int? id)
{
// TODO: get question to show based on method parameter
var model = GetModel(id);
return View(model);
}
[HttpPost]
public ActionResult Index(int? id, QuizModel model)
{
if (!ModelState.IsValid)
{
var freshModel = GetModel(id);
return View(freshModel);
}
// TODO: save selected answer in database
// TODO: get next question based on selected answer (hard coded to 999 for now)
var nextQuestionId = 999;
return RedirectToAction("Index", "Home", new {id = nextQuestionId});
}
private QuizModel GetModel(int? questionId)
{
// just a stub, in lieu of a database
var model = new QuizModel
{
QuestionDisplayText = questionId.HasValue ? "And so on..." : "What is your favorite color?",
QuestionId = 1,
Responses = new List<Response>
{
new Response
{
ChildQuestionId = 2,
ResponseId = 1,
ResponseDisplayText = "Red"
},
new Response
{
ChildQuestionId = 3,
ResponseId = 2,
ResponseDisplayText = "Blue"
},
new Response
{
ChildQuestionId = 4,
ResponseId = 3,
ResponseDisplayText = "Green"
},
}
};
return model;
}
}
}
Finally, I made the following view that makes use of the model:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DeleteMeQuestion.Models.QuizModel>" %>
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<div>
<h1><%: Model.QuestionDisplayText %></h1>
<div>
<ul>
<% foreach (var item in Model.Responses) { %>
<li>
<%= Html.RadioButtonFor(m => m.SelectedResponse, item.ResponseId, new {id="Response" + item.ResponseId}) %>
<label for="Response<%: item.ResponseId %>"><%: item.ResponseDisplayText %></label>
</li>
<% } %>
</ul>
<%= Html.ValidationMessageFor(m => m.SelectedResponse) %>
</div>
<input type="submit" value="Submit" />
<% } %>
</asp:Content>
As I understand your context, you have questions with a list of available answers. Each answer will dictate the next question. Hopefully that makes sense from my model and TODO comments.
This gives you the radio buttons with the same name attribute, but different ID attributes.
If the tables are innodb you can create it like this:
CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY ( account_id ),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
) ENGINE=INNODB;
You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look here for more info.
I met this problem today, and fix it with bellowed steps.
1, Check the log file /var/log/mysqld.log
tail -f /var/log/mysqld.log
2017-03-14T07:06:53.374603Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/mysqld.pid' (Errcode: 2 - No such file or directory)
2017-03-14T07:06:53.374614Z 0 [ERROR] Can't start server: can't create PID file: No such file or directory
The log says that there isn't a file or directory /var/run/mysqld/mysqld.pid
2, Create the directory /var/run/mysqld
mkdir -p /var/run/mysqld/
3, Start the mysqld again service mysqld start
, but still fail, check the log again /var/log/mysqld.log
2017-03-14T07:14:22.967667Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/mysqld.pid' (Errcode: 13 - Permission denied)
2017-03-14T07:14:22.967678Z 0 [ERROR] Can't start server: can't create PID file: Permission denied
It saids permission denied.
4, Grant the permission to mysql
chown mysql.mysql /var/run/mysqld/
5, Restart the mysqld
# service mysqld restart
Restarting mysqld (via systemctl): [ OK ]
After so much effort, found that the basic difference is you need to send the JsonObject
instead of JSONObject
as parameter.
I am using Visual Studio 2013 & SQL Server 2014. I got the below error Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0 not found by visual studio. I have tried all the things like installing
ENU\x64\SharedManagementObjects.msi for X64 OS or
ENU\x86\SharedManagementObjects.msi for X86 OS
ENU\x64\SQLSysClrTypes.msi
Reinstalling Sql Server 2014
What actually solved my problem is to repair the visual studio 2013(or any other version you are using) now the problem is removed . What i think it is problem of Visual Studio not Sql Server as i was able to access and use the Sql Server tool.
def prime(n):
for i in range(2,n):
if n%i==0:
return False
return True
def primefactors():
m=int(input('enter the number:'))
for i in range(2,m):
if (prime(i)):
if m%i==0:
print(i)
return print('end of it')
primefactors()