here is a link to generate a short list of options available to npm; it filters on the keywords unused packages
What you put inside the </dependencies>
tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.
However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>
. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement>
tag.
You can also use the </dependencyManagement>
to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).
Just clean every content under .m2-->repository folder.When you build project all dependencies load here.
In your case may be your project earlier was using old version of any dependency and now version is upgraded.So better clean .m2 folder and build your project with mvn clean install.
Now dependencies with latest version modules will be downloaded in this folder.
Please search "depends.exe" in google, it's a tiny utility to handle this.
Imread uses PIL library, if the library is installed use : "from scipy.ndimage import imread"
Source: http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.ndimage.imread.html
we switched to gradle and this works much better in gradle ;). we just specify a folder we can drop jars into for temporary situations like that. We still have most of our jars defined i the typicaly dependency management section(ie. the same as maven). This is just one more dependency we define.
so basically now we can just drop any jar we want into our lib dir for temporary testing if it is not a in maven repository somewhere.
I use the following workaround : instead of trying to exclude the artifact in all appropriate dependencies, I draw the dependency as "provided" at top level. For example, to avoid shipping xml-apis "whatever version" :
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>[1.0,]</version>
<scope>provided</scope>
</dependency>
Using deadlydog's scheme,
Y => X => A => B,
my problem was when I built Y, the assemblies (A and B, all 15 of them) from X were not showing up in Y's bin folder.
I got it resolved by removing the reference X from Y, save, build, then re-add X reference (a project reference), and save, build, and A and B started showing up in Y's bin folder.
mvn install dependency:copy-dependencies
Works for me with dependencies directory created in target folder. Like it!
If earlier working project crashing suddenly with mentioned error you can try following solution.
This worked for me.
in .mjs files we for now don't have __dirname
hence
res.sendFile('index.html', { root: '.' })
For another instance of Glibc, download gcc 4.7.2, for instance from this github repo (although an official source would be better) and extract it to some folder, then update LD_LIBRARY_PATH
with the path where you have extracted glib.
export LD_LIBRARY_PATH=$glibpath/glib-2.49.4-kgesagxmtbemim2denf65on4iixy3miy/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/libffi-3.2.1-wk2luzhfdpbievnqqtu24pi774esyqye/lib64:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/pcre-8.39-itdbuzevbtzqeqrvna47wstwczud67wx/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/gettext-0.19.8.1-aoweyaoufujdlobl7dphb2gdrhuhikil/lib:$LD_LIBRARY_PATH
This should keep you safe from bricking your CentOS*.
*Disclaimer: I just completed the thought it looks like the OP was trying to express, but I don't fully agree.
mvn -Dschemaname=public liquibase:update
Running:
npm install
from inside your app directory (i.e. where package.json is located) will install the dependencies for your app, rather than install it as a module, as described here. These will be placed in ./node_modules relative to your package.json file (it's actually slightly more complex than this, so check the npm docs here).
You are free to move the node_modules dir to the parent dir of your app if you want, because node's 'require' mechanism understands this. However, if you want to update your app's dependencies with install/update, npm will not see the relocated 'node_modules' and will instead create a new dir, again relative to package.json.
To prevent this, just create a symlink to the relocated node_modules from your app dir:
ln -s ../node_modules node_modules
For me it only take to run these commands in my api directory:
rm -rf node_modules
npm cache clean
npm install
Create a simple project with pom.xml only. Add your dependency and run:
mvn dependency:tree
Unfortunately dependency mojo must use pom.xml or you get following error:
Cannot execute mojo: tree. It requires a project with an existing pom.xml, but the build is not using one.
Dependencies are described In pom.xml of your artifact. Find it using maven infrastructure.
Go to https://search.maven.org/ and enter your groupId and artifactId.
Or you can go to https://repo1.maven.org/maven2/ and navigate first using plugins groupId, later using artifactId and finally using its version.
For example see org.springframework:spring-core
Part of dependency artifact is a pom.xml. That specifies it's dependency. And you can execute mvn dependency:tree on this pom.
Please use this profile
<profiles>
<profile>
<repositories>
<repository>
<id>mvnrepository</id>
<name>mvnrepository</name>
<url>http://www.mvnrepository.com</url>
</repository>
</repositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>mvnrepository</activeProfile>
</activeProfiles>
Although this is an old document, but it helped me resolve the problem of 'HintPath' being ignored on another machine. It was because the referenced DLL needed to be in source control as well:
Excerpt:
To include and then reference an outer-system assembly 1. In Solution Explorer, right-click the project that needs to reference the assembly,,and then click Add Existing Item. 2. Browse to the assembly, and then click OK. The assembly is then copied into the project folder and automatically added to VSS (assuming the project is already under source control). 3. Use the Browse button in the Add Reference dialog box to set a file reference to assembly in the project folder.
1) Copy DLLs from "Externals\ffmpeg\bin" to your project's output directory (where executable stays); 2) Make sure your project is built for x86 target (runs in 32-bit mode).
You don't need to close the project and go to command line to invoke grade:clean. Go to Build-> Rebuild Project
Using npm
Latest version while still respecting the semver in your package.json: npm update <package-name>
.
So, if your package.json says "react": "^15.0.0"
and you run npm update react
your package.json will now say "react": "^15.6.2"
(the currently latest version of react 15).
But since you want to go from react 15 to react 16, that won't do.
Latest version regardless of your semver: npm install --save react@latest
.
If you want a specific version, you run npm install --save react@<version>
e.g. npm install --save [email protected]
.
https://docs.npmjs.com/cli/install
Using yarn
Latest version while still respecting the semver in your package.json: yarn upgrade react
.
Latest version regardless of your semver: yarn upgrade react@latest
.
This exact same error is thrown if you try to late bind using reflection, if the assembly you are binding to gets strong-named or has its public-key token changed. The error is the same even though there is not actually any assembly found with the specified public key token.
You need to add the correct public key token (you can get it using sn -T on the dll) to resolve the error. Hope this helps.
Another interesting case is when you want to have in your project private maven jars. You may want to keep the capabilities of Maven to resolve transitive dependencies. The solution is fairly easy.
Add the following lines in your pom.xml file
<properties><local.repository.folder>${pom.basedir}/libs/</local.repository.folder>
</properties>
<repositories>
<repository>
<id>local-maven-repository</id>
<url>file://${local.repository.folder}</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
Open the .m2/repository folder and copy the directory structure of the project you want to import into the libs folder.
E.g. suppose you want to import the dependency
<dependency>
<groupId>com.mycompany.myproject</groupId>
<artifactId>myproject</artifactId>
<version>1.2.3</version>
</dependency>
Just go on .m2/repository and you will see the following folder
com/mycompany/myproject/1.2.3
Copy everything in your libs folder (again, including the folders under .m2/repository) and you are done.
Martin's solution above works great, but does not handle .o files that reside in subdirectories. Godric points out that the -MT flag takes care of that problem, but it simultaneously prevents the .o file from being written correctly. The following will take care of both of those problems:
DEPS := $(OBJS:.o=.d)
-include $(DEPS)
%.o: %.c
$(CC) $(CFLAGS) -MM -MT $@ -MF $(patsubst %.o,%.d,$@) $<
$(CC) $(CFLAGS) -o $@ $<
You'll have to do this in two steps:
If you don't have an internal repository, and you're just trying to add your JAR to your local repository, you can install it as follows, using any arbitrary groupId/artifactIds:
mvn install:install-file -DgroupId=com.stackoverflow... -DartifactId=yourartifactid... -Dversion=1.0 -Dpackaging=jar -Dfile=/path/to/jarfile
You can also deploy it to your internal repository if you have one, and want to make this available to other developers in your organization. I just use my repository's web based interface to add artifacts, but you should be able to accomplish the same thing using mvn deploy:deploy-file ...
.
Then update the dependency in the pom.xml of the projects that use the JAR by adding the following to the element:
<dependencies>
...
<dependency>
<groupId>com.stackoverflow...</groupId>
<artifactId>artifactId...</artifactId>
<version>1.0</version>
</dependency>
...
</dependencies>
best way for Python 3 is:
pip3 freeze > requirements.txt
it worked for me...
Did not have any luck updating via eclipse. Had to use mvn clean install -U (which resolved everything).
There are some modules and packages only necessary for development, which are not needed in production. Like it says it in the documentation:
If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use. In this case, it's best to list these additional items in a devDependencies hash.
If it helps anyone, I tried everything above (https w/token mode) - and still nothing was working. I got no errors, but nothing would be installed in node_modules or package_lock.json. If I changed the token or any letter in the repo name or user name, etc. - I'd get an error. So I knew I had the right token and repo name.
I finally realized it's because the name of the dependency I had in my package.json didn't match the name in the package.json of the repo I was trying to pull. Even npm install --verbose doesn't say there's any problem. It just seems to ignore the dependency w/o error.
NOTE:
The mentioned LATEST
and RELEASE
metaversions have been dropped for plugin dependencies in Maven 3 "for the sake of reproducible builds", over 6 years ago.
(They still work perfectly fine for regular dependencies.)
For plugin dependencies please refer to this Maven 3 compliant solution.
If you always want to use the newest version, Maven has two keywords you can use as an alternative to version ranges. You should use these options with care as you are no longer in control of the plugins/dependencies you are using.
When you depend on a plugin or a dependency, you can use the a version value of LATEST or RELEASE. LATEST refers to the latest released or snapshot version of a particular artifact, the most recently deployed artifact in a particular repository. RELEASE refers to the last non-snapshot release in the repository. In general, it is not a best practice to design software which depends on a non-specific version of an artifact. If you are developing software, you might want to use RELEASE or LATEST as a convenience so that you don't have to update version numbers when a new release of a third-party library is released. When you release software, you should always make sure that your project depends on specific versions to reduce the chances of your build or your project being affected by a software release not under your control. Use LATEST and RELEASE with caution, if at all.
See the POM Syntax section of the Maven book for more details. Or see this doc on Dependency Version Ranges, where:
[
& ]
) means "closed" (inclusive).(
& )
) means "open" (exclusive).Here's an example illustrating the various options. In the Maven repository, com.foo:my-foo has the following metadata:
<?xml version="1.0" encoding="UTF-8"?><metadata>
<groupId>com.foo</groupId>
<artifactId>my-foo</artifactId>
<version>2.0.0</version>
<versioning>
<release>1.1.1</release>
<versions>
<version>1.0</version>
<version>1.0.1</version>
<version>1.1</version>
<version>1.1.1</version>
<version>2.0.0</version>
</versions>
<lastUpdated>20090722140000</lastUpdated>
</versioning>
</metadata>
If a dependency on that artifact is required, you have the following options (other version ranges can be specified of course, just showing the relevant ones here):
Declare an exact version (will always resolve to 1.0.1):
<version>[1.0.1]</version>
Declare an explicit version (will always resolve to 1.0.1 unless a collision occurs, when Maven will select a matching version):
<version>1.0.1</version>
Declare a version range for all 1.x (will currently resolve to 1.1.1):
<version>[1.0.0,2.0.0)</version>
Declare an open-ended version range (will resolve to 2.0.0):
<version>[1.0.0,)</version>
Declare the version as LATEST (will resolve to 2.0.0) (removed from maven 3.x)
<version>LATEST</version>
Declare the version as RELEASE (will resolve to 1.1.1) (removed from maven 3.x):
<version>RELEASE</version>
Note that by default your own deployments will update the "latest" entry in the Maven metadata, but to update the "release" entry, you need to activate the "release-profile" from the Maven super POM. You can do this with either "-Prelease-profile" or "-DperformRelease=true"
It's worth emphasising that any approach that allows Maven to pick the dependency versions (LATEST, RELEASE, and version ranges) can leave you open to build time issues, as later versions can have different behaviour (for example the dependency plugin has previously switched a default value from true to false, with confusing results).
It is therefore generally a good idea to define exact versions in releases. As Tim's answer points out, the maven-versions-plugin is a handy tool for updating dependency versions, particularly the versions:use-latest-versions and versions:use-latest-releases goals.
For me, adding the following block of code under <dependency management><dependencies>
solved the problem.
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b06</version>
</dependency>
It's not automatic, but doxygen will produce dependency diagrams for #included
files. You will have to go through them visually, but they can be very useful for getting a picture of what is using what.
I found that running the npm install
command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.
Specifically, I was trying to use ng2-completer
$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.
I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.
cd foo/foo_app
$ npm install ng2-completer --save
You can try this
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
</dependencies>`
For my private repository reference I didn't want to include a secure token, and none of the other simple (i.e. specifying only in package.json) worked. Here's what did work:
This solved it for me:
package.json
, according to the errors;node_modules
(rm -rf node_modules
);npm install
.Repeat these steps until there are no more errors.
Based on @Raghuram answer, I find a tutorial on Copying project dependencies, Just:
Open your project pom.xml
file and find this:
<project>
[...]
<build>
<plugins>
...
</plugins>
</build>
[...]
</project>
Than replace the <plugins> ... </plugins>
with:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/alternateLocation</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
And call maven within the command line mvn dependency:copy-dependencies
After it finishes, it will create the folder target/dependency
within all the jar
's dependencies on the current directory where the pom.xml
lives.
Dependency walker works on normal win32 binaries. All .NET dll's and exe's have a small stub header part which makes them look like normal binaries, but all it basically says is "load the CLR" - so that's all that dependency walker will tell you.
To see which things your .NET app actually relies on, you can use the tremendously excellent .NET reflector from Red Gate. (EDIT: Note that .NET Reflector is now a paid product. ILSpy is free and open source and very similar.)
Load your DLL into it, right click, and chose 'Analyze' - you'll then see a "Depends On" item which will show you all the other dll's (and methods inside those dll's) that it needs.
It can sometimes get trickier though, in that your app depends on X dll, and X dll is present, but for whatever reason can't be loaded or located at runtime.
To troubleshoot those kinds of issues, Microsoft have an Assembly Binding Log Viewer which can show you what's going on at runtime
mcc -?
explains that the syntax to make *.exe (Standalone Application) with *.m is:
mcc -m <matlabFile.m>
For example:
mcc -m file.m
will create file.exe in the curent directory.
The setCustomValidity let you change the default validation message.Here is a simple exmaple of how to use it.
var age = document.getElementById('age');
age.form.onsubmit = function () {
age.setCustomValidity("This is not a valid age.");
};
rsync file /path/to/copy/file/to/is/very/deep/there
This might work, if you have the right kind of rsync
.
keyCodes are different from the ASCII values. For a complete keyCode reference, see http://unixpapa.com/js/key.html
For example, Numpad numbers have keyCodes 96 - 105, which corresponds to the beginning of lowercase alphabet in ASCII. This could lead to problems in validating numeric input.
Maybe you get the same project name in your '.project' file,check it,if yes, rename another name.than import again
Open app/build.gradle file
Change buildToolsVersion
to buildToolsVersion "26.0.2"
change compile 'com.android.support:appcompat
to compile 'com.android.support:appcompat-v7:26.0.2'
You could create a copy of the array and then multiply each element with -1.
As an effect the before largest elements would become the smallest.
The indeces of the n smallest elements in the copy are the n greatest elements in the original.
re: indexOutOfBoundsException
, your sublist args are the problem; you need to end the sublist at size-1. Being zero-based, the last element of a list is always size-1, there is no element in the size position, hence the error.
The ServletContext#getRealPath()
is intented to convert a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.
The "/"
represents the web content root. I.e. it represents the web
folder as in the below project structure:
YourWebProject
|-- src
| :
|
|-- web
| |-- META-INF
| | `-- MANIFEST.MF
| |-- WEB-INF
| | `-- web.xml
| |-- index.jsp
| `-- login.jsp
:
So, passing the "/"
to getRealPath()
would return you the absolute disk file system path of the /web
folder of the expanded WAR file of the project. Something like /path/to/server/work/folder/some.war/
which you should be able to further use in File
or FileInputStream
.
Note that most starters don't seem to see/realize that you can actually pass the whole web content path to it and that they often use
String absolutePathToIndexJSP = servletContext.getRealPath("/") + "index.jsp"; // Wrong!
or even
String absolutePathToIndexJSP = servletContext.getRealPath("") + "index.jsp"; // Wronger!
instead of
String absolutePathToIndexJSP = servletContext.getRealPath("/index.jsp"); // Right!
Also note that even though you can write new files into it using FileOutputStream
, all changes (e.g. new files or edited files) will get lost whenever the WAR is redeployed; with the simple reason that all those changes are not contained in the original WAR file. So all starters who are attempting to save uploaded files in there are doing it wrong.
Moreover, getRealPath()
will always return null
or a completely unexpected path when the server isn't configured to expand the WAR file into the disk file system, but instead into e.g. memory as a virtual file system.
getRealPath()
is unportable; you'd better never use itUse getRealPath()
carefully. There are actually no sensible real world use cases for it. Based on my 20 years of Java EE experience, there has always been another way which is much better and more portable than getRealPath()
.
If all you actually need is to get an InputStream
of the web resource, better use ServletContext#getResourceAsStream()
instead, this will work regardless of the way how the WAR is expanded. So, if you for example want an InputStream
of index.jsp
, then do not do:
InputStream input = new FileInputStream(servletContext.getRealPath("/index.jsp")); // Wrong!
But instead do:
InputStream input = servletContext.getResourceAsStream("/index.jsp"); // Right!
Or if you intend to obtain a list of all available web resource paths, use ServletContext#getResourcePaths()
instead.
Set<String> resourcePaths = servletContext.getResourcePaths("/");
You can obtain an individual resource as URL
via ServletContext#getResource()
. This will return null
when the resource does not exist.
URL resource = servletContext.getResource(path);
Or if you intend to save an uploaded file, or create a temporary file, then see the below "See also" links.
On Linux, Unix, Git Bash, or Cygwin, try:
rm -f .git/index.lock
On Windows Command Prompt, try:
del .git\index.lock
For Windows:
From a PowerShell console opened as administrator, try
rm -Force ./.git/index.lock
If that does not work, you must kill all git.exe processes
taskkill /F /IM git.exe
SUCCESS: The process "git.exe" with PID 20448 has been terminated.
SUCCESS: The process "git.exe" with PID 11312 has been terminated.
SUCCESS: The process "git.exe" with PID 23868 has been terminated.
SUCCESS: The process "git.exe" with PID 27496 has been terminated.
SUCCESS: The process "git.exe" with PID 33480 has been terminated.
SUCCESS: The process "git.exe" with PID 28036 has been terminated. \
rm -Force ./.git/index.lock
You can use Ctrl + Shift + / for Windows.
Missing the most important one IMO the container for the controls ::-webkit-media-controls-enclosure
:
&::-webkit-media-controls-enclosure {
border-radius: 5px;
background-color: green;
}
It's a wchar_t
literal, for extended character set. Wikipedia has a little discussion on this topic, and c++ examples.
start from
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
you can iterate through JSONArray and use values directly or create Objects of your own type
which will handle data fields inside of each deletedtrs_array
member
Iterating
for(int i = 0; i < deletedtrs_array.length(); i++){
JSONObject obj = deletedtrs_array.getJSONObject(i);
Log.d("Item no."+i, obj.toString());
// create object of type DeletedTrsWrapper like this
DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj);
// String company_id = obj.getString("companyid");
// String username = obj.getString("username");
// String date = obj.getString("date");
// int report_id = obj.getInt("reportid");
}
Own object type
class DeletedTrsWrapper {
public String company_id;
public String username;
public String date;
public int report_id;
public DeletedTrsWrapper(JSONObject obj){
company_id = obj.getString("companyid");
username = obj.getString("username");
date = obj.getString("date");
report_id = obj.getInt("reportid");
}
}
A simple solution for a delayed auto submit:
<body onload="setTimeout(function() { document.frm1.submit() }, 5000)">
<form action="https://www.google.com" name="frm1">
<input type="hidden" name="q" value="Hello world" />
</form>
</body>
php 5.5 has an imagecrop function http://php.net/manual/en/function.imagecrop.php
solution1 = map(list, zip(*l))
solution2 = [list(i) for i in zip(*l)]
solution3 = []
for i in zip(*l):
solution3.append((list(i)))
print(*solution1)
print(*solution2)
print(*solution3)
# [1, 4, 7], [2, 5, 8], [3, 6, 9]
jQuery's .data() does a couple things but it doesn't add the data to the DOM as an attribute. When using it to grab a data attribute, the first thing it does is create a jQuery data object and sets the object's value to the data attribute. After that, it's essentially decoupled from the data attribute.
Example:
<div data-foo="bar"></div>
If you grabbed the value of the attribute using .data('foo')
, it would return "bar" as you would expect. If you then change the attribute using .attr('data-foo', 'blah')
and then later use .data('foo')
to grab the value, it would return "bar" even though the DOM says data-foo="blah"
. If you use .data()
to set the value, it'll change the value in the jQuery object but not in the DOM.
Basically, .data()
is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. .attr()
is for setting or checking the DOM element's attribute value and will not touch the jQuery data value. If you need them both to change you should use both .data()
and .attr()
. Otherwise, stick with one or the other.
false == 0
and true = !false
i.e. anything that is not zero and can be converted to a boolean is not false
, thus it must be true
.
Some examples to clarify:
if(0) // false
if(1) // true
if(2) // true
if(0 == false) // true
if(0 == true) // false
if(1 == false) // false
if(1 == true) // true
if(2 == false) // false
if(2 == true) // false
cout << false // 0
cout << true // 1
true
evaluates to 1
, but any int
that is not false
(i.e. 0
) evaluates to true
but is not equal to true
since it isn't equal to 1
.
204 responses are sometimes used in AJAX to track clicks and page activity. In this case, the only information being passed to the server in the get request is a cookie and not specific information in request parameters, so this doesn't seem to be the case here.
It seems that clients1.google.com is the server behind google search suggestions. When you visit http://www.google.com, the cookie is passed to http://clients1.google.com/generate_204. Perhaps this is to start up some kind of session on the server? Whatever the use, I doubt it's a very standard use.
You have to single quote your src
string inside of the double quotes:
<div ng-include src="'views/sidepanel.html'"></div>
I just went through this issue and none of the suggestions solved my problem. While I was unable to start MySQL on boot and found the same message in the logs ("Another MySQL daemon already running with the same unix socket"), I was able to start the service once I arrived at the console.
In my configuration file, I found the following line: bind-address=xx.x.x.x
. I randomly decided to comment it out, and the error on boot disappeared. Because the bind address provides security, in a way, I decided to explore it further. I was using the machine's IP address, rather than the IPv4 loopback address - 127.0.0.1
.
In short, by using 127.0.0.1
as the bind-address
, I was able to fix this error. I hope this helps those who have this problem, but are unable to resolve it using the answers detailed above.
\r\n will not work until you set body type as text.
message.setBody(MessageBody.getMessageBodyFromText(msg));
BodyType type = BodyType.Text;
message.getBody().setBodyType(type);
UPDATE [table]
SET [column] = REPLACE([column], '/foo/', '/bar/')
Let me just add a warning to all the existing answers:
When using the SELECT ... FROM syntax, you should keep in mind that it is proprietary syntax for T-SQL and is non-deterministic. The worst part is, that you get no warning or error, it just executes smoothly.
Full explanation with example is in the documentation:
Use caution when specifying the FROM clause to provide the criteria for the update operation. The results of an UPDATE statement are undefined if the statement includes a FROM clause that is not specified in such a way that only one value is available for each column occurrence that is updated, that is if the UPDATE statement is not deterministic.
Now you can upgrade to PHP7.4 and MySQL will go with caching_sha2_password
by default, so default MySQL installation will work with mysqli_connect
No configuration required.
If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
If you only need string values in the array, the following will work:
function hasDuplicates(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}
We use a "hash table" valuesSoFar
whose keys are the values we've seen in the array so far. We do a lookup using in
to see if that value has been spotted already; if so, we bail out of the loop and return true
.
If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).
function hasDuplicates(array) {
var valuesSoFar = [];
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (valuesSoFar.indexOf(value) !== -1) {
return true;
}
valuesSoFar.push(value);
}
return false;
}
The difference is simply that we use an array instead of a hash table for valuesSoFar
, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in
, instead getting an O(n) lookup time of indexOf
.
You can set timeout like this,
con.setConnectTimeout(connectTimeout);
con.setReadTimeout(socketTimeout);
Below is a working example code.
Please note you need to add a reference to Newtonsoft.Json.Linq
string url = "https://yourAPIurl";
WebRequest myReq = WebRequest.Create(url);
string credentials = "xxxxxxxxxxxxxxxxxxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
CredentialCache mycache = new CredentialCache();
myReq.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.WriteLine(content);
var json = "[" + content + "]"; // change this to array
var objects = JArray.Parse(json); // parse as array
foreach (JObject o in objects.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = p.Value.ToString();
Console.Write(name + ": " + value);
}
}
Console.ReadLine();
Reference: TheDeveloperBlog.com
Another solution just using a standard library and deque:
from collections import deque
import itertools
def moving_average(iterable, n=3):
# http://en.wikipedia.org/wiki/Moving_average
it = iter(iterable)
# create an iterable object from input argument
d = deque(itertools.islice(it, n-1))
# create deque object by slicing iterable
d.appendleft(0)
s = sum(d)
for elem in it:
s += elem - d.popleft()
d.append(elem)
yield s / n
# example on how to use it
for i in moving_average([40, 30, 50, 46, 39, 44]):
print(i)
# 40.0
# 42.0
# 45.0
# 43.0
You can simply use EditorTemplates to do that, you need to create a directory named "EditorTemplates" in your controller's view folder and place a seperate view for each of your nested entities (named as entity class name)
Main view :
@model ViewModels.MyViewModels.Theme
@Html.LabelFor(Model.Theme.name)
@Html.EditorFor(Model.Theme.Categories)
Category view (/MyController/EditorTemplates/Category.cshtml) :
@model ViewModels.MyViewModels.Category
@Html.LabelFor(Model.Name)
@Html.EditorFor(Model.Products)
Product view (/MyController/EditorTemplates/Product.cshtml) :
@model ViewModels.MyViewModels.Product
@Html.LabelFor(Model.Name)
@Html.EditorFor(Model.Orders)
and so on
this way Html.EditorFor helper will generate element's names in an ordered manner and therefore you won't have any further problem for retrieving the posted Theme entity as a whole
The notation that is used in
a[::-1]
means that for a given string/list/tuple, you can slice the said object using the format
<object_name>[<start_index>, <stop_index>, <step>]
This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.
In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.
So,
a = '1234'
print a[::2]
would print
13
Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example
a = '1234'
print a[3:0:-1]
This would return
432
Note, that it doesn't return 4321 because, the stop index is not included.
Now in your case,
str(int(a[::-1]))
would just reverse a given integer, that is stored in a string, and then convert it back to a string
i.e "1234" -> "4321" -> 4321 -> "4321"
If what you are trying to do is just reverse the given string, then simply a[::-1] would work .
In an application level, here are something a developer can do:
From server side:
Check if load balancer(if you have),works correctly.
Turn slow TCP timeouts into 503 Fast Immediate response, if you load balancer work correctly, it should pick the working resource to serve, and it's better than hanging there with unexpected error massages.
Eg: If you are using node server, u can use toobusy from npm. Implementation something like:
var toobusy = require('toobusy');
app.use(function(req, res, next) {
if (toobusy()) res.send(503, "I'm busy right now, sorry.");
else next();
});
Why 503? Here are some good insights for overload: http://ferd.ca/queues-don-t-fix-overload.html
We can do some work in client side too:
Try to group calls in batch, reduce the traffic and total requests number b/w client and server.
Try to build a cache mid-layer to handle unnecessary duplicates requests.
For an app created with create-react-app I managed to see the version:
The app was deployed without source map.
The localStorage
can only store string content and you are trying to store a jQuery object since html(htmlString)
returns a jQuery object.
You need to set the string content instead of an object. And use the setItem
method to add data and getItem
to get data.
window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));
I had the exact error when deleting a file. It was a Windows Service running under a Service Account which was unable to delete a .pdf document from a Shared Folder even though it had Full Control of the folder.
What worked for me was navigating to the Security tab of the Shared Folder > Advanced > Share > Add.
I then added the service account to the administrators group, applied the changes and the service account was then able to perform all operations on all files within that folder.
Vincent Povirk's answer won't work completely;
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...
You have to change it in:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...
For details read the ZipFile
docs here.
Try Making the Child Form's StartPosition Property set to Center Parent. This you can select from the form Properties.
I found a solution on another thread that works - use the pull-left class:
<a href="#" class="pull-left"><img src="/path/to/image.png"></a>
Thanks to Michael in this thread:
Set up a System variable from Maven and in java use following call
System.getProperty("Key");
You can also find Toggle Line Numbers
under View
on the top toolbar of the Jupyter notebook in your browser.
This adds/removes the lines numbers in all notebook cells.
For me, Esc+l only added/removed the line numbers of the active cell.
Browser > Inspect > Element >
<.app-root _nghost-hey-c0="" ng-version="8.2.11">
In terminal
:> ng version
:> ng --version
:> ng -v
My answer deals with a more specific case of what you are asking but I think one could draw some ideas from this to apply more generally. Also, I would post this as a comment to Purushoth's answer (on which mine is based), if only I could.
Ok, so my problem was how to fit a web page into the pdf document, without losing the aspect ratio. I used jsPDF in conjuction with html2canvas and I calculated the ratio from my div
's width and height. I applied that same ratio to the pdf document and the page fit perfectly onto the page without any distortion.
var divHeight = $('#div_id').height();
var divWidth = $('#div_id').width();
var ratio = divHeight / divWidth;
html2canvas(document.getElementById("div_id"), {
height: divHeight,
width: divWidth,
onrendered: function(canvas) {
var image = canvas.toDataURL("image/jpeg");
var doc = new jsPDF(); // using defaults: orientation=portrait, unit=mm, size=A4
var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();
height = ratio * width;
doc.addImage(image, 'JPEG', 0, 0, width-20, height-10);
doc.save('myPage.pdf'); //Download the rendered PDF.
}
});
You can call GC.Collect() when you know something about the nature of the app the garbage collector doesn't. It's tempting to think that, as the author, this is very likely. However, the truth is the GC amounts to a pretty well-written and tested expert system, and it's rare you'll know something about the low level code paths it doesn't.
The best example I can think of where you might have some extra information is a app that cycles between idle periods and very busy periods. You want the best performance possible for the busy periods and therefore want to use the idle time to do some clean up.
However, most of the time the GC is smart enough to do this anyway.
If anyone has run into this issue recently, I found I had to add a setting to use my workspace's version of typescript for the auto-imports to work. To do this, add this line to your workspace settings:
{
"typescript.tsdk": "./node_modules/typescript/lib"
}
Then, with a typescript file open in vscode, click the typescript version number in the lower right-hand corner. When the options at the top appear, choose "use workspace version", then reload vscode.
Now auto-imports should work.
Add this in your css to hide just the horizontal scroll bar
iframe{
overflow-x:hidden;
}
Developers of Android and iOS decided that they are powerful and smart enough to reject Modal Dialog conception (that was on market for many-many years already and didn't bother anyone before), unfortunately for us. I believe that there is work around for Android - since you can show dialog from non-ui thread using Runnable class, there should be a way to wait in that thread (non-ui) until dialog is finished.
Edit: Here is my solution, it works great:
int pressedButtonID;
private final Semaphore dialogSemaphore = new Semaphore(0, true);
final Runnable mMyDialog = new Runnable()
{
public void run()
{
AlertDialog errorDialog = new AlertDialog.Builder( [your activity object here] ).create();
errorDialog.setMessage("My dialog!");
errorDialog.setButton("My Button1", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = MY_BUTTON_ID1;
dialogSemaphore.release();
}
});
errorDialog.setButton2("My Button2", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = MY_BUTTON_ID2;
dialogSemaphore.release();
}
});
errorDialog.setCancelable(false);
errorDialog.show();
}
};
public int ShowMyModalDialog() //should be called from non-UI thread
{
pressedButtonID = MY_BUTTON_INVALID_ID;
runOnUiThread(mMyDialog);
try
{
dialogSemaphore.acquire();
}
catch (InterruptedException e)
{
}
return pressedButtonID;
}
I couldn't get the "Attach source..." method to work either, and I tried many different ways. The Javadocs for JavaFX are installed in Program Files\Oracle\JavaFX 2.x SDK\docs. Another way to install the Javadocs is:
Hope this helps some people who were as puzzled as I was.
The answer provided by polygenelubricants splits an array based on given size. I was looking for code that would split an array into a given number of parts. Here is the modification I did to the code:
public static <T>List<List<T>> chopIntoParts( final List<T> ls, final int iParts )
{
final List<List<T>> lsParts = new ArrayList<List<T>>();
final int iChunkSize = ls.size() / iParts;
int iLeftOver = ls.size() % iParts;
int iTake = iChunkSize;
for( int i = 0, iT = ls.size(); i < iT; i += iTake )
{
if( iLeftOver > 0 )
{
iLeftOver--;
iTake = iChunkSize + 1;
}
else
{
iTake = iChunkSize;
}
lsParts.add( new ArrayList<T>( ls.subList( i, Math.min( iT, i + iTake ) ) ) );
}
return lsParts;
}
Hope it helps someone.
for full url use
$('#imageContainerId').prop('src')
for relative image url use
$('#imageContainerId').attr('src')
function showImgUrl(){_x000D_
console.log('for full image url ' + $('#imageId').prop('src') );_x000D_
console.log('for relative image url ' + $('#imageId').attr('src'));_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<img id='imageId' src='images/image1.jpg' height='50px' width='50px'/>_x000D_
_x000D_
<input type='button' onclick='showImgUrl()' value='click to see the url of the img' />
_x000D_
If the IDynamicMetaObjectProvider can provide the dynamic member names, you can get them. See GetMemberNames implementation in the apache licensed PCL library Dynamitey (which can be found in nuget), it works for ExpandoObject
s and DynamicObject
s that implement GetDynamicMemberNames
and any other IDynamicMetaObjectProvider
who provides a meta object with an implementation of GetDynamicMemberNames
without custom testing beyond is IDynamicMetaObjectProvider
.
After getting the member names it's a little more work to get the value the right way, but Impromptu does this but it's harder to point to just the interesting bits and have it make sense. Here's the documentation and it is equal or faster than reflection, however, unlikely to be faster than a dictionary lookup for expando, but it works for any object, expando, dynamic or original - you name it.
Just point to the dictionary at given key and assign a new value:
myDictionary[myKey] = myNewValue;
Hope this helps;
df1 = data.frame(CustomerId=c(1:10),
Hobby = c(rep("sing", 4), rep("pingpong", 3), rep("hiking", 3)),
Product=c(rep("Toaster",3),rep("Phone", 2), rep("Radio",3), rep("Stereo", 2)))
df2 = data.frame(CustomerId=c(2,4,6, 8, 10),State=c(rep("Alabama",2),rep("Ohio",1), rep("Cal", 2)),
like=c("sing", 'hiking', "pingpong", 'hiking', "sing"))
df3 = merge(df1, df2, by.x=c("CustomerId", "Hobby"), by.y=c("CustomerId", "like"))
Assuming df1$Hobby
and df2$like
mean the same thing.
The following shell function, being only based on POSIX standard commands and options should work on most (if not any) Unix and linux system. :
isPidRunning() {
cmd=`
PATH=\`getconf PATH\` export PATH
ps -e -o pid= -o comm= |
awk '$2 ~ "^.*/'"$1"'$" || $2 ~ "^'"$1"'$" {print $1,$2}'
`
[ -n "$cmd" ] &&
printf "%s is running\n%s\n\n" "$1" "$cmd" ||
printf "%s is not running\n\n" $1
[ -n "$cmd" ]
}
$ isPidRunning httpd
httpd is running
586 /usr/apache/bin/httpd
588 /usr/apache/bin/httpd
$ isPidRunning ksh
ksh is running
5230 ksh
$ isPidRunning bash
bash is not running
Note that it will choke when passed the dubious "0]" command name and will also fail to identify processes having an embedded space in their names.
Note too that the most upvoted and accepted solution demands non portable ps
options and gratuitously uses a shell that is, despite its popularity, not guaranteed to be present on every Unix/Linux machine (bash
)
I have today similar problem. But weirder.
host pl.archive.ubuntu.com
dig pl.archive.ubuntu.com
, dig @127.0.1.1 pl.archive.ubuntu.com
$ curl -v http://google.com/
* Trying 172.217.18.78...
* Connected to google.com (172.217.18.78) port 80 (#0)
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 302 Found
< Cache-Control: private
< Content-Type: text/html; charset=UTF-8
< Referrer-Policy: no-referrer
< Location: http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB
< Content-Length: 256
< Date: Thu, 29 Jun 2017 11:08:22 GMT
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact
$ curl -v http://pl.archive.ubuntu.com/
* Could not resolve host: pl.archive.ubuntu.com
* Closing connection 0
curl: (6) Could not resolve host: pl.archive.ubuntu.com
Revelation
Eventually I used strace
on curl and found that it was connection to nscd
deamon.
connect(4, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = 0
Solution
I've restarted the nscd service (Name Service Cache Daemon) and it helped to solve this issue!
systemctl restart nscd.service
You can use the "ORDER BY DESC" option, then put it back in the original order:
(SELECT * FROM tablename ORDER BY id DESC LIMIT 10) ORDER BY id;
Run your script with .
. myscript.sh
This will run the script in the current shell environment.
export
governs which variables will be available to new processes, so if you say
FOO=1
export BAR=2
./runScript.sh
then $BAR
will be available in the environment of runScript.sh
, but $FOO
will not.
You can use this:
Js:
function refreshFrame(){
$('#myFrame').attr('src', "http://blablab.com?v=");
}
Html:
`<iframe id="myFrame" src=""></iframe>`
JS Fiddle : https://jsfiddle.net/wpb20vzx/
You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.
used like: window.Promise
https://www.npmjs.com/package/promise-polyfill
If you want more information on Polyfills check out the following MDN web doc https://developer.mozilla.org/en-US/docs/Glossary/Polyfill
I struggled a lot with this issue. @Albin solution worked like a charm while developing, but it did not work when I changed it to production. After some debugging I realized how to achieve what I needed. I'm using ES6 with CRA (create-react-app), which means it's bundled by Webpack.
Lets say you have a file that exports the functions you need:
myFunctions.js
export function setItem(params) {
// ...
}
export function setUser(params) {
// ...
}
export function setPost(params) {
// ...
}
export function setReply(params) {
// ...
}
And you need to dynamically call these functions elsewhere:
myApiCalls.js
import * as myFunctions from 'path_to/myFunctions';
/* note that myFunctions is imported as an array,
* which means its elements can be easily accessed
* using an index. You can console.log(myFunctions).
*/
function accessMyFunctions(res) {
// lets say it receives an API response
if (res.status === 200 && res.data) {
const { data } = res;
// I want to read all properties in data object and
// call a function based on properties names.
for (const key in data) {
if (data.hasOwnProperty(key)) {
// you can skip some properties that are usually embedded in
// a normal response
if (key !== 'success' && key !== 'msg') {
// I'm using a function to capitalize the key, which is
// used to dynamically create the function's name I need.
// Note that it does not create the function, it's just a
// way to access the desired index on myFunctions array.
const name = `set${capitalizeFirstLetter(key)}`;
// surround it with try/catch, otherwise all unexpected properties in
// data object will break your code.
try {
// finally, use it.
myFunctions[name](data[key]);
} catch (error) {
console.log(name, 'does not exist');
console.log(error);
}
}
}
}
}
}
have a look here for the full syntax: http://en.wikipedia.org/wiki/File_URI_scheme
for unix-like systems it will be as @Alex said file:///your/file/here
whereas for Windows systems would be file:///c|/path/to/file
The make
uses the $
for its own variable expansions. E.g. single character variable $A
or variable with a long name - ${VAR}
and $(VAR)
.
To put the $
into a command, use the $$
, for example:
all:
@echo "Please execute next commands:"
@echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'
Also note that to make
the ""
and ''
(double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @
sign to see what make
sends to shell.) To prevent the shell from expanding $PATH
, second line uses the ''
.
You don't need the class reference for the li
s. Instead of having CSS like
li.top-level-nav { color:black; }
you can write
ul#sidebar > li { color:black; }
This will apply the styling only to li
s that immediately descend from the sidebar ul
.
In this DDJ article, Dan Saks explains one small area where bugs can creep through if you do not typedef your structs (and classes!):
If you want, you can imagine that C++ generates a typedef for every tag name, such as
typedef class string string;
Unfortunately, this is not entirely accurate. I wish it were that simple, but it's not. C++ can't generate such typedefs for structs, unions, or enums without introducing incompatibilities with C.
For example, suppose a C program declares both a function and a struct named status:
int status(); struct status;
Again, this may be bad practice, but it is C. In this program, status (by itself) refers to the function; struct status refers to the type.
If C++ did automatically generate typedefs for tags, then when you compiled this program as C++, the compiler would generate:
typedef struct status status;
Unfortunately, this type name would conflict with the function name, and the program would not compile. That's why C++ can't simply generate a typedef for each tag.
In C++, tags act just like typedef names, except that a program can declare an object, function, or enumerator with the same name and the same scope as a tag. In that case, the object, function, or enumerator name hides the tag name. The program can refer to the tag name only by using the keyword class, struct, union, or enum (as appropriate) in front of the tag name. A type name consisting of one of these keywords followed by a tag is an elaborated-type-specifier. For instance, struct status and enum month are elaborated-type-specifiers.
Thus, a C program that contains both:
int status(); struct status;
behaves the same when compiled as C++. The name status alone refers to the function. The program can refer to the type only by using the elaborated-type-specifier struct status.
So how does this allow bugs to creep into programs? Consider the program in Listing 1. This program defines a class foo with a default constructor, and a conversion operator that converts a foo object to char const *. The expression
p = foo();
in main should construct a foo object and apply the conversion operator. The subsequent output statement
cout << p << '\n';
should display class foo, but it doesn't. It displays function foo.
This surprising result occurs because the program includes header lib.h shown in Listing 2. This header defines a function also named foo. The function name foo hides the class name foo, so the reference to foo in main refers to the function, not the class. main can refer to the class only by using an elaborated-type-specifier, as in
p = class foo();
The way to avoid such confusion throughout the program is to add the following typedef for the class name foo:
typedef class foo foo;
immediately before or after the class definition. This typedef causes a conflict between the type name foo and the function name foo (from the library) that will trigger a compile-time error.
I know of no one who actually writes these typedefs as a matter of course. It requires a lot of discipline. Since the incidence of errors such as the one in Listing 1 is probably pretty small, you many never run afoul of this problem. But if an error in your software might cause bodily injury, then you should write the typedefs no matter how unlikely the error.
I can't imagine why anyone would ever want to hide a class name with a function or object name in the same scope as the class. The hiding rules in C were a mistake, and they should not have been extended to classes in C++. Indeed, you can correct the mistake, but it requires extra programming discipline and effort that should not be necessary.
If your python version is 2.+, you can type below code to the terminal :
pip install seaborn
if python version is 3+, type below:
pip3 install seaborn
Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.
var i = 0;_x000D_
this.setInterval(function() {_x000D_
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
console.log('Counting...');_x000D_
$('#counter').html(i++); //just for explaining and showing_x000D_
} else {_x000D_
console.log('Stopped counting');_x000D_
}_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
$(this).addClass('pauseInterval');_x000D_
},function() { //mouse leave_x000D_
$(this).removeClass('pauseInterval');_x000D_
}_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
$('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
background-color: #eee;_x000D_
font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
width: 50%;_x000D_
background: #ddd;_x000D_
border: 2px solid #009afd;_x000D_
border-radius: 5px;_x000D_
padding: 5px;_x000D_
text-align: center;_x000D_
transition: .3s;_x000D_
margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
border-color: red; _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter"> </p>_x000D_
<button id="pauseInterval">Pause/unpause</button></p>
_x000D_
public static string XmlEscape(string unescaped)
{
XmlDocument doc = new XmlDocument();
XmlNode node = doc.CreateElement("root");
node.InnerText = unescaped;
return node.InnerXml;
}
public static string XmlUnescape(string escaped)
{
XmlDocument doc = new XmlDocument();
XmlNode node = doc.CreateElement("root");
node.InnerXml = escaped;
return node.InnerText;
}
I use this peace of code and I have successeful
<div class="row center-block">
<div style="margin: 0 auto;width: 90%;">
<div class="col-md-12" style="top:10px;">
</div>
<div class="col-md-12" style="top:10px;">
</div>
</div>
You can use the following CSS to style the input element.
input[type="date"] {_x000D_
background-color: red;_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-clear-button {_x000D_
font-size: 18px;_x000D_
height: 30px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-inner-spin-button {_x000D_
height: 28px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
font-size: 15px;_x000D_
}
_x000D_
<input type="date" value="From" name="from" placeholder="From" required="" />
_x000D_
I found this post helpful:
"It can happen when res folder contains unexpected folder names. In my case after merge mistakes I had a folder src/main/res/res. And it caused problems."
from: "https://groups.google.com/forum/#!msg/adt-dev/0pEUKhEBMIA/ZxO5FNRjF8QJ"
Be careful, -
has a special meaning with regexp. In a []
, you can put it without problem if it is placed at the end. In your case, ,-:
is taken as from ,
to :
.
I did this by extending the tomcat DefaultServlet (src) and overriding the getRelativePath() method.
package com.example;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.servlets.DefaultServlet;
public class StaticServlet extends DefaultServlet
{
protected String pathPrefix = "/static";
public void init(ServletConfig config) throws ServletException
{
super.init(config);
if (config.getInitParameter("pathPrefix") != null)
{
pathPrefix = config.getInitParameter("pathPrefix");
}
}
protected String getRelativePath(HttpServletRequest req)
{
return pathPrefix + super.getRelativePath(req);
}
}
... And here are my servlet mappings
<servlet>
<servlet-name>StaticServlet</servlet-name>
<servlet-class>com.example.StaticServlet</servlet-class>
<init-param>
<param-name>pathPrefix</param-name>
<param-value>/static</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>StaticServlet</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
Generally the process will block. If the read operation is on a file descriptor marked as non-blocking or if the process is using asynchronous IO it won't block. Also if the process has other threads that aren't blocked they can continue running.
The decision as to which process runs next is up to the scheduler in the kernel.
I believe a combination of reduce
with JSON.stringify
to perfectly compare Objects and selectively adding those who are not already in the accumulator is an elegant way.
Keep in mind that JSON.stringify
might become a performance issue in extreme cases where the array has many Objects and they are complex, BUT for majority of the time, this is the shortest way to go IMHO.
var collection= [{a:1},{a:2},{a:1},{a:3}]_x000D_
_x000D_
var filtered = collection.reduce((filtered, item) => {_x000D_
if( !filtered.some(filteredItem => JSON.stringify(filteredItem) == JSON.stringify(item)) )_x000D_
filtered.push(item)_x000D_
return filtered_x000D_
}, [])_x000D_
_x000D_
console.log(filtered)
_x000D_
collection.reduce((filtered, item) =>
filtered.some(filteredItem =>
JSON.stringify(filteredItem ) == JSON.stringify(item))
? filtered
: [...filtered, item]
, [])
Elaborating on the previous answer, you can gather all the required snippets before outputting the header, and only then use an action hook to inject all you need on the head.
In your functions.php file, add
$inject_required_scripts = array();
/**
* Call this function before calling get_header() to request custom js code to be injected on head.
*
* @param code the javascript code to be injected.
*/
function require_script($code) {
global $inject_required_scripts;
$inject_required_scripts[] = $code; // store code snippet for later injection
}
function inject_required_scripts() {
global $inject_required_scripts;
foreach($inject_required_scripts as $script)
// inject all code snippets, if any
echo '<script type="text/javascript">'.$script.'</script>';
}
add_action('wp_head', 'inject_required_scripts');
And then in your page or template, use it like
<?php
/* Template Name: coolstuff */
require_script(<<<JS
jQuery(function(){jQuery('div').wrap('<blink/>')});
JS
);
require_script(<<<JS
jQuery(function(){jQuery('p,span,a').html('Internet is cool')});
JS
);
get_header();
[...]
I made it for javascript because it's the most common use, but it can be easily adapted to any tag in the head, and either with inline code or by passing a href/src to an external URL.
Change the FormBorderStyle
to one of the fixed values: FixedSingle
, Fixed3D
,
FixedDialog
or FixedToolWindow
.
The FormBorderStyle
property is under the Appearance category.
Or check this:
// Define the border style of the form to a dialog box.
form1.FormBorderStyle = FormBorderStyle.FixedDialog;
// Set the MaximizeBox to false to remove the maximize box.
form1.MaximizeBox = false;
// Set the MinimizeBox to false to remove the minimize box.
form1.MinimizeBox = false;
// Set the start position of the form to the center of the screen.
form1.StartPosition = FormStartPosition.CenterScreen;
// Display the form as a modal dialog box.
form1.ShowDialog();
The reason why Python base environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the base environment.
create a new separate environment in Anaconda dedicated to TensorFlow as follows:
conda create -n newenvt anaconda python=python_version
replace python_version by your python version
activate the new environment as follows:
activate newenvt
Then install tensorflow into the new environment (newenvt) as follows:
conda install tensorflow
Now you can check it by issuing the following python code and it will work fine.
import tensorflow
There are a least these apt-get
extension packages that can help:
apt-offline - offline apt package manager
apt-zip - Update a non-networked computer using apt and removable media
This is specifically for the case of wanting to download where you have network access but to install on another machine where you do not.
Otherwise, the --download-only
option to apt-get
is your friend:
-d, --download-only
Download only; package files are only retrieved, not unpacked or installed.
Configuration Item: APT::Get::Download-Only.
Are you sure you've connected to the db? (I ask because I don't see a port specified)
try:
mongoose.connection.on("open", function(){
console.log("mongodb is connected!!");
});
Also, you can do a "show collections" in mongo shell to see the collections within your db - maybe try adding a record via mongoose and see where it ends up?
From the look of your connection string, you should see the record in the "test" db.
Hope it helps!
what isn't working about it? here's a tested version:
String.prototype.isValidDate = function() {
const match = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
if (!match || match.length !== 4) {
return false
}
const test = new Date(match[3], match[1] - 1, match[2]);
return (
(test.getMonth() == match[1] - 1) &&
(test.getDate() == match[2]) &&
(test.getFullYear() == match[3])
);
}
var date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'
alert(date.isValidDate() ); // true
Here is a good example -
ul li{
list-style-type: disc;
list-style-position: inside;
padding: 10px 0 10px 20px;
text-indent: -1em;
}
Working Demo: http://jsfiddle.net/d9VNk/
Query Analyzer buffers messages. The PRINT and RAISERROR statements both use this buffer, but the RAISERROR statement has a WITH NOWAIT option. To print a message immediately use the following:
RAISERROR ('Your message', 0, 1) WITH NOWAIT
RAISERROR will only display 400 characters of your message and uses a syntax similar to the C printf function for formatting text.
Please note that the use of RAISERROR with the WITH NOWAIT option will flush the message buffer, so all previously buffered information will be output also.
Slight modification of above answer to copy a folder recursively and to accommodate custom destination.
public void copyFileOrDir(String path, String destinationDir) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path,destinationDir);
} else {
String fullPath = destinationDir + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i], destinationDir + path + "/" + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename, String destinationDir) {
AssetManager assetManager = this.getAssets();
String newFileName = destinationDir + "/" + filename;
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
new File(newFileName).setExecutable(true, false);
}
I think this solution uses less code and is easy to understand even for newbie.
For string field in struct, you can use pointer and reassigning the string to that pointer will be straightforward and simpler.
Define definition of struct:
typedef struct {
int number;
char *name;
char *address;
char *birthdate;
char gender;
} Patient;
Initialize variable with type of that struct:
Patient patient;
patient.number = 12345;
patient.address = "123/123 some road Rd.";
patient.birthdate = "2020/12/12";
patient.gender = "M";
It is that simple. Hope this answer helps many developers.
Yahoo's api provides a CSV dump:
Example: http://finance.yahoo.com/d/quotes.csv?s=msft&f=price
I'm not sure if it is documented or not, but this code sample should showcase all of the features (namely the stat types [parameter f in the query string]. I'm sure you can find documentation (official or not) if you search for it.
http://www.goldb.org/ystockquote.html
Edit
I found some unofficial documentation:
sString = sString.toLowerCase();
sString = Character.toString(sString.charAt(0)).toUpperCase()+sString.substring(1);
1. Installing OpenCV 2.4.3
First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\
.
Wait until all files get extracted. It will create a new directory C:\opencv
which
contains OpenCV header files, libraries, code samples, etc.
Now you need to add the directory C:\opencv\build\x86\vc10\bin
to your system PATH. This directory contains OpenCV DLLs required for running your code.
Open Control Panel → System → Advanced system settings → Advanced Tab → Environment variables...
On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin;
(3), then click Ok.
On some computers, you may need to restart your computer for the system to recognize the environment path variables.
This will completes the OpenCV 2.4.3 installation on your computer.
2. Create a new project and set up Visual C++
Open Visual C++ and select File → New → Project... → Visual C++ → Empty Project. Give a name for your project (e.g: cvtest
) and set the project location (e.g: c:\projects
).
Click Ok. Visual C++ will create an empty project.
Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest
and select Properties → VC++ Directories.
Select Include Directories to add a new entry and type C:\opencv\build\include
.
Click Ok to close the dialog.
Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib
.
Click Ok to close the dialog.
Back to the property dialog, select Linker → Input → Additional Dependencies to add new entries. On the popup dialog, type the files below:
opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib
Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).
Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.
NOTE:
These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:
opencv_core243.lib
opencv_imgproc243.lib
...
instead of:
opencv_core243d.lib
opencv_imgproc243d.lib
...
You've done setting up Visual C++, now is the time to write the real code. Right click your project and select Add → New Item... → Visual C++ → C++ File.
Name your file (e.g: loadimg.cpp
) and click Ok. Type the code below in the editor:
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat im = imread("c:/full/path/to/lena.jpg");
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
imshow("Image", im);
waitKey(0);
}
The code above will load c:\full\path\to\lena.jpg
and display the image. You can
use any image you like, just make sure the path to the image is correct.
Type F5 to compile the code, and it will display the image in a nice window.
And that is your first OpenCV program!
3. Where to go from here?
Now that your OpenCV environment is ready, what's next?
c:\opencv\samples\cpp
.the_input = raw_input("Enter input: ")
And that's it.
Moreover, if you want to make a list of inputs, you can do something like:
a = []
for x in xrange(1,10):
a.append(raw_input("Enter Data: "))
In that case, you'll be asked for data 10 times to store 9 items in a list.
Output:
Enter data: 2
Enter data: 3
Enter data: 4
Enter data: 5
Enter data: 7
Enter data: 3
Enter data: 8
Enter data: 22
Enter data: 5
>>> a
['2', '3', '4', '5', '7', '3', '8', '22', '5']
You can search that list the fundamental way with something like (after making that list):
if '2' in a:
print "Found"
else: print "Not found."
You can replace '2' with "raw_input()" like this:
if raw_input("Search for: ") in a:
print "Found"
else:
print "Not found"
If you want to take the input from a file you feed through commandline (which is normally what you need when doing code problems for competitions, like Google Code Jam or the ACM/IBM ICPC):
example.py
while(True):
line = raw_input()
print "input data: %s" % line
In command line interface:
example.py < input.txt
Hope that helps.
seq -w
will detect the max input width and normalize the width of the output.
for num in $(seq -w 01 05); do
...
done
At time of writing this didn't work on the newest versions of OSX, so you can either install macports and use its version of seq
, or you can set the format explicitly:
seq -f '%02g' 1 3
01
02
03
But given the ugliness of format specifications for such a simple problem, I prefer the solution Henk and Adrian gave, which just uses Bash. Apple can't screw this up since there's no generic "unix" version of Bash:
echo {01..05}
Or:
for number in {01..05}; do ...; done
I also faced the same issues and it was resolved when i created file named with DockerFile and mentioned all the command which wanted to get executed while creation of any image.
Typically we would place one of these at or near the top of the script. Scripts that parse their command lines would do the redirection after parsing.
Send stdout to a file
exec > file
with stderr
exec > file
exec 2>&1
append both stdout and stderr to file
exec >> file
exec 2>&1
As Jonathan Leffler mentioned in his comment:
exec
has two separate jobs. The first one is to replace the currently executing shell (script) with a new program. The other is changing the I/O redirections in the current shell. This is distinguished by having no argument to exec
.
To call the method, you need to qualify function with self.
. In addition to that, if you want to pass a filename, add a filename
parameter (or other name you want).
class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
srcpath = event.src_path
print (srcpath, 'has been ',event.event_type)
print (datetime.datetime.now())
filename = srcpath[12:]
self.dropbox_fn(filename) # <----
def dropbox_fn(self, filename): # <-----
print('In dropbox_fn:', filename)
First get the pid:
ps ax | grep [process name]
And then:
top -p PID
You can watch various processes in the same time:
top -p PID1 -p PID2
For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations
key, so add CoursesComponent
in your main module declarations
as below and remove directives
from AppComponent
metadata.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, CoursesComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
For anyone that might be having this issue. I was building a custom MVC in PHP when I encountered this issue.
I was able to resolve this by setting my assets (css/js/images) files to an absolute path. Instead of using url like href="css/style.css" which use this entire current url to load it. As an example, if you are in http://example.com/user/5, it will try to load at http://example.com/user/5/css/style.css.
To fix it, you can add a / at the start of your asset's url (i.e. href="/css/style.css"). This will tell the browser to load it from the root of your url. In this example, it will try to load http://example.com/css/style.css.
Hope this comment will help you.
Solution
id
is unsigned integer, auto_incrementid
columnBam, immediate 10x+ insert improvement.
To sort by cpu usage: top -o cpu
Use setDataAndType on the Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(newVideoPath), "video/mp4");
startActivity(intent);
Use "video/mp4" as MIME or use "video/*" if you don't know the type.
In addition, it's convenient to define variables referring to objects. For instance,
Sub CreateTable()
Dim lo as ListObject
Set lo = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes)
lo.Name = "Table1"
lo.TableStyle = "TableStyleLight2"
...
End Sub
You will probably find it advantageous at once.
This is something I use:
$cryptoStrong = true; // can be false
$length = 16; // Any length you want
$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
$randomString = bin2hex($bytes);
You can see the Docs for openssl_random_pseudo_bytes here, and the Docs for bin2hex here
I happened that problem on a virtual server, when everything worked correctly on other hosting.
After several modifications I realized that I include
or require_one
works on all calls except in a file.
The problem of this file was the code < ?php ? >
At the beginning and end of the text.
It was a script that was only < ?
, and in that version of apache that was running did not work
First of all, it's actually not accurate to say that
x % 2 == x & 1
Simple counterexample: x = -1
. In many languages, including Java, -1 % 2 == -1
. That is, %
is not necessarily the traditional mathematical definition of modulo. Java calls it the "remainder operator", for example.
With regards to bitwise optimization, only modulo powers of two can "easily" be done in bitwise arithmetics. Generally speaking, only modulo powers of base b can "easily" be done with base b representation of numbers.
In base 10, for example, for non-negative N
, N mod 10^k
is just taking the least significant k
digits.
Add below dependency to your pom.xml
:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.10.2</version>
</dependency>
In Python 3, we use the bytes
object, also known as str
in Python 2.
# Python 3
key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
# Python 2
key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
I find it more convenient to use the base64
module...
# Python 3
key = base64.b16decode(b'130000000800')
# Python 2
key = base64.b16decode('130000000800')
You can also use literals...
# Python 3
key = b'\x13\0\0\0\x08\0'
# Python 2
key = '\x13\0\0\0\x08\0'
Since Oracle is the licensed product, there are issue in adding maven dependency directly. To add any version of the ojdbc.jar, below 2 steps could do.
/opt/apache-maven/bin/mvn install:install-file
-Dfile=<path-to-file>/ojdbc7.jar
-DgroupId=com.oracle
-DartifactId=ojdbc7
-Dversion=12.1.0.1.0
-Dpackaging=jar
This will add the dependency into local repository.
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.1.0</version>
</dependency>
The simplest & least error prone approach is... Use Calendar's roll() method. Like this:
c.roll(Calendar.MONTH, false);
the roll method takes a boolean, which basically means roll the month up(true) or down(false)?
You can do this in jquery by setting the attribute disabled to 'disabled'.
$(this).prop('disabled', true);
I have made a simple example http://jsfiddle.net/4gnXL/2/
You just need to declare a
as a global in thread2
, so that you aren't modifying an a
that is local to that function.
def thread2(threadname):
global a
while True:
a += 1
time.sleep(1)
In thread1
, you don't need to do anything special, as long as you don't try to modify the value of a
(which would create a local variable that shadows the global one; use global a
if you need to)>
def thread1(threadname):
#global a # Optional if you treat a as read-only
while a < 10:
print a
I would check the "End of File" flag:
If temp_rst1.EOF Or temp_rst2.EOF Then MsgBox "null"
There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow "create/use/release" usage, and doesn't allow cross-db work. An example (formatted for space):
using (IDbTransaction tran = conn.BeginTransaction()) {
try {
// your code
tran.Commit();
} catch {
tran.Rollback();
throw;
}
}
Not too messy, but limited to our connection "conn". If we want to call out to different methods, we now need to pass "conn" around.
The alternative is an ambient transaction; new in .NET 2.0, the TransactionScope object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).
For example:
using(TransactionScope tran = new TransactionScope()) {
CallAMethodThatDoesSomeWork();
CallAMethodThatDoesSomeMoreWork();
tran.Complete();
}
Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.
If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.
The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).
All in all, a very, very useful object.
Some caveats:
The links are wrong, you have to do this:
<ul class="nav navbar-nav item">
<li>
<a [routerLink]="['/home']" routerLinkActive="active">Home</a>
</li>
<li>
<a [routerLink]="['/about']" routerLinkActive="active">About this
</a>
</li>
</ul>
You can read this tutorial
Not sure if you still need this, but in http://www.appbrain.com/ , you look up the app and the package name is in the url. For example: http://www.appbrain.com/app/fruit-ninja/com.halfbrick.fruitninja is the link for fruit ninja. Notice the bold
This only worked for me after I've enabled developer usb debugging on the phone:
On your android phone, go to Settings > About, then tap repeatedly on Build Number until Developer Options is enabled.
Seems that the script block passed to Start-Job
is not executed with the same current directory as the Start-Job
command, so make sure to specify fully qualified path if needed.
For example:
Start-Job { C:\absolute\path\to\command.exe --afileparameter C:\absolute\path\to\file.txt }
Nodejs is a scripting language (like Python or Ruby, and unlike PHP or C++). To run your code, you need to enter a command in the terminal / shell / command prompt. Look for an application shortcut in your operating system by one of those names.
The command to run in the terminal will be
node server.js
But you will first need to browse in the terminal to the same folder as the file server.js
. The syntax for using the terminal varies by operating system, look for its documentation.
This will work even when there are multiple instance of jar is running
wmic Path win32_process Where "CommandLine Like '%yourname.jar%'" Call Terminate
That approach will be good if the date-time in question is in UTC, or represents local time in an area that has never observed daylight saving time. The DateTime difference routines do not take into account Daylight Saving Time, and consequently will regard midnight June 1 as being a multiple of 24 hours after midnight January 1. I'm unaware of anything in Windows that reports historical daylight-saving rules for the current locale, so I don't think there's any good way to correctly handle any time prior to the most recent daylight-saving rule change.
$('#drop').change(
function() {
var val1 = $('#pick option:selected').val();
var val2 = $('#drop option:selected').val();
// Do something with val1 and val2 ...
}
);
I have observed that -
I have prepared a method that works like this, you can replace the value of the variable ftpurl with the parameter TargetDestinationPath. I had tested this method on winforms application :
private void UploadProfileImage(string TargetFileName, string TargetDestinationPath, string FiletoUpload)
{
//Get the Image Destination path
string imageName = TargetFileName; //you can comment this
string imgPath = TargetDestinationPath;
string ftpurl = "ftp://downloads.abc.com/downloads.abc.com/MobileApps/SystemImages/ProfileImages/" + imgPath;
string ftpusername = krayknot_DAL.clsGlobal.FTPUsername;
string ftppassword = krayknot_DAL.clsGlobal.FTPPassword;
string fileurl = FiletoUpload;
FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl);
ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword);
ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftpClient.UseBinary = true;
ftpClient.KeepAlive = true;
System.IO.FileInfo fi = new System.IO.FileInfo(fileurl);
ftpClient.ContentLength = fi.Length;
byte[] buffer = new byte[4097];
int bytes = 0;
int total_bytes = (int)fi.Length;
System.IO.FileStream fs = fi.OpenRead();
System.IO.Stream rs = ftpClient.GetRequestStream();
while (total_bytes > 0)
{
bytes = fs.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
total_bytes = total_bytes - bytes;
}
//fs.Flush();
fs.Close();
rs.Close();
FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
string value = uploadResponse.StatusDescription;
uploadResponse.Close();
}
Let me know in case of any issue, or here is one more link that can help you:
https://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx
## you can use request module and promise in express to make any request ##
const promise = require('promise');
const requestModule = require('request');
const curlRequest =(requestOption) =>{
return new Promise((resolve, reject)=> {
requestModule(requestOption, (error, response, body) => {
try {
if (error) {
throw error;
}
if (body) {
try {
body = (body) ? JSON.parse(body) : body;
resolve(body);
}catch(error){
resolve(body);
}
} else {
throw new Error('something wrong');
}
} catch (error) {
reject(error);
}
})
})
};
const option = {
url : uri,
method : "GET",
headers : {
}
};
curlRequest(option).then((data)=>{
}).catch((err)=>{
})
I was reading a lot about this issue and wanted to provide a very quick workaround that helped me.
let style = window.getComputedStyle(document.getElementById('email'))
if (style && style.backgroundColor !== inputBackgroundNormalState) {
this.inputAutofilledByBrowser = true
}
where inputBackgroundNormalState
for my template is 'rgb(255, 255, 255)'.
So basically when browsers apply autocomplete they tend to indicate that the input is autofilled by applying a different (annoying) yellow color on the input.
Edit : this works for every browser
Use your identifier(@"drivingDetails") as Storyboard ID.
f
is an (instance) method. However, you are calling it via fibo.f
, where fibo
is the class object. Hence, f
is unbound (not bound to any class instance).
If you did
a = fibo()
a.f()
then that f
is bound (to the instance a
).
Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of
So you should prevent the default behaviour of the button click
$('#btnSave').click(function (e) {
// prevent the default event behaviour
e.preventDefault();
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
// perform your save call here
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
Change
@RequestMapping(value = "/test", method = RequestMethod.POST)
To
@RequestMapping(value = "/test", method = RequestMethod.GET)
You can pass boolean
by coercing it, put !!
before the variable.
let isRequired = '' || null || undefined
<input :required="!!isRequired"> // it will coerce value to respective boolean
But I would like to pull your attention for the following case where the receiving component has defined type
for props. In that case, if isRequired
has defined type to be string
then passing boolean
make it type check fails and you will get Vue warning. To fix that you may want to avoid passing that prop, so just put undefined
fallback and the prop will not sent to component
let isValue = false
<any-component
:my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
Explanation
I have been through the same problem, and tried above solutions !!
Yes, I don't see the prop
but that actually does not fulfils what required here.
My problem -
let isValid = false
<any-component
:my-prop="isValue ? 'Hey I am when the value exist': false"
/>
In the above case, what I expected is not having my-prop
get passed to the child component - <any-conponent/>
I don't see the prop
in DOM
but In my <any-component/>
component, an error pops out of prop type check failure. As in the child component, I am expecting my-prop
to be a String
but it is boolean
.
myProp : {
type: String,
required: false,
default: ''
}
Which means that child component did receive the prop even if it is false
. Tweak here is to let the child component to take the default-value
and also skip the check. Passed undefined
works though!
<any-component
:my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
This works and my child prop is having the default value.
Besides the usual recommendation:
I have learnt the following from my experience with SQLite3:
Question/comment welcome. ;-)
You could also do it in two steps:
remove = [k for k in mydict if k == val]
for k in remove: del mydict[k]
My favorite approach is usually to just make a new dict:
# Python 2.7 and 3.x
mydict = { k:v for k,v in mydict.items() if k!=val }
# before Python 2.7
mydict = dict((k,v) for k,v in mydict.iteritems() if k!=val)
What version of the framework? With 3.5 you could presumably use:
List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList();
(edited to remove simpler version; I checked and ManagementObjectCollection
only implements the non-generic IEnumerable
form)
Updating Maksymilian Wojakowski's awesome answer for swift 3
extension UIFont {
func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont? {
guard let descriptorL = self.fontDescriptor.withSymbolicTraits(UIFontDescriptorSymbolicTraits(traits)) else{
return nil
}
return UIFont(descriptor: descriptorL, size: 0)
}
func boldItalic() -> UIFont? {
return withTraits(traits: .traitBold, .traitItalic)
}
}
1 additional caveat (besides the answer by kanaka/peter): if you use WSS, and the server certificate is not acceptable to the browser, you may not get any browser rendered dialog (like it happens for Web pages). This is because WebSockets is treated as a so-called "subresource", and certificate accept / security exception / whatever dialogs are not rendered for subresources.
Why not make a function to echo, like this:
function fecho($string) {
echo $string;
ob_flush();
}
I also faced the same issue while I was building email notification application. you just need to add one line. Below one saved my day.
props.put("mail.smtp.starttls.enable", "true");
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. h13-v6sm10627790pgp.13 - gsmtp
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.smruti.email.EmailProject.EmailSend.main(EmailSend.java:99)
Hope this helps you.
Since in your question you said it's a PHP script, maybe the best solution could be to simply add in your script:
ignore_user_abort(TRUE);
In this way even if wget
terminates, the PHP script goes on being processed at least until it does not exceeds max_execution_time
limit (ini directive: 30 seconds by default).
As per wget
anyay you should not change its timeout, according to the UNIX manual the default wget timeout is 900 seconds (15 minutes), whis is much larger that the 5-6 minutes you need.
This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *
First two answers here: How to enable CORS in AngularJs
<input type="password" placeholder="Enter New Password" autocomplete="new-password">
Here you go.
I know this has been answered to death but I'd like to show an actual example of speed differences.
Function directly on object:
function ExampleFn() {
this.print = function() {
console.log("Calling print! ");
}
}
var objects = [];
console.time('x');
for (let i = 0; i < 2000000; i++) {
objects.push(new ExampleFn());
}
console.timeEnd('x');
//x: 1151.960693359375ms
_x000D_
Function on prototype:
function ExampleFn() {
}
ExampleFn.prototype.print = function() {
console.log("Calling print!");
}
var objects = [];
console.time('y');
for (let i = 0; i < 2000000; i++) {
objects.push(new ExampleFn());
}
console.timeEnd('y');
//x: 617.866943359375ms
_x000D_
Here we're creating 2,000,000 new objects with a print
method in Chrome. We're storing every object in an array. Putting print
on the prototype takes about 1/2 as long.
Simon Howard's answer is great. But /\%81v.\+/
fails to highlight tabs that exceed column 81 . So I did a little tweak, based on the stuff I found on VIM wiki and HS's choice of colors above:
highlight OverLength ctermbg=darkred ctermfg=white guibg=#FFD9D9
match OverLength /\%>80v.\+/
And now VIM will highlight anything that exceeds column 80.
I think this will help. It's same as given by Mr. Barmer. But I have enclosed this within php tags.
Here it goes....
<?php if(!empty($_GET['submitted'])):?>
<script>
setTimeout(function() {
swal({
title: "Congratulaions!",
text: "Signed up successfully, now verify your mail",
type: "success",
confirmButtonText: "Ok"
}, function() {
window.location = "index.php";
}, 1000);
});
</script>
<?php endif;?>
By subquery, it should work:
SELECT distinct(Category) from MonitoringJob where Category in(select Category from MonitoringJob order by CreationDate desc);
You need to use theme() function as follows rotating x-axis labels by 90 degrees:
ggplot(...)+...+ theme(axis.text.x = element_text(angle=90, hjust=1))
According to the packages list in Ubuntu Wily Xenial Bionic there is a package named openjfx. This should be a candidate for what you're looking for:
JavaFX/OpenJFX 8 - Rich client application platform for Java
You can install it via:
sudo apt-get install openjfx
It provides the following JAR files to the OpenJDK installation on Ubuntu systems:
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jfxswt.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/ant-javafx.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/javafx-mx.jar
If you want to have sources available, for example for debugging, you can additionally install:
sudo apt-get install openjfx-source
See AddDefaultCharset Directive, AddCharset Directive, and this article.
AddDefaultCharset utf-8
But I have to use Chinese characters now and then. Previously, I translated Chinese characters to Unicode code and include it in the document using the
&#
hack. But it is only useful for page having a few characters.There is a better way to do that: encode the charset information in the filename, and apache will output the proper encoding header based on that. This is possible thanks to the
AddCharset
lines in the conf file, such as the line below:
conf/httpd.conf
:
AddCharset UTF-8 .utf8
So if you have a file whose names ends in
.html.utf8
, apache will serve the page as if it is encoded in UTF-8 and will dump the proper character-encoding directive in the header accordingly.
For Oracle, it is also LENGTH instead of LEN
SELECT MAX(LENGTH(Desc)) FROM table_name
Also, DESC is a reserved word. Although many reserved words will still work for column names in many circumstances it is bad practice to do so, and can cause issues in some circumstances. They are reserved for a reason.
If the word Desc was just being used as an example, it should be noted that not everyone will realize that, but many will realize that it is a reserved word for Descending. Personally, I started off by using this, and then trying to figure out where the column name went because all I had were reserved words. It didn't take long to figure it out, but keep that in mind when deciding on what to substitute for your actual column name.
as of AS 1.2+ there is an auto-check for updates which will let you choose between the stable, dev, canary, and beta channels. However it is just a check instead of a full update script. It does require that you click to install and restart your install ( A problem for a remote server situation)
This error appear because the compiler could not found "my-upload-key.keystore" file in your project
After you have generated the file you need to paste it into project's andorid/app folder
this worked for me!
Spent a day on finding the easiest way to do this. The purpose was to find the fastest way to achieve this goal. I couldn't make it as fast as running javac command from terminal or compiling from netbeans or sublime text 3. But still got a good speed with android studio.
This looks ruff and tuff way but since we don't initiate projects on daily bases that is why I am okay to do this.
I downloaded IntelliJ IDEA community version and created a simply java project. I added a main class and tested a run. Then simply closed IntelliJ IDEA and opened Android Studio and opened the same project there. Then I had to simply attach JDK where IDE helped me by showing a list of available JDKs and I selected 1.8 and then it compiled well. I can now open any main file and press Control+Shift+R to run that main file.
Then I copied all my Java files into src folder by Mac OS Finder. And I am able to compile anything I want to.
There is nothing related to Gradle or Android and compile speed is pretty good.
Thanks buddies
for those like me still stuck with SQL Server 2000, SET ROWCOUNT {number};
can be used before the UPDATE
query
SET ROWCOUNT 100;
UPDATE Table SET ..;
SET ROWCOUNT 0;
will limit the update to 100 rows
It has been deprecated at least since SQL 2005, but as of SQL 2017 it still works. https://docs.microsoft.com/en-us/sql/t-sql/statements/set-rowcount-transact-sql?view=sql-server-2017
Here is the PHP code to check if 'id' parameter exists in the URL or not:
if(isset($_GET['id']))
{
$slide = $_GET['id'] // Getting parameter value inside PHP variable
}
I hope it will help you.
If you use cPanel and have installed CloudLinux you can go to section Software > Select PHP Version > Switch To PHP Options and define max_execution_time among other options.
Short gif: http://cloud.mercadoalvo.com/nDdE
You are able to choose one that you like, but it has to be unique.
Every time I have to enter the SKU I use the App identifier (e.g. de.mycompany.myappname
) because this is already unique.
See the doc : it will close all running tasks using the executable file something.exe
, more or less like linux' killall
I think CAST(ROUND(yourColumn,2) as varchar)
should do the job.
But why do you want to do this presentational formatting in T-SQL?
You can try my package node-global-proxy
which work with all node versions and most of http-client (axios, got, superagent, request etc.)
after install by
npm install node-global-proxy --save
a global proxy can start by
const proxy = require("node-global-proxy").default;
proxy.setConfig({
http: "http://localhost:1080",
https: "https://localhost:1080",
});
proxy.start();
/** Proxy working now! */
More information available here: https://github.com/wwwzbwcom/node-global-proxy
Right click on Drawable folder
click on new
click on image asset
Then you can select an icon type
Question content may have changed, so I'll try to answer thoroughly.
Destructuring allows you to pull values out of anything with properties. You can also define default values when null/undefined and name aliases.
const options = {
filters : {
firstName : "abc"
}
}
const {filters: {firstName = "John", lastName = "Smith"}} = options
// firstName = "abc"
// lastName = "Smith"
NOTE: Capitalization matters
If working with an array, here is how you do it.
In this case, name is extracted from each object in the array, and given its own alias. Since the object might not exist = {}
was also added.
const options = {
filters: [{
name: "abc",
value: "lots"
}]
}
const {filters:[{name : filter1 = "John"} = {}, {name : filter2 = "Smith"} = {}]} = options
// filter1 = "abc"
// filter2 = "Smith"
Browser Support 92% July 2020
import com.google.common.base.Joiner;
String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));
This may be overkill to answer the op's question, but it is good to know about for more complex join operations. This stackoverflow question ranks highly in general google searches in this area, so good to know.
condition binding must have optinal type which mean that you can only bind optional values in if let statement
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
if let tv = tableView as UITableView? {
}
}
}
This will work fine but make sure when you use if let it must have optinal type "?"
Send as many inserts across the wire at one time as possible. The actual insert speed should be the same, but you will see performance gains from the reduction of network overhead.
The answer is in the current spec:
The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.
Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.
Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element.
The section element is not a generic container element. When an element is needed for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element's contents would be listed explicitly in the document's outline.
Reference:
Also see:
It looks like there's been a lot of confusion about this element's purpose, but the one thing that's agreed upon is that it is not a generic wrapper, like <div>
is. It should be used for semantic purposes, and not a CSS or JavaScript hook (although it certainly can be styled or "scripted").
A better example, from my understanding, might look something like this:
<div id="content">
<article>
<h2>How to use the section tag</h2>
<section id="disclaimer">
<h3>Disclaimer</h3>
<p>Don't take my word for it...</p>
</section>
<section id="examples">
<h3>Examples</h3>
<p>But here's how I would do it...</p>
</section>
<section id="closing_notes">
<h3>Closing Notes</h3>
<p>Well that was fun. I wonder if the spec will change next week?</p>
</section>
</article>
</div>
Note that <div>
, being completely non-semantic, can be used anywhere in the document that the HTML spec allows it, but is not necessary.
I'm using display:block
for thead
and tbody
.
Because of that the width of the thead
columns is different from the width of the tbody
columns.
table {
margin:0 auto;
border-collapse:collapse;
}
thead {
background:#CCCCCC;
display:block
}
tbody {
height:10em;overflow-y:scroll;
display:block
}
To fix this I use small jQuery
code but it can be done in JavaScript
only.
var colNumber=3 //number of table columns
for (var i=0; i<colNumber; i++) {
var thWidth=$("#myTable").find("th:eq("+i+")").width();
var tdWidth=$("#myTable").find("td:eq("+i+")").width();
if (thWidth<tdWidth)
$("#myTable").find("th:eq("+i+")").width(tdWidth);
else
$("#myTable").find("td:eq("+i+")").width(thWidth);
}
Here is my working demo: http://jsfiddle.net/gavroche/N7LEF/
Does not work in IE 8
var colNumber=3 //number of table columns_x000D_
_x000D_
_x000D_
for (var i=0; i<colNumber; i++)_x000D_
{_x000D_
var thWidth=$("#myTable").find("th:eq("+i+")").width();_x000D_
var tdWidth=$("#myTable").find("td:eq("+i+")").width(); _x000D_
if (thWidth<tdWidth) _x000D_
$("#myTable").find("th:eq("+i+")").width(tdWidth);_x000D_
else_x000D_
$("#myTable").find("td:eq("+i+")").width(thWidth); _x000D_
}
_x000D_
table {margin:0 auto; border-collapse:separate;}_x000D_
thead {background:#CCCCCC;display:block}_x000D_
tbody {height:10em;overflow-y:scroll;display:block}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<table id="myTable" border="1">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>A really Very Long Header Text</th>_x000D_
<th>Normal Header</th>_x000D_
<th>Short</th> _x000D_
</tr> _x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
Text shorter than header_x000D_
</td>_x000D_
<td>_x000D_
Text is longer than header_x000D_
</td>_x000D_
<td>_x000D_
Exact_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Text shorter than header_x000D_
</td>_x000D_
<td>_x000D_
Text is longer than header_x000D_
</td>_x000D_
<td>_x000D_
Exact_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Text shorter than header_x000D_
</td>_x000D_
<td>_x000D_
Text is longer than header_x000D_
</td>_x000D_
<td>_x000D_
Exact_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Text shorter than header_x000D_
</td>_x000D_
<td>_x000D_
Text is longer than header_x000D_
</td>_x000D_
<td>_x000D_
Exact_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Text shorter than header_x000D_
</td>_x000D_
<td>_x000D_
Text is longer than header_x000D_
</td>_x000D_
<td>_x000D_
Exact_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Text shorter than header_x000D_
</td>_x000D_
<td>_x000D_
Text is longer than header_x000D_
</td>_x000D_
<td>_x000D_
Exact_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Text shorter than header_x000D_
</td>_x000D_
<td>_x000D_
Text is longer than header_x000D_
</td>_x000D_
<td>_x000D_
Exact_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Text shorter than header_x000D_
</td>_x000D_
<td>_x000D_
Text is longer than header_x000D_
</td>_x000D_
<td>_x000D_
Exact_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Text shorter than header_x000D_
</td>_x000D_
<td>_x000D_
Text is longer than header_x000D_
</td>_x000D_
<td>_x000D_
Exact_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Text shorter than header_x000D_
</td>_x000D_
<td>_x000D_
Text is longer than header_x000D_
</td>_x000D_
<td>_x000D_
Exact_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Text shorter than header_x000D_
</td>_x000D_
<td>_x000D_
Text is longer than header_x000D_
</td>_x000D_
<td>_x000D_
Exact_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
It's \n
. When you're reading or writing text mode files, or to stdin/stdout etc, you must use \n
, and C will handle the translation for you. When you're dealing with binary files, by definition you are on your own.
Here's my pure pathlib
recursive directory unlinker:
from pathlib import Path
def rmdir(directory):
directory = Path(directory)
for item in directory.iterdir():
if item.is_dir():
rmdir(item)
else:
item.unlink()
directory.rmdir()
rmdir(Path("dir/"))
I met with the same error. After struggling, I found that it was due to "Space" in the folder name.
For example :
Earlier My folder name was : "Qt Projects"
Later I changed it to : "QtProjects"
and my issue was resolved.
Its very simple but sometimes a major issue.
For Converting a List into Pandas Core Data Frame, we need to use DataFrame Method from pandas Package.
There are Different Ways to Perform the Above Operation.
import pandas as pd
Data = pd.DataFrame(Column_Data)
Data.columns = ['Column_Name']
So, for the above mentioned issue, the code snippet is
import pandas as pd
Content = ['Thanks You',
'Its fine no problem',
'Are you sure']
Data = pd.DataFrame({'Text': Content})
You appear to be trying to mix query expression syntax and "normal" lambda expression syntax. You can either use:
IEnumerable<SelectListItem> stores =
from store in database.Stores
where store.CompanyID == curCompany.ID
select new SelectListItem { Value = store.Name, Text = store.ID};
ViewBag.storeSelector = stores;
Or:
IEnumerable<SelectListItem> stores = database.Stores
.Where(store => store.CompanyID == curCompany.ID)
.Select(s => new SelectListItem { Value = s.Name, Text = s.ID});
ViewBag.storeSelector = stores;
You can't mix the two like you're trying to.
For database list:
show databases
show dbs
For table/collection list:
show collections
show tables
db.getCollectionNames()
This is not the best solve, but if you really don't care it is an easy solution. I simply renamed my class. So I had class Card and I changed it to MyCard.
There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))
or
my_obj.categories.create(name='val1')
EventLog.Log should be set as "Application"
Setting the slice to nil
is the best way to clear a slice. nil
slices in go are perfectly well behaved and setting the slice to nil
will release the underlying memory to the garbage collector.
package main
import (
"fmt"
)
func dump(letters []string) {
fmt.Println("letters = ", letters)
fmt.Println(cap(letters))
fmt.Println(len(letters))
for i := range letters {
fmt.Println(i, letters[i])
}
}
func main() {
letters := []string{"a", "b", "c", "d"}
dump(letters)
// clear the slice
letters = nil
dump(letters)
// add stuff back to it
letters = append(letters, "e")
dump(letters)
}
Prints
letters = [a b c d]
4
4
0 a
1 b
2 c
3 d
letters = []
0
0
letters = [e]
1
1
0 e
Note that slices can easily be aliased so that two slices point to the same underlying memory. The setting to nil
will remove that aliasing.
This method changes the capacity to zero though.
1) Use multiple classes inside the class attribute, separated by whitespace (ref):
<a class="c1 c2">aa</a>
2) To target elements that contain all of the specified classes, use this CSS selector (no space) (ref):
.c1.c2 {
}
You can't use a table name for a variable. You'd have to do this instead:
DECLARE @sqlCommand varchar(1000)
SET @sqlCommand = 'SELECT * from yourtable'
EXEC (@sqlCommand)
Go to the menu Help
> Install New Software
and click the Add
button.
Use something like JBoss Hibernate for the name and insert the following URL for the location:
http://download.jboss.org/jbosstools/neon/stable/updates/
Wait for the product tree to load and then expand the JBoss Web and Java EE Development
folder and select the Hibernate Tools
product and click the Next >
button. Then follow on accepting all the subsequent questions, licence, etc.
When the installation is finished, restart Eclipse as required. After that, to open the Hibernate perspective go to the menu Window
> Perspective
> Open Perspective
> Others
and search for Hibernate.
"C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe"
.Paste the value into Location of the item, and append --kiosk <your url>
:
"C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe" --kiosk http://www.google.com
Press Apply, then OK.
A survey of automatic memory leak checkers
In this answer, I compare several different memory leak checkers in a simple easy to understand memory leak example.
Before anything, see this huge table in the ASan wiki which compares all tools known to man: https://github.com/google/sanitizers/wiki/AddressSanitizerComparisonOfMemoryTools/d06210f759fec97066888e5f27c7e722832b0924
The example analyzed will be:
main.c
#include <stdlib.h>
void * my_malloc(size_t n) {
return malloc(n);
}
void leaky(size_t n, int do_leak) {
void *p = my_malloc(n);
if (!do_leak) {
free(p);
}
}
int main(void) {
leaky(0x10, 0);
leaky(0x10, 1);
leaky(0x100, 0);
leaky(0x100, 1);
leaky(0x1000, 0);
leaky(0x1000, 1);
}
We will try to see how clearly do the different tools point us to the leaky calls.
tcmalloc from gperftools by Google
https://github.com/gperftools/gperftools
Usage on Ubuntu 19.04:
sudo apt-get install google-perftools
gcc -ggdb3 -o main.out main.c -ltcmalloc
PPROF_PATH=/usr/bin/google-pprof \
HEAPCHECK=normal \
HEAPPROFILE=ble \
./main.out \
;
google-pprof main.out ble.0001.heap --text
The output of the program run contains the memory leak analysis:
WARNING: Perftools heap leak checker is active -- Performance may suffer
Starting tracking the heap
Dumping heap profile to ble.0001.heap (Exiting, 4 kB in use)
Have memory regions w/o callers: might report false leaks
Leak check _main_ detected leaks of 272 bytes in 2 objects
The 2 largest leaks:
Using local file ./main.out.
Leak of 256 bytes in 1 objects allocated from:
@ 555bf6e5815d my_malloc
@ 555bf6e5817a leaky
@ 555bf6e581d3 main
@ 7f71e88c9b6b __libc_start_main
@ 555bf6e5808a _start
Leak of 16 bytes in 1 objects allocated from:
@ 555bf6e5815d my_malloc
@ 555bf6e5817a leaky
@ 555bf6e581b5 main
@ 7f71e88c9b6b __libc_start_main
@ 555bf6e5808a _start
If the preceding stack traces are not enough to find the leaks, try running THIS shell command:
pprof ./main.out "/tmp/main.out.24744._main_-end.heap" --inuse_objects --lines --heapcheck --edgefraction=1e-10 --nodefraction=1e-10 --gv
If you are still puzzled about why the leaks are there, try rerunning this program with HEAP_CHECK_TEST_POINTER_ALIGNMENT=1 and/or with HEAP_CHECK_MAX_POINTER_OFFSET=-1
If the leak report occurs in a small fraction of runs, try running with TCMALLOC_MAX_FREE_QUEUE_SIZE of few hundred MB or with TCMALLOC_RECLAIM_MEMORY=false, it might help find leaks more re
Exiting with error code (instead of crashing) because of whole-program memory leaks
and the output of google-pprof
contains the heap usage analysis:
Using local file main.out.
Using local file ble.0001.heap.
Total: 0.0 MB
0.0 100.0% 100.0% 0.0 100.0% my_malloc
0.0 0.0% 100.0% 0.0 100.0% __libc_start_main
0.0 0.0% 100.0% 0.0 100.0% _start
0.0 0.0% 100.0% 0.0 100.0% leaky
0.0 0.0% 100.0% 0.0 100.0% main
The output points us to two of the three leaks:
Leak of 256 bytes in 1 objects allocated from:
@ 555bf6e5815d my_malloc
@ 555bf6e5817a leaky
@ 555bf6e581d3 main
@ 7f71e88c9b6b __libc_start_main
@ 555bf6e5808a _start
Leak of 16 bytes in 1 objects allocated from:
@ 555bf6e5815d my_malloc
@ 555bf6e5817a leaky
@ 555bf6e581b5 main
@ 7f71e88c9b6b __libc_start_main
@ 555bf6e5808a _start
I'm not sure why the third one didn't show up
In any case, when usually when something leaks, it happens a lot of times, and when I used it on a real project, I just ended up being pointed out to the leaking function very easily.
As mentioned on the output itself, this incurs a significant execution slowdown.
Further documentation at:
See also: How To Use TCMalloc?
Tested in Ubuntu 19.04, google-perftools 2.5-2.
Address Sanitizer (ASan) also by Google
https://github.com/google/sanitizers
Previously mentioned at: How to find memory leak in a C++ code/project? TODO vs tcmalloc.
This is already integrated into GCC, so you can just do:
gcc -fsanitize=address -ggdb3 -o main.out main.c
./main.out
and execution outputs:
=================================================================
==27223==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 4096 byte(s) in 1 object(s) allocated from:
#0 0x7fabbefc5448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
#1 0x55bf86c5f17c in my_malloc /home/ciro/test/main.c:4
#2 0x55bf86c5f199 in leaky /home/ciro/test/main.c:8
#3 0x55bf86c5f210 in main /home/ciro/test/main.c:20
#4 0x7fabbecf4b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
Direct leak of 256 byte(s) in 1 object(s) allocated from:
#0 0x7fabbefc5448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
#1 0x55bf86c5f17c in my_malloc /home/ciro/test/main.c:4
#2 0x55bf86c5f199 in leaky /home/ciro/test/main.c:8
#3 0x55bf86c5f1f2 in main /home/ciro/test/main.c:18
#4 0x7fabbecf4b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
Direct leak of 16 byte(s) in 1 object(s) allocated from:
#0 0x7fabbefc5448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
#1 0x55bf86c5f17c in my_malloc /home/ciro/test/main.c:4
#2 0x55bf86c5f199 in leaky /home/ciro/test/main.c:8
#3 0x55bf86c5f1d4 in main /home/ciro/test/main.c:16
#4 0x7fabbecf4b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
SUMMARY: AddressSanitizer: 4368 byte(s) leaked in 3 allocation(s).
which clearly identifies all leaks. Nice!
ASan can also do other cool checks such as out-of-bounds writes: Stack smashing detected
Tested in Ubuntu 19.04, GCC 8.3.0.
Valgrind
Previously mentioned at: https://stackoverflow.com/a/37661630/895245
Usage:
sudo apt-get install valgrind
gcc -ggdb3 -o main.out main.c
valgrind --leak-check=yes ./main.out
Output:
==32178== Memcheck, a memory error detector
==32178== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==32178== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==32178== Command: ./main.out
==32178==
==32178==
==32178== HEAP SUMMARY:
==32178== in use at exit: 4,368 bytes in 3 blocks
==32178== total heap usage: 6 allocs, 3 frees, 8,736 bytes allocated
==32178==
==32178== 16 bytes in 1 blocks are definitely lost in loss record 1 of 3
==32178== at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==32178== by 0x10915C: my_malloc (main.c:4)
==32178== by 0x109179: leaky (main.c:8)
==32178== by 0x1091B4: main (main.c:16)
==32178==
==32178== 256 bytes in 1 blocks are definitely lost in loss record 2 of 3
==32178== at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==32178== by 0x10915C: my_malloc (main.c:4)
==32178== by 0x109179: leaky (main.c:8)
==32178== by 0x1091D2: main (main.c:18)
==32178==
==32178== 4,096 bytes in 1 blocks are definitely lost in loss record 3 of 3
==32178== at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==32178== by 0x10915C: my_malloc (main.c:4)
==32178== by 0x109179: leaky (main.c:8)
==32178== by 0x1091F0: main (main.c:20)
==32178==
==32178== LEAK SUMMARY:
==32178== definitely lost: 4,368 bytes in 3 blocks
==32178== indirectly lost: 0 bytes in 0 blocks
==32178== possibly lost: 0 bytes in 0 blocks
==32178== still reachable: 0 bytes in 0 blocks
==32178== suppressed: 0 bytes in 0 blocks
==32178==
==32178== For counts of detected and suppressed errors, rerun with: -v
==32178== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)
So once again, all leaks were detected.
See also: How do I use valgrind to find memory leaks?
Tested in Ubuntu 19.04, valgrind 3.14.0.
Here is how I create a tag:
private static final String TAG = SomeActivity.class.getSimpleName();
Log.d(TAG, "some description");
You could use getCannonicalName
Here I have following TAG filters:
Here what I type in terminal:
$ adb logcat *View:V *Activity:V Xyz*:E System.out:S
Here is what I ended up doing and it worked great.
First I moved the file input outside of the form so that it is not submitted:
<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
<input id="name" value="#{name}" />
... a few more inputs ...
</form>
Then I changed the uploadPhotos
function to handle only the resizing:
window.uploadPhotos = function(url){
// Read in file
var file = event.target.files[0];
// Ensure it's an image
if(file.type.match(/image.*/)) {
console.log('An image has been loaded');
// Load the image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
// Resize the image
var canvas = document.createElement('canvas'),
max_size = 544,// TODO : pull max size from a site config
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
var resizedImage = dataURLToBlob(dataUrl);
$.event.trigger({
type: "imageResized",
blob: resizedImage,
url: dataUrl
});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}
};
As you can see I'm using canvas.toDataURL('image/jpeg');
to change the resized image into a dataUrl adn then I call the function dataURLToBlob(dataUrl);
to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:
/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = parts[1];
return new Blob([raw], {type: contentType});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB */
Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.
/* Handle image resized events */
$(document).on("imageResized", function (event) {
var data = new FormData($("form[id*='uploadImageForm']")[0]);
if (event.blob && event.url) {
data.append('image_data', event.blob);
$.ajax({
url: event.url,
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
//handle errors...
}
});
}
});
You are correct that **
is the power function.
^
is bitwise XOR.
%
is indeed the modulus operation, but note that for positive numbers, x % m = x
whenever m > x
. This follows from the definition of modulus. (Additionally, Python specifies x % m
to have the sign of m
.)
//
is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the /
in most programming languages. However, Python 3 changed the behavior of /
to perform floating-point division even if the arguments are integers. The //
operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:
| context | `/` behavior | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison |
---------------------------------------------------------------------------
| integer arguments, python 2 | int division | int division |
---------------------------------------------------------------------------
| integer arguments, python 3 | float division | int division |
For more details, see this question: Division in Python 2.7. and 3.3
Try this instead, remove the SelectCommand property and SelectParameters:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>">
Then in the code behind do this:
SqlDataSource1.SelectParameters.Add("userId", userId.ToString());
SqlDataSource1.SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"
While this worked for me, the following code also works:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>"
SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"></asp:SqlDataSource>
SqlDataSource1.SelectParameters.Add("userid", DbType.Guid, userId.ToString());
Sorry to bump an old question but the answer is to count the character length of the cell and not its value.
CellCount = Cells(Row, 10).Value
If Len(CellCount) <= "13" Then
'do something
End If
hope that helps. Cheers
$(document).ready(function() {
$('select#select_2').change(function() {
var selectedText = $(this).find('option:selected').text();
alert(selectedText);
});
});
Some nice guy handled the issue by using the Class 1 StartSSL certificate and shared Apache config that adds certificate support (will work with any certificate) and code for changing links in existing *.plist files automatically. Too long to copy, so here is the link: http://cases.azoft.com/how-to-fix-certificate-is-not-valid-error-on-ios-7/
I don't think this is your problem, but it still looks pretty bad to me. You have a duplicate layer of com.examples.quote in your project. Your Activity section in your AndroidManifest.xml should look more like this:
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You may even have your classes under src/com.example.quotes/com.example.quotes instead of just in com.example.quotes.
I'm not sure if this is causing your problem. But it looks a bit messed up. All your other stuff looks pretty standard to me.
select sum(qty), name
from (
select count(m.owner_id) as qty, o.name
from transport t,owner o,motorbike m
where t.type='motobike' and o.owner_id=m.owner_id
and t.type_id=m.motorbike_id
group by m.owner_id
union all
select count(c.owner_id) as qty, o.name,
from transport t,owner o,car c
where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
group by c.owner_id
) t
group by name
The following format should work:
$.ajax({
type: "POST",
url: "@Url.Action("refresh", "group")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
myDate: '2011-04-02 17:15:45'
}),
success: function (result) {
//do something
},
error: function (req, status, error) {
//error
}
});
.ico
, or is it just named ".ico"?The absolutely easiest way to have a favicon is to place an icon called "favicon.ico" in the root folder. That just works everywhere, no code needed at all.
If you must have it in a subdirectory, use:
<link rel="shortcut icon" href="/img/favicon.ico" />
Note the /
before img
to ensure it is anchored to the root folder.
private void button1_Click( object sender, EventArgs e )
{
string s = @"p1=6&p2=7&p3=8";
NameValueCollection nvc = new NameValueCollection();
foreach ( string vp in Regex.Split( s, "&" ) )
{
string[] singlePair = Regex.Split( vp, "=" );
if ( singlePair.Length == 2 )
{
nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );
}
}
}
The problem with writing scripts at the head of a page is blocking. The browser must stop processing the page until the script is download, parsed and executed. The reason for this is pretty clear, these scripts might insert more into the page changing the result of the rendering, they also may remove things that dont need to be rendered, etc.
Some of the more modern browsers violate this rule by not blocking on the downloading the scripts (ie8 was the first) but overall the download isn't the majority of the time spent blocking.
Check out Even Faster Websites, I just finished reading it and it goes over all of the fast ways to get scripts onto a page, Including putting scripts at the bottom of the page to allow rendering to complete (better UX).
You can use the following regular expression which will match integers (e.g., 123
), floating-point numbers (12.3
), and numbers with exponents (1.2e3
):
^-?\d*\.?\d+([eE]-?\d+)?$
If you want to accept +
signs as well as -
signs (as Oracle does with TO_NUMBER()
), you can change each occurrence of -
above to [+-]
. So you might rewrite your block of code above as follows:
IF (option_id = 0021) THEN
IF NOT REGEXP_LIKE(value, '^[+-]?\d*\.?\d+([eE][+-]?\d+)?$') OR TO_NUMBER(value) < 10000 OR TO_NUMBER(value) > 7200000 THEN
ip_msg(6214,option_name);
RETURN;
END IF;
END IF;
I am not altogether certain that would handle all values so you may want to add an EXCEPTION
block or write a custom to_number()
function as @JustinCave suggests.
I'm using Oh-my-zsh
in my macbook so I've tried many things to get the crontab task runs but finally, my solution was prepending the .zshrc
before the command to run.
*/30 * * * * . $HOME/.zshrc; node /path/for/my_script.js
This task runs every 30 minutes and uses .zshrc
profile to execute my node command.
Don't forget to use the dot before the $HOME
var.
This worked for me endDate: "today"
$('#datepicker').datepicker({
format: "dd/mm/yyyy",
autoclose: true,
orientation: "top",
endDate: "today"
});
You can do it with HttpWebRequest
:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Username = "myusername",
Password = "pass"
});
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
First Div
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
Second Div
</div>
</div>
This does the trick.
Try:
select a.* ,b.* from
(select * from (select ROW_NUMBER() OVER(ORDER BY fc_amount desc) SrNo1, fc_amount as amount1 From entry group by fc_amount) tbl where tbl.SrNo1 = 2) a
,
(select * from (select ROW_NUMBER() OVER(ORDER BY fc_amount asc) SrNo2, fc_amount as amount2 From entry group by fc_amount) tbl where tbl.SrNo2 =2) b
Swift 4 and Constraints
To your tableview add a bottom constraint relative to the bottom safe area. In my case the constraint is called tableViewBottomLayoutConstraint.
@IBOutlet weak var tableViewBottomLayoutConstraint: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(notification:)), name: .UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow , object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide , object: nil)
}
@objc
func keyboardWillAppear(notification: NSNotification?) {
guard let keyboardFrame = notification?.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardHeight: CGFloat
if #available(iOS 11.0, *) {
keyboardHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
} else {
keyboardHeight = keyboardFrame.cgRectValue.height
}
tableViewBottomLayoutConstraint.constant = keyboardHeight
}
@objc
func keyboardWillDisappear(notification: NSNotification?) {
tableViewBottomLayoutConstraint.constant = 0.0
}