This works for me in Windows 10:
C:
cd \Users\YOUR_USER\AppData\Local\Android\Sdk\cmdline-tools\latest\bin
sdkmanager.bat --licenses
After, yes to all
If you are using com.google.android.gms:play-services-maps:16.0.0 or below and your app is targeting API level 28 (Android 9.0) or above, you must include the following declaration within the element of AndroidManifest.xml.
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
This is handled for you if you are using com.google.android.gms:play-services-maps:16.1.0 and is not necessary if your app is targeting a lower API level.
In my case the issue was missing Android SDK Command-line tools
https://adoptopenjdk.net currently supports all distributions of JDK from version 8 onwards. For example https://adoptopenjdk.net/releases.html#x64_win
Here's an example of how I was able to use JDK version 8 with sdkmanager and much more: https://travis-ci.com/mmcc007/screenshots/builds/109365628
For JDK 9 (and I think 10, and possibly 11, but not 12 and beyond), the following should work to get sdkmanager working:
export SDKMANAGER_OPTS="--add-modules java.se.ee"
sdkmanager --list
Answers so far did not adress the problem of sharing code with other people who don't necessarily use Eclipse. Here is one proposition. The key is to use a maven profile to solve the Eclipse Case.
It assumes you have defined a property junit5.version
in your pom like:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit5.version>5.1.1</junit5.version>
</properties>
then in the profiles
section add the following:
<profiles>
<profile>
<id>eclipse</id>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit5.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.1.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
</profile>
</profiles>
All you have to do after this is to select the profile in your local Eclipse: Right click on your project and select Maven > Select Maven Profiles...
(or hit Ctrl + Alt + P), and then check the "eclipse" profile we just created.
With that you are done. Your Eclipse will run Junit 5 tests as expected, but the configuration you added won't pollute other builds or other IDE
Update 2019-10:
As stated in the issue tracker, Google has been working on a new Android SDK Command-line Tools release that runs on current JVMs (9, 10, 11+) and does not depend on deprecated JAXB EE modules!
You can download and use the new Android SDK Command-line Tools inside Android Studio or by manually downloading them from the Google servers:
For the latest versions check the URLs inside the repository.xml.
If you manually unpack the command line tools, take care of placing them in a subfolder inside your $ANDROID_HOME
(e.g. $ANDROID_HOME/cmdline-tools/...
).
If issue remains even after updating dependency version, then delete everything present under
C:\Users\[your_username]\.m2\repository\com\fasterxml
And, make sure following dependencies are present:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
Had similar message
Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'. More than one file was found with OS independent path 'constant-values.html'
To resolve it, I had to enable packages view(1) in Android Studio, then browse through the tree to libraries, and locate the duplicates(2)
Then, ctrl+alt+f12 (or RMB menu)(3) - and found libraries which caused the issue. Made list of files inside those libs which caused the issues, and wrote them to app's build.gradle file inside android section. Other option is to deal with the library, containing duplicate files
packagingOptions {
exclude 'allclasses-frame.html'
exclude 'allclasses-noframe.html'
<..>
At the time of compilation as well as run time, add the switch --add-modules java.xml.bind
javac --add-modules java.xml.bind <java file name>
java --add-modules java.xml.bind <class file>
A good introduction of the JDK 9
modules can also be found at :
https://www.youtube.com/watch?v=KZfbRuvv5qc
It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment
as you can see above).
Try checking to see if Hibernate core is put in as dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.11.Final</version>
<scope>compile</scope>
</dependency>
Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.
On PSv5.1 or higher, where >
and >>
are effectively aliases of Out-File
, you can set the default encoding for >
/ >>
/ Out-File
via the $PSDefaultParameterValues
preference variable:
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
On PSv5.0 or below, you cannot change the encoding for >
/ >>
, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File
.
(The $PSDefaultParameterValues
preference variable was introduced in PSv3.0).
On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
an -Encoding
parameter (which in PSv5.1+ includes >
and >>
), use:
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
If you place this command in your $PROFILE
, cmdlets such as Out-File
and Set-Content
will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding
parameter.
Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues
:
$PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }
Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.
For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.
The automatic $OutputEncoding
variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.
PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.
This means that source-code files without a BOM are assumed to be UTF-8, and using >
/ Out-File
/ Set-Content
defaults to BOM-less UTF-8; explicit use of the utf8
-Encoding
argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom
value.
If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1
file will typically not have a UTF-8 pseudo-BOM:
Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat
, sed
, and awk
- and even some editors such as gedit
- to pass the pseudo-BOM through, i.e., to treat it as data.
bash
with, say, text=$(cat file)
or text=$(<file)
- the resulting variable will contain the pseudo-BOM as the first 3 bytes.Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.
Note:
The following doesn't aspire to cover all standard cmdlets.
Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.
As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.
Cmdlets that write:
Out-File
and >
/ >>
create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content
/ Add-Content
(see next point); New-ModuleManifest
and Export-CliXml
also create UTF-16LE files.
Set-Content
(and Add-Content
if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default
).
Export-Csv
indeed creates ASCII files, as documented, but see the notes re -Append
below.
Export-PSSession
creates UTF-8 files with BOM by default.
New-Item -Type File -Value
currently creates BOM-less(!) UTF-8.
The Send-MailMessage
help topic also claims that ASCII encoding is the default - I have not personally verified that claim.
Start-Transcript
invariably creates UTF-8 files with BOM, but see the notes re -Append
below.
Re commands that append to an existing file:
>>
/ Out-File -Append
make no attempt to match the encoding of a file's existing content.
That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding
, which is not an option with >>
(except indirectly in PSv5.1+, via $PSDefaultParameterValues
, as shown above).
In short: you must know the encoding of an existing file's content and append using that same encoding.
Add-Content
is the laudable exception: in the absence of an explicit -Encoding
argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.
This inconsistency between Out-File -Append
/ >>
and Add-Content
, which also affects PowerShell Core, is discussed in this GitHub issue.
Export-Csv -Append
partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append
assumes UTF-8 is, whereas Add-Content
assumes ANSI.
Start-Transcript -Append
partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.
Cmdlets that read (that is, the encoding used in the absence of a BOM):
Get-Content
and Import-PowerShellDataFile
default to ANSI (Default
), which is consistent with Set-Content
.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.
By contrast, Import-Csv
, Import-CliXml
and Select-String
assume UTF-8 in the absence of a BOM.
Yeah, resolved the exception by adding commons-collections4-4.1 jar file to the CLASSPATH user varible of system. Downloaded from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.1
If you don't provide Spark configuration in JavaSparkContext then you get this error. That is: JavaSparkContext sc = new JavaSparkContext();
Solution: Provide JavaSparkContext sc = new JavaSparkContext(conf);
I faced same issue apply all possible solution but finally this solve my problem
export class AppRoutingModule {
constructor(private router: Router) {
this.router.errorHandler = (error: any) => {
this.router.navigate(['404']); // or redirect to default route
}
}
}
Hope this will help you.
make sure ,use this 404 route wrote on the bottom of the code.
syntax will be like
{
path: 'page-not-found',
component: PagenotfoundComponent
},
{
path: '**',
redirectTo: '/page-not-found'
},
Thank you
now it is:
this.activatedRoute.queryParams.subscribe((params: Params) => {
console.log(params);
});
I had different version of annotations jar. Changed all 3 jars to use SAME version of databind,annotations and core jackson jars
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.6</version>
</dependency>
True, RxJs has separated its map operator in a separate module and now you need to explicity import it like any other operator.
import rxjs/add/operator/map;
and you will be fine.
I have tried all methods, which are mentioned above.But no one method works for me.finally i got solution for above issue and it is working for me.
I tried this method:
In Html:
<li><a (click)= "aboutPageLoad()" routerLinkActive="active">About</a></li>
In TS file:
aboutPageLoad() {
this.router.navigate(['/about']);
}
Just create a valid JSX element. In my case I assigned a component to an object.
const AwesomeButtonComponent = () => <button>AwesomeButton</button>
const next = {
link: "http://awesomeLink.com",
text: "Awesome text",
comp: AwesomeButtonComponent
}
Somewhere else in my Code I wanted to dynamically assign that button.
return (
<div>
{next.comp ? next.comp : <DefaultAwesomeButtonComp/>}
</div>
)
I solve this by declaring a JSX comp which I initialized via the props comp.
const AwesomeBtnFromProps = next.comp
return (
<div>
{next.comp ? <AwesomeBtnFromProps/> : <DefaultAwesomeButtonComp/>}
</div>
)
The spread operator spread the Array into the separate arguments of a function.
let iterableObjB = [1,2,3,4]
function (...iterableObjB) //turned into
function (1,2,3,4)
This error is because of multiple project having the offending resources.
Try out adding the dependencies projects other way around. (like in pom.xml or external depandancies)
The configuration here is working for me:
configurations {
customProvidedRuntime
}
dependencies {
compile(
// Spring Boot dependencies
)
customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}
war {
classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}
springBoot {
providedConfiguration = "customProvidedRuntime"
}
Add the following dependency to your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.2</version>
</dependency>
Well, you're getting a java.lang.NoClassDefFoundError
. In your pom.xml
, hibernate-core
version is 3.3.2.GA
and declared after hibernate-entitymanager
, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final
from hibernate-entitymanager
.
You're using spring-boot
as parent, so no need to declare version of some dependencies, since they are managed by spring-boot
.
Also, hibernate-commons-annotations
is inherited from hibernate-entitymanager
and hibernate-annotations
is an old version of hibernate-commons-annotations
, you can remove both.
Finally, your pom.xml
can look like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
<artifactId>TrafficSpyService</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cloud-connectors</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/org/codehaus</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
Let me know if you have a problem.
I had same issue using different dependancy what helped me is to set scope to compile.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>compile</scope>
</dependency>
I faced similar issue and it was caused because I had written WebServlet Path in the .java file as well as in the web.xml . Removing it from any one location works fine for me.
In the .java file
@WebServlet("/index1.jsp")
and in web.xml
<servlet>
<servlet-name>Logout</servlet-name>
<servlet-class>tpc.Logout</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Logout</servlet-name>
<url-pattern>/index1.jsp</url-pattern>
</servlet-mapping>
No.. It is not proper way. Refer the steps,
For Classpath reference:
Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.
For Deployment Assembly:
Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.
This is the proper way! Don't forget to remove environment variable. It is not required now.
Try this. Surely it will work. Try to use Maven, it will simplify you task.
There's no need for you to use super-call of the ActionBarDrawerToggle
which requires the Toolbar. This means instead of using the following constructor:
ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes)
You should use this one:
ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes)
So basically the only thing you have to do is to remove your custom drawable
:
super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
More about the "new" ActionBarDrawerToggle in the Docs (click).
You can still use angular.isDefined()
You just need to set
$rootScope.angular = angular;
in the "run" phase.
See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview
Right-Click on your project -> Properties -> Deployment Assembly.
On the Left-hand panel Click 'Add' and add the 'Project and External Dependencies'.
'Project and External Dependencies' will have all the spring related jars deployed along with your application
If you are sure you haven't messed the jar, then please clean the project and perform mvn clean install
. This should solve the problem.
Suddenly, without any major change in my project, I too got this error.
All the above did not work for me, since I needed both the support libs V4 and V7.
At the end, because 2 hours ago the project compiled with no problems, I simply told Android Studio to REBUILD the project, and the error was gone.
when working with spring boot the problem was that the tomcat library needs to set to provided
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
In my case the problem was caused by version inconsistency:
Build tools 25
compileSdk 24
targetSdk 24
Support library 24
The solution was simple: Make everything version 25
Had the same problem, it was indeed caused by weblogic stupidly using its own opensaml implementation. To solve it, you have to tell it to load classes from WEB-INF/lib
for this package in weblogic.xml
:
<prefer-application-packages>
<package-name>org.opensaml.*</package-name>
</prefer-application-packages>
maybe <prefer-web-inf-classes>true</prefer-web-inf-classes>
would work too.
I had the same problem and tried most of the solutions suggested above, but none worked for me. Eventually, I rebuild my entire com.springframework (maven) repository (by simply deleting .m2/org/springworkframework directory).
It worked for me.
This bug still exists in 0.8+/1.10
With Jackson
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.2.2'
I had to include as well as the above suggestion before it would compile
exclude 'META-INF/services/com.fasterxml.jackson.core.JsonFactory'
You should create a bound scope variable and watch its changes:
return {
restrict: 'E',
scope: {
name: '='
},
link: function(scope) {
scope.$watch('name', function() {
// all the code here...
});
}
};
I faced a similar situation, so i replaced all the external jar files(poi-bin-3.17-20170915
) and make sure you add other jar
files present in lib and ooxml-lib
folders.
Hope this helps!!!:)
You should add maven-resources-plugin in your pom.xml file. Deleting ~/.m2/repository does not work always.
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4</version>
</plugin>
</plugins>
Now build your project again. It should be successful!
Run a jar file and specify a class path like this:
java -cp <jar_name.jar:libs/*> com.test.App
jar_name.jar
is the full name of the JAR you want to execute
libs/*
is a path to your dependency JARs
com.test.App
is the fully qualified name of the class from the JAR that has the main(String[])
method
The jar and dependent jar should have execute permissions.
I had met a similar problem, after i add a scope property of servlet dependency in pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
Then it was ok . maybe that will help you.
This is my solution:
Copy&paste $ANDROID_SDK/extras/android/support/v7/appcompat to your project ROOT
Open "Project Structure" on Intellij, click "Modules" on "Project Settings", then click "appcompat"->"android', make sure "Library Module" checkbox is checked.
click "YOUR-PROJECT_NAME" under "appcompat", remove "android-support-v4" and "android-support-v7-compat"; ensure the checkbox before "appcompat" is checked. And, click "ok" to close "Project Structure" dialogue.
back to the mainwindow, click "appcompat"->"libs" on the top-left project area. Right-click on "android-support-v4", select menuitem "Add as library", change "Add to Module" to "Your-project". Same with "android-support-v7-compat".
After doing above, intellij should be able to correctly find the android-support-XXXX modules.
Good Luck!
If you are also using Dagger
or Butterknife
you should to add guava as a dependency to your build.gradle
main file like classpath :
com.google.guava:guava:20.0
In other hand, if you are having problems with larger heap for the Gradle daemon you can increase adding to your radle
file:
dexOptions {
javaMaxHeapSize "4g"
}
I use the FileSync plugin for Eclipse so I can live debug on Tomcat & I received NoClassFoundError
because I had added a sync entry for the bin
directory in the Eclipse workspace => classes
in the metadata
for Tomcat but hadn't also added a folder sync for the extlib
directory in Eclipse =>
C:\Users\Stuart\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\myApp\WEB-INF\lib
I had the same problem earlier today. I could not figure out why the class file I was trying to reference was not being seen by the compiler. I had recently changed the namespace of the class file in question to a different but already existing namespace. (I also had using references to the class's new and previous namespaces where I was trying to instantiate it)
Where the compiler was telling me I was missing a reference when trying to instantiate the class, I right clicked and hit "generate class stub". Once Visual Studio generated a class stub for me, I coped and pasted the code from the old class file into this stub, saved the stub and when I tried to compile again it worked! No issues.
Might be a solution specific to my build, but its worth a try.
Deleting full .m2/repository
local repository solved my problem.
Or else you need to know what plugins are you using exactly with their dependencies as one of the plugin suffered a problem while downloading.
You can easily do this with Xcode 6.3.1. Select your NavigationBar in the Document outline. Select the Attributes Inspector. Uncheck Translucent. Set Bar Tint to your desired color. Done!
I use the following maven dependencies to get java mail working. The first one includes the javax.mail API (with no implementation) and the second one is the SUN implementation of the javax.mail API.
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.5</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.5</version>
</dependency>
compile fileTree(dir: 'libs', include: '*.jar')
works fine but not compile files(...)
have tested with Studio Beta 0.8.1
I created a folder named a in /home/prasanth and copied your code to a file named A.java. I compiled from /home/prasanth as javac a/A.java
and run javac a.A
. I got output as
a!
You can close the current window just by using the following code:
Application.Current.Windows[0].Close();
1st Step: Add this content in pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
2nd Step : Execute this command line by line.
cd /go/to/myApp
mvn clean
mvn compile
mvn package
java -cp target/myApp-0.0.1-SNAPSHOT.jar go.to.myApp.select.file.to.execute
I've experimented the exact same error. My problem was that the SetUp method I had created was declared as static.
If using eclipse, one could get a good description by clicking above the error and then checking the Failure trace window, just below... That's how I found the real problem!
The problem is when you set up eclipse to point to JRE instead of JDK. JRE has junit4.jar
in the lib/ext
folder, but not hamcrest.jar
:) So the solution is to check installed JREs in Eclipse, remove the existing one and create a new one pointing to your JDK.
Use ng-value
instead of value
.
ng-value="true"
Version with ng-checked
is worse because of the code duplication.
I faced the same problem,Eclipse splash screen for a second and it disappears.Then i noticed due to auto update of java there are two java version installed in my system. when i uninstalled one eclipse started working.
Thanks you..
If anyone is strugling with the same problem I solved it by adding @EntityScan
in my main class. Just add your model package to the basePackages property.
I've this issue i just update Google Play services and make sure that you are adding the google-play-service-lib project as dependency, it's working now without any code change but i still getting "The Google Play services resources were not found. Check your project configuration to ensure that the resources are included." but this only happens when you have setMyLocationEnabled(true), anyone knows why?
Some of the solutions described here did not work for me. Others did, however they produced warnings on runtime and javadoc was still not linked. After some experimenting, I managed to solve this. The steps are:
Install the Google Play Services as recommended on Android Developers.
Set up your project as recommended on Android Developers.
If you followed 1. and 2., you should see two projects in your workspace: your project and google-play-services_lib project. Copy the docs
folder which contains the javadoc from <android-sdk>/extras/google/google_play_services/
to libs
folder of your project.
Copy google-play-services.jar
from <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/libs
to 'libs' folder of your project.
In google-play-services_lib
project, edit libs/google-play-services.jar.properties . The <path>
in doc=<path>
should point to the subfolder reference
of the folder docs
, which you created in step 3.
In Eclipse, do Project > Clean. Done, javadoc is now linked.
I had the same issue. After about two hours of googling, retries, regenerating API Key many times, etc. i discovered that i enabled the wrong service in the Google APis Console. I enabled Google Maps API v2 Service, but for Android Apps you have to use Google Maps Android API v2. After enabling the right service all started working.
I was running into the same issue but was able to package all dependencies into my jar file using the Maven Shade Plugin
this worked for me /properties/maven uncheck resolve dependencies from Workspace projects.
This method will let you set the Margin in DP
public void setMargin(Context con,ViewGroup.LayoutParams params,int dp) {
final float scale = con.getResources().getDisplayMetrics().density;
// convert the DP into pixel
int pixel = (int)(dp * scale + 0.5f);
ViewGroup.MarginLayoutParams s =(ViewGroup.MarginLayoutParams)params;
s.setMargins(pixel,pixel,pixel,pixel);
yourView.setLayoutParams(params);
}
UPDATE
You can change the parameter that suits your need.
The message you mention is quite clear:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
SLF4J API could not find a binding, and decided to default to a NOP implementation. In your case slf4j-log4j12.jar was somehow not visible when the LoggerFactory class was loaded into memory, which is admittedly very strange. What does "mvn dependency:tree" tell you?
The various dependency declarations may not even be directly at cause here. I strongly suspect that a pre-1.6 version of slf4j-api.jar
is being deployed without your knowledge.
After spending lot of time on internet. I found that NONE of the option worked for I tried Right click on the server -> Clean. didn't work.
What worked is:
You just to add<absolute-ordering/>
tag to your web.xml just under the <display-name>
tag and it should work.for more detail click here
If none of the above answers work, you can run the test in IDE, get the class path and use it in your command. Ex: If you are using Intellij IDEA, you can find it at the top of the console(screenshot below).
Clicking on the highlighted part expands and displays the complete class path.
you need to remove the references to jars inside the folder: JetBrains\IntelliJ IDEA Community Edition 2019.1.3
java -cp "path_copied" org.testng.TestNG testng.xml
I had the same problem recently. In my case my windows 7 machine automatically downloaded java and added C:\ProgramData\Oracle\Java\javapath
to the beginning of my path environment variable, which messed up my java. Once I got rid of that from the path, it worked.
Here´s how I do it:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.project.MainClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
And then I just run:
mvn assembly:assembly
just put all apache comons jar and file upload jar in lib folder of tomcat
You should change the location of the M2_HOME into the following:
set M2_HOME=C:\apache-maven-3.0.4\apache-maven
Furthermore the installation of the JDK looks more a JRE instead of JDK. For Maven you need JDK and NOT JRE.
You need to download log4j and add in your classpath.
For some reason, the lib is present while compiling, but missing while running.
My situation is, two versions of one lib conflict.
For example, A depends on B and C, while B depends on D:1.0, C depends on D:1.1, maven may just import D:1.0. If A uses one class which is in D:1.1 but not in D:1.0, a NoClassDefFoundError will be throwed.
If you are in this situation too, you need to resolve the dependency conflict.
you should add servler-api.jar file in WEB-INF/lib folder
Note: This worked in the past and I received many up votes. Perhaps this is not a solution anymore - but it once was - as the eclipse version was indicated.
This can also be caused by a Java Build Path Problem.
In my case, I had a an error:
A cycle was detected in the build path of project {project}. The cycle consists of projects {x, y, z}.
This can occur when you include other projects in the build path of the project you wish to run. In fact, all the projects will fail to run with the error
Could not find the main class: Example.class
Windows
-> Preferences
-> Java
-> Compiler
-> Building
-> Build Path Problems
Abort build when build path errors occur
toggleThis seems like a can of worms if you end up with other build path errors I image. So use with caution.
I found the solution to this here
Info
After Checking Java Build Path, Then add lines of code in manifest file.
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
To add my 2 cents, the exception can occur even if you call your code through System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke()
.
The point is that you have to call Invoke()
of the Dispatcher
of the control that you're trying to access, which in some cases may not be the same as System.Windows.Threading.Dispatcher.CurrentDispatcher
. So instead you should use YourControl.Dispatcher.Invoke()
to be safe. I was banging my head for a couple of hours before I realized this.
For future readers, it looks like this has changed in the newer versions of .NET (4.0 and above). Now you no longer have to worry about the correct dispatcher when updating UI-backing properties in your VM. WPF engine will marshal cross-thread calls on the correct UI thread. See more details here. Thanks to @aaronburro for the info and link. You may also want to read our conversation below in comments.
I was facing the same issue. In my case, I had a dependency of httpclient with an older version while sendgrid required a newer version of httpclient. Just make sure that the version of httpclient is correct in your dependencies and it would work fine.
I had the same exception and I was excluding javassist
because of its issue with powermock
. Then I was adding it again as below but it was not working:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
<scope>test</scope>
</dependency>
Finally I found out that I have to remove <scope>test</scope>
from javassist
dependency. Hope it helps someone.
Solutions:
Adding 'random' numbers to URLs seems inelegant and expensive to me. It also spoils the URL of the pages, which can look like index.html?t=1614333283241
and btw users will have dozens of URLs cached for only one use.
I think this kind of things is what .htaccess
files are meant to solve at the server side, between your functional code an the users.
I copy/paste this code from here that allows filtering by file extension to force the browser not to cache them. If you want to return to normal behavior, just delete or comment it.
Create or edit an .htaccess
file on every folder you want to prevent caching, then paste this code changing file extensions to your needs, or even to match one individual file.
If the file already exists on your host be cautious modifying what's in it.
(kudos to the link)
# DISABLE CACHING
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
<FilesMatch "\.(css|flv|gif|htm|html|ico|jpe|jpeg|jpg|js|mp3|mp4|png|pdf|swf|txt)$">
<IfModule mod_expires.c>
ExpiresActive Off
</IfModule>
<IfModule mod_headers.c>
FileETag None
Header unset ETag
Header unset Pragma
Header unset Cache-Control
Header unset Last-Modified
Header set Pragma "no-cache"
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Expires "jue, 1 Jan 1970 00:00:00 GMT"
</IfModule>
</FilesMatch>
On my PC I had to open the Tomcat6 entry again after the 7th step mentioned above and then change the default option under Server locations
to Use tomcat installation
.
I did not add any dependencies, I just change the way I was consuming them.
(Uncomment this code if you are using elastic search version < 7.0)
IndexRequest indexRequest = new IndexRequest(
"twitter",
"tweets",
id // this is to make our consumer idempotent
).source(record.value(), XContentType.JSON);
IndexRequest indexRequest = new IndexRequest("tweets")
.source(record.value(), XContentType.JSON)
.id(id); // this is to make our consumer idempotent
I am using bulkrequest and with that I remove that error.
I had the same exception - but only while running in debug mode, this is how I solved the problem (after 3 whole days): in the build.gradle i had : "multiDexEnabled true" set in the defaultConfig section.
defaultConfig {
applicationId "com.xxx.yyy"
minSdkVersion 15
targetSdkVersion 28
versionCode 5123
versionName "5123"
// Enabling multidex support.
multiDexEnabled true
}
but apparently this wasn't enough. but when i changed:
public class MyAppClass extends Application
to:
public class MyAppClass extends MultiDexApplication
this solved it. hope this will help someone
This is what I use to control headers/caching, I'm not an Apache pro, so let me know if there is room for improvement, but I know that this has been working well on all of my sites for some time now.
http://httpd.apache.org/docs/2.2/mod/mod_expires.html
This module controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses. The expiration date can set to be relative to either the time the source file was last modified, or to the time of the client access.
These HTTP headers are an instruction to the client about the document's validity and persistence. If cached, the document may be fetched from the cache rather than from the source until this time has passed. After that, the cache copy is considered "expired" and invalid, and a new copy must be obtained from the source.
# BEGIN Expires
<ifModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 seconds"
ExpiresByType text/html "access plus 1 seconds"
ExpiresByType image/gif "access plus 2592000 seconds"
ExpiresByType image/jpeg "access plus 2592000 seconds"
ExpiresByType image/png "access plus 2592000 seconds"
ExpiresByType text/css "access plus 604800 seconds"
ExpiresByType text/javascript "access plus 216000 seconds"
ExpiresByType application/x-javascript "access plus 216000 seconds"
</ifModule>
# END Expires
http://httpd.apache.org/docs/2.2/mod/mod_headers.html
This module provides directives to control and modify HTTP request and response headers. Headers can be merged, replaced or removed.
# BEGIN Caching
<ifModule mod_headers.c>
<filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
<filesMatch "\.(css)$">
Header set Cache-Control "max-age=604800, public"
</filesMatch>
<filesMatch "\.(js)$">
Header set Cache-Control "max-age=216000, private"
</filesMatch>
<filesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=216000, public, must-revalidate"
</filesMatch>
<filesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=1, private, must-revalidate"
</filesMatch>
</ifModule>
# END Caching
if your Program.java is in "src/mypkg/subpkg/" directory:
go to "src" dir
Then to compile use "javac mypkg/subpkg/Program.java"
To run use "java mypkg.subpkg.Program.class"
If you use yum search you can find the python dev package for your version of python.
For me I was using python 3.5. I ran the following
yum search python | grep devel
Which returned the following
I was then able to install the correct package for my version of python with the following cmd.
sudo yum install python35u-devel.x86_64
This works on centos for ubuntu or debian you would need to use apt-get
There is no such limit on the string length. To be certain, I just tested to create a string containing 60 megabyte.
The problem is likely that you are sending the data in a GET request, so it's sent in the URL. Different browsers have different limits for the URL, where IE has the lowest limist of about 2 kB. To be safe, you should never send more data than about a kilobyte in a GET request.
To send that much data, you have to send it in a POST request instead. The browser has no hard limit on the size of a post, but the server has a limit on how large a request can be. IIS for example has a default limit of 4 MB, but it's possible to adjust the limit if you would ever need to send more data than that.
Also, you shouldn't use += to concatenate long strings. For each iteration there is more and more data to move, so it gets slower and slower the more items you have. Put the strings in an array and concatenate all the items at once:
var items = $.map(keys, function(item, i) {
var value = $("#value" + (i+1)).val().replace(/"/g, "\\\"");
return
'{"Key":' + '"' + Encoder.htmlEncode($(this).html()) + '"' + ",'+
'" + '"Value"' + ':' + '"' + Encoder.htmlEncode(value) + '"}';
});
var jsonObj =
'{"code":"' + code + '",'+
'"defaultfile":"' + defaultfile + '",'+
'"filename":"' + currentFile + '",'+
'"lstResDef":[' + items.join(',') + ']}';
You need to set the classpath to find your compiled class:
java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2
System.setProperty("gate.home", "/some/directory");
For more information, see:
System.setProperty( String key , String value )
.When I caught the exception java.lang.NoClassDefFoundError: com/google/common/base/Function
it was caused by errors in Project Libraries.
Please check it in your project settings. For Intellij IDEA go to File - Project Structure and select Modules tab. All I needed to do to resolve this exception was re-adding the selenium library
use simplejson or cjson for speedups
import simplejson as json
json.loads(obj)
or
cjson.decode(obj)
I had the same issue, the problem was in the @ContextConfiguration in me test classes, i was loading the servlet context too i just change:
@ContextConfiguration(locations = { "classpath*:**\*-context.xml", "classpath*:**\*-config.xml" })
to:
@ContextConfiguration(locations = { "classpath:**\*-context.xml", "classpath:**\*-config.xml" })
and that´s it. this way im only loading all the files with the pattern *-context.xml in me test path.
Cheesle is right. There's no way for the classloader to find the embedded jars. If you put enough debug commands on the command line you should be able to see the 'java' command failing to add the jars to a classpath
What you want to make is sometimes called an 'uberjar'. I found one-jar as a tool to help make them, but I haven't tried it. Sure there's many other approaches.
You have included a dependency on the SLF4J API, which is what you use in your application for logging, but you must also include an implementation that does the real logging work.
For example to log through Log4J you would add this dependency:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.2</version>
</dependency>
The recommended implementation would be logback-classic, which is the successor of Log4j, made by the same guys that made SLF4J and Log4J:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.24</version>
</dependency>
Note: The versions may be incorrect.
What is the package name of your class? If there is no package name, then most likely the solution is:
java -cp FileManagement Main
JAVA_HOME
is not necessary if you start java and javac from the command line. But JAVA_HOME
should point to the real jdk directory, C:\Program Files\Java\jdk1.7.0
in your case.
I'd never use the CLASSPATH
environment variable outside of build scripts, especially not global defined. The -cp
flag is better. But in your case, as you do not need additional libraries (rt.jar
doesn't count), you won't need a classpath declaration. A missing -cp
is equivalent to a -cp .
and that's what you need here)
The (I was pretty sure, that a source file needs one public class... or was it one public class at most ?)HelloWorld
class needs to be declared as public
. This actually may be the cause for your problems.
package pac001;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Entry_box{
public static final String[] relationship = {"Marrid", "Unmarried"};
public static void main(String[] args)
{
//TAKING USER ID NUMBER
int a = Integer.parseInt(JOptionPane.showInputDialog("Enter ID no: "));
// TAKING INPUT FOR RELATIONSHIP
JFrame frame = new JFrame("Input Dialog Example #3");
String Relationship = (String) JOptionPane.showInputDialog(frame,"Select Your Relationship","Married",
JOptionPane.QUESTION_MESSAGE, null, relationship,relationship[0]);
//PRINTING THE ID NUMBER
System.out.println("ID no: "+a);
// PRINTING RESULT FOR RELATIONSHIP INPUT
System.out.printf("Mariitual Status: %s\n", Relationship);
}
}
I had this same error with ADT22. Resolved it checking "Android Private Libraries" in properties -> Java build path -> Order and export. If you are using any library projects, the same should be done for them as well.
While this is a wild guess and may not be applicable in your specific situation, this could've saved me an hour or so.
In case you have "converted" a plain project into Java project (by editing .project file and adding appropriate tag), make sure you also have a proper specified - my project didn't get built even though Eclipse attempted to and run no builders (success!):
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
Well, according to Wikipedia, with a WAR file, the classes that get loaded into the classpath are in the "/WEB-INF/classes" and "/WEB-INF/lib" directory.
You could try simply putting a copy of the classes on the root file system of the zip file (which is what a war/jar is). I'm not sure if that would work though.
You can always just create two separate files.
Add following to your maven dependency
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
Setting the scope to compile did it for me
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
<scope>compile</scope>
</dependency>
Difference Between ClassNotFoundException Vs NoClassDefFoundError
This was the easiest solution that I found.
Select Table
Press ALT + F1
Scroll and view constraint names
Then the query is simple:
ALTER TABLE [Table]
DROP CONSTRAINT [Constraint]
I had this:
class Util {
static boolean isNeverAsync = System.getenv().get("asyncc_exclude_redundancy").equals("yes");
}
you can probably see the problem, the env var might return null instead of string. So just to test my theory, I changed it to:
class Util {
static boolean isNeverAsync = false;
}
and the problem went away. Too bad that Java can't give you the exact stack trace of the error though, kinda weird.
My situation was a little complicated. I had to do three steps since I was using a .dll in the resources directory, for JNI code. My files were
S:\Accessibility\tools\src\main\resources\dlls\HelloWorld.dll
S:\Accessibility\tools\src\test\java\com\accessibility\HelloWorld.class
My code contained the following line
System.load(HelloWorld.class.getResource("/dlls/HelloWorld.dll").getPath());
First, I had to move to the classpath directory
cd /D "S:\Accessibility\tools\src\test\java"
Next, I had to change the classpath to point to the current directory so that my class would be loaded and I had to change the classpath to point to he resources directory so my dll would be loaded.
set classpath=%classpath%;.;..\..\..\src\main\resources;
Then, I had to run java using the classname.
java com.accessibility.HelloWorld
In Intellij 13, it looks it's slightly different again. Here are the instructions for Intellij 13:
Classes
(even if it's properties), press OK and OK againUbuntu 12.04 this works...
JAVA_HOME=/usr/lib/jvm/java-6-openjdk-i386/jre
if you use external libraries in your program and you try to pack all together in a jar file it's not that simple, because of classpath issues etc.
I'd prefer to use OneJar for this issue.
Update [https://www.infoq.com/articles/single-file-execution-java11/]:
In Java SE 11, you get the option to launch a single source code file directly, without intermediate compilation. Just for your convenience, so that newbies like you don't have to run javac + java (of course, leaving them confused why that is).
Update your format to:
SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd hh:mm:ss Z yyyy");
In a project I worked at we solved this problem by implement something we called 'Batch' requests. We defined a path /batch
where we accepted json in the following format:
[
{
path: '/docs',
method: 'post',
body: {
doc_number: 1,
binder: 1
}
},
{
path: '/docs',
method: 'post',
body: {
doc_number: 5,
binder: 8
}
},
{
path: '/docs',
method: 'post',
body: {
doc_number: 6,
binder: 3
}
},
]
The response have the status code 207 (Multi-Status) and looks like this:
[
{
path: '/docs',
method: 'post',
body: {
doc_number: 1,
binder: 1
}
status: 200
},
{
path: '/docs',
method: 'post',
body: {
error: {
msg: 'A document with doc_number 5 already exists'
...
}
},
status: 409
},
{
path: '/docs',
method: 'post',
body: {
doc_number: 6,
binder: 3
},
status: 200
},
]
You could also add support for headers in this structure. We implemented something that proved useful which was variables to use between requests in a batch, meaning we can use the response from one request as input to another.
Facebook and Google have similar implementations:
https://developers.google.com/gmail/api/guides/batch
https://developers.facebook.com/docs/graph-api/making-multiple-requests
When you want to create or update a resource with the same call I would use either POST or PUT depending on the case. If the document already exist, do you want the entire document to be:
In case you want the behavior from alternative 1 you should use a POST and in case you want the behavior from alternative 2 you should use PUT.
http://restcookbook.com/HTTP%20Methods/put-vs-post/
As people already suggested you could also go for PATCH, but I prefer to keep API's simple and not use extra verbs if they are not needed.
For those who want to substrat two timestamps (instead of dates), there is a similar solution:
SELECT ( CAST( date2 AS DATE ) - CAST( date1 AS DATE ) ) * 1440 AS minutesInBetween
FROM ...
or
SELECT ( CAST( date2 AS DATE ) - CAST( date1 AS DATE ) ) * 86400 AS secondsInBetween
FROM ...
I faced the same problem, and I solved it in a tricky way. First make global variables, v1, v2, and v3. And in the onclick, send an indicator, 1, 2, or 3 and in the function check for 1, 2, 3 to put the v1, v2, and v3 like:
onclick="myfun(1)"
onclick="myfun(2)"
onclick="myfun(3)"
function myfun(var)
{
if (var ==1)
alert(v1);
if (var ==2)
alert(v2);
if (var ==3)
alert(v3);
}
Im late to the party, but this worked great for me and the code should explain itself;
<script type="text/javascript">
function formAJAX(btn){
var $form = $(btn).closest('[action]');
var str = $form.find('[name]').serialize();
$.post($form.attr('action'), str, function(data){
//do stuff
});
}
<script>
HTML:
<tr action="scriptURL.php">
<td>
Field 1:<input type="text" name="field1"/>
</td>
<td>
Field 2:<input type="text" name="field2" />
</td>
<td><button type="button" onclick="formAJAX(this)">Update</button></td>
</tr>
There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.
You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.
When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.
In Spring or Spring boot application.properties file here is the way to escape the special characters;
table.whereclause=where id'\='100
This will maybe give you a hint on what went wrong.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal bdTest = new BigDecimal(0.745);
BigDecimal bdTest1 = new BigDecimal("0.745");
bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("bdTest:" + bdTest); // prints "bdTest:0.74"
System.out.println("bdTest1:" + bdTest1); // prints "bdTest:0.75"
}
}
The problem is, that your input (a double x=0.745;
) can not represent 0.745 exactly. It actually saves a value slightly lower. For BigDecimals
, this is already below 0.745, so it rounds down...
Try not to use the BigDecimal(double/float)
constructors.
If you just want to display storage (disk) path use this:
Storage::disk('local')->url('screenshots/1.jpg'); // storage/screenshots/1.jpg
Storage::disk('local')->url(''): // storage
Also, if you are interested, I created a package (https://github.com/fsasvari/laravel-uploadify) just for Laravel so you can use all those fields on Eloquent model fields:
$car = Car::first();
$car->upload_cover_image->url();
$car->upload_cover_image->name();
$car->upload_cover_image->basename();
$car->upload_cover_image->extension();
$car->upload_cover_image->filesize();
You aren't creating any buttons, you just have an empty list.
You can forget the list and just create the buttons in the loop.
private void button1_Click(object sender, EventArgs e)
{
int top = 50;
int left = 100;
for (int i = 0; i < 10; i++)
{
Button button = new Button();
button.Left = left;
button.Top = top;
this.Controls.Add(button);
top += button.Height + 2;
}
}
The fastest and current way is to use Pillow, installed via pip install Pillow
.
The code is then:
from PIL import Image
img = Image.open('input_file.jpg').convert('L')
img.save('output_file.jpg')
To save memory, do not unnecessarily store/duplicate the data in memory (i.e. do not assign them to variables outside the loop). Just process the output immediately as soon as the input comes in.
It really doesn't matter whether you're using BufferedReader
or not. It will not cost significantly much more memory as some implicitly seem to suggest. It will at highest only hit a few % from performance. The same applies on using NIO. It will only improve scalability, not memory use. It will only become interesting when you've hundreds of threads running on the same file.
Just loop through the file, write every line immediately to other file as you read in, count the lines and if it reaches 100, then switch to next file, etcetera.
Kickoff example:
String encoding = "UTF-8";
int maxlines = 100;
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream("/bigfile.txt"), encoding));
int count = 0;
for (String line; (line = reader.readLine()) != null;) {
if (count++ % maxlines == 0) {
close(writer);
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/smallfile" + (count / maxlines) + ".txt"), encoding));
}
writer.write(line);
writer.newLine();
}
} finally {
close(writer);
close(reader);
}
def f(x) -> str:
return x+4
print(f(45))
# will give the result :
49
# or with other words '-> str' has NO effect to return type:
print(f(45).__class__)
<class 'int'>
Added trim() to the key in object, and name it str, so it would be more clear that we are dealing with string here.
export const getAllCookies = () => document.cookie.split(';').reduce((ac, str) => Object.assign(ac, {[str.split('=')[0].trim()]: str.split('=')[1]}), {});
FWIW, htpasswd -n username
will output the result directly to stdout, and avoid touching files altogether.
You will need separate files for each resolution I am afraid. There is a really good article on campaign monitor describing how they created and implemented their icons for each iOS device too:
http://www.campaignmonitor.com/blog/post/3234/designing-campaign-monitor-ios-icons/
An abstract class is one that isn't fully implemented but provides something of a blueprint for subclasses. It may be partially implemented in that it contains fully-defined concrete methods, but it can also hold abstract methods. These are methods with a signature but no method body. Any subclass must define a body for each abstract method, otherwise it too must be declared abstract. Because abstract classes cannot be instantiated, they must be extended by at least one subclass in order to be utilized. Think of the abstract class as the generic class, and the subclasses are there to fill in the missing information.
Considering that both strings may be very large, there are 2 main approaches bitwise search
and localeCompare
I recommed this function
function compareLargeStrings(a,b){
if (a.length !== b.length) {
return false;
}
return a.localeCompare(b) === 0;
}
foreach(PropertyInfo propertyInfo in original.GetType().GetProperties()) {
if (propertyInfo.GetValue(updatedUser, null) == null)
propertyInfo.SetValue(updatedUser, propertyInfo.GetValue(original, null), null);
}
db.Entry(original).CurrentValues.SetValues(updatedUser);
db.SaveChanges();
I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.
I am a bit late to answer this but none of the above worked for me.
This is what worked for me
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
//your styles here
}
yes, its possible, run this command:
lets say you have user called thoko
grant select any table, insert any table, delete any table, update any table to thoko;
note: worked on oracle database
Zapping - you can use this javascript lib; DefiantJS. There is no need to restructure JSON data into objects to ease searching. Instead, you can search the JSON structure with an XPath expression like this:
var data = [
{
"id": "one",
"pId": "foo1",
"cId": "bar1"
},
{
"id": "two",
"pId": "foo2",
"cId": "bar2"
},
{
"id": "three",
"pId": "foo3",
"cId": "bar3"
}
],
res = JSON.search( data, '//*[id="one"]' );
console.log( res[0].cId );
// 'bar1'
DefiantJS extends the global object JSON with a new method; "search" which returns array with the matches (empty array if none were found). You can try it out yourself by pasting your JSON data and testing different XPath queries here:
http://www.defiantjs.com/#xpath_evaluator
XPath is, as you know, a standardised query language.
In fact, we can simply use the standard bootstrap text colors, instead of hacking the CSS formats.
Standard Color examples: text-primary
, text-secondary
, text-success
, text-danger
, text-warning
, text-info
In the Navbar code sample bellow, the text Homepage
would be in the orange color (text-warning
).
<a class="navbar-brand text-warning" href="/" > Homepage </a>
In the Navbar menu item sample bellow, the text Menu Item
would be in the blue color (text-primary
).
<a class="dropdown-item text-primary" href="/my-link">Menu Item</a>
How about;
function keyValue(key, value){
this.Key = key;
this.Value = value;
};
keyValue.prototype.updateTo = function(newKey, newValue) {
this.Key = newKey;
this.Value = newValue;
};
array[1].updateTo("xxx", "999");
Give this a try...
server {
listen 80;
server_name dev.int.com;
access_log off;
location / {
proxy_pass http://IP:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:8080/jira /;
proxy_connect_timeout 300;
}
location ~ ^/stash {
proxy_pass http://IP:7990;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:7990/ /stash;
proxy_connect_timeout 300;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/nginx/html;
}
}
Why not use order by asc limit 1
and the reverse, order by desc limit 1
?
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
You could come across another problem. After installing Boost on the Linux Mint I've had the same problem. Linking -lboost_system
or -lboost_system-mt
haven't worked because library have had name libboost_system.so.1.54.0
.
So the solution is to create symbolic link to the original file. In my case
sudo ln -s /usr/lib/x86_64-linux-gnu/libboost_system.so.1.54.0 /usr/lib/libboost_system.so
For more information see this question.
Please check your web.xml again. You might be making some silly mistake. As my application is working fine with the same init-param configuration...
Please copy paste the web.xml, if the problem still persists.
dataframe['column'].squeeze()
should solve this. It basically changes the dataframe column to a list.
document.getElementsByClassName
returns an HTMLCollection
(an array-like object) of all elements matching the class name. The style
property is defined for Element
not for HTMLCollection
. You should access the first element using the bracket(subscript) notation.
document.getElementsByClassName('appBanner')[0].style.visibility = 'hidden';
To change the style rules of all elements matching the class, using the Selectors API:
[].forEach.call(document.querySelectorAll('.appBanner'), function (el) {
el.style.visibility = 'hidden';
});
If for...of
is available:
for (let el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';
SOLUTION
Remove the Quotes around the /p:PublishDir setting
i.e.
Instead of quotes
/p:PublishDir="\\BSIIS3\c$\DATA\WEBSITES\benesys.net\benesys.net\TotalEducationTest\"
Use no quotes
/p:PublishDir=\\BSIIS3\c$\DATA\WEBSITES\benesys.net\benesys.net\TotalEducationTest\
I am sorry I did not post my finding sooner. I actually had to research again to see what needed to be changed. Who would have thought removing quotes would have worked? I discovered this when viewing a coworkers build for another solution and noticed it did not have quotes.
There are lots of answers here but unfortunately all of them are quite old and therefore rely on attr
/removeAttr
which is really not the way to go.
@coffeeyesplease correctly mentions that a good, cross-browser solution is to use
$("select").val([]);
Another good cross-browser solution is
// Note the use of .prop instead of .attr
$("select option").prop("selected", false);
You can see it run a self-test here. Tested on IE 7/8/9, FF 11, Chrome 19.
Since the latest versions you can simply add a margin
to your slides:
.slick-slide {
margin: 0 20px;
}
There's no need for any kind of negative margins, since slick's calculation is based on the elements outerHeight
.
When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like
public interface Thunk { void apply(); }
somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.
In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.
Here is a simple explanation about how to create a temp dir using templates.
PARENT_DIR=./temp_dirs # (optional) specify a dir for your tempdirs
mkdir $PARENT_DIR
TEMPLATE_PREFIX='tmp' # prefix of your new tempdir template
TEMPLATE_RANDOM='XXXX' # Increase the Xs for more random characters
TEMPLATE=${PARENT_DIR}/${TEMPLATE_PREFIX}.${TEMPLATE_RANDOM}
# create the tempdir using your custom $TEMPLATE, which may include
# a path such as a parent dir, and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -d $TEMPLATE)
echo $NEW_TEMP_DIR_PATH
# create the tempdir in parent dir, using default template
# 'tmp.XXXXXXXXXX' and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -p $PARENT_DIR)
echo $NEW_TEMP_DIR_PATH
# create a tempdir in your systems default tmp path e.g. /tmp
# using the default template 'tmp.XXXXXXXXXX' and assign path to var
NEW_TEMP_DIR_PATH=$(mktemp -d)
echo $NEW_TEMP_DIR_PATH
# Do whatever you want with your generated temp dir and var holding its path
Easiest way to clear/reset the text field on click is to clear/reset the scope
<input type="text" class="form-control" ng-model="searchAll" ng-click="clearfunction(this)"/>
In Controller
$scope.clearfunction=function(event){
event.searchAll=null;
}
Options -Indexes
I have to try create .htaccess file that current directory that i want to disallow directory index listing. But, sorry i don't know about recursive in .htaccess code.
Try it.
If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.
I hope it, will be helpfull.
HTML :
<a href="#" class="btn btn-default" file-name="'fileName.extension'" ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>
DIRECTIVE :
directive('fileDownload',function(){
return{
restrict:'A',
scope:{
fileDownload:'=',
fileName:'=',
},
link:function(scope,elem,atrs){
scope.$watch('fileDownload',function(newValue, oldValue){
if(newValue!=undefined && newValue!=null){
console.debug('Downloading a new file');
var isFirefox = typeof InstallTrigger !== 'undefined';
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
var isIE = /*@cc_on!@*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isBlink = (isChrome || isOpera) && !!window.CSS;
if(isFirefox || isIE || isChrome){
if(isChrome){
console.log('Manage Google Chrome download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var downloadLink = angular.element('<a></a>');//create a new <a> tag element
downloadLink.attr('href',fileURL);
downloadLink.attr('download',scope.fileName);
downloadLink.attr('target','_self');
downloadLink[0].click();//call click function
url.revokeObjectURL(fileURL);//revoke the object from URL
}
if(isIE){
console.log('Manage IE download>10');
window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName);
}
if(isFirefox){
console.log('Manage Mozilla Firefox download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var a=elem[0];//recover the <a> tag from directive
a.href=fileURL;
a.download=scope.fileName;
a.target='_self';
a.click();//we call click function
}
}else{
alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
}
}
});
}
}
})
IN CONTROLLER:
$scope.myBlobObject=undefined;
$scope.getFile=function(){
console.log('download started, you can show a wating animation');
serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
.then(function(data){//is important that the data was returned as Aray Buffer
console.log('Stream download complete, stop animation!');
$scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
},function(fail){
console.log('Download Error, stop animation and show error message');
$scope.myBlobObject=[];
});
};
IN SERVICE:
function getStream(params){
console.log("RUNNING");
var deferred = $q.defer();
$http({
url:'../downloadURL/',
method:"PUT",//you can use also GET or POST
data:params,
headers:{'Content-type': 'application/json'},
responseType : 'arraybuffer',//THIS IS IMPORTANT
})
.success(function (data) {
console.debug("SUCCESS");
deferred.resolve(data);
}).error(function (data) {
console.error("ERROR");
deferred.reject(data);
});
return deferred.promise;
};
BACKEND(on SPRING):
@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
@RequestBody Map<String,String> spParams
) throws IOException {
OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}
In case of direct @Value injection, the most elegant way is writing the key-values as an inline json (use ' and " chars to avoid cumbersome escapings) and parsing it using SPEL:
#in yaml file:
my:
map:
is: '{ "key1":"val1",
"key2":"val2" }'
in your @Component or @Bean, :
@Component
public class MyClass{
@Value("#{${my.map.is}}")
Map<String,String> myYamlMap;
}
for a more YAML convenient syntax, you can avoid the json curly braces altogether, directly typing the key value pairs
my:
map:
is: '"a":"b", "foo":"bar"'
and add the missing curly braces directly to your @Value SPEL expression:
@Value("#{{${my.map.is}}}")
Map<String,String> myYamlMap;
the value will be resolved from the yaml, the wrapping curlies will be concatenated to it, and finally the SPEL expression will resolve the string as map.
I just noticed that this question is quite old. Nevertheless, I consider the following aspects to be worth adding:
Use MongoDB if you don't know yet how you're going to query your data.
MongoDB is suited for Hackathons, startups or every time you don't know how you'll query the data you inserted. MongoDB does not make any assumptions on your underlying schema. While MongoDB is schemaless and non-relational, this does not mean that there is no schema at all. It simply means that your schema needs to be defined in your app (e.g. using Mongoose). Besides that, MongoDB is great for prototyping or trying things out. Its performance is not that great and can't be compared to Redis.
Use Redis in order to speed up your existing application.
Redis can be easily integrated as a LRU cache. It is very uncommon to use Redis as a standalone database system (some people prefer referring to it as a "key-value"-store). Websites like Craigslist use Redis next to their primary database. Antirez (developer of Redis) demonstrated using Lamernews that it is indeed possible to use Redis as a stand alone database system.
Redis does not make any assumptions based on your data.
Redis provides a bunch of useful data structures (e.g. Sets, Hashes, Lists), but you have to explicitly define how you want to store you data. To put it in a nutshell, Redis and MongoDB can be used in order to achieve similar things. Redis is simply faster, but not suited for prototyping. That's one use case where you would typically prefer MongoDB. Besides that, Redis is really flexible. The underlying data structures it provides are the building blocks of high-performance DB systems.
Caching
Caching using MongoDB simply doesn't make a lot of sense. It would be too slow.
If you have enough time to think about your DB design.
You can't simply throw in your documents into Redis. You have to think of the way you in which you want to store and organize your data. One example are hashes in Redis. They are quite different from "traditional", nested objects, which means you'll have to rethink the way you store nested documents. One solution would be to store a reference inside the hash to another hash (something like key: [id of second hash]). Another idea would be to store it as JSON, which seems counter-intuitive to most people with a *SQL-background.
If you need really high performance.
Beating the performance Redis provides is nearly impossible. Imagine you database being as fast as your cache. That's what it feels like using Redis as a real database.
If you don't care that much about scaling.
Scaling Redis is not as hard as it used to be. For instance, you could use a kind of proxy server in order to distribute the data among multiple Redis instances. Master-slave replication is not that complicated, but distributing you keys among multiple Redis-instances needs to be done on the application site (e.g. using a hash-function, Modulo etc.). Scaling MongoDB by comparison is much simpler.
Prototyping, Startups, Hackathons
MongoDB is perfectly suited for rapid prototyping. Nevertheless, performance isn't that good. Also keep in mind that you'll most likely have to define some sort of schema in your application.
When you need to change your schema quickly.
Because there is no schema! Altering tables in traditional, relational DBMS is painfully expensive and slow. MongoDB solves this problem by not making a lot of assumptions on your underlying data. Nevertheless, it tries to optimize as far as possible without requiring you to define a schema.
TL;DR - Use Redis if performance is important and you are willing to spend time optimizing and organizing your data. - Use MongoDB if you need to build a prototype without worrying too much about your DB.
Further reading:
Creating your own drop down list is more of a pain than it's worth. You can use some JavaScript to make the IE drop down work.
It uses a bit of the YUI library and a special extension for fixing IE select boxes.
You will need to include the following and wrap your <select>
elements in a <span class="select-box">
Put these before the body tag of your page:
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/yahoo_2.0.0-b3.js" type="text/javascript">
</script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/event_2.0.0-b3.js" type="text/javascript">
</script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/dom_2.0.2-b3.js" type="text/javascript">
</script>
<script src="ie-select-width-fix.js" type="text/javascript">
</script>
<script>
// for each select box you want to affect, apply this:
var s1 = new YAHOO.Hack.FixIESelectWidth( 's1' ); // s1 is the ID of the select box you want to affect
</script>
Post acceptance edit:
You can also do this without the YUI library and Hack control. All you really need to do is put an onmouseover="this.style.width='auto'" onmouseout="this.style.width='100px'" (or whatever you want) on the select element. The YUI control gives it that nice animation but it's not necessary. This task can also be accomplished with jquery and other libraries (although, I haven't found explicit documentation for this)
-- amendment to the edit:
IE has a problem with the onmouseout for select controls (it doesn't consider mouseover on options being a mouseover on the select). This makes using a mouseout very tricky. The first solution is the best I've found so far.
Sort by _id
descending:
collection.find(filter={"keyword": keyword}, sort=[( "_id", -1 )])
Sort by _id
ascending:
collection.find(filter={"keyword": keyword}, sort=[( "_id", 1 )])
For those who are looking for a tiny and smart solution:
String.prototype.toDate = function(format)
{
var normalized = this.replace(/[^a-zA-Z0-9]/g, '-');
var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
var formatItems = normalizedFormat.split('-');
var dateItems = normalized.split('-');
var monthIndex = formatItems.indexOf("mm");
var dayIndex = formatItems.indexOf("dd");
var yearIndex = formatItems.indexOf("yyyy");
var hourIndex = formatItems.indexOf("hh");
var minutesIndex = formatItems.indexOf("ii");
var secondsIndex = formatItems.indexOf("ss");
var today = new Date();
var year = yearIndex>-1 ? dateItems[yearIndex] : today.getFullYear();
var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1;
var day = dayIndex>-1 ? dateItems[dayIndex] : today.getDate();
var hour = hourIndex>-1 ? dateItems[hourIndex] : today.getHours();
var minute = minutesIndex>-1 ? dateItems[minutesIndex] : today.getMinutes();
var second = secondsIndex>-1 ? dateItems[secondsIndex] : today.getSeconds();
return new Date(year,month,day,hour,minute,second);
};
Example:
"22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss");
"2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss");
Decorating one of the action params with [FromBody] solved the issue for me:
public async Task<IHttpActionResult> SetAmountOnEntry(string id, [FromBody]int amount)
However ASP.NET would infer it correctly if complex object was used in the method parameter:
public async Task<IHttpActionResult> UpdateEntry(string id, MyEntry entry)
With Java 8 you have several options, combining method references and the built-in comparing
comparator:
import static java.util.Comparator.comparing;
Collection<CustomObject> list = new ArrayList<CustomObject>();
Collections.sort(list, comparing(CustomObject::getId));
//or
list.sort(comparing(CustomObject::getId));
ALTER function dbo.FN_ReturnNumberRows(@Start int, @End int) returns @Numbers table (Number int) as
begin
insert into @Numbers
select n = ROW_NUMBER() OVER (ORDER BY n)+@Start-1 from (
select top (@End-@Start+1) 1 as n from information_schema.columns as A
cross join information_schema.columns as B
cross join information_schema.columns as C
cross join information_schema.columns as D
cross join information_schema.columns as E) X
return
end
GO
select * from dbo.FN_ReturnNumberRows(10,9999)
var list = (from t in ctn.Items
where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
orderby t.Delivery.SubmissionDate
select t).Take(5);
You can use an inline if inside your ngStyle:
[ngStyle]="styleOne?{'background-color': 'red'} : {'background-color': 'blue'}"
A batter way in my opinion is to store your background color inside a variable and then set the background-color as the variable value:
[style.background-color]="myColorVaraible"
Courtesy of this post, you can do the following:
from IPython.display import Image
Image(filename='test.png')
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
Example:
Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.
DROP TABLE IF EXISTS B,C,A;
This can be placed in the beginning of the script instead of individually dropping each table.
Try this:
@echo off
setlocal
cd /d %~dp0
Call :UnZipFile "C:\Temp\" "c:\path\to\batch.zip"
exit /b
:UnZipFile <ExtractTo> <newzipfile>
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs% echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%
Revision
To have it perform the unzip on each zip file creating a folder for each use:
@echo off
setlocal
cd /d %~dp0
for %%a in (*.zip) do (
Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
)
exit /b
If you don't want it to create a folder for each zip, change
Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
to
Call :UnZipFile "C:\Temp\" "c:\path\to\%%~nxa"
EDIT : my bad! With my answer, the icon won't behave as a toggler Actually, it will be shown even when not collapsed... Still searching...
This would work :
<button class="btn btn-primary" type="button" data-toggle="collapse"
data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span>
<i class="fas fa-bars"></i>
</span>
</button>
The trick proposed by my answer is to replace the navbar-toggler
with a classical button class btn
and then, as answered earlier, use an icon font.
Note, that if you keep <button class="navbar-toggler">
, the button will have a "strange" shape.
As stated in this post on github, bootstrap uses some "css trickery", so users don't have to rely on fonts.
So, just don't use the "navbar-toggler"
class on your button if you want to use an icon font.
Cheers.
Add this to you PageLoad and it will solve your problem:
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.lblbtndoc1);
In my case (using webpack 4) within an anonymous function, that I was using as a callback.
I had to use window.$.ajax()
instead of $.ajax()
despite having:
import $ from 'jquery';
window.$ = window.jQuery = $;
pylab
, not matplotlib.pyplot
You may try using hist
to put your data info along with the fitted curve as below:
import numpy as np
import scipy.stats as stats
import pylab as pl
h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]) #sorted
fit = stats.norm.pdf(h, np.mean(h), np.std(h)) #this is a fitting indeed
pl.plot(h,fit,'-o')
pl.hist(h,normed=True) #use this to draw histogram of your data
pl.show() #use may also need add this
Here's an example: App.config
<applicationSettings>
<MyApp.My.MySettings>
<setting name="Printer" serializeAs="String">
<value>1234 </value>
</setting>
</MyApp.My.MySettings>
</applicationSettings>
Dim strPrinterName as string = My.settings.Printer
You can use an array literal:
array = [ '1', '2', '3' ]
You can also use a range:
array = ('1'..'3').to_a # parentheses are required
# or
array = *('1'..'3') # parentheses not required, but included for clarity
For arrays of whitespace-delimited strings, you can use Percent String syntax:
array = %w[ 1 2 3 ]
You can also pass a block to Array.new
to determine what the value for each entry will be:
array = Array.new(3) { |i| (i+1).to_s }
Finally, although it doesn't produce the same array of three strings as the other answers above, note also that you can use enumerators in Ruby 1.8.7+ to create arrays; for example:
array = 1.step(17,3).to_a
#=> [1, 4, 7, 10, 13, 16]
Klaus solution has less overhead, on the other hand this one may be more readable
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}
def search(myDict, lookup):
for key, value in myDict.items():
for v in value:
if lookup in v:
return key
search(myDict, 'Mary')
With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As javascript reads down a page).
<head>
<script type="text/javascript">
function insert(){
var src = document.getElementById("gamediv");
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src.appendChild(img);
}
</script>
</head>
<body>
<div id="gamediv">
<script type="text/javascript">
insert();
</script>
</div>
</body>
I've been fighting with this for quite a while. Since this is the first hit on Google when I searched for the solution, let me post where I've gotten so far.
SET @d := '2011-09-01';
SELECT @d AS d, cast( @d := DATE_ADD( @d , INTERVAL 1 DAY ) AS DATE ) AS new_d
FROM [yourTable]
WHERE @d <= '2012-05-01';
Replace [yourTable]
with a table from your database. The trick is that the number of rows in the table you select must be >= the number of dates you want to be returned. I tried using the table placeholder DUAL, but it would only return one single row.
I'm adding another answer to this as I had the same problem and solved it the same way:
I had installed SSL on apache2 using a2enmod ssl
, which seems to have added an extra configuration in /etc/apache2/ports.conf
:
NameVirtualHost *:80
Listen 80
NameVirtualHost *:443
Listen 443
<IfModule mod_ssl.c>
Listen 443
</IfModule>
<IfModule mod_gnutls.c>
Listen 443
</IfModule>
I had to comment out the first Listen 443
after the NameVirtualHost *:443
directive:
NameVirtualHost *:443
#Listen 443
But I'm thinking I can as well let it and comment the others. Anyway, thank you for the solution :)
Use this it works and so simple :
var price=22.5m;
Console.WriteLine(
"the price: {0}",price.ToString("C", new System.Globalization.CultureInfo("en-US")));
Assuming all of these columns are int
, then the first thing to sort out is converting one or more of them to a better data type - int
division performs truncation, so anything less than 100% would give you a result of 0:
select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)
from
CSPGI09_OVERSHIPMENT
Here, I've mutiplied one of the numbers by 100.0
which will force the result of the calculation to be done with float
s rather than int
s. By choosing 100
, I'm also getting it ready to be treated as a %
.
I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (-
and /
) at the same level, and so were relying on the precedence rules to define which operator applied first.
To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:
Given the following function to test, located in module.a_function.to_test.py
:
from some_other.module import SomeOtherClass
def add_results():
my_object = SomeOtherClass('some_contextual_parameters')
result_a = my_object.method_a()
result_b = my_object.method_b()
return result_a + result_b
To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass
by using patch.object()
in combination with sys.modules
:
@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
mocked_other_class().method_a.return_value = 4
mocked_other_class().method_b.return_value = 7
self.assertEqual(add_results(), 11)
This works no matter the number of methods of SomeOtherClass
you need to patch, with independent results.
Also, using the same patching method, an actual instance of SomeOtherClass
can be returned if need be:
@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
other_class_instance = SomeOtherClass('some_controlled_parameters')
mocked_other_class.return_value = other_class_instance
...
If you are on mac machine and had installed nginx using
brew install nginx
then
brew services list
is the command for you. This will return a list of services installed via brew and their corresponding status.
If the rest of your system is OK with DateTimeOffset instead of DateTime, there's a really convenient feature:
long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();
Another aproach is:
let result = { ...item, location : { ...response } }
But Object spread isn't yet standardized.
May also be helpful: https://stackoverflow.com/a/32926019/5341953
I would heartily recommend relative URLs for pointing bits of the same site to other bits of the same site.
Don't forget that a change to HTTPS - even if in the same site - is going to need an absolute URL.
I found this question while trying to get the shortest Pythonic generation of this sequence (later realizing I had seen a similar one in a Python Enhancement Proposal), and I haven't noticed anyone else coming up with my specific solution (although the top answer gets close, but still less elegant), so here it is, with comments describing the first iteration, because I think that may help readers understand:
def fib():
a, b = 0, 1
while True: # First iteration:
yield a # yield 0 to start with and then
a, b = b, a + b # a will now be 1, and b will also be 1, (0 + 1)
and usage:
for index, fibonacci_number in zip(range(10), fib()):
print('{i:3}: {f:3}'.format(i=index, f=fibonacci_number))
prints:
0: 0
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
9: 34
10: 55
(For attribution purposes, I recently noticed a similar implementation in the Python documentation on modules, even using the variables a
and b
, which I now recall having seen before writing this answer. But I think this answer demonstrates better usage of the language.)
The Online Encyclopedia of Integer Sequences defines the Fibonacci Sequence recursively as
F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1
Succinctly defining this recursively in Python can be done as follows:
def rec_fib(n):
'''inefficient recursive function as defined, returns Fibonacci number'''
if n > 1:
return rec_fib(n-1) + rec_fib(n-2)
return n
But this exact representation of the mathematical definition is incredibly inefficient for numbers much greater than 30, because each number being calculated must also calculate for every number below it. You can demonstrate how slow it is by using the following:
for i in range(40):
print(i, rec_fib(i))
It can be memoized to improve speed (this example takes advantage of the fact that a default keyword argument is the same object every time the function is called, but normally you wouldn't use a mutable default argument for exactly this reason):
def mem_fib(n, _cache={}):
'''efficiently memoized recursive function, returns a Fibonacci number'''
if n in _cache:
return _cache[n]
elif n > 1:
return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2))
return n
You'll find the memoized version is much faster, and will quickly exceed your maximum recursion depth before you can even think to get up for coffee. You can see how much faster it is visually by doing this:
for i in range(40):
print(i, mem_fib(i))
(It may seem like we can just do the below, but it actually doesn't let us take advantage of the cache, because it calls itself before setdefault is called.)
def mem_fib(n, _cache={}):
'''don't do this'''
if n > 1:
return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2))
return n
As I have been learning Haskell, I came across this implementation in Haskell:
fib@(0:tfib) = 0:1: zipWith (+) fib tfib
The closest I think I can get to this in Python at the moment is:
from itertools import tee
def fib():
yield 0
yield 1
# tee required, else with two fib()'s algorithm becomes quadratic
f, tf = tee(fib())
next(tf)
for a, b in zip(f, tf):
yield a + b
This demonstrates it:
[f for _, f in zip(range(999), fib())]
It can only go up to the recursion limit, though. Usually, 1000, whereas the Haskell version can go up to the 100s of millions, although it uses all 8 GB of my laptop's memory to do so:
> length $ take 100000000 fib
100000000
A commenter asks:
Question for the Fib() function which is based on iterator: what if you want to get the nth, for instance 10th fib number?
The itertools documentation has a recipe for this:
from itertools import islice
def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)
and now:
>>> nth(fib(), 10)
55
There is a version conflict between jar/dependency please check all version of spring is same. if you use maven remove version of dependency and use Spring.io dependency.it handle version conflict. Add this in your pom
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>2.0.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
You may also use element.insertAdjacentHTML('beforeend', data);
Please read the "Security considerations" on MDN.
I believe the solution by @slipset was correct, but wasn't cross-browser ready.
According to Javascript.info, events (when referenced outside markup events) are cross-browser ready once you assure it's defined with this simple line: event = event || window.event
.
So the complete cross-browser ready function would look like this:
function doSomething(param){
event = event || window.event;
var source = event.target || event.srcElement;
console.log(source);
}
You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.
You can get the Java EE Edition of eclipse with has it pre-installed.
To create and run your first servlet:
doGet()
method.That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.
You have one DateFormat
, but you need two: one for the input, and another for the output.
You've got one for the output, but I don't see anything that would match your input. When you give the input string to the output format, it's no surprise that you see that exception.
DateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss.SSS-Z");
No, not at the moment. Google pointed out at the Google IO 2011, that card emulation is not supported and won't be supported for a while. Main (and easy to understand) problem: Which App should get the right on the phone to emulate a smartcard?
Don't think so...you can only use openTextFile
for reading (1
), writing (2
), or appending (8
). Reference here.
If you were using VB6 instead of VBScript, you could do:
Open "Filename" [For Mode] [AccessRestriction] [LockType] As #FileNumber
Using the Random
mode. For example:
Open "C:\New\maddy.txt" For Random As #1
Use char* strncpy(char* dest, char* src, int n)
from <cstring>
. In your case you will need to use the following code:
char* substr = malloc(4);
strncpy(substr, buff+10, 4);
Full documentation on the strncpy
function here.
Just install python newest version's installer it will automatically detect your python version and will say upgrade python and starts upgrading
Here's more modern approach:
.parent {display: flow-root;}
No more clearfixes.
p.s. Using overflow: hidden; hides the box-shadow so...
where somefield like '%a%' or somefield like '%b%'
There is a hacky way to do it.
Set some boolean field to indicate whether the work was completed. Then before the block of code, set a timer to run a piece of code after your timeout. The timer will check if the block of code had finished executing, and if not, throw an exception. Otherwise it will do nothing.
The end of the block of code should, of course, set the field to true to indicate the work was done.
What you should do is create a service to share data between controllers.
Nice tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk
The code you have is a white with low opacity.
If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.
Here is a simple demo.
If you want it to look 'more white', make it less opaque:
background:rgba(255,255,255, 0.9);
Simple try to remove name attribute from input element.
So it has to look like
<input type="checkbox" checked="" id="class_box_2" value="2">
Just thinking about it from a speed issue I believe the case sensitive example provided in the link above would be by far the fastest solution.
var token = "\r\n";
var newToken = " ";
var oldStr = "This is a test\r\nof the emergency broadcasting\r\nsystem.";
newStr = oldStr.split(token).join(newToken);
newStr would be "This is a test of the emergency broadcast system."
var test = $('input[name="testing"]:hidden');
test.val('work!');
Another option is to do like this:
<html>
<body>
<?php
//...php code...
?>
<script type="text/javascript">
document.write("Hello World!");
</script>
<?php
//....php code...
?>
</body>
</html>
and if you want to use PHP inside your JavaScript, do like this:
<html>
<body>
<?php
$text = "Hello World!";
?>
<script type="text/javascript">
document.write("<?php echo $text ?>");
</script>
<?php
//....php code...
?>
</body>
</html>
Hope this can help.
See this IEEE_754_types.h
header for the union types to extract: float
, double
and long double
, (endianness handled). Here is an extract:
/*
** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
** Single Precision (float) -- Standard IEEE 754 Floating-point Specification
*/
# define IEEE_754_FLOAT_MANTISSA_BITS (23)
# define IEEE_754_FLOAT_EXPONENT_BITS (8)
# define IEEE_754_FLOAT_SIGN_BITS (1)
.
.
.
# if (IS_BIG_ENDIAN == 1)
typedef union {
float value;
struct {
__int8_t sign : IEEE_754_FLOAT_SIGN_BITS;
__int8_t exponent : IEEE_754_FLOAT_EXPONENT_BITS;
__uint32_t mantissa : IEEE_754_FLOAT_MANTISSA_BITS;
};
} IEEE_754_float;
# else
typedef union {
float value;
struct {
__uint32_t mantissa : IEEE_754_FLOAT_MANTISSA_BITS;
__int8_t exponent : IEEE_754_FLOAT_EXPONENT_BITS;
__int8_t sign : IEEE_754_FLOAT_SIGN_BITS;
};
} IEEE_754_float;
# endif
And see dtoa_base.c
for a demonstration of how to convert a double
value to string form.
Furthermore, check out section 1.2.1.1.4.2 - Floating-Point Type Memory Layout of the C/CPP Reference Book, it explains super well and in simple terms the memory representation/layout of all the floating-point types and how to decode them (w/ illustrations) following the actually IEEE 754 Floating-Point specification.
It also has links to really really good ressources that explain even deeper.
A very detailed and analytic discussion on the topic is available on THIS page
It has the example codes and the pros/cons of different options.
protected void Page_Init(object sender, EventArgs e)
{
String hostdet = Request.ServerVariables["HTTP_HOST"].ToString();
}
For a given application launch, you can do it as jim says.
If you want to set it for the entire workspace, you can also set it under
Window->
Preferences->
Java->
Installed JREs
Each JRE has a "Default VM arguments" (which I believe are completely ignored if any VM args are set for a run configuration.)
You could even set up different JRE/JDKs with different parameters and have some projects use one, other projects use another.
I use ls -R, piped to grep like this:
$ ls -R | grep -i "pattern"
where -R means recursively list all the files, and -i means case-insensitive. Finally, the patter could be something like this: "std*.h" or "^io" (anything that starts with "io" in the file name)
double r2()
{
return (rand() % 10001) / 10000.0;
}
Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file
Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:
wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz
And then proceed to install it.
UPDATE: Adding complete instructions (copied from the comment below)
run the following to extract the tar:
tar xvf apache-maven-3.2.1-bin.tar.gz
Next add the env varibles such as
export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1
export M2=$M2_HOME/bin
export PATH=$M2:$PATH
Verify
mvn -version
I was getting this error as well.
I was using:
import ReactDOM from 'react-dom';
Fix was doing this, instead:
import {ReactDOM} from 'react-dom';
I've had similar situation and my problem was related to Active Directory and sitting behind vpn.
Found this gold after working like that for half a year: http://bjg.io/guide/cygwin-ad/
All you basicaly need is to disable db
in /etc/nsswitch.conf
(you can find it in your git directory) from passwd
and group
section, so the file looks like:
# Begin /etc/nsswitch.conf
passwd: files
group: files
db_enum: cache builtin
db_home: cygwin desc
db_shell: cygwin desc
db_gecos: cygwin desc
# End /etc/nsswitch.conf
and then update your local password and group settings once:
$ mkpasswd -l -c > /etc/passwd
$ mkgroup -l -c > /etc/group
If you use DISTINCT with multiple columns, the result set won't be grouped as it will with GROUP BY, and you can't use aggregate functions with DISTINCT.
Have you tried just
dictionary["cat"] = 5;
:)
Update
dictionary["cat"] = 5+2;
dictionary["cat"] = dictionary["cat"]+2;
dictionary["cat"] += 2;
Beware of non-existing keys :)
A compiler independent way, but not processor independent way to get these:
int inf = 0x7F800000;
return *(float*)&inf;
int nan = 0x7F800001;
return *(float*)&nan;
This should work on any processor which uses the IEEE 754 floating point format (which x86 does).
UPDATE: Tested and updated.
Found this by searching for "linux output formatted columns".
http://www.unix.com/shell-programming-scripting/117543-formatting-output-columns.html
For your needs, it's like:
awk '{ printf "%-20s %-40s\n", $1, $2}'
I you are using jQuery you can put the checkboxes in a form and then use something like this:
var formData = jQuery("#" + formId).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
success: success
});
It's built in Eclipse since ages. Which Eclipse version are you using? How were you trying to create a new JUnit test case? It should be File > New > Other > Java - JUnit - JUnit Test Case (you can eventually enter Filter text "junit").
This error means that the SELECT store_key FROM store
query has returned two or more rows in the SERVER1
database. If you would like to update all customers, use a join instead of a scalar =
operator. You need a condition to "connect" customers to store items in order to do that.
If you wish to update all customer_id
s to the same store_key
, you need to supply a WHERE
clause to the remotely executed SELECT
so that the query returns a single row.
If you want to configure your project logging using log4Net, while using a class library, There is no actual need of any config file. You can configure your log4net logger in a class and can use that class as library.
As log4net provides all the options to configure it.
Please find the code below.
public static void SetLogger(string pathName, string pattern)
{
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = pattern;
patternLayout.ActivateOptions();
RollingFileAppender roller = new RollingFileAppender();
roller.AppendToFile = false;
roller.File = pathName;
roller.Layout = patternLayout;
roller.MaxSizeRollBackups = 5;
roller.MaximumFileSize = "1GB";
roller.RollingStyle = RollingFileAppender.RollingMode.Size;
roller.StaticLogFileName = true;
roller.ActivateOptions();
hierarchy.Root.AddAppender(roller);
MemoryAppender memory = new MemoryAppender();
memory.ActivateOptions();
hierarchy.Root.AddAppender(memory);
hierarchy.Root.Level = log4net.Core.Level.Info;
hierarchy.Configured = true;
}
Now instead of calling XmlConfigurator.Configure(new FileInfo("app.config")) you can directly call SetLogger with desired path and pattern to set the logger in Global.asax application start function.
And use the below code to log the error.
public static void getLog(string className, string message)
{
log4net.ILog iLOG = LogManager.GetLogger(className);
iLOG.Error(message); // Info, Fatal, Warn, Debug
}
By using following code you need not to write a single line neither in application web.config nor inside the app.config of library.
Referenced file contains errors (http://www.springframework.org/schema/context/spring-context-3.0.xsd)
i faced this problem, when i was configuring dispatcher-servlet.xml ,you can remove this:
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
from your xml and you can also follow the steps go to window -> preferences -> validation -> and unchecked XML validator and XML schema validator.
You can create your mask array in one step like this
mask_data = input_mask_data < 3
This creates a boolean array which can then be used as a pixel mask. Note that we haven't changed the input array (as in your code) but have created a new array to hold the mask data - I would recommend doing it this way.
>>> input_mask_data = np.random.randint(0, 5, (3, 4))
>>> input_mask_data
array([[1, 3, 4, 0],
[4, 1, 2, 2],
[1, 2, 3, 0]])
>>> mask_data = input_mask_data < 3
>>> mask_data
array([[ True, False, False, True],
[False, True, True, True],
[ True, True, False, True]], dtype=bool)
>>>
You are not reading the properties file correctly. The propertySource should pass the parameter as: file:appclient.properties
or classpath:appclient.properties
. Change the annotation to:
@PropertySource(value={"classpath:appclient.properties"})
However I don't know what your PropertiesConfig
file contains, as you're importing that also. Ideally the @PropertySource
annotation should have been kept there.
cat script.sh
var1=$1
var2=$2
if [ "$#" -eq 2 ]
then
if [ -d $var1 ]
then
echo directory ${var1} exist
else
echo Directory ${var1} Does not exists
fi
if [ -d $var2 ]
then
echo directory ${var2} exist
else
echo Directory ${var2} Does not exists
fi
else
echo "Arguments are not equals to 2"
exit 1
fi
execute it like below -
./script.sh directory1 directory2
Output will be like -
directory1 exit
directory2 Does not exists
I'm using if for day-to-day work and I find it stable. Lately the plugin has made good progress and has added:
Be sure to skim the EGit User Guide for a good overview of the current functionality.
I find that I only need to drop to the comand line for interactive rebases.
As an official Eclipse project I am confident that EGit will receive all the main features of the command-line client.
Here is the code help you to download file from server at the same time you can see the progress of downloading on your status bar.
See the functionality in below image of my code:
STEP - 1 : Create on DownloadFileFromURL.java class file to download file content from server. Here i create an asynchronous task to download file.
public class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
private NotificationManager mNotifyManager;
private NotificationCompat.Builder build;
private File fileurl;
int id = 123;
OutputStream output;
private Context context;
private String selectedDate;
private String ts = "";
public DownloadFileFromURL(Context context, String selectedDate) {
this.context = context;
this.selectedDate = selectedDate;
}
protected void onPreExecute() {
super.onPreExecute();
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
build = new NotificationCompat.Builder(context);
build.setContentTitle("Download")
.setContentText("Download in progress")
.setChannelId(id + "")
.setAutoCancel(false)
.setDefaults(0)
.setSmallIcon(R.drawable.ic_menu_download);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(id + "",
"Social Media Downloader",
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("no sound");
channel.setSound(null, null);
channel.enableLights(false);
channel.setLightColor(Color.BLUE);
channel.enableVibration(false);
mNotifyManager.createNotificationChannel(channel);
}
build.setProgress(100, 0, false);
mNotifyManager.notify(id, build.build());
String msg = "Download started";
//CustomToast.showToast(context,msg);
}
@Override
protected String doInBackground(String... f_url) {
int count;
ts = selectedDate.split("T")[0];
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ Const.DownloadPath + ts + ".pdf");
fileurl = new File(Environment.getExternalStorageDirectory()
+ Const.DownloadPath + ts + ".pdf");
byte[] data = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int cur = (int) ((total * 100) / lenghtOfFile);
publishProgress(Math.min(cur, 100));
if (Math.min(cur, 100) > 98) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}
Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "\n " + cur);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
build.setProgress(100, progress[0], false);
mNotifyManager.notify(id, build.build());
super.onProgressUpdate(progress);
}
@Override
protected void onPostExecute(String file_url) {
build.setContentText("Download complete");
build.setProgress(0, 0, false);
mNotifyManager.notify(id, build.build());
} }
Note: If you want code with import package then Click Here
Now Step 2: You need to call above ayncronous task on your click event. for example i have set on pdf image icon. To call AsyncTask use below code:
new DownloadFileFromURL(fContext,filename).execute(serverFileUrl);
Note: Here You can see filename variable in file parameter. This is the name which i use to save my downloaded file in local device. currently i am downloading only pdf file but you can use you url in serverFileUrl parameter.
Sure. On my (pretty vanilla) Cygwin setup, bash
is in c:\cygwin\bin
so I can run a bash
script (say testit.sh
) from a Windows batch file using a command like:
C:\cygwin\bin\bash testit.sh
... which can be included in a .bat
file as easily as it can be typed at the command line, and with the same effect.
const object1 = {
a: 'somestring',
b: 42
};
for (let [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">
In above html tag we have different attributes like src
, alt
, width
and height
.
If you want to get the any attribute value from above html tag you have to pass attribute value in getAttribute()
method
Syntax:
getAttribute(attributeValue)
getAttribute(src) you get w3schools.jpg
getAttribute(height) you get 142
getAttribute(width) you get 104
Try something like this: http://jsfiddle.net/D7E3E/4/
Using a container with overflow: hidden
EDIT: @Dominic Green beat me.
As a bonus, here is a code example of a split function and macro that is easy to use and where you can choose the container type :
#include <iostream>
#include <vector>
#include <string>
#define split(str, delim, type) (split_fn<type<std::string>>(str, delim))
template <typename Container>
Container split_fn(const std::string& str, char delim = ' ') {
Container cont{};
std::size_t current, previous = 0;
current = str.find(delim);
while (current != std::string::npos) {
cont.push_back(str.substr(previous, current - previous));
previous = current + 1;
current = str.find(delim, previous);
}
cont.push_back(str.substr(previous, current - previous));
return cont;
}
int main() {
auto test = std::string{"This is a great test"};
auto res = split(test, ' ', std::vector);
for(auto &i : res) {
std::cout << i << ", "; // "this", "is", "a", "great", "test"
}
return 0;
}
I found that this happens because: http://support.microsoft.com/kb/913399
SQL Server only releases all the pages that a heap table uses when the following conditions are true: A deletion on this table occurs. A table-level lock is being held. Note A heap table is any table that is not associated with a clustered index.
If pages are not deallocated, other objects in the database cannot reuse the pages.
However, when you enable a row versioning-based isolation level in a SQL Server 2005 database, pages cannot be released even if a table-level lock is being held.
Microsoft's solution: http://support.microsoft.com/kb/913399
To work around this problem, use one of the following methods: Include a TABLOCK hint in the DELETE statement if a row versioning-based isolation level is not enabled. For example, use a statement that is similar to the following:
DELETE FROM TableName WITH (TABLOCK)
Note represents the name of the table. Use the TRUNCATE TABLE statement if you want to delete all the records in the table. For example, use a statement that is similar to the following:
TRUNCATE TABLE TableName
Create a clustered index on a column of the table. For more information about how to create a clustered index on a table, see the "Creating a Clustered Index" topic in SQL
You'll notice at the bottom of the link that it is NOT noted that it applies to SQL Server 2008 but I think it does
code for a simple copy.
cp -r ./SourceFolder ./DestFolder
code for a copy with success result
cp -rv ./SourceFolder ./DestFolder
code for Forcefully if source contains any readonly file it will also copy
cp -rf ./SourceFolder ./DestFolder
for details help
cp --help
Still seeing this error in 2020. As was stated by stt106 above, there are many, many possible causes. In my case, it was during automated insertion of data into a worksheet, and a date had been incorrectly typed in as year 1019 instead of 2019. Since i was inserting using a data array, it was difficult to find the problem until I switched to row-by-row insertion.
This was my old code, which "hid" the problem data.
Dim DataArray(MyDT.Rows.Count + 1, MyDT.Columns.Count + 1) As Object
Try
XL.Range(XL.Cells(2, 1), XL.Cells(MyDT.Rows.Count, MyDT.Columns.Count)).Value = DataArray
Catch ex As Exception
MsgBox("Fatal Error in F100 at 1270: " & ex.Message)
End
End Try
When inserting the same data by single rows at a time, it stopped with the same error but now it was easy to find the offending data.
I am adding this information so many years later, in case this helps someone else.
you can do this easily by using jquery using .css property... try this one: http://api.jquery.com/css/
Using en-CA as an example, if you're using date-fns
:
<script type="module">
import { enCA } from 'https://cdn.skypack.dev/date-fns/locale';
console.log(enCA.formatLong.date({width:'short'}))
// yyyy-MM-dd
</script>
_x000D_
Source: https://github.com/date-fns/date-fns/blob/master/src/locale/en-CA/_lib/formatLong/index.js
For CLDR & Paul Irish:
import locale from 'cldr-dates-modern/main/en-CA/ca-gregorian.json'
console.log(locale.main['en-CA'].dates.calendars.gregorian.dateFormats.short)
// y-MM-dd
Source: https://github.com/unicode-cldr/cldr-dates-modern/blob/master/main/en-CA/ca-gregorian.json
I found that the example I was using had an xml document specification on the first line. I was using a stylesheet I got at this blog entry and the first line was
<?xmlversion="1.0"encoding="utf-8"?>
which was causing the error. When I removed that line, so that the stylesheet started with the line
<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
my transform worked. By the way, that blog post was the first good, easy-to follow example I have found for trying to get information from the XML definition of an SSIS package, but I did have to modify the paths in the example for my SSIS 2008 packages, so you might too. I also created a version to extract the "flow" from the precedence constraints. My final one looks like this:
<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8" />
<xsl:template match="/">
<xsl:text>From,To~</xsl:text>
<xsl:text>
</xsl:text>
<xsl:for-each select="//DTS:PrecedenceConstraints/DTS:PrecedenceConstraint">
<xsl:value-of select="@DTS:From"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="@DTS:To"/>
<xsl:text>~</xsl:text>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
and gave me a CSV with the tilde as my line delimiter. I replaced that with a line feed in my text editor then imported into excel to get a with look at the data flow in the package.
Did you restart the server after you changed the config file?
Can you telnet to the server from a different machine?
Can you telnet to the server from the server itself?
telnet <ip address> 80
telnet localhost 80
Yes it can mean so, or it can be a simple iterator. For example: Example as iterator:
a=set(['1','2','3'])
for x in a:
print ('This set contains the value ' + x)
Similarly as a check:
a=set('ILovePython')
if 'I' in a:
print ('There is an "I" in here')
edited: edited to include sets rather than lists and strings
Connection timeouts (assuming a local network and several client machines) typically result from
a) some kind of firewall on the way that simply eats the packets without telling the sender things like "No Route to host"
b) packet loss due to wrong network configuration or line overload
c) too many requests overloading the server
d) a small number of simultaneously available threads/processes on the server which leads to all of them being taken. This happens especially with requests that take a long time to run and may combine with c).
Hope this helps.
Use sum()
in place of count()
Try below:
SELECT
ccc_news . * ,
SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
ccc_news
LEFT JOIN
ccc_news_comments
ON
ccc_news_comments.news_id = ccc_news.news_id
WHERE
`ccc_news`.`category` = 'news_layer2'
AND `ccc_news`.`status` = 'Active'
GROUP BY
ccc_news.news_id
ORDER BY
ccc_news.set_order ASC
LIMIT 20
According to Apple documentation of NSDate compare:
Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.
- (NSComparisonResult)compare:(NSDate *)anotherDate
Parameters
anotherDate
The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.
Return Value
If:
The receiver and anotherDate are exactly equal to each other,
NSOrderedSame
The receiver is later in time than anotherDate,
NSOrderedDescending
The receiver is earlier in time than anotherDate,
NSOrderedAscending
In other words:
if ([date1 compare:date2] == NSOrderedSame) ...
Note that it might be easier in your particular case to read and write this :
if ([date2 isEqualToDate:date2]) ...
Is this what you're looking for?
if (request instanceof HttpServletRequest) {
String url = ((HttpServletRequest)request).getRequestURL().toString();
String queryString = ((HttpServletRequest)request).getQueryString();
}
To Reconstruct:
System.out.println(url + "?" + queryString);
Info on HttpServletRequest.getRequestURL()
and HttpServletRequest.getQueryString()
.
first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]
print( set( first_list + second_list ) )
Remove the '#' and do
Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
System.Globalization.NumberStyles.AllowHexSpecifier));
Try CSS:
img {
object-fit: cover;
height: 48px;
}
I would suggest using closest
, which selects the closest matching parent element:
$('input[name="submitButton"]').closest("form");
Instead of filtering by the name, I would do this:
$('input[type=submit]').closest("form");
Why do you consider regex the best tool for this? If your purpose is to detect whether an illegal character is present in a string, testing each character in a loop will be both simpler and more efficient than constructing a regex.
On my Mac:
/System/Library/Frameworks/JavaVM.framework/Home/
btw, did you tried which java
?
if you just want to add timeout as an additional option for the entire existing script, you can make it test for the timeout-option, and then make it call it self recursively without that option.
example.sh:
#!/bin/bash
if [ "$1" == "-t" ]; then
timeout 1m $0 $2
else
#the original script
echo $1
sleep 2m
echo YAWN...
fi
running this script without timeout:
$./example.sh -other_option # -other_option
# YAWN...
running it with a one minute timeout:
$./example.sh -t -other_option # -other_option
If you are dealing with String[] instead of int[], We can use
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(StringArray));
Try this, may this will help you
SELECT DATEDIFF(DAY, DATEADD(DAY,-1,'2013-03-13 00:00:00.000') , GETDATE())
I ran into the same problem after restructuring the settings as per the instructions from Daniel Greenfield's book Two scoops of Django.
I resolved the issue by setting
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings.local")
in manage.py
and wsgi.py
.
Update:
In the above solution, local
is the file name (settings/local.py) inside my settings folder, which holds the settings for my local environment.
Another way to resolve this issue is to keep all your common settings inside settings/base.py and then create 3 separate settings files for your production, staging and dev environments.
Your settings folder will look like:
settings/
__init__.py
base.py
local.py
prod.py
stage.py
and keep the following code in your settings/__init__.py
from .base import *
env_name = os.getenv('ENV_NAME', 'local')
if env_name == 'prod':
from .prod import *
elif env_name == 'stage':
from .stage import *
else:
from .local import *
You can use the extra arguments to setTimeout to pass parameters to the callback function.
for (var i = 1; i <= 2; i++) {
setTimeout(function(j) { alert(j) }, 100, i);
}
Note: This doesn't work on IE9 and below browsers.
I came across .netrc
and found it relevant to this.
Create a file ~/.netrc
with the following content:
machine github.com
login <github username>
password <github password or Personal access tokens >
Done!
Additionally, for latest GO versions, you might need to add this to the environment variables GOPRIVATE=github.com
(I've added it to my .zshrc
)
netrc
also makes my development environment setup better as my personal github access for HTTPS is been configured now to be used across the machine (just like my SSH configuration).
Generate GitHub personal access tokens: https://github.com/settings/tokens
See this answer for its use with Git on Windows specifically
Ref: netrc man page
If you want to stick with the SSH authentication, then mask the request to use ssh forcefully
git config --global url."[email protected]:".insteadOf "https://github.com/"
More methods for setting up git access: https://gist.github.com/technoweenie/1072829#gistcomment-2979908
label1.Text = DateTime.Now.ToLongTimeString();//its for current date
label1.Text = DateTime.Now.ToLongDateString();//its for current time
30x30 is points, which means 30px @1x, 60px @2x, not somewhere in-between. Also, it's not a great idea to embed the title of the tab into the image—you're going to have pretty poor accessibility and localization results like that.
To detect operating system using JavaScript it is better to use navigator.userAgent instead of navigator.appVersion
{_x000D_
var OSName = "Unknown OS";_x000D_
if (navigator.userAgent.indexOf("Win") != -1) OSName = "Windows";_x000D_
if (navigator.userAgent.indexOf("Mac") != -1) OSName = "Macintosh";_x000D_
if (navigator.userAgent.indexOf("Linux") != -1) OSName = "Linux";_x000D_
if (navigator.userAgent.indexOf("Android") != -1) OSName = "Android";_x000D_
if (navigator.userAgent.indexOf("like Mac") != -1) OSName = "iOS";_x000D_
console.log('Your OS: ' + OSName);_x000D_
}
_x000D_
1.) I need to check if the object is not null; Is the following expression correct;
if (person == null){ }
YES. This is how you check if object is null
.
2.) I need to know if the ID contains an Int.
if(person.getId()==null){}
NO Since id
is defined as primitive int
, it will be default initialized with 0
and it will never be null
. There is no need to check primitive types, if they are null. They will never be null. If you want, you can compare against the default value 0
as if(person.getId()==0){}
.
Remember that a JavaScript code unit is 16 bits wide. Therefore the hex string form will be 4 digits per code unit.
usage:
var str = "\u6f22\u5b57"; // "\u6f22\u5b57" === "??"
alert(str.hexEncode().hexDecode());
String to hex form:
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
return result
}
Back again:
String.prototype.hexDecode = function(){
var j;
var hexes = this.match(/.{1,4}/g) || [];
var back = "";
for(j = 0; j<hexes.length; j++) {
back += String.fromCharCode(parseInt(hexes[j], 16));
}
return back;
}
(Too many answers are redundant and outdated.) The best solution now is this:
history.replaceState(null, null, ' ');
if you still stuck or you get this
C:\\\Users\\\name of your\\\AppData\\\Local\\\Programs\\\Python\\\Python36
simply do this replace 2 \ with one
C:\Users\akshay\AppData\Local\Programs\Python\Python36
Just in addition to @David Brown´s answer, if you want to block an IP, you must first allow all then block the IPs as such:
<RequireAll>
Require all granted
Require not ip 10.0.0.0/255.0.0.0
Require not ip 172.16.0.0/12
Require not ip 192.168
</RequireAll>
First line allows all
Second line blocks from 10.0.0.0 to 10.255.255.255
Third line blocks from 172.16.0.0 to 172.31.255.255
Fourth line blocks from 192.168.0.0 to 192.168.255.255
You may use any of the notations mentioned above to suit you CIDR needs.
Edit 2020: This does not work any more. It seems so, that the browser vendors patched this out. Because the most browsers rely on chromium, it might be in its core.
Old answer: You can also hook mouseenter (this event is fired after page reload, when the mousecursor is inside the page). Extending Corrupted's code should do the trick:
var x = null;_x000D_
var y = null;_x000D_
_x000D_
document.addEventListener('mousemove', onMouseUpdate, false);_x000D_
document.addEventListener('mouseenter', onMouseUpdate, false);_x000D_
_x000D_
function onMouseUpdate(e) {_x000D_
x = e.pageX;_x000D_
y = e.pageY;_x000D_
console.log(x, y);_x000D_
}_x000D_
_x000D_
function getMouseX() {_x000D_
return x;_x000D_
}_x000D_
_x000D_
function getMouseY() {_x000D_
return y;_x000D_
}
_x000D_
You can also set x and y to null on mouseleave-event. So you can check if the user is on your page with it's cursor.
This worked for me.
I created a folder then changed into the folder using CD option from command prompt.
Then executed the jar from there.
d:\LS\afterchange>jar xvf ..\mywar.war
It means you're passing the variable by reference.
In fact, in a declaration of a type, it means reference, just like:
int x = 42;
int& y = x;
declares a reference to x
, called y
.
Best way is to use templating => add id to your input and then use it value
<input type="text" #notaryLockup (keyup) = "searchNotary(notaryLockup.value)"placeholder="Entrez des information" >
searchNotary(value: string) {
// your logic
}
this way you will never have Typescript error when strict verification is activated => See angular Docs
Try this
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />
if you want 0 or 1 "description" elements, Or
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />
if you want 0 to infinity number of "description" elements.
can check it in packages.config file.
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.0.2" targetFramework="net40-Client" />
</packages>
I know this question is old but this was my first time I had to use a confirmation dialog. I think this is the shortest way to do it.
$(element).onClick(function(){ // This can be a function or whatever, this is just a trigger
var conBox = confirm("Are you sure ?");
if(conBox){
// Do what you have to do
}
else
return;
});
I hope you like it :)
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
The Win32_Process
class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.
If this is not an option for you, you can try using the taskkill
command:
Dim oShell : Set oShell = CreateObject("WScript.Shell")
' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000
' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True
INSERT INTO Destination SELECT * FROM Source;
See SQL As Understood By SQLite: INSERT for a formal definition.
Wasted several hours only to realize that viewport meta was missing from my code. Adding here just in case some one else misses it out.
As soon as I added this, the toggle started working fine.
<meta name="viewport" content="width=device-width, initial-scale=1">
Active Directory is a database based system that provides authentication, directory, policy, and other services in a Windows environment
LDAP (Lightweight Directory Access Protocol) is an application protocol for querying and modifying items in directory service providers like Active Directory, which supports a form of LDAP.
Short answer: AD is a directory services database, and LDAP is one of the protocols you can use to talk to it.
Spring cannot instantiate your TestController because its only constructor requires a parameter. You can add a no-arg constructor or you add @Autowired annotation to the constructor:
@Autowired
public TestController(KeeperClient testClient) {
TestController.testClient = testClient;
}
In this case, you are explicitly telling Spring to search the application context for a KeeperClient bean and inject it when instantiating the TestControlller.
SQL keywords are case insensitive themselves.
Names of tables, columns etc, have a case sensitivity which is database dependent - you should probably assume that they are case sensitive unless you know otherwise (In many databases they aren't though; in MySQL table names are SOMETIMES case sensitive but most other names are not).
Comparing data using =, >, < etc, has a case awareness which is dependent on the collation settings which are in use on the individual database, table or even column in question. It's normal however, to keep collation fairly consistent within a database. We have a few columns which need to store case-sensitive values; they have a collation specifically set.
I already found the solution to this problem which I forgot to post here.
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {
@Mock
Person person;
@Test
public void testPrintName() throws Exception {
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
Test test= new Test();
test.testMethod();
}
}
Key points to this solution are:
Running my test cases with PowerMockRunner: @RunWith(PowerMockRunner.class)
Instruct Powermock to prepare Test.class
for manipulation of private fields: @PrepareForTest({ Test.class })
And finally mock the constructor for Person class:
PowerMockito.mockStatic(Person.class);
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
Another useful tool for this from the command line interface, is the pager command.
eg
pager grep -v Sleep | more; show full processlist;
Then you can page through the results.
You can also look for certain users, IPs or queries with grep or sed in this way.
The pager command is persistent per session.
Haven't tested this very extensively, but works in Python 2.5.2.
>>> d = {"x":2, "h":15, "a":2222}
>>> it = iter(sorted(d.iteritems()))
>>> it.next()
('a', 2222)
>>> it.next()
('h', 15)
>>> it.next()
('x', 2)
>>>
If you are used to doing for key, value in d.iteritems(): ...
instead of iterators, this will still work with the solution above
>>> d = {"x":2, "h":15, "a":2222}
>>> for key, value in sorted(d.iteritems()):
>>> print(key, value)
('a', 2222)
('h', 15)
('x', 2)
>>>
With Python 3.x, use d.items()
instead of d.iteritems()
to return an iterator.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>teste4</groupId>
<artifactId>teste4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>bootstrap</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.Final</version>
</dependency>
</dependencies>
</project>
try this:
textarea {
border-style: none;
border-color: Transparent;
overflow: auto;
outline: none;
}
jsbin: http://jsbin.com/orozon/2/
in bootstrap use .list-inline
css class
<ul class="list-inline">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h
# This code works fine in QtSpim simulator
.data
buffer: .space 20
str1: .asciiz "Enter string"
str2: .asciiz "You wrote:\n"
.text
main:
la $a0, str1 # Load and print string asking for string
li $v0, 4
syscall
li $v0, 8 # take in input
la $a0, buffer # load byte space into address
li $a1, 20 # allot the byte space for string
move $t0, $a0 # save string to t0
syscall
la $a0, str2 # load and print "you wrote" string
li $v0, 4
syscall
la $a0, buffer # reload byte space to primary address
move $a0, $t0 # primary address = t0 address (load pointer)
li $v0, 4 # print string
syscall
li $v0, 10 # end program
syscall
This is a Python 101 type question,
It's a simple question but one where the answer is not so simple.
In python3, a "bytes" object represents a sequence of bytes, a "string" object represents a sequence of unicode code points.
To convert between from "bytes" to "string" and from "string" back to "bytes" you use the bytes.decode and string.encode functions. These functions take two parameters, an encoding and an error handling policy.
Sadly there are an awful lot of cases where sequences of bytes are used to represent text, but it is not necessarily well-defined what encoding is being used. Take for example filenames on unix-like systems, as far as the kernel is concerned they are a sequence of bytes with a handful of special values, on most modern distros most filenames will be UTF-8 but there is no gaurantee that all filenames will be.
If you want to write robust software then you need to think carefully about those parameters. You need to think carefully about what encoding the bytes are supposed to be in and how you will handle the case where they turn out not to be a valid sequence of bytes for the encoding you thought they should be in. Python defaults to UTF-8 and erroring out on any byte sequence that is not valid UTF-8.
print(bytesThing)
Python uses "repr" as a fallback conversion to string. repr attempts to produce python code that will recreate the object. In the case of a bytes object this means among other things escaping bytes outside the printable ascii range.
Here is the answer with blue box-shadow,border,outline removed with file name fix in custom-file input of bootstrap appear on choose filename and if you not choose any file then show No file chosen.
$(document).on('change', 'input[type="file"]', function (event) { _x000D_
var filename = $(this).val();_x000D_
if (filename == undefined || filename == ""){_x000D_
$(this).next('.custom-file-label').html('No file chosen');_x000D_
}_x000D_
else _x000D_
{ $(this).next('.custom-file-label').html(event.target.files[0].name); }_x000D_
});
_x000D_
input[type=file]:focus,.custom-file-input:focus~.custom-file-label {_x000D_
outline:none!important;_x000D_
border-color: transparent;_x000D_
box-shadow: none!important;_x000D_
}_x000D_
.custom-file,_x000D_
.custom-file-label,_x000D_
.custom-file-input {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container py-5">_x000D_
<div class="input-group mb-3">_x000D_
<div class="input-group-prepend">_x000D_
<span class="input-group-text">Upload</span>_x000D_
</div>_x000D_
<div class="custom-file">_x000D_
<input type="file" class="custom-file-input" id="inputGroupFile01">_x000D_
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
zip
will transpose the list, after that you can concatenate the outputs.
In [3]: zip(*[ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ])
Out[3]: [('0,0', '1,0', '2,0'), ('0,1', '1,1', '2,1')]
.htaccess php_value is working only if you use PHP Server API as module of Web server Apache. Use IfModule syntax:
# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
php_value error_reporting 30711
</IfModule>
If you use PHP Server API CGI/FastCGI use
ini_set('error_reporting', 30711);
or
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
in your PHP code, or PHP configuration files .user.ini | php.ini modification:
error_reporting = E_ALL & ~E_STRICT & ~E_NOTICE
on your virtual host, server level.
I'm also going to assume that you mean "list" when you say "array." Sven Marnach's solution is good. If you are going to be doing repeated checks on the list, then it might be worth converting it to a set or frozenset, which can be faster for each check. Assuming your list of strs is called subjects
:
subject_set = frozenset(subjects)
if query in subject_set:
# whatever
public void EndTask(string taskname)
{
string processName = taskname.Replace(".exe", "");
foreach (Process process in Process.GetProcessesByName(processName))
{
process.Kill();
}
}
//EndTask("notepad");
Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.
PATH: Answered long ago, however, it maybe more helpful to think of -p as "Path" (easier to remember), as in this causes mkdir to create every part of the path that isn't already there.
mkdir -p /usr/bin/comm/diff/er/fence
if /usr/bin/comm already exists, it acts like: mkdir /usr/bin/comm/diff mkdir /usr/bin/comm/diff/er mkdir /usr/bin/comm/diff/er/fence
As you can see, it saves you a bit of typing, and thinking, since you don't have to figure out what's already there and what isn't.
;
to separate command \\
on any backslashes \
. "'
for passing safe address to switch command like "'PATH'".This ps1 command install locale pfx certificate.
powershell -Command "$pfxPassword = ConvertTo-SecureString -String "12345678" -Force -AsPlainText ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\My -Password $pfxPassword ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\Root -Password $pfxPassword"
There is no any problem to write multiple lines of execution withing a single try catch block like below
try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}
The moment any execption occure either in install_engine
or install_break
function the control will be passed to catch function.
One more recommendation is to eat your exception properly. Which means instead of writing die('Message')
it is always advisable to have exception process properly. You may think of using die()
function in error handling but not in exception handling.
When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:
try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}
try{
install_body();
paint_body();
install_interiour();
}
catch(Exception $e){
throw new exception('Body Makeover faield')
}
The menu location seems to have changed to:
Query Designer --> Pane --> SQL
This answer above from CtrlX is the correct answer, but it may not work completely. I added this line to my php.ini file:
date.timezone = "America/Los_Angeles"
but it did not remove the PHP error for all my files because some of my PHP scripts are in subfolders. So I had to edit .htaccess file to setup php.ini to be used recursively (in subfolders):
suphp_configpath /home/account_name/public_html
where account_name is your cpanel account name and public_html is the folder your php.ini file is in.
update addresses set cid=id where id in (select id from customers)
Yes. For that ensure that you declare the worksheet
For example
Previous Code
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet3")
Debug.Print ws.Cells(23, 4).Value
End Sub
New Code
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet4")
Debug.Print ws.Cells(23, 4).Value
End Sub
\n
is a line feed (LF) character, character code 10. \r
is a carriage return (CR) character, character code 13. What they do differs from system to system. On Windows, for instance, lines in text files are terminated using CR followed immediately by LF (e.g., CRLF). On Unix systems and their derivatives, only LF is used. (Macs prior to Mac OS X used CR, but Mac OS X is a *nix derivative and so uses LF.)
In the old days, LF literally did just a line feed on printers (moving down one line without moving where you are horizonally on the page), and CR similarly moved back to the beginning of the line without moving the paper up, hence some systems (like Windows) sending CR (return to the left-hand side) and LF (and feed the paper up).
Because of all this confusion, some output targets will accept multiple line break sequences, so you could see the same effect from either character depending on what you're outputting to.
One other alternative is to use function name in #if
. The #if
will detect if the parameter is function and if it is then it will call it and use its return for truthyness check. Below myFunction gets current context as this
.
{{#if myFunction}}
I'm Happy!
{{/if}}
To check if one or more columns all exist, you can use set.issubset
, as in:
if set(['A','C']).issubset(df.columns):
df['sum'] = df['A'] + df['C']
As @brianpck points out in a comment, set([])
can alternatively be constructed with curly braces,
if {'A', 'C'}.issubset(df.columns):
See this question for a discussion of the curly-braces syntax.
Or, you can use a list comprehension, as in:
if all([item in df.columns for item in ['A','C']]):
Try This code:
public class GenericCompare<T> : IEqualityComparer<T> where T : class
{
private Func<T, object> _expr { get; set; }
public GenericCompare(Func<T, object> expr)
{
this._expr = expr;
}
public bool Equals(T x, T y)
{
var first = _expr.Invoke(x);
var sec = _expr.Invoke(y);
if (first != null && first.Equals(sec))
return true;
else
return false;
}
public int GetHashCode(T obj)
{
return obj.GetHashCode();
}
}
Example of its use would be
collection = collection
.Except(ExistedDataEles, new GenericCompare<DataEle>(x=>x.Id))
.ToList();
This declaration:
double F[1000][1000000];
would occupy 8 * 1000 * 1000000 bytes on a typical x86 system. This is about 7.45 GB. Chances are your system is running out of memory when trying to execute your code, which results in a segmentation fault.
The nested lexical scope example that someone gave gives several benefits.
I think that is a very good example of the differences between the two languages. Ruby is simply more flexible. Python can be flexible, but you often have to do extreme contortions to get there, which makes it not worth the hassle.
Sorry for not posting under the original answer, I guess I don't have privileges to do that.
In my case, I stumbled upon one issue with using printf solution:
$ printf "%x" 008
bash: printf: 008: invalid octal number
The easiest way was to use solution with bc, suggested in post higher:
$ bc <<< "obase=16; 008"
8
I would check:
The simplest starting point is probably to try to connect manually from the client machine using telnet or Putty. If that succeeds, then the problem is in your client code. If it doesn't, you need to work out why it hasn't. Wireshark may help you on this front.
After try several code, and still not working, I go to official documentation of select2.js. here the link: https://select2.org/programmatic-control/add-select-clear-items
from that the way to clear selection select2 js is:
$('#mySelect2').val(null).trigger('change');
Importing my project (which had 3 different modules in it) - as File -> Module From Existing Sources fixed it for me.
Ideally you should try not to modify the internal data representation for the purpose of creating the table. Whats the problem with String.format()? It will return you new string with required width.
Your result object is a jQuery element, not a javascript array. The array you wish must be under .get()
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array. http://api.jquery.com/map/
Big O describes the fundamental scaling nature of an algorithm.
There is a lot of information that Big O does not tell you about a given algorithm. It cuts to the bone and gives only information about the scaling nature of an algorithm, specifically how the resource use (think time or memory) of an algorithm scales in response to the "input size".
Consider the difference between a steam engine and a rocket. They are not merely different varieties of the same thing (as, say, a Prius engine vs. a Lamborghini engine) but they are dramatically different kinds of propulsion systems, at their core. A steam engine may be faster than a toy rocket, but no steam piston engine will be able to achieve the speeds of an orbital launch vehicle. This is because these systems have different scaling characteristics with regards to the relation of fuel required ("resource usage") to reach a given speed ("input size").
Why is this so important? Because software deals with problems that may differ in size by factors up to a trillion. Consider that for a moment. The ratio between the speed necessary to travel to the Moon and human walking speed is less than 10,000:1, and that is absolutely tiny compared to the range in input sizes software may face. And because software may face an astronomical range in input sizes there is the potential for the Big O complexity of an algorithm, it's fundamental scaling nature, to trump any implementation details.
Consider the canonical sorting example. Bubble-sort is O(n2) while merge-sort is O(n log n). Let's say you have two sorting applications, application A which uses bubble-sort and application B which uses merge-sort, and let's say that for input sizes of around 30 elements application A is 1,000x faster than application B at sorting. If you never have to sort much more than 30 elements then it's obvious that you should prefer application A, as it is much faster at these input sizes. However, if you find that you may have to sort ten million items then what you'd expect is that application B actually ends up being thousands of times faster than application A in this case, entirely due to the way each algorithm scales.
I had the same problem but I could not make work the solution with flexboxes above. So I created my own template, that includes:
I used flexboxes but in a more simple way, using only properties display: flex and flex-direction: row|column:
I do use angular and I want my component sizes to be 100% of their parent element.
The key is to set the size (in percents) for all parents inorder to limit their size. In the following example myapp height has 100% of the viewport.
The main component has 90% of the viewport, because header and footer have 5%.
I posted my template here: https://jsfiddle.net/abreneliere/mrjh6y2e/3
body{
margin: 0;
color: white;
height: 100%;
}
div#myapp
{
display: flex;
flex-direction: column;
background-color: red; /* <-- painful color for your eyes ! */
height: 100%; /* <-- if you remove this line, myapp has no limited height */
}
div#main /* parent div for sidebar and content */
{
display: flex;
width: 100%;
height: 90%;
}
div#header {
background-color: #333;
height: 5%;
}
div#footer {
background-color: #222;
height: 5%;
}
div#sidebar {
background-color: #666;
width: 20%;
overflow-y: auto;
}
div#content {
background-color: #888;
width: 80%;
overflow-y: auto;
}
div.fized_size_element {
background-color: #AAA;
display: block;
width: 100px;
height: 50px;
margin: 5px;
}
Html:
<body>
<div id="myapp">
<div id="header">
HEADER
<div class="fized_size_element"></div>
</div>
<div id="main">
<div id="sidebar">
SIDEBAR
<div class="fized_size_element"></div>
<div class="fized_size_element"></div>
<div class="fized_size_element"></div>
<div class="fized_size_element"></div>
<div class="fized_size_element"></div>
<div class="fized_size_element"></div>
<div class="fized_size_element"></div>
<div class="fized_size_element"></div>
</div>
<div id="content">
CONTENT
</div>
</div>
<div id="footer">
FOOTER
</div>
</div>
</body>