It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.
Just restarting the server with command npm start
did the trick. Thanks all for the suggestions.
No, the errors occurs only after the Intelephense extension is automatically updated.
To solve the problem, you can downgrade it to the previous version by click "Install another version" in the Intelephense extension. There are no errors on version 1.2.3.
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
npm --depth 9999 update
fixed the issue for me--apparently because package-lock.json
was insisting on the outdated versions.
The problem is that you are using gulp 4 and the syntax in gulfile.js is of gulp 3. So either downgrade your gulp to 3.x.x or make use of gulp 4 syntaxes.
Syntax Gulp 3:
gulp.task('default', ['sass'], function() {....} );
Syntax Gulp 4:
gulp.task('default', gulp.series(sass), function() {....} );
You can read more about gulp and gulp tasks on: https://medium.com/@sudoanushil/how-to-write-gulp-tasks-ce1b1b7a7e81
did all the above didn't work... may be some issue with NPM
Yarn
was helpful ..
Yarn Install
I struggled with the same problem just a minute ago. My project was generated using the v 1.6.0 of angular-cli.
1. npm update -g @angular/cli
2. editing my package.json changing the line
"@angular/cli": "1.6.0",
to
"@angular/cli": "^1.6.0",
3. npm update
I hope my help is effective ?
The new way to do it is to use enabledBorder
like this:
new TextField(
decoration: new InputDecoration(
enabledBorder: const OutlineInputBorder(
borderSide: const BorderSide(color: Colors.grey, width: 0.0),
),
focusedBorder: ...
border: ...
),
)
Others have answered so I'll add my 2-cents.
You can either use autoconfiguration (i.e. don't use a @Configuration to create a datasource) or java configuration.
Auto-configuration:
define your datasource type then set the type properties. E.g.
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.driver-class-name=org.h2.Driver
spring.datasource.hikari.jdbc-url=jdbc:h2:mem:testdb
spring.datasource.hikari.username=sa
spring.datasource.hikari.password=password
spring.datasource.hikari.max-wait=10000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.leak-detection-threshold=600000
spring.datasource.hikari.maximum-pool-size=100
spring.datasource.hikari.pool-name=MyDataSourcePoolName
Java configuration:
Choose a prefix and define your data source
spring.mysystem.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.mysystem.datasource.jdbc-
url=jdbc:sqlserver://databaseserver.com:18889;Database=MyDatabase;
spring.mysystem.datasource.username=dsUsername
spring.mysystem.datasource.password=dsPassword
spring.mysystem.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.mysystem.datasource.max-wait=10000
spring.mysystem.datasource.connection-timeout=30000
spring.mysystem.datasource.idle-timeout=600000
spring.mysystem.datasource.max-lifetime=1800000
spring.mysystem.datasource.leak-detection-threshold=600000
spring.mysystem.datasource.maximum-pool-size=100
spring.mysystem.datasource.pool-name=MySystemDatasourcePool
Create your datasource bean:
@Bean(name = { "dataSource", "mysystemDataSource" })
@ConfigurationProperties(prefix = "spring.mysystem.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
You can leave the datasource type out, but then you risk spring guessing what datasource type to use.
I had same issue. After browsing and struggling with issue found the below solution
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
imports: [
HttpModule,
HttpClientModule
]
Import HttpModule
and HttpClientModule
in app.module.ts and add into the imports like mentioned above.
Instead of using --no-optional
every single time, we can just add it to npm or yarn config.
For Yarn, there is a default no-optional config, so we can just edit that:
yarn config set ignore-optional true
For npm, there is no default config set, so we can create one:
npm config set ignore-optional true
If you are matching with sqlite database:
In your php folder open php.ini file, go to:
;extension=pdo_sqlite
Just remove the semicolon and it will work.
Since you add ..
after cmake, it will jump up and up (just like cd ..
) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use .
instead of ..
.
Michael has given a very comprehensive answer, but I'd like to point out a few things which you can still do to be able to use grids in IE in a nearly painless way.
repeat
functionality is supportedYou can still use the repeat functionality, it's just hiding behind a different syntax. Instead of writing repeat(4, 1fr)
, you have to write (1fr)[4]
. That's it.
See this series of articles for the current state of affairs: https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/
Grid gaps are supported in all browsers except IE. So you can use the @supports
at-rule to set the grid-gaps conditionally for all new browsers:
Example:
.grid {
display: grid;
}
.item {
margin-right: 1rem;
margin-bottom: 1rem;
}
@supports (grid-gap: 1rem) {
.grid {
grid-gap: 1rem;
}
.item {
margin-right: 0;
margin-bottom: 0;
}
}
It's a little verbose, but on the plus side, you don't have to give up grids altogether just to support IE.
I can't stress this enough - half the pain of grids is solved just be using autoprefixer in your build step. Write your CSS in a standards-complaint way, and just let autoprefixer do it's job transforming all older spec properties automatically. When you decide you don't want to support IE, just change one line in the browserlist config and you'll have removed all IE-specific code from your built files.
I was receiving the same error when not specifying the app
name before pattern name.
In my case:
app-name
: Blog
pattern-name
: post-delete
reverse_lazy('Blog:post-delete')
worked.
the problem is in url pattern of servlet-mapping.
<url-pattern>/DispatcherServlet</url-pattern>
let's say our controller is
@Controller
public class HomeController {
@RequestMapping("/home")
public String home(){
return "home";
}
}
when we hit some URL on our browser. the dispatcher servlet will try to map this url.
the url pattern of our serlvet currently is /Dispatcher
which means resources are served from {contextpath}/Dispatcher
but when we request http://localhost:8080/home
we are actually asking resources from /
which is not available.
so either we need to say dispatcher servlet to serve from /
by doing
<url-pattern>/</url-pattern>
our make it serve from /Dispatcher by doing /Dispatcher/*
E.g
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>springsecuritydemo</display-name>
<servlet>
<description></description>
<display-name>offers</display-name>
<servlet-name>offers</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>offers</servlet-name>
<url-pattern>/Dispatcher/*</url-pattern>
</servlet-mapping>
</web-app>
and request it with http://localhost:8080/Dispatcher/home
or put just /
to request like
http://localhost:8080/home
I was facing same problem.
When I rightclick-> run on server then select my server manually it worked.
Do
Alt+Shift+X
then mannually select your server. It might help.
I am using Laravel 5.5.14 and none of the above worked for me. So here are the steps I did to make it work.
1.Install font-awesome by using npm:
npm install font-awesome --save
2.Move the fonts to your public directory by adding this line in your webpack.mixin.js
mix.copyDirectory('node_modules/font-awesome/fonts', 'public/fonts/font-awesome');
3.Open your app.scss to specify the path of the fonts in your node_modules and which relative path to use for compilation:
$fa-font-path: "../fonts/font-awesome" !default;
@import "~font-awesome/scss/font-awesome.scss";
Still not sure the answer, but a possible workaround is
import * as Chart from 'chart.js';
A somewhat unlikely situation.
I have removed the yarn.lock
file, which referenced an older version of webpack.
So check to see the differences in your yarn.lock
file as a possiblity.
Assuming you don't want to immediately decode it again like others are suggesting here, you can parse it to a string and then just strip the leading 'b
and trailing '
.
>>> x = "Hi there "
>>> x = "Hi there ".encode("utf-8")
>>> x
b"Hi there \xef\xbf\xbd"
>>> str(x)[2:-1]
"Hi there \\xef\\xbf\\xbd"
The easiest way to save the packages from an environment to be installed in another computer is:
$ conda list -e > req.txt
then you can install the environment using
$ conda create -n <environment-name> --file req.txt
if you use pip
, please use the following commands: reference https://pip.pypa.io/en/stable/reference/pip_freeze/
$ env1/bin/pip freeze > requirements.txt
$ env2/bin/pip install -r requirements.txt
Here's a function that returns substring of a given substring when start and end indices are provided. For complete reference you can visit the links given below.
func substring(string: String, fromIndex: Int, toIndex: Int) -> String? {
if fromIndex < toIndex && toIndex < string.count /*use string.characters.count for swift3*/{
let startIndex = string.index(string.startIndex, offsetBy: fromIndex)
let endIndex = string.index(string.startIndex, offsetBy: toIndex)
return String(string[startIndex..<endIndex])
}else{
return nil
}
}
Here's a link to the blog post that I have created to deal with string manipulation in swift. String manipulation in swift (Covers swift 4 as well)
I appreciate this question and all the info with it. I have something in mind that's kind of a question and an answer when it comes to String.Index.
I'm trying to see if there is an O(1) way to access a Substring (or Character) inside a String because string.index(startIndex, offsetBy: 1) is O(n) speed if you look at the definition of index function. Of course we can do something like:
let characterArray = Array(string)
then access any position in the characterArray however SPACE complexity of this is n
= length of string, O(n) so it's kind of a waste of space.
I was looking at Swift.String documentation in Xcode and there is a frozen public struct called Index
. We can initialize is as:
let index = String.Index(encodedOffset: 0)
Then simply access or print any index in our String object as such:
print(string[index])
Note: be careful not to go out of bounds`
This works and that's great but what is the run-time and space complexity of doing it this way? Is it any better?
Create new Maven file with path as classpath and goal as class name
You need to define propTypes
as a static getter if you want it inside the class declaration:
static get propTypes() {
return {
children: PropTypes.any,
onClickOut: PropTypes.func
};
}
If you want to define it as an object, you need to define it outside the class, like this:
IxClickOut.propTypes = {
children: PropTypes.any,
onClickOut: PropTypes.func,
};
Also it's better if you import prop types from prop-types
, not react
, otherwise you'll see warnings in console (as preparation for React 16):
import PropTypes from 'prop-types';
Had the same problem when updating my mac to macOS Catalina, while using pipenv
. Pipenv creates and manages a virtualenv
for you, so the earlier suggestion from @Anoop-Malav is the same, just using pipenv to remove the virtual environment based on the current dir and reset it:
pipenv --rm
pipenv shell # recreate a virtual env with your current Pipfile
you can check the type. s3 has a special application/x-directory
bucket.objects({:delimiter=>"/", :prefix=>"f1/"}).each { |obj| p obj.object.content_type }
Your can use your tokenizer and pad sequencing for a new piece of text. This is followed by model prediction. This will return the prediction as a numpy array plus the label itself.
For example:
new_complaint = ['Your service is not good']
seq = tokenizer.texts_to_sequences(new_complaint)
padded = pad_sequences(seq, maxlen=maxlen)
pred = model.predict(padded)
print(pred, labels[np.argmax(pred)])
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
Here is the simplest way to resolve this error:
1) Go to your pom.xml file path
2) And edit the pom.xml like:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
</plugin>
</plugins>
3) Save the file That's it.
If you need to handle DOM events not already provided by React you have to add DOM listeners after the component is mounted:
Update: Between React 13, 14, and 15 changes were made to the API that affect my answer. Below is the latest way using React 15 and ES7. See answer history for older versions.
class MovieItem extends React.Component {
componentDidMount() {
// When the component is mounted, add your DOM listener to the "nv" elem.
// (The "nv" elem is assigned in the render function.)
this.nv.addEventListener("nv-enter", this.handleNvEnter);
}
componentWillUnmount() {
// Make sure to remove the DOM listener when the component is unmounted.
this.nv.removeEventListener("nv-enter", this.handleNvEnter);
}
// Use a class arrow function (ES7) for the handler. In ES6 you could bind()
// a handler in the constructor.
handleNvEnter = (event) => {
console.log("Nv Enter:", event);
}
render() {
// Here we render a single <div> and toggle the "aria-nv-el-current" attribute
// using the attribute spread operator. This way only a single <div>
// is ever mounted and we don't have to worry about adding/removing
// a DOM listener every time the current index changes. The attrs
// are "spread" onto the <div> in the render function: {...attrs}
const attrs = this.props.index === 0 ? {"aria-nv-el-current": true} : {};
// Finally, render the div using a "ref" callback which assigns the mounted
// elem to a class property "nv" used to add the DOM listener to.
return (
<div ref={elem => this.nv = elem} aria-nv-el {...attrs} className="menu_item nv-default">
...
</div>
);
}
}
I'm not sure if we have the same problem since webpack only support one output per configuration as of Jun 2016. I guess you already seen the issue on Github.
But I separate the output path by using the multi-compiler. (i.e. separating the configuration object of webpack.config.js
).
var config = {
// TODO: Add common Configuration
module: {},
};
var fooConfig = Object.assign({}, config, {
name: "a",
entry: "./a/app",
output: {
path: "./a",
filename: "bundle.js"
},
});
var barConfig = Object.assign({}, config,{
name: "b",
entry: "./b/app",
output: {
path: "./b",
filename: "bundle.js"
},
});
// Return Array of Configurations
module.exports = [
fooConfig, barConfig,
];
If you have common configuration among them, you could use the extend library or Object.assign
in ES6 or {...}
spread operator in ES7.
You have to pass the route parameters to the route
method, for example:
<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>
It's because, both routes have a {nickname}
in the route declaration. I've used $nickname
for example but make sure you change the $nickname
to appropriate value/variable, for example, it could be something like the following:
<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>
Same thing happend to me after upgrading distro.
Running sudo apt-get install php7.0-mysql
fixed it for me.
For me I think there might be some issue in installing android NDK from android studio. I was able to resolve this in following manner
Downloaded android ndk from
https://developer.android.com/ndk/downloads/index.html
and placed inside ndk-bundle (where your android sdk is installed ). For more info check this screens.
I just have a idea. Use the symbolic link to solve the error and you can still use your prefix for globally installed packages.
ln -s [your prefix path] [path in the '~/.nvm']
then you will have a symbolic folder in the ~/.nvm
folder, but in fact, your global packages are still installed in [your prefix path]. Then the error will not show again and you can use nvm use **
normally.
ps: it's worked for me on mac
.
pps: do not forget to set $PATH
to your npm bin
folder to use the globally installed packages.
If you getting this error in an IDE's terminal/commands prompt, try delete node_modules, close IDE, and run the npm install
command again.
The time when IDE started but still not completed its analysis of node_modules tree is a tricky moment, when packages installation may fail because IDE still scanning node_modules contents.
I created a React component for this specific case: https://github.com/coreyleelarson/react-typekit
Just need to pass in your Typekit Kit ID as a prop and you're good to go.
import React from 'react';
import Typekit from 'react-typekit';
const HtmlLayout = () => (
<html>
<body>
<h1>My Example React Component</h1>
<Typekit kitId="abc123" />
</body>
</html>
);
export default HtmlLayout;
In my case adding following lines to lambda.js {my deployed is on AWS Lambda} fixed the issue.
'font/opentype',
'font/sfnt',
'font/ttf',
'font/woff',
'font/woff2'
With json-loader
installed, now you can simply use:
import suburbs from '../suburbs.json';
or, even more simply:
import suburbs from '../suburbs';
After facing a similar issue, below is what I did :
To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");
.
Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*"
instead of any specific URL to allow any URL.
public class RestApplication
extends Application
{
private Set<Object> singletons = new HashSet<Object>();
public MessageApplication()
{
singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
CorsFilter corsFilter = new CorsFilter();
// To allow all origins for CORS add following, otherwise add only specific urls.
// corsFilter.getAllowedOrigins().add("*");
System.out.println("To only allow restrcited urls ");
corsFilter.getAllowedOrigins().add("http://localhost:4200");
singletons = new LinkedHashSet<Object>();
singletons.add(corsFilter);
}
@Override
public Set<Object> getSingletons()
{
return singletons;
}
}
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<!-- Auto scan rest service -->
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
The most important code which I was missing when I was getting this issue was, I was not adding my class extending javax.ws.rs.Application i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.
Spark 2.2+
Spark 2.2 introduces typedLit
to support Seq
, Map
, and Tuples
(SPARK-19254) and following calls should be supported (Scala):
import org.apache.spark.sql.functions.typedLit
df.withColumn("some_array", typedLit(Seq(1, 2, 3)))
df.withColumn("some_struct", typedLit(("foo", 1, 0.3)))
df.withColumn("some_map", typedLit(Map("key1" -> 1, "key2" -> 2)))
Spark 1.3+ (lit
), 1.4+ (array
, struct
), 2.0+ (map
):
The second argument for DataFrame.withColumn
should be a Column
so you have to use a literal:
from pyspark.sql.functions import lit
df.withColumn('new_column', lit(10))
If you need complex columns you can build these using blocks like array
:
from pyspark.sql.functions import array, create_map, struct
df.withColumn("some_array", array(lit(1), lit(2), lit(3)))
df.withColumn("some_struct", struct(lit("foo"), lit(1), lit(.3)))
df.withColumn("some_map", create_map(lit("key1"), lit(1), lit("key2"), lit(2)))
Exactly the same methods can be used in Scala.
import org.apache.spark.sql.functions.{array, lit, map, struct}
df.withColumn("new_column", lit(10))
df.withColumn("map", map(lit("key1"), lit(1), lit("key2"), lit(2)))
To provide names for structs
use either alias
on each field:
df.withColumn(
"some_struct",
struct(lit("foo").alias("x"), lit(1).alias("y"), lit(0.3).alias("z"))
)
or cast
on the whole object
df.withColumn(
"some_struct",
struct(lit("foo"), lit(1), lit(0.3)).cast("struct<x: string, y: integer, z: double>")
)
It is also possible, although slower, to use an UDF.
Note:
The same constructs can be used to pass constant arguments to UDFs or SQL functions.
This is caused by non-matching Spring Boot dependencies. Check your classpath to find the offending resources. You have explicitly included version 1.1.8.RELEASE, but you have also included 3 other projects. Those likely contain different Spring Boot versions, leading to this error.
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 had referenced this article and many others and did not find a clear cut concise response to help. I am offering my discovery, arrived at with some references from this thread, in the following:
Spring-Boot version: 1.3.5.RELEASE
Spring-Core version: 4.2.6.RELEASE
Dependency Management: Brixton.SR1
The following is the pertinent yaml excerpt:
tools:
toolList:
-
name: jira
matchUrl: http://someJiraUrl
-
name: bamboo
matchUrl: http://someBambooUrl
I created a Tools.class:
@Component
@ConfigurationProperties(prefix = "tools")
public class Tools{
private List<Tool> toolList = new ArrayList<>();
public Tools(){
//empty ctor
}
public List<Tool> getToolList(){
return toolList;
}
public void setToolList(List<Tool> tools){
this.toolList = tools;
}
}
I created a Tool.class:
@Component
public class Tool{
private String name;
private String matchUrl;
public Tool(){
//empty ctor
}
public String getName(){
return name;
}
public void setName(String name){
this.name= name;
}
public String getMatchUrl(){
return matchUrl;
}
public void setMatchUrl(String matchUrl){
this.matchUrl= matchUrl;
}
@Override
public String toString(){
StringBuffer sb = new StringBuffer();
String ls = System.lineSeparator();
sb.append(ls);
sb.append("name: " + name);
sb.append(ls);
sb.append("matchUrl: " + matchUrl);
sb.append(ls);
}
}
I used this combination in another class through @Autowired
@Component
public class SomeOtherClass{
private Logger logger = LoggerFactory.getLogger(SomeOtherClass.class);
@Autowired
private Tools tools;
/* excluded non-related code */
@PostConstruct
private void init(){
List<Tool> toolList = tools.getToolList();
if(toolList.size() > 0){
for(Tool t: toolList){
logger.info(t.toString());
}
}else{
logger.info("*****----- tool size is zero -----*****");
}
}
/* excluded non-related code */
}
And in my logs the name and matching url's were logged. This was developed on another machine and thus I had to retype all of the above so please forgive me in advance if I inadvertently mistyped.
I hope this consolidation comment is helpful to many and I thank the previous contributors to this thread!
This error had me foxed for three days, the situation I faced produced the same error. Following all the advice I could find, I played with the configuration but to no avail.
Eventually I found it, the difference, the Service I was executing was contained in a common jar, the issue turned out to be AspectJ not treating the Service instantiation the same. In effect the proxy was simply calling the underlying method without all the normal Spring magic being executed before the method call.
In the end the @Scope annotation placed on the service as per the example solved the issue:
@Service
@Scope(proxyMode = ScopedProxyMode.INTERFACES)
@Transactional
public class CoreServiceImpl implements CoreService {
@PersistenceContext
protected EntityManager entityManager;
@Override
public final <T extends AbstractEntity> int deleteAll(Class<T> clazz) {
CriteriaDelete<T> criteriaDelete = entityManager.getCriteriaBuilder().createCriteriaDelete(clazz);
criteriaDelete.from(clazz);
return entityManager.createQuery(criteriaDelete).executeUpdate();
}
}
The method I have posted is a delete method but the annotations affect all persistence methods in the same way.
I hope this post helps someone else who has struggled with the same issue when loading a service from a jar
this error probably is occurred most of the time due to missing closing tag. and further you can the following dependency to resolve this issue while supporting legacy HTML formate.
as it your code charset="UTF-8"> here is no closing for meta tag.
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
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();
You might want to add the following to your pom and try compiling
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
This error also happens if you have got the order of your components wrong.
Example: this wrong:
<ComponentA>
<ComponentB>
</ComponentA>
</ComponentB>
correct way:
<ComponentA>
<ComponentB>
</ComponentB>
</ComponentA>
This works for me:
FROM postgres:9.6
USER postgres
# Copy postgres config file into container
COPY postgresql.conf /etc/postgresql
# Override default postgres config file
CMD ["postgres", "-c", "config_file=/etc/postgresql/postgresql.conf"]
When I upgraded to Spring 4 I needed to update the jackson dependencies as follows:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.1</version>
</dependency>
I could not get Adam Taras's answer to work (i.e. using the relative path ../my.json
).
Here was my solution (pretty quick and painless if you have node installed):
npm install -g http-server
http-server --cors
(CORS has to be enabled for this to work)http://localhost:8080/my.json
in input field and click "Explore"Please try this code:
npm install
If you're using React Native, you can use the array notation:
<View style={[styles.base, styles.background]} />
Check out my detailed blog post about this.
in my case, after restarting my server the problem was gone.
exit/close the "php artisan serve" command and
re-run the command "php artisan serve" command.
I was facing the same issue. Everything was fine but in
bootstrap/cache/config.php
always had the incomplete password. Upon digging further, realized that the password had '#' character in it and that was getting dropped. As '#' is used to mark a line as a comment.
I had the same issues with Repository not being found. So what I did was to move everything into 1 package. And this worked meaning that there was nothing wrong with my code. I moved the Repos & Entities into another package and added the following to SpringApplication class.
@EnableJpaRepositories("com...jpa")
@EntityScan("com...jpa")
After that, I moved the Service (interface & implementation) to another package and added the following to SpringApplication class.
@ComponentScan("com...service")
This solved my issues.
Array.from()
takes an iterable object to convert to an array and an optional map function. You could create an object with a .length
property as follows:
return Array.from({length: this.props.level}, (item, index) =>
<span className="indent" key={index}></span>
);
When you give id as a primary key then a pop up is come and those aske you to how many size of this primary key. So you just leave blank because by default int value is set 11. Click then ok on those pop up without any enter a number. in this type of error never will you face in future. Thank you
Make sure HDFS is online. Start it by $HADOOP_HOME/sbin/start-dfs.sh
Once you do that, your test with telnet localhost 9001
should work.
If you only have one bean of type EmployeeService, and the interface EmployeeService does not have other implementations, you can simply put "@Service" before the EmployeeServiceImpl and "@Autowire" before the setter method. Otherwise, you should name the special bean like @Service("myspecial") and put "@autowire @Qualifier("myspecial") before the setter method.
This worked for me, no jquery or select wrapper with input class, just material.js and this vanilla js:
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
As you can tell I got the materialize css actual style and not the browsers default.
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.
Use multiple datasource or realizing the separation of reading & writing.
you must have a knowledge of Class AbstractRoutingDataSource
which support dynamic datasource choose.
Here is my datasource.yaml
and I figure out how to resolve this case. You can refer to this project spring-boot + quartz. Hope this will help you.
dbServer:
default: localhost:3306
read: localhost:3306
write: localhost:3306
datasource:
default:
type: com.zaxxer.hikari.HikariDataSource
pool-name: default
continue-on-error: false
jdbc-url: jdbc:mysql://${dbServer.default}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
username: root
password: lh1234
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false
read:
type: com.zaxxer.hikari.HikariDataSource
pool-name: read
continue-on-error: false
jdbc-url: jdbc:mysql://${dbServer.read}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
username: root
password: lh1234
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false
write:
type: com.zaxxer.hikari.HikariDataSource
pool-name: write
continue-on-error: false
jdbc-url: jdbc:mysql://${dbServer.write}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
username: root
password: lh1234
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false
@Mihai-Andrei Dinculescu's answer is correct, but for the benefit of searchers, there is also a subtle point that can cause this error.
Adding a '/' on the end of your URL will stop EnableCors from working in all instances (e.g. from the homepage).
I.e. This will not work
var cors = new EnableCorsAttribute("http://testing.azurewebsites.net/", "*", "*");
config.EnableCors(cors);
but this will work:
var cors = new EnableCorsAttribute("http://testing.azurewebsites.net", "*", "*");
config.EnableCors(cors);
The effect is the same if using the EnableCors Attribute.
Simply translating the "old for loop way" into streams:
private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {
int subLength = prefix.length();
return input.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().substring(subLength),
entry -> AttributeType.GetByName(entry.getValue())));
}
You can use Environment Replacement in your Dockerfile
as follows:
ENV PATH="/opt/gtk/bin:${PATH}"
add servlet-api jar file which is present in the lib folder under tomcat folder. You can do this as follows Project -> properties -> java build path -> under libraries click add external jars after that go to project -> clean -> build all. this worked for me.
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
+---....
I actually had the same problem.
when I run
mvn clean package
on my maven project, I get this certificate error by the maven tool.
I followed @Andy 's Answer till the point where I downloaded the .cer file
after that the rest of the answer didn't work for me but I did the following(I am running on Linux Debian machine)
first of all, run:
keytool -list -keystore "Java path+"/jre/lib/security/cacerts""
for example in my case it is:
keytool -list -keystore /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/security/cacerts
if it asks about the password, just hit enter.
this command is supposed to list all the ssl certificates accepted by the java. when I ran this command, in my case I got 93 certificates for example.
Now add the downloaded file .cer to the cacerts file by running the following command:
sudo keytool -importcert -file /home/hal/Public/certificate_file_downloaded.cer -keystore /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/security/cacerts
write your sudo password then it will ask you about the keystore password
the default one is changeit
then say y that you trust this certificate.
if you run the command
keytool -list -keystore /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/security/cacerts
once again, in my case, I got 94 contents of the cacerts file
it means, it was added successfully.
Okay here's a simple fix for getting 'done' button to show and work in an app in both iOS 9, iOS 8 and below when I got similar error. It could be observed after running an app and viewing it via 'View's Hierarchy' (i.e. clicking on the 'View Hierarchy' icon from Debug Area bar while app is running on device and inspecting your views in Storyboard), that the keyboard is presented on different windows in iOS 9 compared to iOS 8 and below versions and have to be accounted for. addButtonToKeyboard
- (id)addButtonToKeyboard
{
if (!doneButton)
{
// create custom button
UIButton * doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(-2, 163, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
[doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
[doneButton addTarget:self action:@selector(saveNewLead:) forControlEvents:UIControlEventTouchUpInside];
}
NSArray *windows = [[UIApplication sharedApplication] windows];
//Check to see if running below iOS 9,then return the second window which bears the keyboard
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0) {
return windows[windows.count - 2];
}
else {
UIWindow* keyboardWithDoneButtonWindow = [ windows lastObject];
return keyboardWithDoneButtonWindow;
}
}
And this is how you could removeKeyboardButton from keyboard if you want.
- (void)removeKeyboardButton {
id windowTemp = [self addButtonToKeyboard];
if (windowTemp) {
for (UIView *doneButton in [windowTemp subviews]) {
if ([doneButton isKindOfClass:[UIButton class]]) {
[doneButton setHidden:TRUE];
}
}
}
}
I have also faced same issue when I work with Hibernate and Spring Jpa Data Repository. I forgot to place @Transactional
on spring data repository method.
Its working for me after annotating with @Transactional
.
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
The following works:
sudo apt-get --purge remove mysql-client mysql-server mysql-common
sudo apt-get autoremove
Giving flex a value solved the problem for me, e.g.
flex: 1 0 auto
Had similar issue. Had to pin the maven deploy plugin to specific version in pom.xml:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
This version is what broke my builds:
[INFO] --- maven-deploy-plugin:3.0.0-M1:deploy (default-cli) @ dbl ---
$ nvm alias default {NODE_VERSION}
when we use the above command, only update the node version but the npm
still uses the old version.
Here is another solution for update the both node
and npm
, in my case i want to use node 8.9.4
and i have used the below command.
$ nvm use default 8.9.4
And the command returns the output.
Now using node v8.9.4 (npm v5.6.0)
in swift 4 to convert to url use URL
let fileUrl = URL.init(fileURLWithPath: filePath)
or
let fileUrl = URL(fileURLWithPath: filePath)
If you decide to add a .pch file manually and you want to use Objective-C just like before xCode 6 you will also have to import UIKit and Foundation frameworks in the .pch file. Otherwise you will have to import these frameworks manually in each header file. You can add the following code anyway as it tests for the language used:
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#endif
I had this problem for several days, it turns out if I created the db inside phpMyAdmin it wouldn't appear to Laravel, so, I created the db through MySqlWorkbench, and it worked :)
I had a batch of files that looked like this: be90-01.png and needed to change the dash to underscore. I used this, which worked well:
for f in *; do mv "$f" "`echo $f | tr '-' '_'`"; done
example given below
protocol NameOfProtocol: class {
// member of protocol
}
class ClassName: UIViewController {
weak var delegate: NameOfProtocol?
}
virtualenv --python=/usr/local/bin/python3 <VIRTUAL ENV NAME>
this will add python3
path for your virtual enviroment.
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
.
If all that's needed is to send html code inline in the code, we can use below
var app = express();
app.get('/test.html', function (req, res) {
res.header('Content-Type', 'text/html').send("<html>my html code</html>");
});
You need something like this, maybe it can be improved. This is a first attempt:
...
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
...
@Configuration
...
@org.springframework.context.annotation.PropertySource("classpath:/config/default.properties")
...
public class GeneralApplicationConfiguration implements WebApplicationInitializer
{
@Autowired
Environment env;
public void someMethod() {
...
Map<String, Object> map = new HashMap();
for(Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) {
PropertySource propertySource = (PropertySource) it.next();
if (propertySource instanceof MapPropertySource) {
map.putAll(((MapPropertySource) propertySource).getSource());
}
}
...
}
...
Basically, everything from the Environment that's a MapPropertySource
(and there are quite a lot of implementations) can be accessed as a Map
of properties.
Here's a quick recipe I found:
var gulp = require('gulp');
// npm install gulp yargs gulp-if gulp-uglify
var args = require('yargs').argv;
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var isProduction = args.env === 'production';
gulp.task('scripts', function() {
return gulp.src('**/*.js')
.pipe(gulpif(isProduction, uglify())) // only minify if production
.pipe(gulp.dest('dist'));
});
gulp scripts --env production
Original Ref (not available anymore): https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-params-from-cli.md
From Updated Ref: https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-arguments-from-cli.md
// npm install --save-dev gulp gulp-if gulp-uglify minimist
var gulp = require('gulp');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var minimist = require('minimist');
var knownOptions = {
string: 'env',
default: { env: process.env.NODE_ENV || 'production' }
};
var options = minimist(process.argv.slice(2), knownOptions);
gulp.task('scripts', function() {
return gulp.src('**/*.js')
.pipe(gulpif(options.env === 'production', uglify())) // only minify if production
.pipe(gulp.dest('dist'));
});
gulp scripts --env production
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
One liner explanation
The standard versioning system is major.minor.build (e.g. 2.4.1)
npm checks and fixes the version of a particular package based on these characters
~ : major version is fixed, minor version is fixed, matches any build number
e.g. : ~2.4.1 means it will check for 2.4.x where x is anything
^ : major version is fixed, matches any minor version, matches any build number
e.g. : ^2.4.1 means it will check for 2.x.x where x is anything
I found solution. It works fine when I throw away next line from form:
enctype="multipart/form-data"
And now it pass all parameters at request ok:
<form action="/registration" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>
In MySQL you can use,
(SELECT CITY,
LENGTH(CITY) AS CHR_LEN
FROM STATION
ORDER BY CHR_LEN ASC,
CITY
LIMIT 1)
UNION
(SELECT CITY,
LENGTH(CITY) AS CHR_LEN
FROM STATION
ORDER BY CHR_LEN DESC,
CITY
LIMIT 1)
I discovered that the order of adding roles and features is important. On a fresh system I activate the role "application server" and there check explicitly .net, web server support and finally process activation service Then automatically a dialogue comes up that the role "Web server" needs to be added also.
The problem with the two Powershell answers here is that the prefix can end up being duplicated since the script will potentially run over the file both before and after it has been renamed, depending on the directory being resorted as the renaming process runs. To get around this, simply use the -Exclude
option:
Get-ChildItem -Exclude "house chores-*" | rename-item -NewName { "house chores-" + $_.Name }
This will prevent the process from renaming any one file more than once.
I started this gist a year ago: https://gist.github.com/PascalPrecht/5411171
Brian Ford (member of the core team) has written this blog post about it: http://briantford.com/blog/angular-bower
And then we started with this component spec (which is not quite complete): https://github.com/angular/angular-component-spec
Since the last ng-conf there's this document for best practices by the core team: https://docs.google.com/document/d/1XXMvReO8-Awi1EZXAXS4PzDzdNvV6pGcuaF4Q9821Es/pub
Before teaching yourself Spring and Struts, you should probably learn Java. Output like this
org.classes.database.Employee@d9b02
is the result of the Object#toString()
method which all objects inherit from the Object
class, the superclass of all classes in Java.
The List
sub classes implement this by iterating over all the elements and calling toString()
on those. It seems, however, that you haven't implemented (overriden) the method in your Employee
class.
Your JSTL here
<c:forEach items="${eList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>
</tr>
</c:forEach>
is fine except for the fact that you don't have a page, request, session, or application scoped attribute named eList
.
You need to add it
<% List eList = (List)session.getAttribute("empList");
request.setAttribute("eList", eList);
%>
Or use the attribute empList
in the forEach
.
<c:forEach items="${empList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>
</tr>
</c:forEach>
One of the reasons for this error is the use of the jaxb implementation from the jdk. I am not sure why such a problem can appear in pretty simple xml parsing situations. You may use the latest version of the jaxb library from a public maven repository:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.12</version>
</dependency>
You can simply use event.target.dataset object . This will give you the object with all data attributes.
You should autowire interface AbstractManager
instead of class MailManager
. If you have different implemetations of AbstractManager
you can write @Component("mailService")
and then @Autowired @Qualifier("mailService")
combination to autowire specific class.
This is due to the fact that Spring creates and uses proxy objects based on the interfaces.
As an alternative, you can also use an apply
combined with format
(or better with f-strings) which I find slightly more readable if one e.g. also wants to add a suffix or manipulate the element itself:
df = pd.DataFrame({'col':['a', 0]})
df['col'] = df['col'].apply(lambda x: "{}{}".format('str', x))
which also yields the desired output:
col
0 stra
1 str0
If you are using Python 3.6+, you can also use f-strings:
df['col'] = df['col'].apply(lambda x: f"str{x}")
yielding the same output.
The f-string version is almost as fast as @RomanPekar's solution (python 3.6.4):
df = pd.DataFrame({'col':['a', 0]*200000})
%timeit df['col'].apply(lambda x: f"str{x}")
117 ms ± 451 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit 'str' + df['col'].astype(str)
112 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Using format
, however, is indeed far slower:
%timeit df['col'].apply(lambda x: "{}{}".format('str', x))
185 ms ± 1.07 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
I am facing same Issue after run my build.
The error message tell us to specify your goal
So I specify the goal Ex:-test.
Now It's running fine
You will need to run
sudo apt-get install build-essential
first assuming you're on a debain/ubuntu system
This problem will occurred due to some unnecessary changes made in my.cnf file.
Try to diff /etc/mysql/my.cnf
with one of working mysql servers my.cnf file.
I just replaced /etc/mysql/my.cnf
file with new my.cnf file and this works for me.
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
change PYTHONHOME to the parent folder of the bin file of python, like /usr,which is the parent folder of /usr/bin.
Add this import <%@page import="java.util.Map" %>
This worked for me, but I also needed to add <%@ page import="java.util.HashMap" %>.
It seems that the above answer is true, that if you have the newer tomcat you might not need to add these lines, but as I could not change my whole system, this worked.
Thank you
The answer by @Stenyg only works for older Raspbian images. The recently released Raspbian based on Debian Buster requires an updated toolchain:
In Debian Buster the gcc compiler and glibc was updated to version 8.3. The toolchain in git://github.com/raspberrypi/tools.git
is still based on the older gcc 6 version. This means that using git://github.com/raspberrypi/tools.git
will lead to many compile errors.
This tutorial is based on @Stenyg answer. In addition to many other solutions in the internet, this tutorial also supports older Rasperry Pi (A, B, B+, Zero) based on the ARMv6 CPU. See also: GCC 8 Cross Compiler outputs ARMv7 executable instead of ARMv6
There is no official git repository containing an updated toolchain (See https://github.com/raspberrypi/tools/issues/102).
I created a new github repository which includes building and precompiled toolchains for ARMv6 based on GCC8 and newer:
https://github.com/Pro/raspi-toolchain
As mentioned in the project's readme, these are the steps to get the toolchain. You can also build it yourself (see the README for further details).
wget https://github.com/Pro/raspi-toolchain/releases/latest/download/raspi-toolchain.tar.gz
/opt/cross-pi-gcc
since it's not location independent.sudo tar xfz raspi-toolchain.tar.gz --strip-components=1 -C /opt
You are done! The toolchain is now in /opt/cross-pi-gcc
Optional, add the toolchain to your path, by adding:
export PATH=$PATH:/opt/cross-pi-gcc/bin
to the end of the file named ~/.bashrc
Now you can either log out and log back in (i.e. restart your terminal session), or run . ~/.bashrc
in your terminal to pick up the PATH
addition in your current terminal session.
To cross-compile for your own Raspberry Pi, which may have some custom libraries installed, you need to get these libraries onto your host.
Create a folder $HOME/raspberrypi
.
In your raspberrypi
folder, make a folder called rootfs
.
Now you need to copy the entire /lib
and /usr
directory to this newly created folder. I usually bring the rpi image up and copy it via rsync:
rsync -vR --progress -rl --delete-after --safe-links [email protected]:/{lib,usr,opt/vc/lib} $HOME/raspberrypi/rootfs
where 192.168.1.PI
is replaced by the IP of your Raspberry Pi.
To tell CMake to take your own toolchain, you need to have a toolchain file which initializes the compiler settings.
Get this toolchain file from here: https://github.com/Pro/raspi-toolchain/blob/master/Toolchain-rpi.cmake
Now you should be able to compile your cmake
programs simply by adding this extra flag: -D CMAKE_TOOLCHAIN_FILE=$HOME/raspberrypi/pi.cmake
and setting the correct environment variables:
export RASPBIAN_ROOTFS=$HOME/raspberry/rootfs
export PATH=/opt/cross-pi-gcc/bin:$PATH
export RASPBERRY_VERSION=1
cmake -DCMAKE_TOOLCHAIN_FILE=$HOME/raspberry/Toolchain-rpi.cmake ..
An example hello world is shown here: https://github.com/Pro/raspi-toolchain/blob/master/build_hello_world.sh
In the init.py of the settings directory write the correct import, like:
from Project.settings.base import *
No need to change wsgi.py or manage.py
From the MSDN website:
This error frequently occurs if you declare a variable in a loop or a try or if block and then attempt to access it from an enclosing code block or a separate code block.
So declare the variable outside the block.
I have the error of system.typeintialzationException, which is due to when I tried to move the file like:
File.Move(DestinationFilePath, SourceFilePath)
That error was due to I had swapped the path actually, correct one is:
File.Move(SourceFilePath, DestinationFilePath)
You should use Modernizr, it will add a class to the body tag.
also:
function getIeVersion()
{
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
else if (navigator.appName == 'Netscape')
{
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
Note that IE11 is still is in preview, and the user agent may change before release.
The User-agent string for IE 11 is currently this one :
Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko
Which means your can simply test, for versions 11.xx,
var isIE11 = !!navigator.userAgent.match(/Trident.*rv 11\./)
If you are using Spring Boot, then add thymeleaf dependency into your pom.xml:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64
You may need to try the following
yum install php-mysql-5.3.3-40.el6_6.x86_64
If you are using Java code based on Spring MVC configuration then enable the DefaultServletHandlerConfigurer
in the WebMvcConfigurerAdapter
object.
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
If you are looking for a direct approach and using a local
File in that case.
Try
<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>
This is the case of JS
with inline styling where Image
is a local file that you must have imported with a path.
I test examples in js. Simplest solution - just add word u need inside / /:
var reg = /cat/;
reg.test('some cat here');//1 test
true // result
reg.test('acatb');//2 test
true // result
Now if u need this specific word with boundaries, not inside any other signs-letters. We use b marker:
var reg = /\bcat\b/
reg.test('acatb');//1 test
false // result
reg.test('have cat here');//2 test
true // result
We have also exec() method in js, whichone returns object-result. It helps f.g. to get info about place/index of our word.
var matchResult = /\bcat\b/.exec("good cat good");
console.log(matchResult.index); // 5
If we need get all matched words in string/sentence/text, we can use g modifier (global match):
"cat good cat good cat".match(/\bcat\b/g).length
// 3
Now the last one - i need not 1 specific word, but some of them. We use | sign, it means choice/or.
"bad dog bad".match(/\bcat|dog\b/g).length
// 1
HTML Code
<html>
<body>
<head>
<title></title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
//============================= DATABASE CONNECTIVITY d ====================
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else
//============================= DATABASE CONNECTIVITY u ====================
//============================= Retrieve data from DB d ====================
$sql = "SELECT name, size, type FROM videos";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
$path = "uploaded/" . $row["name"];
echo $path . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
//============================= Retrieve data from DB d ====================
?>
</body>
</html>
This problem was due to the use of AngularJS 1.1.5 (which was unstable, and obviously had some bug or different implementation of the routing than it was in 1.0.7)
turning it back to 1.0.7 solved the problem instantly.
have tried the 1.2.0rc1 version, but have not finished testing as I had to rewrite some of the router functionality since they took it out of the core.
anyway, this problem is fixed when using AngularJS vs 1.0.7.
Maybe gcc is not in your path? Try finding gcc using which gcc
and add it to your path if it's not already there.
In my case I had to run php artisan optimize:clear
in order to make everything to work again.
First check whether the java classes are compiled or not in your [PROJECT_NAME]\target\classes directory.
If not you have some compilation errors in your java classes.
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
Another possible cause is to have the wrong order of RequestMapping attributes. As spring doc says:
An @RequestMapping handler method can have a very flexible signatures. The supported method arguments and return values are described in the following section. Most arguments can be used in arbitrary order with the only exception of BindingResult arguments. This is described in the next section.
If you scroll down the doc, you will see that the BindingResult has to be immediatelly after the model attribute, since we can have multiple model objects per request and thus multiple bindings
The Errors or BindingResult parameters have to follow the model object that is being bound immediately as the method signature might have more than one model object and Spring will create a separate BindingResult instance for each of them so the following sample won’t work:
Here are two examples:
Invalid ordering of BindingResult and @ModelAttribute.
@RequestMapping(method = RequestMethod.POST) public String processSubmit(@ModelAttribute("pet") Pet pet, Model model, BindingResult result) { ... } Note, that there is a Model parameter in between Pet and BindingResult. To get this working you have to reorder the parameters as follows:
@RequestMapping(method = RequestMethod.POST) public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, Model model) { ... }
The problem located on the following line
SELECT @Prefix + LEN(CAST(@maxCode AS VARCHAR(10))+1) + CAST(@maxCode AS VARCHAR(100))
Use this instead
SELECT @Prefix + CAST(LEN(CAST(@maxCode AS VARCHAR(10))+1) AS VARCHAR(100)) + CAST(@maxCode AS VARCHAR(100))
Full Code:
CREATE PROC [dbo].[getVoucherNo]
AS
BEGIN
DECLARE @Prefix VARCHAR(10)='J'
DECLARE @startFrom INT=1
DECLARE @maxCode VARCHAR(100)
DECLARE @sCode INT
IF((SELECT COUNT(*) FROM dbo.Journal_Entry) > 0)
BEGIN
SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(VoucharNo,LEN(@startFrom)+1,LEN(VoucharNo)- LEN(@Prefix)) AS INT))+1 AS varchar(100)) FROM dbo.Journal_Entry;
SET @sCode=CAST(@maxCode AS INT)
SELECT @Prefix + CAST(LEN(CAST(@maxCode AS VARCHAR(10))+1) AS VARCHAR(100)) + CAST(@maxCode AS VARCHAR(100))
END
ELSE
BEGIN
SELECT(@Prefix + CAST(@startFrom AS VARCHAR))
END
END
SELECT CONVERT(varchar(11),Getdate(),105)
You can use Oracle.ManagedDataAccess.dll instead (download from Oracle), include that dll in you project bin dir, add reference to that dll in the project. In code, "using Oracle.MangedDataAccess.Client". Deploy project to server as usual. No need install Oracle Client on server. No need to add assembly info in web.config.
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 don't know about "standard way".
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text # or whatever
As noted by @Boris and @Stefan, on Python 3.9+ you can use
text.removeprefix(prefix)
with the same behavior.
When the Resolve Conflicts->Content Menu are disabled, one may be on the Pending files list. We need to select the Conflicted files option from the drop down (top)
hope it helps
Use decode
:
print(curses.version.decode())
# 2.2
You can use this:
curl_setopt_array($ch, $options);
$resultado = curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info["url"]);
I use grep for removing prefixes from paths (which aren't handled well by sed
):
echo "$input" | grep -oP "^$prefix\K.*"
\K
removes from the match all the characters before it.
I believe your issue is with regards to the server. The angular documentation with regards to HTML5 mode (at the link in your question) states:
Server side Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
I believe you'll need to setup a url rewrite from /about to /.
Use pandas:
import pandas as pd
my_csv = pd.read_csv(filename)
column = my_csv.column_name
# you can also use my_csv['column_name']
Discard unneeded columns at parse time:
my_filtered_csv = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])
P.S. I'm just aggregating what other's have said in a simple manner. Actual answers are taken from here and here.
It looks like your are trying to produce/recieve json output. I see two problems with your approach. 1) You didn't specify the application/json in your Accept header 2) You need to specify produces="application/json" in your @RequestMapping
Your user.jsp:
<form:form action="profile/proffesional" modelAttribute="PROFESSIONAL">
---
---
</form:form>
In your controller class:
(make it as a meaning full method name..Hear i think you are insert record in DB.)
@RequestMapping(value = "proffessional", method = RequestMethod.POST)
public @ResponseBody
String proffessionalDetails(
@ModelAttribute UserProfessionalForm professionalForm,
BindingResult result, Model model) {
UserProfileVO userProfileVO = new UserProfileVO();
userProfileVO.setUser(sessionData.getUser());
userService.saveUserProfile(userProfileVO);
model.addAttribute("PROFESSIONAL", professionalForm);
return "Your Professional Details Updated";
}
I had the same issue, this solved it for me:
ALTER TABLE `my_table` ROW_FORMAT=DYNAMIC;
From MYSQL Documentation:
The DYNAMIC row format maintains the efficiency of storing the entire row in the index node if it fits (as do the COMPACT and REDUNDANT formats), but this new format avoids the problem of filling B-tree nodes with a large number of data bytes of long columns. The DYNAMIC format is based on the idea that if a portion of a long data value is stored off-page, it is usually most efficient to store all of the value off-page. With DYNAMIC format, shorter columns are likely to remain in the B-tree node, minimizing the number of overflow pages needed for any given row.
First, create staticfiles folder. Inside that folder create css, js, and img folder.
settings.py
import os
PROJECT_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'staticfiles'),
)
main urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings
admin.autodiscover()
urlpatterns = patterns('',
.......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
template
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
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";
}
You should try these tools :
xmlstarlet
: can edit, select, transform... Not installed by default, xpath1xmllint
: often installed by default with libxml2-utils
, xpath1 (check my wrapper to have --xpath
switch on very old releases and newlines delimited output (v < 2.9.9)xpath
: installed via perl's module XML::XPath
, xpath1xml_grep
: installed via perl's module XML::Twig
, xpath1 (limited xpath usage)xidel
: xpath3saxon-lint
: my own project, wrapper over @Michael Kay's Saxon-HE Java library, xpath3xmllint
comes with libxml2-utils
(can be used as interactive shell with the --shell
switch)
xmlstarlet
is xmlstarlet
.
xpath
comes with perl's module XML::Xpath
xml_grep
comes with perl's module XML::Twig
xidel
is xidel
saxon-lint
using SaxonHE 9.6 ,XPath 3.x (+retro compatibility)
Ex :
xmllint --xpath '//element/@attribute' file.xml
xmlstarlet sel -t -v "//element/@attribute" file.xml
xpath -q -e '//element/@attribute' file.xml
xidel -se '//element/@attribute' file.xml
saxon-lint --xpath '//element/@attribute' file.xml
.
I tried many things from internet. Only below method worked for me. If every answer in this question don't work, try below steps in below order. Note :
package-lock
fileC:\Users\ YOUR LOGIN NAME \AppData\Roaming\npm
" and
"C:\Users\ YOUR LOGIN NAME \AppData\Roaming\npm-cache
"AppData
and delete them too.npm cache clean --force
npm cache verify
npm install --force
$ ./configure --enable-libopencv
ERROR: opencv not found using pkg-config
$ cat /usr/lib64/pkgconfig/opencv.pc
# Package Information for pkg-config
prefix=/usr
exec_prefix=${prefix}
libdir=${exec_prefix}/lib64
includedir_old=${prefix}/include/opencv
includedir_new=${prefix}/include
Name: OpenCV
Description: Open Source Computer Vision Library
Version: 3.1.0
Libs: -L${exec_prefix}/lib64 -lopencv_shape -lopencv_stitching -lopencv_superres -lopencv_videostab -lopencv_aruco -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib -lopencv_cvv -lopencv_dnn -lopencv_dpm -lopencv_fuzzy -lopencv_hdf -lopencv_line_descriptor -lopencv_optflow -lopencv_plot -lopencv_reg -lopencv_saliency -lopencv_stereo -lopencv_structured_light -lopencv_rgbd -lopencv_surface_matching -lopencv_tracking -lopencv_datasets -lopencv_text -lopencv_face -lopencv_video -lopencv_ximgproc -lopencv_calib3d -lopencv_features2d -lopencv_flann -lopencv_xobjdetect -lopencv_objdetect -lopencv_ml -lopencv_xphoto -lopencv_highgui -lopencv_videoio -lopencv_imgcodecs -lopencv_photo -lopencv_imgproc -lopencv_core
Libs.private: -L/usr/lib64 -lQt5Test -lQt5Concurrent -lQt5OpenGL -L/lib64 -lwebp -lpng -ltiff -ljasper -ljpeg -lImath -lIlmImf -lIex -lHalf -lIlmThread -lgdal -lgstvideo-1.0 -lgstapp-1.0 -lgstbase-1.0 -lgstriff-1.0 -lgstpbutils-1.0 -lgstreamer-1.0 -lucil -lunicap -lpangoft2-1.0 -lpango-1.0 -lgobject-2.0 -lfontconfig -lfreetype -lglib-2.0 -ldc1394 -lv4l1 -lv4l2 -lgphoto2 -lgphoto2_port -lexif -lQt5Core -lQt5Gui -lQt5Widgets -lhdf5_hl -lhdf5 -lz -ldl -lm -ltesseract -llept -lpthread -lrt -lGLU -lGL
Cflags: -I${includedir_old} -I${includedir_new}
$ pkg-config --cflags --libs opencv
-I/usr/include/opencv -lopencv_shape -lopencv_stitching -lopencv_superres -lopencv_videostab -lopencv_aruco -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib -lopencv_cvv -lopencv_dnn -lopencv_dpm -lopencv_fuzzy -lopencv_hdf -lopencv_line_descriptor -lopencv_optflow -lopencv_plot -lopencv_reg -lopencv_saliency -lopencv_stereo -lopencv_structured_light -lopencv_rgbd -lopencv_surface_matching -lopencv_tracking -lopencv_datasets -lopencv_text -lopencv_face -lopencv_video -lopencv_ximgproc -lopencv_calib3d -lopencv_features2d -lopencv_flann -lopencv_xobjdetect -lopencv_objdetect -lopencv_ml -lopencv_xphoto -lopencv_highgui -lopencv_videoio -lopencv_imgcodecs -lopencv_photo -lopencv_imgproc -lopencv_core
$ uname -a
Linux fedora-23-x64 4.8.13-100.fc23.x86_64 #1 SMP Fri Dec 9 14:51:40 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
You need to iterate both the groups and the items. $.each() takes a collection as first parameter and data.response.venue.tips.groups.items.text
tries to point to a string. Both groups
and items
are arrays.
Verbose version:
$.getJSON(url, function (data) {
// Iterate the groups first.
$.each(data.response.venue.tips.groups, function (index, value) {
// Get the items
var items = this.items; // Here 'this' points to a 'group' in 'groups'
// Iterate through items.
$.each(items, function () {
console.log(this.text); // Here 'this' points to an 'item' in 'items'
});
});
});
Or more simply:
$.getJSON(url, function (data) {
$.each(data.response.venue.tips.groups, function (index, value) {
$.each(this.items, function () {
console.log(this.text);
});
});
});
In the JSON you specified, the last one would be:
$.getJSON(url, function (data) {
// Get the 'items' from the first group.
var items = data.response.venue.tips.groups[0].items;
// Find the last index and the last item.
var lastIndex = items.length - 1;
var lastItem = items[lastIndex];
console.log("User: " + lastItem.user.firstName + " " + lastItem.user.lastName);
console.log("Date: " + lastItem.createdAt);
console.log("Text: " + lastItem.text);
});
This would give you:
User: Damir P.
Date: 1314168377
Text: ajd da vidimo hocu li znati ponoviti
If you insert ng-click="$event.stopPropagation" on the parent element of your template, the stopPropogation will be caught as it bubbles up the tree, so you only have to write it once for your entire template.
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 this is late but I ended up here with a search for my error 500 with DEBUG=False
, in my case it did turn out to be the ALLOWED_HOSTS
but I was using os.environ.get('variable')
to populate the hosts, I did not notice this until I enabled logging, you can log all errors to file with the below and it will log even when DEBUG=False
:
# settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'mysite.log',
'formatter': 'verbose'
},
},
'loggers': {
'django': {
'handlers':['file'],
'propagate': True,
'level':'DEBUG',
},
'MYAPP': {
'handlers': ['file'],
'level': 'DEBUG',
},
}
}
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.
Here's how to do this with lxml without having to hard-code the namespaces or scan the text for them (as Martijn Pieters mentions):
from lxml import etree
tree = etree.parse("filename")
root = tree.getroot()
root.findall('owl:Class', root.nsmap)
UPDATE:
5 years later I'm still running into variations of this issue. lxml helps as I showed above, but not in every case. The commenters may have a valid point regarding this technique when it comes merging documents, but I think most people are having difficulty simply searching documents.
Here's another case and how I handled it:
<?xml version="1.0" ?><Tag1 xmlns="http://www.mynamespace.com/prefix">
<Tag2>content</Tag2></Tag1>
xmlns without a prefix means that unprefixed tags get this default namespace. This means when you search for Tag2, you need to include the namespace to find it. However, lxml creates an nsmap entry with None as the key, and I couldn't find a way to search for it. So, I created a new namespace dictionary like this
namespaces = {}
# response uses a default namespace, and tags don't mention it
# create a new ns map using an identifier of our choice
for k,v in root.nsmap.iteritems():
if not k:
namespaces['myprefix'] = v
e = root.find('myprefix:Tag2', namespaces)
Try running:
PATH=$PATH:~/npm/bin
and then do a test by running express
in the command line. This worked for me.
No previous solution worked for me.
I've installed both by apt-get
and manually downloading the tessdata, moved around /usr
and so on and no one worked even if i exported the variable thousand times.
Finally, on a last try before start to cry i've tried to pass the path directly to the instance of Tesseract().
In Python: tr = Tesseract("/usr/local/share/tesseract-ocr/")
and now it works. To clarify, im using tesserwrap
module.
IIS 7 or IIS 8 or 8.5 version - if you are migrating from 2003 to 2012/2008 make sure web service are in application type instead virtual directory
Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.
Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):
onClick=""
OR
The element css needs to have the following declaration:
cursor:pointer
Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working
I think this is what you want:
>>> def twoDigitHex( number ):
... return '%02x' % number
...
>>> twoDigitHex( 2 )
'02'
>>> twoDigitHex( 255 )
'ff'
<@include>
- The directive tag instructs the JSP compiler to merge contents of the included file into the JSP before creating the generated servlet code. It is the equivalent to cutting and pasting the text from your include page right into your JSP.
<jsp:include>
- The JSP Action tag on the other hand instructs the container to pause the execution of this page, go run the included page, and merge the output from that page into the output from this page.
Depending on your needs, you may either use
<@include>
or<jsp:include>
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
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#.
Check for the status of the database:
service postgresql status
If the database is not running, start the db:
sudo service postgresql start
When you use just "localhost" the MySQL client library tries to use a Unix domain socket for the connection instead of a TCP/IP connection. The error is telling you that the socket, called MySQL
, cannot be used to make the connection, probably because it does not exist (error number 2).
From the MySQL Documentation:
On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. This occurs even if a --port or -P option is given to specify a port number. To ensure that the client makes a TCP/IP connection to the local server, use --host or -h to specify a host name value of 127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by using the --protocol=TCP option.
There are a few ways to solve this problem.
127.0.0.1
instead of localhost
when you connect. The Unix socket might by faster and safer to use, though.php.ini
: open the MySQL configuration file my.cnf
to find where MySQL creates the socket, and set PHP's mysqli.default_socket
to that path. On my system it's /var/run/mysqld/mysqld.sock
.Configure the socket directly in the PHP script when opening the connection. For example:
$db = new MySQLi('localhost', 'kamil', '***', '', 0,
'/var/run/mysqld/mysqld.sock')
Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.
Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable
You can download the Apache Standard Taglib and include the jar in your project.
In Clean Code: A Handbook of Agile Software Craftsmanship there is an explicit recommendation against the usage of this prefix:
You also don't need to prefix member variables with
m_
anymore. Your classes and functions should be small enough that you don't need them.
There is also an example (C# code) of this:
Bad practice:
public class Part
{
private String m_dsc; // The textual description
void SetName(string name)
{
m_dsc = name;
}
}
Good practice:
public class Part
{
private String description;
void SetDescription(string description)
{
this.description = description;
}
}
We count with language constructs to refer to member variables in the case of explicitly ambiguity (i.e., description
member and description
parameter): this
.
Try adding animation-fill-mode: forwards;
. For example like this:
-webkit-animation: bubble 1.0s forwards; /* for less modern browsers */
animation: bubble 1.0s forwards;
You may have to change the debugger port if your port is already used by another program. To do so:
Or, maybe in other versions:
You can use JsonWriteNullProperties
for older versions of Jackson.
For Jackson 1.9+, use JsonSerialize.include
.
The easiest way I found is just to redirect the requests that trigger 404 to the client. This is done by adding an hashtag even when $locationProvider.html5Mode(true)
is set.
This trick works for environments with more Web Application on the same Web Site and requiring URL integrity constraints (E.G. external authentication). Here is step by step how to do
Set the <base>
element properly
<base href="@(Request.ApplicationPath + "/")">
First redirect 404 to a custom page, for example "Home/Error"
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Home/Error" />
</customErrors>
</system.web>
Implement a simple ActionResult
to "translate" input in a clientside route.
public ActionResult Error(string aspxerrorpath) {
return this.Redirect("~/#/" + aspxerrorpath);
}
This is the simplest way.
It is possible (advisable?) to enhance the Error function with some improved logic to redirect 404 to client only when url is valid and let the 404 trigger normally when nothing will be found on client. Let's say you have these angular routes
.when("/", {
templateUrl: "Base/Home",
controller: "controllerHome"
})
.when("/New", {
templateUrl: "Base/New",
controller: "controllerNew"
})
.when("/Show/:title", {
templateUrl: "Base/Show",
controller: "controllerShow"
})
It makes sense to redirect URL to client only when it start with "/New" or "/Show/"
public ActionResult Error(string aspxerrorpath) {
// get clientside route path
string clientPath = aspxerrorpath.Substring(Request.ApplicationPath.Length);
// create a set of valid clientside path
string[] validPaths = { "/New", "/Show/" };
// check if clientPath is valid and redirect properly
foreach (string validPath in validPaths) {
if (clientPath.StartsWith(validPath)) {
return this.Redirect("~/#/" + clientPath);
}
}
return new HttpNotFoundResult();
}
This is just an example of improved logic, of course every web application has different needs
I had the same problem after transferring all my applications from my old Mac to my new one.
I found the solution by running brew doctor
:
Warning: Broken symlinks were found. Remove them with
brew prune
After running brew prune
, Homebrew is finally back on track :)
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)
You seem to be misunderstanding how import
searches for modules. When you use an import statement it always searches the actual module path (and/or sys.modules
); it doesn't make use of module objects in the local namespace that exist because of previous imports. When you do:
import package.subpackage.module
from package.subpackage import module
from module import attribute1
The second line looks for a package called package.subpackage
and imports module
from that package. This line has no effect on the third line. The third line just looks for a module called module
and doesn't find one. It doesn't "re-use" the object called module
that you got from the line above.
In other words from someModule import ...
doesn't mean "from the module called someModule that I imported earlier..." it means "from the module named someModule that you find on sys.path...". There is no way to "incrementally" build up a module's path by importing the packages that lead to it. You always have to refer to the entire module name when importing.
It's not clear what you're trying to achieve. If you only want to import the particular object attribute1, just do from package.subpackage.module import attribute1
and be done with it. You need never worry about the long package.subpackage.module
once you've imported the name you want from it.
If you do want to have access to the module to access other names later, then you can do from package.subpackage import module
and, as you've seen you can then do module.attribute1
and so on as much as you like.
If you want both --- that is, if you want attribute1
directly accessible and you want module
accessible, just do both of the above:
from package.subpackage import module
from package.subpackage.module import attribute1
attribute1 # works
module.someOtherAttribute # also works
If you don't like typing package.subpackage
even twice, you can just manually create a local reference to attribute1:
from package.subpackage import module
attribute1 = module.attribute1
attribute1 # works
module.someOtherAttribute #also works
The simplest solution may be to add HINTS
to each find_*
request.
For example:
find_library(CURL_LIBRARY
NAMES curl curllib libcurl_imp curllib_static
HINTS "${CMAKE_PREFIX_PATH}/curl/lib"
)
For Boost I would strongly recommend using the FindBoost standard module and setting the BOOST_DIR
variable to point to your Boost libraries.
You can alias the column names one by one, like so
SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2`
FROM `foobar`
Edit You can access INFORMATION_SCHEMA.COLUMNS
directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(
select CONCAT('Foobar_', COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'Foobar'
In java config,make sure you have import your config in RootConfig like this @Import(PersistenceJPAConfig.class)
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) );
The simplest and the most efficient way is to use an uber plugin like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<finalName>uber-${project.artifactId}-${project.version}</finalName>
</configuration>
</plugin>
You will have de-normalized all in one JAR file.
@Controller
@RequestMapping(value = "/topic")
@Transactional
i solve this problem by adding @Transactional
,i think this can make session open
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
This version is using recursion
import pprint
from collections import deque
pp = pprint.PrettyPrinter(indent=4)
inp = raw_input("Enter a sentence to show as trie\n")
words = inp.split(" ")
trie = {}
def trie_recursion(trie_ds, word):
try:
letter = word.popleft()
out = trie_recursion(trie_ds.get(letter, {}), word)
except IndexError:
# End of the word
return {}
# Dont update if letter already present
if not trie_ds.has_key(letter):
trie_ds[letter] = out
return trie_ds
for word in words:
# Go through each word
trie = trie_recursion(trie, deque(word))
pprint.pprint(trie)
Output:
Coool <algos> python trie.py
Enter a sentence to show as trie
foo bar baz fun
{
'b': {
'a': {
'r': {},
'z': {}
}
},
'f': {
'o': {
'o': {}
},
'u': {
'n': {}
}
}
}
Just to show yet another option (for SQL Server 2008 and above):
Make 'maven.test.skip' as false in pom file, while building project test reource will come under test-classes.
<maven.test.skip>false</maven.test.skip>
Just another possibility: Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:
Producer:
@Service
public void FooServiceImpl implements FooService{}
Consumer:
@Autowired
private FooService fooService;
or
@Autowired
private void setFooService(FooService fooService) {}
but not ok if you use it by name:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");
It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined
In this case, assigning name to @Service("fooService")
would make it work.
I think it comes from this line in your XML file:
<context:component-scan base-package="org.assessme.com.controller." />
Replace it by:
<context:component-scan base-package="org.assessme.com." />
It is because your Autowired service is not scanned by Spring since it is not in the right package.
I furiously read all of this page, hoping to find a solution for:
"configure: error: C compiler cannot create executables"
In the end nothing worked, because my problem was a "typing" one, and was related to CFLAGS. In my .bash_profile file I had:
export ARM_ARCH="arm64”
export CFLAGS="-arch ${ARM_ARCH}"
As you can observe --- export ARM_ARCH="arm64” --- the last quote sign is not the same with the first quote sign. The first one ( " ) is legal while the second one ( ” ) is not.
This happended because I made the mistake to use TextEdit (I'm working under MacOS), and this is apparently a feature called SmartQuotes: the quote sign CHANGES BY ITSELF TO THE ILLEGAL STYLE whenever you edit something just next to it.
Lesson learned: use a proper text editor...
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.
In your NGINX vhost file, in location block which processes your PHP files (usually location ~ \.php$ {
) through FastCGI, make sure you have next lines:
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
After that don't forget to restart fpm and nginx.
Additional:
NGINX vhost paths
/etc/nginx/sites-enabled/
- LinuxRestart NGINX:
sudo service nginx restart
- Linuxbrew service restart nginx
- MacRestart FPM:
Determine fpm process name:
- systemctl list-unit-files | grep fpm
- Linux
- brew services list | grep php
- Mac
and then restart it with:
sudo service <service-name> restart
- Linuxbrew services restart <service-name>
- MacI experienced the same issue as the OP - Wordpress keeps redirecting to install-php after migration.
Problem was my database tables are named as prefix_tablename
and I missed the underscore from $table_prefix
in wp-config
.
$table_prefix = 'myprefix';
should have been
$table_prefix = 'myprefix_';
A simple solution is:
if (newStr4.startsWith("Mon") || newStr4.startsWith("Tue") || newStr4.startsWith("Wed"))
// ... you get the idea ...
A fancier solution would be:
List<String> days = Arrays.asList("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT");
String day = newStr4.substring(0, 3).toUpperCase();
if (days.contains(day)) {
// ...
}
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.
If you have several specific properties that you want to transition in the same way (because you also have some properties you specifically don't want to transition, say opacity
), another option is to do something like this (prefixes omitted for brevity):
.myclass {
transition: all 200ms ease;
transition-property: box-shadow, height, width, background, font-size;
}
The second declaration overrides the all
in the shorthand declaration above it and makes for (occasionally) more concise code.
/* prefixes omitted for brevity */_x000D_
.box {_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
background: red;_x000D_
box-shadow: red 0 0 5px 1px;_x000D_
transition: all 500ms ease;_x000D_
/*note: not transitioning width */_x000D_
transition-property: height, background, box-shadow;_x000D_
}_x000D_
_x000D_
.box:hover {_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
box-shadow: blue 0 0 10px 3px;_x000D_
background: blue;_x000D_
}
_x000D_
<p>Hover box for demo</p>_x000D_
<div class="box"></div>
_x000D_
Something along the lines:
<VirtualHost hostname:80>
...
SetEnv VARIABLE_NAME variable_value
...
</VirtualHost>
I've just faced the same issue and I came to believe that the other answers are a bit more complicated than they need to be, so here's my approach for those who don't want to rely on more libraries or decorators:
A CORS request actually consists of two HTTP requests. A preflight request and then an actual request that is only made if the preflight passes successfully.
Before the actual cross domain POST
request, the browser will issue an OPTIONS
request. This response should not return any body, but only some reassuring headers telling the browser that it's alright to do this cross-domain request and it's not part of some cross site scripting attack.
I wrote a Python function to build this response using the make_response
function from the flask
module.
def _build_cors_prelight_response():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Headers", "*")
response.headers.add("Access-Control-Allow-Methods", "*")
return response
This response is a wildcard one that works for all requests. If you want the additional security gained by CORS, you have to provide a whitelist of origins, headers and methods.
This response will convince your (Chrome) browser to go ahead and do the actual request.
When serving the actual request you have to add one CORS header - otherwise the browser won't return the response to the invoking JavaScript code. Instead the request will fail on the client-side. Example with jsonify
response = jsonify({"order_id": 123, "status": "shipped"}
response.headers.add("Access-Control-Allow-Origin", "*")
return response
I also wrote a function for that.
def _corsify_actual_response(response):
response.headers.add("Access-Control-Allow-Origin", "*")
return response
allowing you to return a one-liner.
from flask import Flask, request, jsonify, make_response
from models import OrderModel
flask_app = Flask(__name__)
@flask_app.route("/api/orders", methods=["POST", "OPTIONS"])
def api_create_order():
if request.method == "OPTIONS": # CORS preflight
return _build_cors_prelight_response()
elif request.method == "POST": # The actual request following the preflight
order = OrderModel.create(...) # Whatever.
return _corsify_actual_response(jsonify(order.to_dict()))
else
raise RuntimeError("Weird - don't know how to handle method {}".format(request.method))
def _build_cors_prelight_response():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add('Access-Control-Allow-Headers', "*")
response.headers.add('Access-Control-Allow-Methods', "*")
return response
def _corsify_actual_response(response):
response.headers.add("Access-Control-Allow-Origin", "*")
return response
it is too late I know, howewer there is no succesfully answer. I found the answer from another website. I fixed the issue when I delete the System.Runtime assemblydependency. I deleted this.
<dependentAssembly>
<assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly>
Best Regards
The answers here took the OP's question too literally. How can these answers be expanded into a scenario where there are MANY child elements, not just a single <a>
tag? Here's one way.
Let's say you have a photo gallery with a blacked out background and the photos centered in the browser. When you click the black background (but not anything inside of it) you want the overlay to close.
Here's some possible HTML:
<div class="gallery" style="background: black">
<div class="contents"> <!-- Let's say this div is 50% wide and centered -->
<h1>Awesome Photos</h1>
<img src="img1.jpg"><br>
<img src="img2.jpg"><br>
<img src="img3.jpg"><br>
<img src="img4.jpg"><br>
<img src="img5.jpg">
</div>
</div>
And here's how the JavaScript would work:
$('.gallery').click(
function()
{
$(this).hide();
}
);
$('.gallery > .contents').click(
function(e) {
e.stopPropagation();
}
);
This will stop the click events from elements inside .contents
from every research .gallery
so the gallery will close only when you click in the faded black background area, but not when you click in the content area. This can be applied to many different scenarios.
C# has, in total, 6 access modifiers:
private: The member declared with this accessibility can be visible within the containing type, it is not visible to any derived types, other types in the same assembly or types outside of the containing assembly. i.e., access is limited to the containing type only.
protected: The member declared with this accessibility can be visible within the types derived from the containing type within the containing assembly, and the types derived from the containing type outside of the containing assembly. i.e., access is limited to derived types of the containing type.
internal: The member declared with this accessibility can be visible within the assembly containing this member, it is not visible to any assembly outside of the containing assembly. i.e., access is limited to containing assembly only.
internal protected: The member declared with this accessibility can be visible within the types derived from the containing type within or outside of the containing assembly, it is also visible to any types within the containing assembly. i.e., access is limited to containing assembly or derived types.
public: The member declared with this accessibility can be visible within the assembly containing this member, or any other assembly that references the containing assembly. i.e., access is not limited.
In C# 7.2, a new level of accessibility was added:
private protected: The member declared with this accessibility can be visible within the types derived from this containing type within the containing assembly. It is not visible to any types not derived from the containing type, or outside of the containing assembly. i.e., the access is limited to derived types within the containing assembly.
Source including a sample code of the new private protected access modifier
This message is the __str__
attribute of exit
look at these examples :
1
>>> print exit
Use exit() or Ctrl-D (i.e. EOF) to exit
2
>>> exit.__str__()
'Use exit() or Ctrl-D (i.e. EOF) to exit'
3
>>> getattr(exit, '__str__')()
'Use exit() or Ctrl-D (i.e. EOF) to exit'
I assume you called a function with an argument which was defined without taking any.
def f()
puts "hello world"
end
f(1) # <= wrong number of arguments (1 for 0)
For security reasons, the shell will not search the current directory (by default) for an executable. You have to be specific, and tell bash
that your script is in the current directory (.
):
$ ./MigrateNshell.sh
Add "barryvdh/laravel-cors": "^0.7.3"
at the end of require
array inside composer.json
Save composer.json and run composer update
You are done !
Use the "indirect" function on conditional formatting.
=INDIRECT("g"&ROW())="X"
=$A$1:$Z$1500
(or however wide/long you want the conditional formatting to extend depending on your worksheet)For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.
You can repeat this to do multiple row formatting depending on a column value. Just change either the g
column or x
specific text in the formula and set different formats.
For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR"
, then it will format every row that has CAR
in the H Column as the format you specified.
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to
find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;
Just to sum up!
while (rs.next())
{
if (f.exists() && !f.isDirectory())
continue;
//proceed
}
ALTER TABLE tbl_Country DROP COLUMN IsDeleted;
Here's a working example.
Note that the COLUMN
keyword is optional, as MySQL will accept just DROP IsDeleted
. Also, to drop multiple columns, you have to separate them by commas and include the DROP
for each one.
ALTER TABLE tbl_Country
DROP COLUMN IsDeleted,
DROP COLUMN CountryName;
This allows you to DROP
, ADD
and ALTER
multiple columns on the same table in the one statement. From the MySQL reference manual:
You can issue multiple
ADD
,ALTER
,DROP
, andCHANGE
clauses in a singleALTER TABLE
statement, separated by commas. This is a MySQL extension to standard SQL, which permits only one of each clause perALTER TABLE
statement.
We do it this way...
String.prototype.getValueByKey = function (k) {
var p = new RegExp('\\b' + k + '\\b', 'gi');
return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p) + k.length + 1).substr(0, this.substr(this.search(p) + k.length + 1).search(/(&|;|$)/))) : "";
};
I found this snippet here. The idea is to go up the DOM node hierarchy until a __vue__
property is found.
function getVueFromElement(el) {
while (el) {
if (el.__vue__) {
return el.__vue__
} else {
el = el.parentNode
}
}
}
In Chrome:
Don't use NULL
, C++ allows you to use the unadorned 0
instead:
previous = 0;
next = 0;
And, as at C++11, you generally shouldn't be using either NULL
or 0
since it provides you with nullptr
of type std::nullptr_t
, which is better suited to the task.
As many people have commented, responsive design very often sets width by %
width:inherit
will inherit the CSS width NOT the computed width -- Which means the child container inherits width:100%
But, I think, almost as often responsive design sets max-width
too, therefore:
#container {
width:100%;
max-width:800px;
}
#contained {
position:fixed;
width:inherit;
max-width:inherit;
}
This worked very satisfyingly to solve my problem of making a sticky menu be restrained to the original parent width whenever it got "stuck"
Both the parent and child will adhere to the width:100%
if the viewport is less than the maximum width. Likewise, both will adhere to the max-width:800px
when the viewport is wider.
It works with my already responsive theme in a way that I can alter the parent container without having to also alter the fixed child element -- elegant and flexible
ps: I personally think it does not matter one bit that IE6/7 do not use inherit
Just restart R Studio after installing the new version of R. To confirm you're on the new version, >version and you should see the new details.
I use often abstract classes in conjuction with Template method pattern.
In main abstract class I wrote the skeleton of main algorithm and make abstract methods as hooks where suclasses can make a specific implementation; I used often when writing data parser (or processor) that need to read data from one different place (file, database or some other sources), have similar processing step (maybe small differences) and different output.
This pattern looks like Strategy pattern but it give you less granularity and can degradated to a difficult mantainable code if main code grow too much or too exceptions from main flow are required (this considerations came from my experience).
Just a small example:
abstract class MainProcess {
public static class Metrics {
int skipped;
int processed;
int stored;
int error;
}
private Metrics metrics;
protected abstract Iterator<Item> readObjectsFromSource();
protected abstract boolean storeItem(Item item);
protected Item processItem(Item item) {
/* do something on item and return it to store, or null to skip */
return item;
}
public Metrics getMetrics() {
return metrics;
}
/* Main method */
final public void process() {
this.metrics = new Metrics();
Iterator<Item> items = readObjectsFromSource();
for(Item item : items) {
metrics.processed++;
item = processItem(item);
if(null != item) {
if(storeItem(item))
metrics.stored++;
else
metrics.error++;
}
else {
metrics.skipped++;
}
}
}
}
class ProcessFromDatabase extends MainProcess {
ProcessFromDatabase(String query) {
this.query = query;
}
protected Iterator<Item> readObjectsFromSource() {
return sessionFactory.getCurrentSession().query(query).list();
}
protected boolean storeItem(Item item) {
return sessionFactory.getCurrentSession().saveOrUpdate(item);
}
}
Here another example.
This usually appears when you want to use UIActivityViewController
in iPad.
Add below, before you present the controller to mark the arrow.
activityViewController.popoverPresentationController?.sourceRect = senderView.frame // senderView can be your button/view you tapped to call this VC
I assume you already have below, if not, add together:
activityViewController.popoverPresentationController?.sourceView = self.view
There is no float: center; in css. Use margin: 0 auto; instead. So like this:
.mydivclass {
margin: 0 auto;
}
Let us see the difference between the two HTTP authentication using Wireshark
(Tool to analyse packets sent or received) .
1. Http Basic Authentication
As soon as the client types in the correct username:password,as requested by the Web-server, the Web-Server checks in the Database if the credentials are correct and gives the access to the resource .
Here is how the packets are sent and received :
In the first packet the Client fill the credentials using the POST method at the resource - lab/webapp/basicauth
.In return the server replies back with http response code 200 ok ,i.e, the username:password were correct .
Now , In the Authorization
header it shows that it is Basic Authorization followed by some random string .This String is the encoded (Base64) version of the credentials admin:aadd
(including colon ) .
2 . Http Digest Authentication(rfc 2069)
So far we have seen that the Basic Authentication sends username:password in plaintext over the network .But the Digest Auth sends a HASH of the Password using Hash algorithm.
Here are packets showing the requests made by the client and response from the server .
As soon as the client types the credentials requested by the server , the Password is converted to a response
using an algorithm and then is sent to the server , If the server Database has same response as given by the client the server gives the access to the resource , otherwise a 401 error .
In the above Authorization
, the response
string is calculated using the values of Username
,Realm
,Password
,http-method
,URI
and Nonce
as shown in the image :
Hence , we can see that the Digest Authentication is more Secure as it involve Hashing (MD5 encryption) , So the packet sniffer tools cannot sniff the Password although in Basic Auth the exact Password was shown on Wireshark.
A post back is anything that cause the page from the client's web browser to be pushed back to the server.
There's alot of info out there, search google for postbacks.
Most of the time, any ASP control will cause a post back (button/link click) but some don't unless you tell them to (checkbox/combobox)
You can also try this:
CREATE function [dbo].[fn_FormatPhone](@Phone varchar(30))
returns varchar(30)
As
Begin
declare @FormattedPhone varchar(30)
set @Phone = replace(@Phone, '.', '-') --alot of entries use periods instead of dashes
set @FormattedPhone =
Case
When isNumeric(@Phone) = 1 Then
case
when len(@Phone) = 10 then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 4, 3)+ '-' +substring(@Phone, 7, 4)
when len(@Phone) = 7 then substring(@Phone, 1, 3)+ '-' +substring(@Phone, 4, 4)
else @Phone
end
When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 8, 4)
When @phone like '[0-9][0-9][0-9] [0-9][0-9][0-9] [0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
Else @Phone
End
return @FormattedPhone
end
use on it select
(SELECT [dbo].[fn_FormatPhone](f.coffphone)) as 'Phone'
Output will be
XOR behaves like Austin explained, as an exclusive OR, either A or B but not both and neither yields false.
There are 16 possible logical operators for two inputs since the truth table consists of 4 combinations there are 16 possible ways to arrange two boolean parameters and the corresponding output.
They all have names according to this wikipedia article
Are you sure you selected Console Application? I'm running VS 2010 and with the vanilla settings a C# console app builds to \bin\debug. Try to create a new Console Application project, with the language set to C#. Build the project, and go to Project/[Console Application 1]Properties. In the Build tab, what is the Output path? It should default to bin\debug, unless you have some restricted settings on your workstation,etc. Also review the build output window and see if any errors are being thrown - in which case nothing will be built to the output folder, of course...
Here is a simple example which works for me:
temp1=true
temp2=false
if [ "$temp1" = true ] || [ "$temp2" = true ]
then
echo "Do something."
else
echo "Do something else."
fi
I have a more automated solution for this.
<form role="form" enctype="multipart/form-data" action="{{ $url }}" method="{{ $method }}">
{{ csrf_field() }}
<!-- You can add extra form fields here -->
<input hidden id="file" name="file"/>
<!-- You can add extra form fields here -->
<div class="dropzone dropzone-file-area" id="fileUpload">
<div class="dz-default dz-message">
<h3 class="sbold">Drop files here to upload</h3>
<span>You can also click to open file browser</span>
</div>
</div>
<!-- You can add extra form fields here -->
<button type="submit">Submit</button>
</form>
Dropzone.options.fileUpload = {
url: 'blackHole.php',
addRemoveLinks: true,
accept: function(file) {
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function() {
let content = fileReader.result;
$('#file').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
}
// Get file content
$file = base64_decode(request('file'));
No need to disable DropZone Discovery and the normal form submit will be able to send the file with any other form fields through standard form serialization.
This mechanism stores the file contents as base64 string in the hidden input field when it gets processed. You can decode it back to binary string in PHP through the standard base64_decode()
method.
I don't know whether this method will get compromised with large files but it works with ~40MB files.
nickf's solution modified:
function addhttp($url) {
if (!preg_match("@^https?://@i", $url) && !preg_match("@^ftps?://@i", $url)) {
$url = "http://" . $url;
}
return $url;
}
You should define the __unicode__
method on your model, and the template will call it automatically when you reference the instance.
Adding my 2 cents. My simple version based on net session which works all the time so far in Windows 7 / Windows 10. Why over complicate it?
if (!(net session)) {$path = "& '" + $myinvocation.mycommand.definition + "'" ; Start-Process powershell -Verb runAs -ArgumentList $path ; exit}
just add to the top of the script and it will run as administrator.
Use the Node.js console.time()
and console.timeEnd()
:
var i;
console.time("dbsave");
for(i = 1; i < LIMIT; i++){
db.users.save({id : i, name : "MongoUser [" + i + "]"}, end);
}
end = function(err, saved) {
console.log(( err || !saved )?"Error":"Saved");
if(--i === 1){console.timeEnd("dbsave");}
};
Just use this command to disable it.
adb shell am clear-debug-app
It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.
#include <stdio.h>
int IncMultInt(int a, int b)
{
a++;
return a * b;
}
int main(int argc, char *argv[])
{
int a = 5;
int b = 7;
printf("%d * %d = %d\n", a, b, IncMultInt(a, b));
b = 9;
// Create some local code with it's own local variable
printf("%d * %d = %d\n", a, b, ( { int _a = a+1; _a * b; } ) );
return 0;
}
So here is the controller code.
public IActionResult AddURLTest()
{
return ViewComponent("AddURL");
}
You can load it using JQuery load method.
$(document).ready (function(){
$("#LoadSignIn").click(function(){
$('#UserControl').load("/Home/AddURLTest");
});
});
source code link
Here is how I do it and works both for create and edit:
//How to do it with enums
<div class="editor-field">
@Html.RadioButtonFor(x => x.gender, (int)Gender.Male) Male
@Html.RadioButtonFor(x => x.gender, (int)Gender.Female) Female
</div>
//And with Booleans
<div class="editor-field">
@Html.RadioButtonFor(x => x.IsMale, true) Male
@Html.RadioButtonFor(x => x.IsMale, false) Female
</div>
the provided values (true and false) are the values that the engine will render as the values for the html element i.e.:
<input id="IsMale" type="radio" name="IsMale" value="True">
<input id="IsMale" type="radio" name="IsMale" value="False">
And the checked property is dependent on the Model.IsMale value.
Razor engine seems to internally match the set radio button value to your model value, if a proper from and to string convert exists for it. So there is no need to add it as an html attribute in the helper method.
There's a nodejs tool which supports json schema v4 at https://github.com/krg7880/json-schema-generator
It works either as a command line tool, or as a nodejs library:
var jsonSchemaGenerator = require('json-schema-generator'),
obj = { some: { object: true } },
schemaObj;
schemaObj = jsonSchemaGenerator(json);
Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security
. Your JAVA_HOME should always be ../JAVA/JDK
.
This is my solution. It works also in Fragment.
webView.setOnKeyListener(new OnKeyListener()
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
I wrote this trying to solve the same problem:
https://github.com/robtandy/randomdict
It has O(1) random access to keys, values, and items.
If you are using JSP 2.0 and above It will come with the EL support:
so that you can write in plain english and use and
with empty
operators to write your test:
<c:if test="${(empty object_1.attribute_A) and (empty object_2.attribute_B)}">
You need to make the x-factor into an ordered
factor with the ordering you want, e.g
x <- data.frame("variable"=letters[1:5], "value"=rnorm(5)) ## example data
x <- x[with(x,order(-value)), ] ## Sorting
x$variable <- ordered(x$variable, levels=levels(x$variable)[unclass(x$variable)])
ggplot(x, aes(x=variable,y=value)) + geom_bar() +
scale_y_continuous("",formatter="percent") + coord_flip()
I don't know any better way to do the ordering operation. What I have there will only work if there are no duplicate levels for x$variable
.
I believe you are not the only one who has problems when trying to deploy Crystal Report for VS 2010. Based on the error message you had, have you checked:
Please make sure you just have one CR version installed on your system. If you do have other CR version installed, consider to uninstall it so that your application is not "confused" about the CR version.
You need to make sure you download the correct CR version. Since you are using VS 2010, you need to refer to CRforVS_redist_install_64bit_13_0_1.zip (for 64 bit machine) or CRforVS_redist_install_32bit_13_0_1.zip (for 32 bit machine). These two are the redistributable packages. You can download full package from the below link as well: CRforVS_13_0_1.exe Note: It is sometimes necessary to install 32bit CR runtime even on 64bit OS
Make sure you setup FULL TRUST permission on your root folder
The LOCAL SERVICE permission must be setup on your application pool
Make sure the aspnet_client folder exists on your root folder.
If you can make sure all the 5 points above, your Crystal Report should work without any fuss.
Another important thing to note down here is that if you host your Crystal Report with a shared host, you need to check it with them of whether they really support Crystal Report. If you still have problems, you can switch to http://www.asphostcentral.com, who provides Crystal Report support.
Good luck!
After following the first and second steps mentioned in the hcpl's answer in the same thread, we added , '*.aar'], dir: 'libs' in the our-android-app-project-based-on-gradle/app/build.gradle file as shown below:
...
dependencies {
implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
...
Our gradle version is com.android.tools.build:gradle:3.2.1
I believe that the Roots starter theme has a fantastic function to get the current page title. It is very hackable, covers all bases, and can be easily used with the wp_title
hook.
/**
* Page titles
*/
function roots_title() {
if (is_home()) {
if (get_option('page_for_posts', true)) {
echo get_the_title(get_option('page_for_posts', true));
} else {
_e('Latest Posts', 'roots');
}
} elseif (is_archive()) {
$term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
if ($term) {
echo $term->name;
} elseif (is_post_type_archive()) {
echo get_queried_object()->labels->name;
} elseif (is_day()) {
printf(__('Daily Archives: %s', 'roots'), get_the_date());
} elseif (is_month()) {
printf(__('Monthly Archives: %s', 'roots'), get_the_date('F Y'));
} elseif (is_year()) {
printf(__('Yearly Archives: %s', 'roots'), get_the_date('Y'));
} elseif (is_author()) {
$author = get_queried_object();
printf(__('Author Archives: %s', 'roots'), $author->display_name);
} else {
single_cat_title();
}
} elseif (is_search()) {
printf(__('Search Results for %s', 'roots'), get_search_query());
} elseif (is_404()) {
_e('Not Found', 'roots');
} else {
the_title();
}
}
For information on php extensions
etc, on site.
Create a new file and name it info.php
(or some other name.php
)
Write this code in it:
<?php
phpinfo ();
?>
Save the file in the root
(home)of the site
example.com/info.php
All the php
information on your site will be displayed.The problem I was having, is that I kept adding a semi-colon ;
at the end of the url()
value, which prevented the code from working.
? NOT WORKING CODE:
$('#image_element').css('background-image', 'url(http://example.com/img.jpg);');
? WORKING CODE:
$('#image_element').css('background-image', 'url(http://example.com/img.jpg)');
Notice the omitted semi-colon ;
at the end in the working code. I simply didn't know the correct syntax, and it's really hard to notice it. Hopefully this helps someone else in the same boat.
As most answers state setdefault
or defaultdict
would let you set a default value when a key doesn't exist. However, I would like to point out a small caveat with regard to the use cases of setdefault
. When the Python interpreter executes setdefault
it will always evaluate the second argument to the function even if the key exists in the dictionary. For example:
In: d = {1:5, 2:6}
In: d
Out: {1: 5, 2: 6}
In: d.setdefault(2, 0)
Out: 6
In: d.setdefault(2, print('test'))
test
Out: 6
As you can see, print
was also executed even though 2 already existed in the dictionary. This becomes particularly important if you are planning to use setdefault
for example for an optimization like memoization
. If you add a recursive function call as the second argument to setdefault
, you wouldn't get any performance out of it as Python would always be calling the function recursively.
Since memoization was mentioned, a better alternative is to use functools.lru_cache decorator if you consider enhancing a function with memoization. lru_cache handles the caching requirements for a recursive function better.
You can use the -i privatekeyfilelocation
in case you are using a private key instead of password based.
List(1,2,3) :+ 4
Results in List[Int] = List(1, 2, 3, 4)
Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).
Here is a simple snippet that sorts a javascript representation of a Json.
function isObject(v) {
return '[object Object]' === Object.prototype.toString.call(v);
};
JSON.sort = function(o) {
if (Array.isArray(o)) {
return o.sort().map(JSON.sort);
} else if (isObject(o)) {
return Object
.keys(o)
.sort()
.reduce(function(a, k) {
a[k] = JSON.sort(o[k]);
return a;
}, {});
}
return o;
}
It can be used as follows:
JSON.sort({
c: {
c3: null,
c1: undefined,
c2: [3, 2, 1, 0],
},
a: 0,
b: 'Fun'
});
That will output:
{
a: 0,
b: 'Fun',
c: {
c2: [3, 2, 1, 0],
c3: null
}
}
This is my easiest solution:
public IActionResult InfoTag()
{
return Ok(new {name = "Fabio", age = 42, gender = "M"});
}
or
public IActionResult InfoTag()
{
return Json(new {name = "Fabio", age = 42, gender = "M"});
}
Problem is that your folder is not identified as a Source folder.
Wep, another way to achieve the same result. We use it for its readability.
Instead of doing this hard-to-read sentence:
Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> list = new Gson().fromJson(jsonArray, listType);
Create a empty class that extends a List of your object:
public class YourClassList extends ArrayList<YourClass> {}
And use it when parsing the JSON:
List<YourClass> list = new Gson().fromJson(jsonArray, YourClassList.class);
Your table will need to be created with a unique ID field that will ideally have the AUTO_INCREMENT attribute. example:
CREATE TABLE Persons
(
P_Id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (P_Id)
)
Then you can access the 3rd record in this table with:
SELECT * FROM Persons WHERE P_Id = 3
Many of the other answers here seem to address this issue from the perspective of a JavaScript function running in the browser. I'll shoot and answer assuming that when the asker said "Shell Script" he meant a Node.js backend JavaScript. Possibly using commander.js to use frame your code :)
You could use the child_process module from node's API. I pasted the example code below.
var exec = require('child_process').exec, child;
child = exec('cat *.js bad_file | wc -l',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
child();
Hope this helps!
I just wanted to give my two cents.
This is according to @Powerlord 's answer.
Puts "null" instead of null strings.
private static Dictionary<string, string> map = new Dictionary<string, string>();
public static void put(string key, string value)
{
if (value == null) value = "null";
map[key] = value;
}
public static string get(string key, string defaultValue)
{
try
{
return map[key];
}
catch (KeyNotFoundException e)
{
return defaultValue;
}
}
public static string get(string key)
{
return get(key, "null");
}
From the Tools menu, click on Options, select Designers from the side menu and untick prevent changes that can lead to recreation of a table. Then save the changes
This is documented in section 3.9.3 of the Spring 3.0 manual:
For a fallback match, the bean name is considered a default qualifier value.
In other words, the default behaviour is as though you'd added @Qualifier("country")
to the setter method.
You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file
.
Instead of
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
Use
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.
Your code is correct. You can also assign one directly to the other (see Joachim Pileborg's answer).
When you later come to compare the two structs, you need to be careful to compare the structs the long way, one member at a time, instead of using memcmp
; see How do you compare structs for equality in C?
So I have a load of release folders, where those folders may be checked out from one of a few different repos, and may be dev, qa or master branches or may be production releases, checked out from a tag, and the tag may be annotated or not. I have a script that will look at the target folder and get be back an answer in the form -. The problem is different versions of git return different status' for a tag checkout.
So I found git show-ref --tags
worked initially, except for the annotated tags. However adding -d added a separate entry to the list of tags, one for the tag, the other for the annotation (the annotation commit was identified as ^{} which I stripped out with sed).
So this is the core of my script, for anyone that wants it:-
REPO=`git --git-dir=${TARGET} remote show origin -n | \
grep "Fetch URL:" | \
sed -E "s/^.*\/(.*)$/\1/" | \
sed "s/.git$//"`
TAG=`git --git-dir=${TARGET} show-ref -d --tags | \
grep \`git --git-dir=${TARGET} show --quiet --format=format:%H HEAD\` | \
cut -d\ -f2 | \
cut -d/ -f3 | \
sed "s/\^{}$//"`
if [ "${TAG}" == "" ] ; then
BRANCH=`git --git-dir=${TARGET} show-ref --heads | \
grep \`git --git-dir=${TARGET} show --quiet --format=format:%H HEAD\` | \
cut -d\ -f2 | \
cut -d/ -f3`
TAG=${BRANCH}
fi
Add a Button
and on click of the Button
add this code:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
Useful links:
Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.
if (window.location.href.indexOf("?added-to-cart=555") > -1) {
alert("found it");
}
Try the CURRENT_USER()
function. This returns the username that MySQL used to authenticate your client connection. It is this username that determines your privileges.
This may be different from the username that was sent to MySQL by the client (for example, MySQL might use an anonymous account to authenticate your client, even though you sent a username). If you want the username the client sent to MySQL when connecting use the USER()
function instead.
The value indicates the user name you specified when connecting to the server, and the client host from which you connected. The value can be different from that of CURRENT_USER().
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_current-user
Here's my thread control function:
#!/bin/bash
# This function just checks jobs in background, don't do more things.
# if jobs number is lower than MAX, then return to get more jobs;
# if jobs number is greater or equal to MAX, then wait, until someone finished.
# Usage:
# thread_max 8
# thread_max 0 # wait, until all jobs completed
thread_max() {
local CHECK_INTERVAL="3s"
local CUR_THREADS=
local MAX=
[[ $1 ]] && MAX=$1 || return 127
# reset MAX value, 0 is easy to remember
[ $MAX -eq 0 ] && {
MAX=1
DEBUG "waiting for all tasks finish"
}
while true; do
CUR_THREADS=`jobs -p | wc -w`
# workaround about jobs bug. If don't execute it explicitily,
# CUR_THREADS will stick at 1, even no jobs running anymore.
jobs &>/dev/null
DEBUG "current thread amount: $CUR_THREADS"
if [ $CUR_THREADS -ge $MAX ]; then
sleep $CHECK_INTERVAL
else
return 0
fi
done
}
I have solved this problem on my side by 2 ways:
Adding this configuration in pom.xml
<configuration><argLine>-Xmx1024m</argLine></configuration>
Switch to used JDK 1.7 instead of 1.6
it can be done by using this command: tcptraceroute -p destination port destination IP
. like: tcptraceroute -p 9100 10.0.0.50
but don't forget to install tcptraceroute package on your system. tcpdump and nc by default installed on the system. regards
Just saying for those who using Imagick class in PHP:
$im -> gaussianBlurImage(0.8, 10); //blur
$im -> setImageCompressionQuality(85); //set compress quality to 85
Try:
insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
ts.tax_status_id,
( select r.recipient_id
from recipient r
where r.recipient_code = ?
)
from tax_status ts
where ts.tax_status_code = ?
I've created a new class to handle binding RadioButtons and CheckBoxes to enums. It works for flagged enums (with multiple checkbox selections) and non-flagged enums for single-selection checkboxes or radio buttons. It also requires no ValueConverters at all.
This might look more complicated at first, however, once you copy this class into your project, it's done. It's generic so it can easily be reused for any enum.
public class EnumSelection<T> : INotifyPropertyChanged where T : struct, IComparable, IFormattable, IConvertible
{
private T value; // stored value of the Enum
private bool isFlagged; // Enum uses flags?
private bool canDeselect; // Can be deselected? (Radio buttons cannot deselect, checkboxes can)
private T blankValue; // what is considered the "blank" value if it can be deselected?
public EnumSelection(T value) : this(value, false, default(T)) { }
public EnumSelection(T value, bool canDeselect) : this(value, canDeselect, default(T)) { }
public EnumSelection(T value, T blankValue) : this(value, true, blankValue) { }
public EnumSelection(T value, bool canDeselect, T blankValue)
{
if (!typeof(T).IsEnum) throw new ArgumentException($"{nameof(T)} must be an enum type"); // I really wish there was a way to constrain generic types to enums...
isFlagged = typeof(T).IsDefined(typeof(FlagsAttribute), false);
this.value = value;
this.canDeselect = canDeselect;
this.blankValue = blankValue;
}
public T Value
{
get { return value; }
set
{
if (this.value.Equals(value)) return;
this.value = value;
OnPropertyChanged();
OnPropertyChanged("Item[]"); // Notify that the indexer property has changed
}
}
[IndexerName("Item")]
public bool this[T key]
{
get
{
int iKey = (int)(object)key;
return isFlagged ? ((int)(object)value & iKey) == iKey : value.Equals(key);
}
set
{
if (isFlagged)
{
int iValue = (int)(object)this.value;
int iKey = (int)(object)key;
if (((iValue & iKey) == iKey) == value) return;
if (value)
Value = (T)(object)(iValue | iKey);
else
Value = (T)(object)(iValue & ~iKey);
}
else
{
if (this.value.Equals(key) == value) return;
if (!value && !canDeselect) return;
Value = value ? key : blankValue;
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
And for how to use it, let's say you have an enum for running a task manually or automatically, and can be scheduled for any days of the week, and some optional options...
public enum StartTask
{
Manual,
Automatic
}
[Flags()]
public enum DayOfWeek
{
Sunday = 1 << 0,
Monday = 1 << 1,
Tuesday = 1 << 2,
Wednesday = 1 << 3,
Thursday = 1 << 4,
Friday = 1 << 5,
Saturday = 1 << 6
}
public enum AdditionalOptions
{
None = 0,
OptionA,
OptionB
}
Now, here's how easy it is to use this class:
public class MyViewModel : ViewModelBase
{
public MyViewModel()
{
StartUp = new EnumSelection<StartTask>(StartTask.Manual);
Days = new EnumSelection<DayOfWeek>(default(DayOfWeek));
Options = new EnumSelection<AdditionalOptions>(AdditionalOptions.None, true, AdditionalOptions.None);
}
public EnumSelection<StartTask> StartUp { get; private set; }
public EnumSelection<DayOfWeek> Days { get; private set; }
public EnumSelection<AdditionalOptions> Options { get; private set; }
}
And here's how easy it is to bind checkboxes and radio buttons with this class:
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<!-- Using RadioButtons for exactly 1 selection behavior -->
<RadioButton IsChecked="{Binding StartUp[Manual]}">Manual</RadioButton>
<RadioButton IsChecked="{Binding StartUp[Automatic]}">Automatic</RadioButton>
</StackPanel>
<StackPanel Orientation="Horizontal">
<!-- Using CheckBoxes for 0 or Many selection behavior -->
<CheckBox IsChecked="{Binding Days[Sunday]}">Sunday</CheckBox>
<CheckBox IsChecked="{Binding Days[Monday]}">Monday</CheckBox>
<CheckBox IsChecked="{Binding Days[Tuesday]}">Tuesday</CheckBox>
<CheckBox IsChecked="{Binding Days[Wednesday]}">Wednesday</CheckBox>
<CheckBox IsChecked="{Binding Days[Thursday]}">Thursday</CheckBox>
<CheckBox IsChecked="{Binding Days[Friday]}">Friday</CheckBox>
<CheckBox IsChecked="{Binding Days[Saturday]}">Saturday</CheckBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<!-- Using CheckBoxes for 0 or 1 selection behavior -->
<CheckBox IsChecked="{Binding Options[OptionA]}">Option A</CheckBox>
<CheckBox IsChecked="{Binding Options[OptionB]}">Option B</CheckBox>
</StackPanel>
</StackPanel>
Paraphrasing from http://java.sun.com/javase/6/docs/api/java/io/File.html:
The classes under java.io
resolve relative pathnames against the current user directory, which is typically the directory in which the virtual machine was started.
Eclipse sets the working directory to the top-level project folder.
Use:
int rename(const char * oldname, const char * newname);
The rename() function is defined in the stdio.h header file. It renames a file or directory from oldname to newname. The rename operation is the same as move, hence you can also use this function to move a file.
There's also terms query which should save you some work. Here example from docs:
{
"terms" : {
"tags" : [ "blue", "pill" ],
"minimum_should_match" : 1
}
}
Under hood it constructs boolean should. So it's basically the same thing as above but shorter.
There's also a corresponding terms filter.
So to summarize your query could look like this:
{
"filtered": {
"query": {
"match": { "title": "hello world" }
},
"filter": {
"terms": {
"tags": ["c", "d"]
}
}
}
}
With greater number of tags this could make quite a difference in length.
if you want to get the whole period:
from sqlalchemy import and_, func
query = DBSession.query(User).filter(and_(func.date(User.birthday) >= '1985-01-17'),\
func.date(User.birthday) <= '1988-01-17'))
That means range: 1985-01-17 00:00 - 1988-01-17 23:59
use this code to solve the issue
app.get('/', function(req, res){
res.render("index");
});
Well... so many good answers but i wanna to add more on it. A brief look on Inner class in Java- Java allows us to define a class within another class and Being able to nest classes in this way has certain advantages:
It can hide(It increases encapsulation) the class from other classes - especially relevant if the class is only being used by the class it is contained within. In this case there is no need for the outside world to know about it.
It can make code more maintainable as the classes are logically grouped together around where they are needed.
The inner class has access to the instance variables and methods of its containing class.
We have mainly three types of Inner Classes
Some of the important points to be remember
Let`s try to see the above concepts practically_
public class MyInnerClass {
public static void main(String args[]) throws InterruptedException {
// direct access to inner class method
new MyInnerClass.StaticInnerClass().staticInnerClassMethod();
// static inner class reference object
StaticInnerClass staticInnerclass = new StaticInnerClass();
staticInnerclass.staticInnerClassMethod();
// access local inner class
LocalInnerClass localInnerClass = new MyInnerClass().new LocalInnerClass();
localInnerClass.localInnerClassMethod();
/*
* Pay attention to the opening curly braces and the fact that there's a
* semicolon at the very end, once the anonymous class is created:
*/
/*
AnonymousClass anonymousClass = new AnonymousClass() {
// your code goes here...
};*/
}
// static inner class
static class StaticInnerClass {
public void staticInnerClassMethod() {
System.out.println("Hay... from Static Inner class!");
}
}
// local inner class
class LocalInnerClass {
public void localInnerClassMethod() {
System.out.println("Hay... from local Inner class!");
}
}
}
I hope this will helps to everyone. Please refer for more
Why dont you just add a new Partial View with i's own specific controller passing the required model to the partial view and finally Render the mentioned partial view on your Layout.cshtml using RenderPartial or RenderAction ?
I use this method for showing the logged in user's info like name , profile picture and etc.
Here are some useful delete operations for mongodb using mongo shell
To delete particular document in collections: db.mycollection.remove( {name:"stack"} )
To delete all documents in collections: db.mycollection.remove()
To delete any particular collection : db.mycollection.drop()
to delete database :
first go to that database by use mydb
command and then
db.dropDatabase()
Just Make use of the CloseMXL.Excel Library. It's easy and pretty fast too.
Class
private DataTable getAllList()
{
string constr = ConfigurationManager.ConnectionStrings["RConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT EmpId, gender, EmpName, pOnHold FROM Employee WHERE EmpId= '"+ AnyVariable + "' ORDER BY EmpName"))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
da.SelectCommand = cmd;
da.Fill(dt);
dt.Columns[0].ColumnName = "Employee Id";
dt.Columns[1].ColumnName = "Gender";
dt.Columns[2].ColumnName = "Employee Name";
dt.Columns[3].ColumnName = "On Hold";
return dt;
}
}
}
}
Then another method which get the Dataset
public DataSet getDataSetExportToExcel()
{
DataSet ds = new DataSet();
DataTable dtEmp = new DataTable("CLOT List");
dtEmp = getAllList();
ds.Tables.Add(dtEmp);
ds.Tables[0].TableName = "Employee"; //If you which to use Mutliple Tabs
return ds;
}
Now you Button Click Event
protected void btn_Export_Click(object sender, EventArgs e)
{
DataSet ds = getDataSetExportToExcel();
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(ds);
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=EmployeeonHoldList.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
I may not use shell command because of security in the company so the best way I found on internet.
Sub OpenFileOrFolderOrWebsite()
'Shows how to open files and / or folders and / or websites / or create emails using the FollowHyperlink method
Dim strXLSFile As String, strPDFFile As String, strFolder As String, strWebsite As String
Dim strEmail As String, strSubject As String, strEmailHyperlink As String
strFolder = "C:\Test Files\"
strXLSFile = strFolder & "Test1.xls"
strPDFFile = strFolder & "Test.pdf"
strWebsite = "http://www.blalba.com/"
strEmail = "mailto:[email protected]"
strSubject = "?subject=Test"
strEmailHyperlink = strEmail & strSubject
'**************FEEL FREE TO COMMENT ANY OF THESE TO TEST JUST ONE ITEM*********
'Open Folder
ActiveWorkbook.FollowHyperlink Address:=strFolder, NewWindow:=True
'Open excel workbook
ActiveWorkbook.FollowHyperlink Address:=strXLSFile, NewWindow:=True
'Open PDF file
ActiveWorkbook.FollowHyperlink Address:=strPDFFile, NewWindow:=True
'Open VBAX
ActiveWorkbook.FollowHyperlink Address:=strWebsite, NewWindow:=True
'Create New Email
ActiveWorkbook.FollowHyperlink Address:=strEmailHyperlink, NewWindow:=True
'******************************************************************************
End Sub
so actually its
strFolder = "C:\Test Files\"
and
ActiveWorkbook.FollowHyperlink Address:=strFolder, NewWindow:=True
Well, at the risk of making things too easy...
for (var member in myObject) delete myObject[member];
...would seem to be pretty effective in cleaning the object in one line of code with a minimum of scary brackets. All members will be truly deleted instead of left as garbage.
Obviously if you want to delete the object itself, you'll still have to do a separate delete() for that.
How about:
function changeText() {
$("#demoTable td").each(function () {
$(this).html().replace("8: Tap on APN and Enter <B>www</B>", "");
}
}
For testing only two values, I'd personally do this:
if x ~= 0 and x ~= 1 then
print( "X must be equal to 1 or 0" )
return
end
If you need to test against more than two values, I'd stuff your choices in a table acting like a set, like so:
choices = {[0]=true, [1]=true, [3]=true, [5]=true, [7]=true, [11]=true}
if not choices[x] then
print("x must be in the first six prime numbers")
return
end
See ?read.table
. Basically, when you use read.table
, you specify a number indicating the column:
##Row names in the first column
read.table(filname.txt, row.names=1)
You need to set the value of $title
before echoing it.
Also, you should really sanitize any data before using it in queries as this is a security risk
In Kibana 6.5, you can generate CSV under the Share Tab -> CSV Reports.
The request will be queued. Once the CSV is generated, it will be available for download under Management -> Reporting
If you are using Excel 2013 Than do the following File > Option > Advanced > Under Display options for this worksheet: uncheck the checkbox before Show formulas in cells instead of their calculated results This should resolve the issue.
From http://www.gnu.org/s/bash/manual/bash.html#Special-Parameters
?
Expands to the exit status of the most recently executed foreground pipeline.
I had set:
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender log4j.appender.R.DatePattern='.'yyyy-MM-dd # Archive log files (Keep one year of daily files) log4j.appender.R.MaxBackupIndex=367
Like others before me, the DEBUG option showed me the error:
log4j:WARN No such property [maxBackupIndex] in org.apache.log4j.DailyRollingFileAppender.
Here is an idea I have not tried yet, suppose I set the DatePattern such that the files overwrite each other after the required time period. To retain a year's worth I could try setting:
log4j.appender.R.DatePattern='.'MM-dd
Would it work or would it cause an error ? Like that it will take a year to find out, I could try:
log4j.appender.R.DatePattern='.'dd
but it will still take a month to find out.
I had the same error in Chrome. The Chrome console told me that the error was in the 1st line of the HTML file.
It was actually in the .js file. So watch out for setValidNou(1060, $(this).val(), 0')
error types.
In your model:
validates_presence_of :address1, message: 'Put some address please'
In your view
<% m.errors.each do |attr, msg| %>
<%= msg %>
<% end %>
If you do instead
<%= attr %> <%= msg %>
you get this error message with the attribute name
address1 Put some address please
if you want to get the error message for one single attribute
<%= @model.errors[:address1] %>
Some applications may detect click source at low OS level. If you really need that kind of hack, you may just run target app in virtual machine's window, and run cliker in host OS, it can help.
AS per point 1, your PEAR path is c:\xampplite\php\pear\
However, your path is pointing to \xampplite\php\pear\PEAR
Putting the two one above the other you can clearly see one is too long:
c:\xampplite\php\pear\
\xampplite\php\pear\PEAR
Your include path is set to go one PEAR too deep into the pear tree. The PEAR subfolder of the pear folder includes the PEAR component. You need to adjust your include path up one level.
(you don't need the c: by the way, your path is fine as is, just too deep)
The #!
line tells the kernel (specifically, the implementation of the execve
system call) that this program is written in an interpreted language; the absolute pathname that follows identifies the interpreter. Programs compiled to machine code begin with a different byte sequence -- on most modern Unixes, 7f 45 4c 46
(^?ELF) that identifies them as such.
You can put an absolute path to any program you want after the #!
, as long as that program is not itself a #!
script. The kernel rewrites an invocation of
./script arg1 arg2 arg3 ...
where ./script
starts with, say, #! /usr/bin/perl
, as if the command line had actually been
/usr/bin/perl ./script arg1 arg2 arg3
Or, as you have seen, you can use #! /bin/sh
to write a script intended to be interpreted by sh
.
The #!
line is only processed if you directly invoke the script (./script
on the command line); the file must also be executable (chmod +x script
). If you do sh ./script
the #!
line is not necessary (and will be ignored if present), and the file does not have to be executable. The point of the feature is to allow you to directly invoke interpreted-language programs without having to know what language they are written in. (Do grep '^#!' /usr/bin/*
-- you will discover that a great many stock programs are in fact using this feature.)
Here are some rules for using this feature:
#!
must be the very first two bytes in the file. In particular, the file must be in an ASCII-compatible encoding (e.g. UTF-8 will work, but UTF-16 won't) and must not start with a "byte order mark", or the kernel will not recognize it as a #!
script.#!
must be an absolute path (starts with /
). It cannot contain space, tab, or newline characters.#!
and the /
. Do not put more than one space there.#!
line, they will not be expanded.#! /usr/bin/awk -f
), sometimes it's just useful (#! /usr/bin/perl -Tw
). Unfortunately, you cannot put two or more arguments after the absolute path.#! /usr/bin/env interpreter
instead of #! /absolute/path/to/interpreter
. This is almost always a mistake. It makes your program's behavior depend on the $PATH
variable of the user who invokes the script. And not all systems have env
in the first place.setuid
or setgid
privileges can't use #!
; they have to be compiled to machine code. (If you don't know what setuid
is, don't worry about this.)Regarding csh
, it relates to sh
roughly as Nutrimat Advanced Tea Substitute does to tea. It has (or rather had; modern implementations of sh
have caught up) a number of advantages over sh
for interactive usage, but using it (or its descendant tcsh
) for scripting is almost always a mistake. If you're new to shell scripting in general, I strongly recommend you ignore it and focus on sh
. If you are using a csh
relative as your login shell, switch to bash
or zsh
, so that the interactive command language will be the same as the scripting language you're learning.
Why don't you use:
<li><a href="#">bla</a></li>
a {
opacity: 0.0;
font-size: 1px;
}
li {
background-image: url('test.jpg');
}
If you haven't any span or div element, it works perfectly for links.
Java EE is a collection of specifications for developing and deploying enterprise applications.
In general, enterprise applications refer to software hosted on servers that provide the applications that support the enterprise.
The specifications (defined by Sun) describe services, application programming interfaces (APIs), and protocols.
The 13 core technologies that make up Java EE are:
The Java EE product provider is typically an application-server, web-server, or database-system vendor who provides classes that implement the interfaces defined in the specifications. These vendors compete on implementations of the Java EE specifications.
When a company requires Java EE experience what are they really asking for is experience using the technologies that make up Java EE. Frequently, a company will only be using a subset of the Java EE technologies.
The ones method is much faster than using repmat:
>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds.
And, in my opinion, makes for much more readable code.
You can create an std::string
#include <string>
#include <vector>
int main(int argc, char *argv[])
{
// check if there is more than one argument and use the second one
// (the first argument is the executable)
if (argc > 1)
{
std::string arg1(argv[1]);
// do stuff with arg1
}
// Or, copy all arguments into a container of strings
std::vector<std::string> allArgs(argv, argv + argc);
}
UPDATE tb_Company SET CompanyIndustry = UCASE(LEFT(CompanyIndustry, 1)) +
SUBSTRING(CompanyIndustry, 2, LEN(CompanyIndustry))
I had a similar problem which I fixed by moving some fragment transaction code from onResume()
into onStart()
.
To be more precise: My app is a launcher. After pressing the Android Home button, the user can choose a launcher until his/her decision is remembered. When going "back" at this point (e. g. by tapping in the greyish area) the app crashed.
Maybe this helps somebody.
_.isArray(image_array) && !_.isEmpty(image_array)
Okay, per http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang%20faq.htm:
NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.
Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:
export NLS_LANG=AMERICAN_AMERICA.UTF8
Oracle gets a big fat F for usability.
You can use the adb
command which comes in the tools dir of the SDK:
adb shell
It will give you a command line prompt where you can browse and access the filesystem. Or you can extract the files you want:
adb pull /sdcard/the_file_you_want.txt
Also, if you use eclipse with the ADT, there's a view to browse the file system (Window->Show View->Other... and choose Android->File Explorer)
Old question, but apparently Google likes it so I thought I put an answer down here after some research about this problem.
If you create a figure from scratch you can give it a size option while creation:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(3, 6))
plt.plot(range(10)) #plot example
plt.show() #for control
fig.savefig('temp.png', dpi=fig.dpi)
figsize(width,height) adjusts the absolute dimension of your plot and helps to make sure both plots look the same.
As stated in another answer the dpi option affects the relative size of the text and width of the stroke on lines, etc. Using the option dpi=fig.dpi makes sure the relative size of those are the same both for show() and savefig().
Alternatively the figure size can be changed after creation with:
fig.set_size_inches(3, 6, forward=True)
forward allows to change the size on the fly.
If you have trouble with too large borders in the created image you can adjust those either with:
plt.tight_layout()
#or:
plt.tight_layout(pad=2)
or:
fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight')
#or:
fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight', pad_inches=0.5)
The first option just minimizes the layout and borders and the second option allows to manually adjust the borders a bit. These tips helped at least me to solve my problem of different savefig() and show() images.
Avoid deleting your items in a for loop and calling notifyDataSetChanged in every iteration. Instead just call the clear method in your list myList.clear();
and then notify your adapter
public void clearData() {
myList.clear(); // clear list
mAdapter.notifyDataSetChanged(); // let your adapter know about the changes and reload view.
}
I suggest to use "return false" instead of useing some javascript in the href-tag:
<form id="">
...
</form>
<a href="#" onclick="document.getElementById('myform').submit(); return false;">send form</a>
In addition to @delmadord's answer and your comments:
Currently there is no method to create subquery in FROM
clause, so you need to manually use raw statement, then, if necessary, you will merge all the bindings:
$sub = Abc::where(..)->groupBy(..); // Eloquent Builder instance
$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder
->count();
Mind that you need to merge bindings in correct order. If you have other bound clauses, you must put them after mergeBindings
:
$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
// ->where(..) wrong
->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder
// ->where(..) correct
->count();
For Ubuntu 14.04
Just removed the package Oxideqt-dodecs then install flash or ubuntu restricted extras
and you are good to go!!
Without dropdown ID:
$("#SelectedCountryId").change(function () {
$('option:selected', $(this)).text();
}
All the methods above do not handle deep cloning of objects where it is nested to n levels. I did not check its performance over others but it is short and simple.
The first example below shows object cloning using Object.assign
which clones just till first level.
var person = {_x000D_
name:'saksham',_x000D_
age:22,_x000D_
skills: {_x000D_
lang:'javascript',_x000D_
experience:5_x000D_
}_x000D_
}_x000D_
_x000D_
newPerson = Object.assign({},person);_x000D_
newPerson.skills.lang = 'angular';_x000D_
console.log(newPerson.skills.lang); //logs Angular
_x000D_
Using the below approach deep clones object
var person = {_x000D_
name:'saksham',_x000D_
age:22,_x000D_
skills: {_x000D_
lang:'javascript',_x000D_
experience:5_x000D_
}_x000D_
}_x000D_
_x000D_
anotherNewPerson = JSON.parse(JSON.stringify(person));_x000D_
anotherNewPerson.skills.lang = 'angular';_x000D_
console.log(person.skills.lang); //logs javascript
_x000D_
hash[:new_key] = hash.delete :old_key
Use LayoutParams (as explained already). However be careful which LayoutParams to choose. According to https://stackoverflow.com/a/11971553/3184778 "you need to use the one that relates to the PARENT of the view you're working on, not the actual view"
If for example the TextView is inside a TableRow, then you need to use TableRow.LayoutParams instead of RelativeLayout or LinearLayout
I know this is old, but... Another option may be to use the FileSystemWatcher like so:
void SomeMethod()
{
System.IO.FileSystemWatcher m_Watcher = new System.IO.FileSystemWatcher();
m_Watcher.Path = path;
m_Watcher.Filter = "*.*";
m_Watcher.NotifyFilter = m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
m_Watcher.Created += new FileSystemEventHandler(OnChanged);
m_Watcher.EnableRaisingEvents = true;
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
string path = e.FullPath;
lock (listLock)
{
pathsToUpload.Add(path);
}
}
This would allow you to watch the directories for file changes with an extremely lightweight process, that you could then use to store the names of the files that changed so that you could back them up at the appropriate time.
An alternative to NCover can be PartCover, is an open source code coverage tool for .NET very similar to NCover, it includes a console application, a GUI coverage browser, and XSL transforms for use in CruiseControl.NET.
It is a very interesting product.
OpenCover has replaced PartCover.
Extending la_f0ka's comment, esp. if you also need the index position in your code, you should be able to do
s = 'ABCDEFG'
for pos in 0...s.length
puts s[pos].chr
end
The .chr
is important as Ruby < 1.9 returns the code of the character at that position instead of a substring of one character at that position.
Using ngClass
to disabled the button for invalid form is not good practice in Angular2 when its providing inbuilt features to enable and disable the button if form is valid and invalid respectively without doing any extra efforts/logic.
[disabled]
will do all thing like if form is valid then it will be enabled and if form is invalid then it will be disabled automatically.
See Example:
<form (ngSubmit)="f.form.valid" #f="ngForm" novalidate>
<input type="text" placeholder="Name" [(ngModel)]="txtName" name="txtname" #textname="ngModel" required>
<input type="button" class="mdl-button" [disabled]="!f.form.valid" (click)="onSave()" name="">
Use the styles
left: 0px;
or/and
right: 0px;
or/and
top: 0px;
or/and
bottom: 0px;
I think for most cases that will do the job
(Google search brought me to this question even though I did not ask for perl)
I had a problem with running scripts (albeit bash not perl). Apache had a config of ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
however Apache error log showed File does not exist: /var/www/cgi-bin/test.html
.
Tried putting the script in both /usr/lib/cgi-bin/
and /var/www/cgi-bin/
but neither were working.
After a prolonged googling session what cracked it for me was
sudo a2enmod cgi
and everything fell into place using /usr/lib/cgi-bin/
.
Xcode 5 lost my Mac Provisioning Profile while the one for iOS was present. The tips elsewhere helped solve the problem; this is what I did, because I noticed the lists were too short and did not include *Mac Team Provisioning Profile: **
This might happen with Pod Frameworks
.
I was facing the same issue with AnswerBotProvidersSDK.framework
and my mistake was, I set Run Script checked for Install builds only in targets build phases.
Incorrect settings:
Correct Settings:
Sometimes when we do these steps:
alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);
The last statement fails with
ORA-00955 "name is already used by an existing object"
Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.
You can combine the dropping of primary key constraint and unique index into a single sql statement:
alter table my_table drop constraint my_pk drop index;
check this: ORA-00955 "name is already used by an existing object"
I use substr
too, but in a different way. I want to extract the last 6 characters of "Give me your food." Here are the steps:
(1) Split the characters
splits <- strsplit("Give me your food.", split = "")
(2) Extract the last 6 characters
tail(splits[[1]], n=6)
Output:
[1] " " "f" "o" "o" "d" "."
Each of the character can be accessed by splits[[1]][x]
, where x is 1 to 6.
Just an another ussage example for Notepad++ (regular expression search mode)
Find: (g|c|u|d)(et|reate|pdate|elete)_(.)([^\s (]+)
Replace: \U\1\E$2\U\3\E$4
Example:
get_user -> GetUser
create_user -> CreateUser
update_user -> UpdateUser
delete_user -> DeleteUser
ContextMenuStrip
CellContextMenuStripNeeded
e.ColumnIndex
, e.RowIndex
.I believe that e.RowIndex
is what you are asking for.
Suggestion: when user causes your event CellContextMenuStripNeeded
to fire, use e.RowIndex
to get data from your grid, such as the ID. Store the ID as the menu event's tag item.
Now, when user actually clicks your menu item, use the Sender property to fetch the tag. Use the tag, containing your ID, to perform the action you need.
if you want to copy in same Jenkins but in different subfolders, create new item -> use copy from. new Job will be cloned in same directory. Then use move option to move it in desired directory
I know this is an old question but I figured out I should pitch my answer anyways.
The following snippet iterates through each character of the text and uses the IsNumber() method, which returns true if the character is a number and false the other way, to check if all the characters are numbers. If all are numbers, the method returns true. If not it returns false.
using System;
private bool ValidateText(string text){
char[] characters = text.ToCharArray();
foreach(char c in characters){
if(!char.IsNumber(c))
return false;
}
return true;
}
When using literal strings (start with @") this might be easier
char tab = '\u0009';
string A = "Apple";
string B = "Bob";
string myStr = String.Format(@"{0}:{1}{2}", A, tab, B);
Would result in Apple:<tab>Bob
this is nice and simple and gets all the nodes.
$ip = Resolve-DNSName google.com
$ip
also try inputting an ip instead of a domain name and check out those results too!
It's recommended to use a query parameter when the information is optional.
Route Parameters or Query Parameters?
There is no hard-and-fast rule. In general,
prefer a route parameter when
- the value is required.
- the value is necessary to distinguish one route path from another.
prefer a query parameter when
- the value is optional.
- the value is complex and/or multi-variate.
from https://angular.io/guide/router#optional-route-parameters
You just need to take out the parameter from the route path.
@RouteConfig([
{
path: '/user/',
component: User,
as: 'User'
}])
I use:
rails db:drop
to delete the databases.rails db:create
to create the databases based on config/database.yml
The previous commands may be replaced with rails db:reset
.
Don't forget to run rails db:migrate
to run the migrations.
Kotlin
this.findViewById<View>(android.R.id.content)
.rootView
.setBackgroundColor(ContextCompat.getColor(this, R.color.black))
There are no auto incrementing features in Oracle for a column. You need to create a SEQUENCE object. You can use the sequence like:
insert into table(batch_id, ...) values(my_sequence.nextval, ...)
...to return the next number. To find out the last created sequence nr (in your session), you would use:
my_sequence.currval
This site has several complete examples on how to use sequences.
Important:
Read the note at the end.
Quick answer :
Use to_string()
. (available since c++11)
example :
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string pi = "pi is " + to_string(3.1415926);
cout<< "pi = "<< pi << endl;
return 0;
}
run it yourself : http://ideone.com/7ejfaU
These are available as well :
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
Important Note:
As @Michael Konecný rightfully pointed out, using to_string()
is risky at best that is its very likely to cause unexpected results.
From http://en.cppreference.com/w/cpp/string/basic_string/to_string :
With floating point types
std::to_string
may yield unexpected results as the number of significant digits in the returned string can be zero, see the example.
The return value may differ significantly from whatstd::cout
prints by default, see the example.std::to_string
relies on the current locale for formatting purposes, and therefore concurrent calls tostd::to_string
from multiple threads may result in partial serialization of calls.C++17
providesstd::to_chars
as a higher-performance locale-independent alternative.
The best way would be to use stringstream
as others such as @dcp demonstrated in his answer.:
This issue is demonstrated in the following example :
run the example yourself : https://www.jdoodle.com/embed/v0/T4k
#include <iostream>
#include <sstream>
#include <string>
template < typename Type > std::string to_str (const Type & t)
{
std::ostringstream os;
os << t;
return os.str ();
}
int main ()
{
// more info : https://en.cppreference.com/w/cpp/string/basic_string/to_string
double f = 23.43;
double f2 = 1e-9;
double f3 = 1e40;
double f4 = 1e-40;
double f5 = 123456789;
std::string f_str = std::to_string (f);
std::string f_str2 = std::to_string (f2); // Note: returns "0.000000"
std::string f_str3 = std::to_string (f3); // Note: Does not return "1e+40".
std::string f_str4 = std::to_string (f4); // Note: returns "0.000000"
std::string f_str5 = std::to_string (f5);
std::cout << "std::cout: " << f << '\n'
<< "to_string: " << f_str << '\n'
<< "ostringstream: " << to_str (f) << "\n\n"
<< "std::cout: " << f2 << '\n'
<< "to_string: " << f_str2 << '\n'
<< "ostringstream: " << to_str (f2) << "\n\n"
<< "std::cout: " << f3 << '\n'
<< "to_string: " << f_str3 << '\n'
<< "ostringstream: " << to_str (f3) << "\n\n"
<< "std::cout: " << f4 << '\n'
<< "to_string: " << f_str4 << '\n'
<< "ostringstream: " << to_str (f4) << "\n\n"
<< "std::cout: " << f5 << '\n'
<< "to_string: " << f_str5 << '\n'
<< "ostringstream: " << to_str (f5) << '\n';
return 0;
}
output :
std::cout: 23.43
to_string: 23.430000
ostringstream: 23.43
std::cout: 1e-09
to_string: 0.000000
ostringstream: 1e-09
std::cout: 1e+40
to_string: 10000000000000000303786028427003666890752.000000
ostringstream: 1e+40
std::cout: 1e-40
to_string: 0.000000
ostringstream: 1e-40
std::cout: 1.23457e+08
to_string: 123456789.000000
ostringstream: 1.23457e+08
When you have an assignment operator in a statement, the LHS of the operator must be something the language calls an lvalue. If the LHS of the operator does not evaluate to an lvalue, the value from the RHS cannot be assigned to the LHS.
You cannot use:
10 = 20;
since 10
does not evaluate to an lvalue.
You can use:
int i;
i = 20;
since i
does evaluate to an lvalue.
You cannot use:
int i;
i + 1 = 20;
since i + 1
does not evaluate to an lvalue.
In your case, p + 1
does not evaluate to an lavalue. Hence, you cannot use
p + 1 = p;
From ggplot2 2.0.0
you can use the margin =
argument of element_text()
to change the distance between the axis title and the numbers. Set the values of the margin
on t
op, r
ight, b
ottom, and l
eft side of the element.
ggplot(mpg, aes(cty, hwy)) + geom_point()+
theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))
margin
can also be used for other element_text
elements (see ?theme
), such as axis.text.x
, axis.text.y
and title
.
addition
in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top")
, you'll need a different theme setting - e.g. axis.title.x.top
. See https://github.com/tidyverse/ggplot2/issues/4343.
Consider this example:
public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real|How|To|||";
System.out.println
(java.util.Arrays.toString(testString.split("\\|")));
// output : [Real, How, To]
}
}
The result does not include the empty strings between the "|" separator. To keep the empty strings :
public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real|How|To|||";
System.out.println
(java.util.Arrays.toString(testString.split("\\|", -1)));
// output : [Real, How, To, , , ]
}
}
For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html
Here is an example using a 3rd party wrapper library for Vue called vue-moment
.
In addition to binding Moment instance into Vue's root scope, this library includes moment
and duration
filters.
This example includes localization and is using ES6 module imports, an official standard, instead of NodeJS's CommonJS module system requires.
import Vue from 'vue';
import moment from 'moment';
import VueMoment from 'vue-moment';
// Load Locales ('en' comes loaded by default)
require('moment/locale/es');
// Choose Locale
moment.locale('es');
Vue.use(VueMoment, { moment });
Now you can use the Moment instance directly in your Vue templates without any additional markup:
<small>Copyright {{ $moment().year() }}</small>
Or the filters:
<span>{{ 3600000 | duration('humanize') }}</span>
<!-- "an hour" -->
<span>{{ [2, 'years'] | duration('add', 1, 'year') | duration('humanize') }}</span>
<!-- "3 years" -->
I had put the restriction on the app that only United States residence could use the app. I was working from Canada at the time this error message appeared. After removing the restriction everything worked.
Have you tried it without the ANSI join ?
CREATE MATERIALIZED VIEW MV_Test
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS
SELECT V.*, P.* FROM TPM_PROJECTVERSION V,TPM_PROJECT P
WHERE P.PROJECTID = V.PROJECTID
Turns out the docs tell you the answer! The UIButton will ignore the title change if it already has an Attributed String to use (with seems to be the default you get when using Xcode interface builder).
I used the following:
[self.loginButton
setAttributedTitle:[[NSAttributedString alloc] initWithString:@"Error !!!" attributes:nil]
forState:UIControlStateDisabled];
[self.loginButton setEnabled:NO];
int x = 0xFF; //your number - 11111111
How do I for example read a 3 bit integer value starting at the second bit
int y = x & ( 0x7 << 2 ) // 0x7 is 111
// and you shift it 2 to the left
Here are a couple possible solutions...
I have not tried all of these myself yet, but I will be trying them all soon.
Note: I do not have any personal or financial connection to any of these tools.
1) VB Script to EXE Converter (NOT Compiler): (Free)
vbs2exe.com.
The exe produced appears to be a true EXE.
From their website:
VBS to EXE is a free online converter that doesn't only convert your vbs files into exe but it also:
1- Encrypt your vbs file source code using 128 bit key.
2- Allows you to call win32 API
3- If you have troubles with windows vista especially when UAC is enabled then you may give VBS to EXE a try.
4- No need for wscript.exe to run your vbs anymore.
5- Your script is never saved to the hard disk like some others converters. it is a TRUE exe not an extractor.
This solution should work even if wscript/cscript is not installed on the computer.
Basically, this creates a true .EXE file. Inside the created .EXE is an "engine" that replaces wscript/cscript, and an encrypted copy of your VB Script code. This replacement engine executes your code IN MEMORY without calling wscript/cscript to do it.
2) Compile and Convert VBS to EXE...:
ExeScript
The current version is 3.5.
This is NOT a Free solution. They have a 15 day trial. After that, you need to buy a license for a hefty $44.96 (Home License/noncommercial), or $89.95 (Business License/commercial usage).
It seems to work in a similar way to the previous solution.
According to a forum post there:
Post: "A Exe file still need Windows Scripting Host (WSH) ??"
WSH is not required if "Compile" option was used, since ExeScript
implements it's own scripting host. ...
3) Encrypt the script with Microsoft's ".vbs to .vbe" encryption tool.
Apparently, this does not work for Windows 7/8, and it is possible there are ways to "decrypt" the .vbe file. At the time of writing this, I could not find a working link to download this. If I find one, I will add it to this answer.
/*The simplest way to get/display total physical memory in VB.net (Tested)
public sub get_total_physical_mem()
dim total_physical_memory as integer
total_physical_memory=CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024))
MsgBox("Total Physical Memory" + CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString + "Mb" )
end sub
*/
//The simplest way to get/display total physical memory in C# (converted Form http://www.developerfusion.com/tools/convert/vb-to-csharp)
public void get_total_physical_mem()
{
int total_physical_memory = 0;
total_physical_memory = Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024));
Interaction.MsgBox("Total Physical Memory" + Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString() + "Mb");
}
An other way which makes then your jsfiddle less buggy (needed double click on open).
This doesn't use any delegated event to body level
Set tabindex="-1"
to DIV .popup ( and for style CSS outline:0
)
$(".link").click(function(e){
e.preventDefault();
$(".popup").fadeIn(300,function(){$(this).focus();});
});
$('.close').click(function() {
$(".popup").fadeOut(300);
});
$(".popup").on('blur',function(){
$(this).fadeOut(300);
});
The original checked
attribute (HTML 4 and before) did not require a value on it - if it existed, the element was "checked", if not, it wasn't.
This, however is not valid for XHTML that followed HTML 4.
The standard proposed to use checked="checked"
as a condition for true - so both ways you posted end up doing the same thing.
It really doesn't matter which one you use - use the one that makes most sense to you and stick to it (or agree with your team which way to go).
var dir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
I jumped in for the top rated answer and found myself not getting what I expected. I had to read the comments to find what I was looking for.
For that reason I am posting the answer listed in the comments to give it the exposure it deserves.
You could use the arrays CopyTo()
method.
Or with LINQ you can use Skip()
and Take()
...
byte[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
var subset = arr.Skip(2).Take(2);
With bootstrap 3 the best way to go about achieving what you want is ...with offsetting columns. Please see these examples for more detail:
http://getbootstrap.com/css/#grid-offsetting
In short, and without seeing your divs here's an example what might help, without using any custom classes. Just note how the "col-6" is used and how half of that is 3 ...so the "offset-3" is used. Splitting equally will allow the centered spacing you're going for:
<div class="container">
<div class="col-sm-6 col-sm-offset-3">
your centered, floating column
</div></div>
if (capital.touched && capital != undefined && capital.length < 1 ) {
//capital does exists
}
In order to sync
multiple models along with custom pivot data, you need this:
$user->roles()->sync([
1 => ['expires' => true],
2 => ['expires' => false],
...
]);
Ie.
sync([
related_id => ['pivot_field' => value],
...
]);
edit
Answering the comment:
$speakers = (array) Input::get('speakers'); // related ids
$pivotData = array_fill(0, count($speakers), ['is_speaker' => true]);
$syncData = array_combine($speakers, $pivotData);
$user->roles()->sync($syncData);
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
Sometimes while installing JDK, you may get a dll is missing error. Because of this, it won't copy the tools.jar file to the java folder. So please reinstall the JDK in a different location and if it is successful then you will see the tools.jar file.
Define tooltip text
<input type="text" id="firstname" name="firstname" tooltipText="Type in your firstname in this box">
Initialize and configure the script
<script type="text/javascript">
var tooltipObj = new DHTMLgoodies_formTooltip();
tooltipObj.setTooltipPosition('right');
tooltipObj.setPageBgColor('#EEE');
tooltipObj.setCloseMessage('Exit');
tooltipObj.initFormFieldTooltip();
</script>
Funny detail about php: extended classes can use non-static functions of a parent class in a static matter. Outside you will get a strict error.
error_reporting(E_ALL);
class GrandPa
{
public function __construct()
{
print("construct grandpa<br/>");
$this->grandPaFkt();
}
protected function grandPaFkt(){
print(">>do Grandpa<br/>");
}
}
class Pa extends GrandPa
{
public function __construct()
{ parent::__construct();
print("construct Pa <br/>");
}
public function paFkt(){
print(">>do Pa <br>");
}
}
class Child extends Pa
{
public function __construct()
{
GrandPa::__construct();
Pa::paFkt();//allright
//parent::__construct();//whatever you want
print("construct Child<br/>");
}
}
$test=new Child();
$test::paFkt();//strict error
So inside a extended class (Child) you can use
parent::paFkt();
or
Pa::paFkt();
to access a parent (or grandPa's) (not private) function.
Outside class def
$test::paFkt();
will trow strict error (non static function).
Assuming you have a CSV of this structure:
"a","b"
1,2
3,4
5,6
And you want the output to be:
[{'a': '1', ' "b"': '2'}, {'a': '3', ' "b"': '4'}, {'a': '5', ' "b"': '6'}]
A zip function (not yet mentioned) is simple and quite helpful.
def read_csv(filename):
with open(filename) as f:
file_data=csv.reader(f)
headers=next(file_data)
return [dict(zip(headers,i)) for i in file_data]
Operators first()
and take(1)
aren't the same.
The first()
operator takes an optional predicate
function and emits an error
notification when no value matched when the source completed.
For example this will emit an error:
import { EMPTY, range } from 'rxjs';
import { first, take } from 'rxjs/operators';
EMPTY.pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
... as well as this:
range(1, 5).pipe(
first(val => val > 6),
).subscribe(console.log, err => console.log('Error', err));
While this will match the first value emitted:
range(1, 5).pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
On the other hand take(1)
just takes the first value and completes. No further logic is involved.
range(1, 5).pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
Then with empty source Observable it won't emit any error:
EMPTY.pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
Jan 2019: Updated for RxJS 6
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
align-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
.item {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: gold;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>_x000D_
<div class="item">1</div>_x000D_
<div class="item">2</div>_x000D_
<div class="item">3</div>_x000D_
</div>_x000D_
<div>_x000D_
<div class="item">4</div>_x000D_
<div class="item">5</div>_x000D_
<div class="item">6</div>_x000D_
</div>_x000D_
<div>_x000D_
<div class="item">7</div>_x000D_
<div class="item">8</div>_x000D_
<div class="item">9</div>_x000D_
</div>_x000D_
<div class="item">10</div>_x000D_
</div>
_x000D_
you could try wrapping the items in a dom element like here. with this you dont have to know a lot of css just having a good structure will solve the problem.
just try this..
you need to open the connection using connection.open()
on the SqlCommand.Connection
object before executing ExecuteNonQuery()
We can not bind this to setTimeout()
, as it always execute with global object (Window), if you want to access this
context in the callback function then by using bind()
to the callback function we can achieve as:
setTimeout(function(){
this.methodName();
}.bind(this), 2000);
For anyone using XCode 7, it's very easy to design for a specific device size (instead of the default square-ish canvas).
In Interface Builder, select your ViewController or Scene from the left menu. Then under Show the Attributes Inspector
, go to the Simulated Metrics
, and pick the desired Size
from the dropdown menu.
This not the best way to manage session in react you can use web tokens to encrypt your data that you want save,you can use various number of services available a popular one is JSON web tokens(JWT) with web-tokens you can logout after some time if there no action from the client And after creating the token you can store it in your local storage for ease of access.
jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
res.json({
token
});
user object in here is the user data which you want to keep in the session
localStorage.setItem('session',JSON.stringify(token));
Uncheck this in Windows Explorer.
"Hide file type extensions for known types"
We can implement the basic authorization without needing any module
//1.
var http = require('http');
//2.
var credentials = {
userName: "vikas kohli",
password: "vikas123"
};
var realm = 'Basic Authentication';
//3.
function authenticationStatus(resp) {
resp.writeHead(401, { 'WWW-Authenticate': 'Basic realm="' + realm + '"' });
resp.end('Authorization is needed');
};
//4.
var server = http.createServer(function (request, response) {
var authentication, loginInfo;
//5.
if (!request.headers.authorization) {
authenticationStatus (response);
return;
}
//6.
authentication = request.headers.authorization.replace(/^Basic/, '');
//7.
authentication = (new Buffer(authentication, 'base64')).toString('utf8');
//8.
loginInfo = authentication.split(':');
//9.
if (loginInfo[0] === credentials.userName && loginInfo[1] === credentials.password) {
response.end('Great You are Authenticated...');
// now you call url by commenting the above line and pass the next() function
}else{
authenticationStatus (response);
}
});
server.listen(5050);
Source:- http://www.dotnetcurry.com/nodejs/1231/basic-authentication-using-nodejs
I had the same error, and in my case X and y were dataframes so I had to convert them to matrices first:
X = X.values.astype(np.float)
y = y.values.astype(np.float)
Edit: The originally suggested X.as_matrix() is Deprecated
Simply use something like the following - the string should be there already:
<?php
if(isset($_SERVER['SERVER_SOFTWARE'])){
echo $_SERVER['SERVER_SOFTWARE'];
}
?>
Usually this means that your schema and mapping files are not in synch and there is a renamed or missing column someplace.
Here you can find solution created by pavlo_ua: If you have .Net > 2.0 and If you have .Net == 2.0 (search for pavlo_ua answer)
Cheers, jbk
edit: So to have clear answer not just link
You can set Text of combobox when its style is set as DropDown (and it is editable). When you have .Net version < 3.0 there is no IsReadonly property so we need to use win api to set textbox of combobox as readonly:
private bool m_readOnly = false;
private const int EM_SETREADONLY = 0x00CF;
internal delegate bool EnumChildWindowsCallBack( IntPtr hwnd, IntPtr lParam );
[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
[ DllImport( "user32.dll" ) ]
internal static extern int EnumChildWindows( IntPtr hWndParent, EnumChildWindowsCallBack lpEnumFunc, IntPtr lParam );
private bool EnumChildWindowsCallBackFunction(IntPtr hWnd, IntPtr lparam)
{
if( hWnd != IntPtr.Zero )
{
IntPtr readonlyValue = ( m_readOnly ) ? new IntPtr( 1 ) : IntPtr.Zero;
SendMessage( hWnd, EM_SETREADONLY, readonlyValue, IntPtr.Zero );
comboBox1.Invalidate();
return true;
}
return false;
}
private void MakeComboBoxReadOnly( bool readOnly )
{
m_readOnly = readOnly;
EnumChildWindowsCallBack callBack = new EnumChildWindowsCallBack(this.EnumChildWindowsCallBackFunction );
EnumChildWindows( comboBox1.Handle, callBack, IntPtr.Zero );
}
Remove all spaces in string
// Remove only spaces
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/ /g,'');
"
Textwithspaces1111
andsome
breaklines
"
// Remove spaces and breaklines
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/\s/g,'');
"Textwithspaces1111andsomebreaklines"
Concerning the answer by BoltClock and John, I personally had issues with the initial keyword when using IE11. It works fine in Chrome, but in IE it seems to have no effect.
According to this answer IE does not support the initial keyword: Div display:initial not working as intended in ie10 and chrome 29
I tried setting it blank instead as suggested here: how to revert back to normal after display:none for table row
This worked and was good enough for my scenario. Of course to set the real initial value the above answer is the only good one I could find.
You can include the branch to track when setting up remotes, to keep things working as you might expect:
git remote add --track master origin [email protected]:group/project.git # git
git remote add --track master origin [email protected]:group/project.git # git w/IP
git remote add --track master origin http://github.com/group/project.git # http
git remote add --track master origin http://172.16.1.100/group/project.git # http w/IP
git remote add --track master origin /Volumes/Git/group/project/ # local
git remote add --track master origin G:/group/project/ # local, Win
This keeps you from having to manually edit your git config or specify branch tracking manually.
(if above command will not allow to update the .bashrc file then you can open this file in notepad by writing command at terminal i.e. "leafpad ~/.bashrc")
shift + Z + Z
)if you are using FragmentActivity. then do like this
first call This inside your Fragment.
public void callParentMethod(){
getActivity().onBackPressed();
}
and then Call onBackPressed
method in side your parent FragmentActivity
class.
@Override
public void onBackPressed() {
//super.onBackPressed();
//create a dialog to ask yes no question whether or not the user wants to exit
...
}
var img = $('<img />', {
id: 'Myid',
src: 'MySrc.gif',
alt: 'MyAlt'
});
img.appendTo($('#YourDiv'));
TASKLIST
doesn't set an exit code that you could check in a batch file. One workaround to checking the exit code could be parsing its standard output (which you are presently redirecting to NUL
). Apparently, if the process is found, TASKLIST
will display its details, which include the image name too. Therefore, you could just use FIND
or FINDSTR
to check if the TASKLIST
's output contains the name you have specified in the request. Both FIND
and FINDSTR
set a non-null exit code if the search was unsuccessful. So, this would work:
@echo off
tasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" > nul
if not errorlevel 1 (taskkill /f /im "notepad.exe") else (
specific commands to perform if the process was not found
)
exit
There's also an alternative that doesn't involve TASKLIST
at all. Unlike TASKLIST
, TASKKILL
does set an exit code. In particular, if it couldn't terminate a process because it simply didn't exist, it would set the exit code of 128. You could check for that code to perform your specific actions that you might need to perform in case the specified process didn't exist:
@echo off
taskkill /f /im "notepad.exe" > nul
if errorlevel 128 (
specific commands to perform if the process
was not terminated because it was not found
)
exit
This should do the job
//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");
//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
To mock a static method that return void for e.g. Fileutils.forceMKdir(File file),
Sample code:
File file =PowerMockito.mock(File.class);
PowerMockito.doNothing().when(FileUtils.class,"forceMkdir",file);
The problem is this block:
using (var sr = new StreamReader(ms))
{
Console.WriteLine(sr.ReadToEnd());
}
When the StreamReader
is closed (after leaving the using), it closes it's underlying stream as well, so now the MemoryStream
is closed. When the StreamWriter
gets closed, it tries to flush everything to the MemoryStream
, but it is closed.
You should consider not putting the StreamReader
in a using block.
If you only want to ssh a few times, such as on a borrowed or shared computer, try:
ssh buck@hostname
or
ssh -l buck hostname
Apache Commons Collection class.
StringUtils.equalsAny(CharSequence string, CharSequence... searchStrings)
So in your case, it would be
StringUtils.equalsAny(str, "val1", "val2", "val3");
Two Solutions:
Based on the previous answer that give me some errors, finaly I use this code with GetOpenedWindows
function:
public class InfoWindow
{
public IntPtr Handle = IntPtr.Zero;
public FileInfo File = new FileInfo( Application.ExecutablePath );
public string Title = Application.ProductName;
public override string ToString() {
return File.Name + "\t>\t" + Title;
}
}//CLASS
/// <summary>Contains functionality to get info on the open windows.</summary>
public static class RuningWindows
{
internal static event EventHandler WindowActivatedChanged;
internal static Timer TimerWatcher = new Timer();
internal static InfoWindow WindowActive = new InfoWindow();
internal static void DoStartWatcher() {
TimerWatcher.Interval = 500;
TimerWatcher.Tick += TimerWatcher_Tick;
TimerWatcher.Start();
}
/// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
/// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
public static IDictionary<IntPtr , InfoWindow> GetOpenedWindows()
{
IntPtr shellWindow = GetShellWindow();
Dictionary<IntPtr , InfoWindow> windows = new Dictionary<IntPtr , InfoWindow>();
EnumWindows( new EnumWindowsProc( delegate( IntPtr hWnd , int lParam ) {
if ( hWnd == shellWindow ) return true;
if ( !IsWindowVisible( hWnd ) ) return true;
int length = GetWindowTextLength( hWnd );
if ( length == 0 ) return true;
StringBuilder builder = new StringBuilder( length );
GetWindowText( hWnd , builder , length + 1 );
var info = new InfoWindow();
info.Handle = hWnd;
info.File = new FileInfo( GetProcessPath( hWnd ) );
info.Title = builder.ToString();
windows[hWnd] = info;
return true;
} ) , 0 );
return windows;
}
private delegate bool EnumWindowsProc( IntPtr hWnd , int lParam );
public static string GetProcessPath( IntPtr hwnd )
{
uint pid = 0;
GetWindowThreadProcessId( hwnd , out pid );
if ( hwnd != IntPtr.Zero ) {
if ( pid != 0 ) {
var process = Process.GetProcessById( (int) pid );
if ( process != null ) {
return process.MainModule.FileName.ToString();
}
}
}
return "";
}
[DllImport( "USER32.DLL" )]
private static extern bool EnumWindows( EnumWindowsProc enumFunc , int lParam );
[DllImport( "USER32.DLL" )]
private static extern int GetWindowText( IntPtr hWnd , StringBuilder lpString , int nMaxCount );
[DllImport( "USER32.DLL" )]
private static extern int GetWindowTextLength( IntPtr hWnd );
[DllImport( "USER32.DLL" )]
private static extern bool IsWindowVisible( IntPtr hWnd );
[DllImport( "USER32.DLL" )]
private static extern IntPtr GetShellWindow();
[DllImport( "user32.dll" )]
private static extern IntPtr GetForegroundWindow();
//WARN: Only for "Any CPU":
[DllImport( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
private static extern int GetWindowThreadProcessId( IntPtr handle , out uint processId );
static void TimerWatcher_Tick( object sender , EventArgs e )
{
var windowActive = new InfoWindow();
windowActive.Handle = GetForegroundWindow();
string path = GetProcessPath( windowActive.Handle );
if ( string.IsNullOrEmpty( path ) ) return;
windowActive.File = new FileInfo( path );
int length = GetWindowTextLength( windowActive.Handle );
if ( length == 0 ) return;
StringBuilder builder = new StringBuilder( length );
GetWindowText( windowActive.Handle , builder , length + 1 );
windowActive.Title = builder.ToString();
if ( windowActive.ToString() != WindowActive.ToString() ) {
//fire:
WindowActive = windowActive;
if ( WindowActivatedChanged != null ) WindowActivatedChanged( sender , e );
Console.WriteLine( "Window: " + WindowActive.ToString() );
}
}
}//CLASS
Warning: You can only compil/debug under "Any CPU" to access to 32bits Apps...
i fixed my problem by this code on linux file system
if (!file.exists())
Files.createFile(file.toPath());
svn info
, I believe, is what you want.
If you just wanted the revision, maybe you could do something like:
svn info | grep "Revision:"
For SSIS you could go with:
RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE())
Expression builder screen:
Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class:
class Base
{
// some virtual methods
};
class Derived : public Base
{
~Derived()
{
// Do some important cleanup
}
};
Here, you'll notice that I didn't declare Base's destructor to be virtual
. Now, let's have a look at the following snippet:
Base *b = new Derived();
// use b
delete b; // Here's the problem!
Since Base's destructor is not virtual
and b
is a Base*
pointing to a Derived
object, delete b
has undefined behaviour:
[In
delete b
], if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.
In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak.
To sum up, always make base classes' destructors virtual
when they're meant to be manipulated polymorphically.
If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call delete
on a base class pointer.
You can learn more about virtuality and virtual base class destructor in this article from Herb Sutter.
You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.
Think of it like this…
In the unit test
@Spy
on it@Mock
all of the other class/service/database (i.e. external dependencies) In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mock
ed.
In this very simple example, a function that creates an object will be difficult to test
public void doSomethingCool(String foo) {
MyObject obj = new MyObject(foo);
// can't do much with obj in a unit test unless it is returned
}
But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.
public void doSomethingCool(String foo) {
MyObject obj = MyObjectService.getMeAnObject(foo);
}
as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.
I prepared a piece of code to show you how to use the task for some of these scenarios.
// method to run tasks in a parallel
public async Task RunMultipleTaskParallel(Task[] tasks) {
await Task.WhenAll(tasks);
}
// methode to run task one by one
public async Task RunMultipleTaskOneByOne(Task[] tasks)
{
for (int i = 0; i < tasks.Length - 1; i++)
await tasks[i];
}
// method to run i task in parallel
public async Task RunMultipleTaskParallel(Task[] tasks, int i)
{
var countTask = tasks.Length;
var remainTasks = 0;
do
{
int toTake = (countTask < i) ? countTask : i;
var limitedTasks = tasks.Skip(remainTasks)
.Take(toTake);
remainTasks += toTake;
await RunMultipleTaskParallel(limitedTasks.ToArray());
} while (remainTasks < countTask);
}
The accepted answer builds two LocalDate
objects, which are quite expensive if you are reading lot of data.
I use this:
public static int getDaysBetween(DateTime earlier, DateTime later)
{
return (int) TimeUnit.MILLISECONDS.toDays(later.getMillis()- earlier.getMillis());
}
By calling getMillis()
you use already existing variables.
MILLISECONDS.toDays()
then, uses a simple arithmetic calculation, does not create any object.
Here is a bit specific example, I would like to show. Say you have many duplicate entries in some of your rows. If you have string entries you could easily use string methods to find all indexes to drop.
ind_drop = df[df['column_of_strings'].apply(lambda x: x.startswith('Keyword'))].index
And now to drop those rows using their indexes
new_df = df.drop(ind_drop)
Simple way of creating newtonsoft JObject from Properties.
This is a Sample User Properties
public class User
{
public string Name;
public string MobileNo;
public string Address;
}
and i want this property in newtonsoft JObject is:
JObject obj = JObject.FromObject(new User()
{
Name = "Manjunath",
MobileNo = "9876543210",
Address = "Mumbai, Maharashtra, India",
});
Output will be like this:
{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\conf
Your Port ID in Server.xml File in Source folder is 8080. change the Port Number to 8081...etc
I had this problem and all I had to do is return true
from touchend and the warning went away.
If you are using JAVA8 API then this code will help.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateTimeString = LocalDateTime.now().format(formatter);
System.out.println(dateTimeString);
It will print the date in the given format.
But if you again create a object of LocalDateTime it will print the 'T' in between the date and time.
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println(dateTime.toString());
So as mentioned in earlier posts as well, the representation and usage is different.
Its better to use "yyyy-MM-dd'T'HH:mm:ss" pattern and convert the string/date object accordingly.
Also you can use the following command:
git push -u origin master
This creates (-u) another branch in your remote repo. Once the authentication using ssh is done that is.
In this part of your SP:
IF @DateFirst <> '' and @DateLast <> ''
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + @DateFirst
+ ' and convert (Date,DateLog) <=''' + @DateLast
you are trying to concatenate strings and datetimes.
As the datetime
type has higher priority than varchar
/nvarchar
, the +
operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= '''
and others) to datetime or numeric values. And fails.
That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.
To amend the situation, you need to add explicit casting of your datetime variables to strings:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst)
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)
You'll also need to add closing single quotes:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst) + ''''
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''
Have you tried by setting the MIME type of your .m4v to "video/m4v" or "video/x-m4v" ?
Browsers might use the canPlayType
method internally to check if a <source>
is candidate to playback.
In Chrome, I have these results:
document.createElement("video").canPlayType("video/mp4"); // "maybe"
document.createElement("video").canPlayType("video/m4v"); // ""
document.createElement("video").canPlayType("video/x-m4v"); // "maybe"
I see a lot of suggestions here, but this collection is missing the following.
button.setOnClickListener(::onButtonClicked)
and in the current class we have a method like this:
private fun onButtonClicked(view: View) {
// do stuff
}