If you want your scripts to load after page has been rendered, you can use:
function getScript(a, b) {
var c = document.createElement("script");
c.src = a;
var d = document.getElementsByTagName("head")[0],
done = false;
c.onload = c.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
b();
c.onload = c.onreadystatechange = null;
d.removeChild(c)
}
};
d.appendChild(c)
}
//call the function
getScript("http://www.google-analytics.com/ga.js", function() {
// do stuff after the script has loaded
});
You can use:
newinv=inventory+[add]
but using append is better since it doesn't create a new list:
inventory.append(add)
git reset HEAD^
then the modified files should show up.
You could move the modified files into a new branch
use,
git checkout -b newbranch
git checkout commit -m "files modified"
git push origin newbranch
git checkout master
then you should be on a clean branch, and your changes should be stored in newbranch. You could later just merge this change into the master branch
It appears newid() can't be used in where clause, so this solution requires an inner query:
SELECT *
FROM (
SELECT *, ABS(CHECKSUM(NEWID())) AS Rnd
FROM MyTable
) vw
WHERE Rnd % 100 < 10 --10%
use your code within
<script type="text/javascript">
function window.onload()
{
var d = new Date()
var gmtOffSet = -d.getTimezoneOffset();
var gmtHours = Math.floor(gmtOffSet / 60);
var GMTMin = Math.abs(gmtOffSet % 60);
var dot = ".";
var retVal = "" + gmtHours + dot + GMTMin;
document.getElementById('<%= offSet.ClientID%>').value = retVal;
}
</script>
just came across while browsing, might help you javascript-getting-and-setting-caret-position-in-textarea
. You can use it for textbox also.
Use Convert.ToDouble(value)
rather than (double)value
. It takes an object
and supports all of the types you asked for! :)
Also, your method is always returning a string
in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value)
)
Short Answer:
Optional.isPresent()
valueOptional.isPresent() == false
In real code, you might want to consider the second approach when the required resource is expensive to get.
// Always get heavy resource
getResource(resourceId).orElse(getHeavyResource());
// Get heavy resource when required.
getResource(resourceId).orElseGet(() -> getHeavyResource())
For more details, consider the following example with this function:
public Optional<String> findMyPhone(int phoneId)
The difference is as below:
X : buyNewExpensivePhone() called
+——————————————————————————————————————————————————————————————————+——————————————+
| Optional.isPresent() | true | false |
+——————————————————————————————————————————————————————————————————+——————————————+
| findMyPhone(int phoneId).orElse(buyNewExpensivePhone()) | X | X |
+——————————————————————————————————————————————————————————————————+——————————————+
| findMyPhone(int phoneId).orElseGet(() -> buyNewExpensivePhone()) | | X |
+——————————————————————————————————————————————————————————————————+——————————————+
When optional.isPresent() == false
, there is no difference between two ways. However, when optional.isPresent() == true
, orElse()
always calls the subsequent function whether you want it or not.
Finally, the test case used is as below:
Result:
------------- Scenario 1 - orElse() --------------------
1.1. Optional.isPresent() == true (Redundant call)
Going to a very far store to buy a new expensive phone
Used phone: MyCheapPhone
1.2. Optional.isPresent() == false
Going to a very far store to buy a new expensive phone
Used phone: NewExpensivePhone
------------- Scenario 2 - orElseGet() --------------------
2.1. Optional.isPresent() == true
Used phone: MyCheapPhone
2.2. Optional.isPresent() == false
Going to a very far store to buy a new expensive phone
Used phone: NewExpensivePhone
Code:
public class TestOptional {
public Optional<String> findMyPhone(int phoneId) {
return phoneId == 10
? Optional.of("MyCheapPhone")
: Optional.empty();
}
public String buyNewExpensivePhone() {
System.out.println("\tGoing to a very far store to buy a new expensive phone");
return "NewExpensivePhone";
}
public static void main(String[] args) {
TestOptional test = new TestOptional();
String phone;
System.out.println("------------- Scenario 1 - orElse() --------------------");
System.out.println(" 1.1. Optional.isPresent() == true (Redundant call)");
phone = test.findMyPhone(10).orElse(test.buyNewExpensivePhone());
System.out.println("\tUsed phone: " + phone + "\n");
System.out.println(" 1.2. Optional.isPresent() == false");
phone = test.findMyPhone(-1).orElse(test.buyNewExpensivePhone());
System.out.println("\tUsed phone: " + phone + "\n");
System.out.println("------------- Scenario 2 - orElseGet() --------------------");
System.out.println(" 2.1. Optional.isPresent() == true");
// Can be written as test::buyNewExpensivePhone
phone = test.findMyPhone(10).orElseGet(() -> test.buyNewExpensivePhone());
System.out.println("\tUsed phone: " + phone + "\n");
System.out.println(" 2.2. Optional.isPresent() == false");
phone = test.findMyPhone(-1).orElseGet(() -> test.buyNewExpensivePhone());
System.out.println("\tUsed phone: " + phone + "\n");
}
}
FYI for those using the UI Navicat:
You MUST set your preferences to utilize a file as to where
to store the history.
If this is blank your Navicat will be blank.
PS: I have no affiliation with or in association to Navicat or it's affiliates. Just looking to help.
In your html
<table class="table1">
<tr>
<td>
...
</table>
<table class="table2">
<tr>
<td>
...
</table>
In your css:
table.table1 {...}
table.table1 tr {...}
table.table1 td {...}
table.table2 {...}
table.table2 tr {...}
table.table2 td {...}
If you just want the content as string
, then the simple solution is to use the ReadFile
function from the io/ioutil
package. This function returns a slice of bytes
which you can easily convert to a string
.
package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("file.txt") // just pass the file name
if err != nil {
fmt.Print(err)
}
fmt.Println(b) // print the content as 'bytes'
str := string(b) // convert content to a 'string'
fmt.Println(str) // print the content as a 'string'
}
You can achieve with following way
this.projectService.create(project)
.subscribe(
result => {
console.log(result);
},
error => {
console.log(error);
this.errors = error
}
);
}
if (!this.errors) {
//route to new page
}
Why not using exit codes? If a git repository exists in the current directory, then git branch
and git tag
commands return exit code of 0; otherwise, a non-zero exit code will be returned. This way, you can determine if a git repository exist or not. Simply, you can run:
git tag > /dev/null 2>&1 && [ $? -eq 0 ]
Advantage: Flexibe. It works for both bare and non-bare repositories, and in sh, zsh and bash.
git tag
: Getting tags of the repository to determine if exists or not.> /dev/null 2>&1
: Preventing from printing anything, including normal and error outputs.[ $? -eq 0 ]
: Check if the previous command returned with exit code 0 or not. As you may know, every non-zero exit means something bad happened. $?
gets the exit code of the previous command, and [
, -eq
and ]
perform the comparison.As an example, you can create a file named check-git-repo
with the following contents, make it executable and run it:
#!/bin/sh
if git tag > /dev/null 2>&1 && [ $? -eq 0 ]; then
echo "Repository exists!";
else
echo "No repository here.";
fi
Javascript executor always does the job perfectly:
((JavascriptExecutor) driver).executeScript("scroll(0,300)");
where (0,300)
are the horizontal and vertical distances respectively. Put your distances as per your requirements.
If you a perfectionist and like to get the exact distance you like to scroll up to on the first attempt, use this tool, MeasureIt. It's a brilliant firefox add-on.
You need to add a name
attribute.
Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3
.
In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]
) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.
Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs
For PHP you can use:
<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">
all of the solution here are great but not necessarily can be implemented for old mysql servers (at least at my case). so you can use sub-queries (i think it is less complicated).
select sum(t1.cnt) from
(SELECT column, COUNT(column) as cnt
FROM
table
GROUP BY
column
HAVING
COUNT(column) > 1) as t1 ;
You can use the response.text
to write to a file:
import requests
files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()
I have this simple solution I have been using and its works.
In App/Exceptions/Handler.php
Add this at top:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Then inside the render method
public function render($request, Exception $exception)
{
.......
if ($exception instanceof NotFoundHttpException){
$segment = $request->segments();
//eg. http://site.dev/member/profile
//module => member
// view => member.index
//where member.index is the root of your angular app could be anything :)
if(head($segment) != 'api' && $module = $segment[0]){
return response(view("$module.index"), 404);
}
return response()->fail('not_found', $exception->getCode());
}
.......
return parent::render($request, $exception);
}
In XML Serializing, you can use the [XmlIgnore] attribute (System.Xml.Serialization.XmlIgnoreAttribute) to ignore a property when serializing a class.
This may be of use to you (Or it just may be of use to anyone who found this question when attempting to find out how to ignore a property when Serializing in XML, as I was).
This will work for most of the website names :
SELECT ID, REVERSE(PARSENAME(REVERSE(WebsiteName), 2)) FROM dbo.YourTable .....
Add hamcrest-all-X.X.jar
to your classpath.
Latest version as of Feb 2015 is 1.3: http://code.google.com/p/hamcrest/downloads/detail?name=hamcrest-all-1.3.jar&can=2&q=
NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];
Using cmd (BAT) file:
@echo off
color 1F
echo.
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "PrepareEnvironment.ps1"
:EOF
echo Waiting seconds
timeout /t 10 /nobreak > NUL
If you need run as administrator:
By following the steps below, you will have 2 Build Systems in sublime - "JavaC" and "JavaC_Input".
"JavaC" would let you run code that doesn't require user input and display the results in sublime's terminal simulator, which is convenient and nice-looking. "JavaC_Input" lets you run code that requires user input in a separate terminal window, it's able to accept user input. You can also run non-input-requiring code in this build system, so if you don't mind the pop-up, you can just stick with this build system and don't switch. You switch between build systems from Tools -> Build System. And you compile&run code using ctrl+b.
Here are the steps to achieve this:
(note: Make sure you already have the basic setup of the java system: install JDK and set up correct CLASSPATH and PATH, I won't elaborate on this)
"JavaC" build system setup
1, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec.bat".
@ECHO OFF
cd %~dp1
javac %~nx1
java %~n1
2, Then edit C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\JavaC.sublime-build (if there isn't any, create one), the contents will be
{
"cmd": ["javacexec.bat", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java"
}
"JavaC_Input" build system setup
1, Install Cygwin [http://www.cygwin.com/]
2, Go to C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\, then create a file called "JavaC_Input.sublime-build" with the following content
{
"cmd": ["javacexec_input.bat", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java"
}
3, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec_input.bat".
@echo off
javac -Xlint:unchecked %~n1.java
start cmd /k java -ea %~n1
require
for installed gemsrequire_relative
for local filesrequire
uses your $LOAD_PATH
to find the files.
require_relative
uses the current location of the file using the statement
Require relies on you having installed (e.g. gem install [package]
) a package somewhere on your system for that functionality.
When using require
you can use the "./
" format for a file in the current directory, e.g. require "./my_file"
but that is not a common or recommended practice and you should use require_relative
instead.
This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use
require_relative '../../../filename'
(up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).
Note that require_relative
uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative
path "stable" as it always be relative to the file requiring it in the same way.
You should call the events after the document is ready, like this:
$(document).ready(function () {
// Your code
});
This is because you are trying to manipulate elements before they are rendered by the browser.
So, in the case you posted it should look something like this
$(document).ready(function () {
var editorTitle = $('#editorTitle').val();
var editorText = $('#editorText').html();
});
Hope it helps.
Tips: always save your jQuery object in a variable for later use and only code that really need to run after the document have loaded should go inside the ready() function.
When you have Eclipse for Android developement installed:
What I did, I initialized values in the constructor of the entity
Note: DefaultValue attributes won't set the values of your properties automatically, you have to do it yourself
Use the style word-break:break-all;
. I know it works on tables.
You could try this solution :
In your location
block when you use proxy_pass
do something like this:
location ... {
add_header yourHeaderName yourValue;
proxy_pass xxxx://xxx_my_proxy_addr_xxx;
# Now use this solution:
proxy_ignore_headers yourHeaderName // but set by proxy
# Or if above didn't work maybe this:
proxy_hide_header yourHeaderName // but set by proxy
}
I'm not sure would it be exactly what you need but try some manipulation of this method and maybe result will fit your problem.
Also you can use this combination:
proxy_hide_header headerSetByProxy;
set $sent_http_header_set_by_proxy yourValue;
The other difference between divide and conquer and dynamic programming could be:
Divide and conquer:
Dynamic programming:
Removing print statements can also fix the problem.
Apart from loading images, this error also happens when your code is printing continuously at a high rate, which is causing the error "IOPub data rate exceeded". E.g. if you have a print statement in a for loop somewhere that is being called over 1000 times.
You can try ES6 Modules in Google Chrome Beta (61) / Chrome Canary.
Reference Implementation of ToDo MVC by Paul Irish - https://paulirish.github.io/es-modules-todomvc/
I've basic demo -
//app.js
import {sum} from './calc.js'
console.log(sum(2,3));
//calc.js
let sum = (a,b) => { return a + b; }
export {sum};
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h1>ES6</h1>
<script src="app.js" type="module"></script>
</body>
</html>
Hope it helps!
Alternative and fast solution : I faced the same error. I reopened the "wierd" csv file in GNUMERIC on my lubuntu machine and exported the file as csv file. This corrected the issue.
I'm not quite happy with this implementation yet, I wanted to have a custom constructor that does DirectoryIndex._make(next(os.walk(input_path)))
such that you can just pass the path you want a file listing for. Edits welcome!
import collections
import os
DirectoryIndex = collections.namedtuple('DirectoryIndex', ['root', 'dirs', 'files'])
for file_name in DirectoryIndex(*next(os.walk('.'))).files:
file_path = os.path.join(path, file_name)
Create an extension method?
Console.WriteLine(value.ToGBString());
// ...
public static class DoubleExtensions
{
public static string ToGBString(this double value)
{
return value.ToString(CultureInfo.GetCultureInfo("en-GB"));
}
}
Add an item and set its "Selected" property to true, you will probably want to set "appenddatabounditems" property to true also so your initial value isn't deleted when databound.
If you are talking about setting an initial value that is in your databound items then hook into your ondatabound event and set which index you want to selected=true you will want to wrap it in "if not page.isPostBack then ...." though
Protected Sub DepartmentDropDownList_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles DepartmentDropDownList.DataBound
If Not Page.IsPostBack Then
DepartmentDropDownList.SelectedValue = "somevalue"
End If
End Sub
^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$
live demo: https://regex101.com/r/HUNasA/2
I have tested various expressions to match my requirements.
As a user I can hit browser search bar with following strings:
valid urls
invalid urls
A way to write a common subset of HTML and XHTML
In the hope of greater portability.
In HTML, <script>
is magic escapes everything until </script>
appears.
So you can write:
<script>x = '<br/>';
and <br/>
won't be considered a tag.
This is why strings such as:
x = '</scripts>'
must be escaped like:
x = '</scri' + 'pts>'
See: Why split the <script> tag when writing it with document.write()?
But XML (and thus XHTML, which is a "subset" of XML, unlike HTML), doesn't have that magic: <br/>
would be seen as a tag.
<![CDATA[
is the XHTML way to say:
don't parse any tags until the next
]]>
, consider it all a string
The //
is added to make the CDATA work well in HTML as well.
In HTML <![CDATA[
is not magic, so it would be run by JavaScript. So //
is used to comment it out.
The XHTML also sees the //
, but will observe it as an empty comment line which is not a problem:
//
That said:
<!DOCTYPE html>
vs <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
script
syntaxBut that violates the golden rule of the Internet:
don't trust third parties, or your product will break
These days (Oct 2020) you can use just the following
git clone $CI_REPOSITORY_URL
Which will expand to something like:
git clone https://gitlab-ci-token:[MASKED]@gitlab.com/gitlab-examples/ci-debug-trace.git
Where the "token" password is ephemeral token, it should be revoked after a build is complete.
You can use java.util.Scanner
(API):
import java.util.Scanner;
//...
Scanner in = new Scanner(System.in);
int num = in.nextInt();
It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).
For simple usage, I perfer ab(apache benchmark) and siege, later one is needed as ab don't support cookie and would create endless sessions from dynamic site.
both are simple to start:
ab -c n -t 30 url
siege -b -c n -t 30s url
siege can run with more urls.
last siege version turn verbose on in siegerc, which is annoy. you can only disable it by edit that file(/usr/local/etc/siegerc
).
It might be too late to answer this in 2019. but I tried all the answers and none worked for me. So I solved it simply this way:
@Html.EditorFor(m => m.SellDateForInstallment, "{0:dd/MM/yyyy}",
new {htmlAttributes = new { @class = "form-control", @type = "date" } })
EditorFor
is what worked for me.
Note that SellDateForInstallment
is a Nullable
datetime object.
public DateTime? SellDateForInstallment { get; set; } // Model property
The Mobile Device Browser File is a great way to detect mobile (and other) broswers for ASP.NET projects: http://mdbf.codeplex.com/
I'd recommend to use an array for storing all values via __set()
.
class foo {
protected $values = array();
public function __get( $key )
{
return $this->values[ $key ];
}
public function __set( $key, $value )
{
$this->values[ $key ] = $value;
}
}
This way you make sure, that you can't access the variables in another way (note that $values
is protected), to avoid collisions.
Alternatively to using MARS (MultipleActiveResultSets) you can write your code so you dont open multiple result sets.
What you can do is to retrieve the data to memory, that way you will not have the reader open. It is often caused by iterating through a resultset while trying to open another result set.
Sample Code:
public class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
public class Blog
{
public int BlogID { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
public class Post
{
public int PostID { get; set; }
public virtual Blog Blog { get; set; }
public string Text { get; set; }
}
Lets say you are doing a lookup in your database containing these:
var context = new MyContext();
//here we have one resultset
var largeBlogs = context.Blogs.Where(b => b.Posts.Count > 5);
foreach (var blog in largeBlogs) //we use the result set here
{
//here we try to get another result set while we are still reading the above set.
var postsWithImportantText = blog.Posts.Where(p=>p.Text.Contains("Important Text"));
}
We can do a simple solution to this by adding .ToList() like this:
var largeBlogs = context.Blogs.Where(b => b.Posts.Count > 5).ToList();
This forces entityframework to load the list into memory, thus when we iterate though it in the foreach loop it is no longer using the data reader to open the list, it is instead in memory.
I realize that this might not be desired if you want to lazyload some properties for example. This is mostly an example that hopefully explains how/why you might get this problem, so you can make decisions accordingly
this solution it gonna be ok on Redhat 8.0
sudo yum install libxml2-devel
The dict.items
iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items()
will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items)
. And now, just as an example:
>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
... print key, value
...
world 2999
hello 34
The AttributeError
is an exception thrown when an object does not have the attribute you tried to access. The class dict
does not have any predictors
attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.
you can use "Automatically generate script on every save", if you are using management studio. This is not certainly logging. Check if useful for you.. ;)
its even easier:
fileList.Where(item => filterList.Contains(item))
in case you want to filter not for an exact match but for a "contains" you can use this expression:
var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));
(Three years late...) but I believe the answer to your second question is that SSRS essentially treats data from your datasets as unsorted; I'm not sure if it ignores any ORDER BY in the sql, or if it just assumes the data is unsorted.
To sort your groups in a particular order, you need to specify it in the report:
For the report I just created, the default sort order on the category was alphabetic on the category group which was basically a string code. But sometimes it can be useful to sort by some other characteristic of the data; for example, my report is of Average and Maximum processing times for messages identified by some code (the category). By setting the sort order of the group to be on [MaxElapsedMs], Z->A it draws my attention to the worst-performing message-types.
This sort of presentation won't be useful for every report but it can be an excellent tool to guide readers to have a better understanding of the data; though on other occasions you might prefer a report to have the same ordering every time it runs, in which case sorting on the category label itself may be best... and I guess there are circumstances where changing the sort order could harm understanding, such as if the categories implied some sort of ordering (such as date values?)
In my case, using Mockito 2.0, I had to change all the any()
parameters to nullable()
in order to stub the real call.
All good answers above. One extra thing you should keep in mind - you can also have a pure virtual destructor. The only difference is that you still need to implement it.
Confused?
--- header file ----
class foo {
public:
foo() {;}
virtual ~foo() = 0;
virtual bool overrideMe() {return false;}
};
---- source ----
foo::~foo()
{
}
The main reason you'd want to do this is if you want to provide interface methods, as I have, but make overriding them optional.
To make the class an interface class requires a pure virtual method, but all of your virtual methods have default implementations, so the only method left to make pure virtual is the destructor.
Reimplementing a destructor in the derived class is no big deal at all - I always reimplement a destructor, virtual or not, in my derived classes.
If someone is using react, following will be useful:
https://stackoverflow.com/a/62111884/1015678
const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));
You just need to:
Step 1: Go home directory of C:\ with typing cd.. (2 times)
Step 2: It appears now C:\>
Step 3: Type dir Windows\System32\run
That's all, it shows complete files & folder details inside target folder.
Details: I used Windows\System32\com
folder as example, you should type your own folder name etc. Windows\System32\run
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fName.Length; i++)
{
if (char.IsLetterOrDigit(fName[i]))
{
sb.Append(fName[i]);
}
}
I know the OP tagged the question with javascript
but in my case I was looking exactly the same thing but from a Java backend (with Camel).
An interesting thing that can also be useful if you are using an integration framework like Camel, jsonPath
is also supported by a specific Camel Component since Camel 2.13.
Example from the Camel doc above:
from("queue:books.new")
.choice()
.when().jsonpath("$.store.book[?(@.price < 10)]")
.to("jms:queue:book.cheap")
.when().jsonpath("$.store.book[?(@.price < 30)]")
.to("jms:queue:book.average")
.otherwise()
.to("jms:queue:book.expensive")
which is quite straightforward to use.
I just edited my iPhone's 'hosts' file successfully (on Jailbroken iOS 4.0).
simophone.local
]root
alpine
/etc/hosts
fileThe phone does cache some webpages and DNS queries, so a reboot or clearing the cache may help. Hope that helps someone.
Simon.
I recommend using DateTime objects instead of strings, because you cannot easily compare strings, which is required for sorting. You also get additional advantages for working with dates.
Once you have the DateTime objects, sorting is quite easy:
usort($array, function($a, $b) {
return ($a['date'] < $b['date']) ? -1 : 1;
});
If you are looking for an alternative way, try adding your credentials using AmazonCLI
from the terminal type:-
aws configure
then fill in your keys and region.
This is just torazaburo's answer, updated to use a MouseEvent object.
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
el.dispatchEvent(ev);
}
A couple of notes:
Apache ant doesn't know anything about JAVA_OPTS, while Tomcat's startup scripts do. For Apache ant, use ANT_OPTS to affect the environment for the JVM that runs /ant/, but not for the things that ant might launch.
The maximum heap size you can set depends entirely on the environment: for most 32-bit systems, the maximum amount of heap space you can request, regardless of available memory, is in the 2GiB range. The largest heap on a 64-bit system is "really big". Also, you are practically limited by physical memory as well, since the heap is managed by the JVM and you don't want a lot of swapping going on to the disk.
For server environments, you typically want to set -Xms and -Xmx to the same value: this will fix the size of the heap at a certain size and the garbage collector has less work to do because the heap will never have to be re-sized.
Bind the button, this is done with jQuery:
$("#my-table input[type='button']").click(function(){
var parameter = $(this).val();
window.location = "http://yoursite.com/page?variable=" + parameter;
});
$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];
Php also can use properties with dashes:
garex@ustimenko ~/src/ekapusta/deploy $ psysh
Psy Shell v0.4.4 (PHP 5.5.3-1ubuntu2.6 — cli) by Justin Hileman
>>> $q = new stdClass;
=> <stdClass #000000005f2b81c80000000076756fef> {}
>>> $q->{'qwert-y'} = 123
=> 123
>>> var_dump($q);
class stdClass#174 (1) {
public $qwert-y =>
int(123)
}
=> null
I recommended an experimental new attribute CSS I tested on latest browser and it's good:
image-rendering: optimizeSpeed; /* */
image-rendering: -moz-crisp-edges; /* Firefox */
image-rendering: -o-crisp-edges; /* Opera */
image-rendering: -webkit-optimize-contrast; /* Chrome (and Safari) */
image-rendering: optimize-contrast; /* CSS3 Proposed */
-ms-interpolation-mode: nearest-neighbor; /* IE8+ */
With this the browser will know the algorithm for rendering
With that firmly in mind, let's do this! Once your apps hit a certain point, denormalizing data is very common. Done correctly, it can save numerous expensive database lookups at the cost of a little more housekeeping.
To return a list
of friend names we'll need to create a custom Django Field class that will return a list when accessed.
David Cramer posted a guide to creating a SeperatedValueField on his blog. Here is the code:
from django.db import models
class SeparatedValuesField(models.TextField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
self.token = kwargs.pop('token', ',')
super(SeparatedValuesField, self).__init__(*args, **kwargs)
def to_python(self, value):
if not value: return
if isinstance(value, list):
return value
return value.split(self.token)
def get_db_prep_value(self, value):
if not value: return
assert(isinstance(value, list) or isinstance(value, tuple))
return self.token.join([unicode(s) for s in value])
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
The logic of this code deals with serializing and deserializing values from the database to Python and vice versa. Now you can easily import and use our custom field in the model class:
from django.db import models
from custom.fields import SeparatedValuesField
class Person(models.Model):
name = models.CharField(max_length=64)
friends = SeparatedValuesField()
When you use a function ...
<p onclick="update_url('/en/step2');">Link</p>
<script>
function update_url(url) {
history.pushState(null, null, url);
}
</script>
DELETE FROM table_name
WHERE id BETWEEN 79 AND 296;
create an empty modal box on the current page and below is the ajax call you can see how to fetch the content in result from another html page.
$.ajax({url: "registration.html", success: function(result){
//alert("success"+result);
$("#contentBody").html(result);
$("#myModal").modal('show');
}});
once the call is done you will get the content of the page by the result to then you can insert the code in you modal's content id using.
You can call controller and get the page content and you can show that in your modal.
below is the example of Bootstrap 3 modal in that we are loading content from registration.html page...
index.html
------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function loadme(){
//alert("loadig");
$.ajax({url: "registration.html", success: function(result){
//alert("success"+result);
$("#contentBody").html(result);
$("#myModal").modal('show');
}});
}
</script>
</head>
<body>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" onclick="loadme()">Load me</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body" id="contentBody">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
registration.html
--------------------
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {
border: 3px solid #f1f1f1;
font-family: Arial;
}
.container {
padding: 20px;
background-color: #f1f1f1;
width: 560px;
}
input[type=text], input[type=submit] {
width: 100%;
padding: 12px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
input[type=checkbox] {
margin-top: 16px;
}
input[type=submit] {
background-color: #4CAF50;
color: white;
border: none;
}
input[type=submit]:hover {
opacity: 0.8;
}
</style>
<body>
<h2>CSS Newsletter</h2>
<form action="/action_page.php">
<div class="container">
<h2>Subscribe to our Newsletter</h2>
<p>Lorem ipsum text about why you should subscribe to our newsletter blabla. Lorem ipsum text about why you should subscribe to our newsletter blabla.</p>
</div>
<div class="container" style="background-color:white">
<input type="text" placeholder="Name" name="name" required>
<input type="text" placeholder="Email address" name="mail" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
</label>
</div>
<div class="container">
<input type="submit" value="Subscribe">
</div>
</form>
</body>
</html>
There are some good answers here already. But it's worthwhile to drive home the difference in parallelism offered:
success()
returns the original promisethen()
returns a new promiseThe difference is then()
drives sequential operations, since each call returns a new promise.
$http.get(/*...*/).
then(function seqFunc1(response){/*...*/}).
then(function seqFunc2(response){/*...*/})
$http.get()
seqFunc1()
seqFunc2()
success()
drives parallel operations, since handlers are chained on the same promise.
$http(/*...*/).
success(function parFunc1(data){/*...*/}).
success(function parFunc2(data){/*...*/})
$http.get()
parFunc1()
, parFunc2()
in parallelMy issue was related to using multiple accounts. This is how I was able to switch accounts.
Open Team Explorer
From the big drop down menu near the top of the pane...
Navigate to: Projects and my Teams>Manage Connections
Navigate to: Manage Connections>Connect to Team Project
Use the "Switch User" link to switch accounts.
Now the workspace names will match the chosen account.
This is due to the series df[cat]
containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna
operation.
In other words
pandas data type 'Object' indicates mixed types rather than str type
so using the following line:
df[cat] = le.fit_transform(df[cat].astype(str))
should help
Global exclusions look like they're being worked on, but until then...
From the Sonatype maven reference (bottom of the page):
Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.
As an example:
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</dependencyManagement>
It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.
$1, $2, etc will contain the value of captures from the last successful match - it's important to check whether the match succeeded before accessing them, i.e.
if ( $var =~ m/( )/ ) { # use $1 etc... }
An example of the problem - $1 contains 'Quick' in both print statements below:
#!/usr/bin/perl
'Quick brown fox' =~ m{ ( quick ) }ix;
print "Found: $1\n";
'Lazy dog' =~ m{ ( quick ) }ix;
print "Found: $1\n";
Edit: it's 2020, I would use flex box instead.
Original answer:
Html
<body>
<div class="centered">
</div>
</body>
CSS
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
U can also play around the tintcolor and button image to indirectly change the color.
This is an extension to BigJim's brilliant answer.
In my case I had a NodeBase
class with a Children
dictionary, and I needed a way to generically do O(1) lookups from the children. I was attempting to return a private dictionary field in the getter of Children
, so obviously I wanted to avoid expensive copying/iterating. Therefore I used Bigjim's code to cast the Dictionary<whatever specific type>
to a generic Dictionary<NodeBase>
:
// Abstract parent class
public abstract class NodeBase
{
public abstract IDictionary<string, NodeBase> Children { get; }
...
}
// Implementing child class
public class RealNode : NodeBase
{
private Dictionary<string, RealNode> containedNodes;
public override IDictionary<string, NodeBase> Children
{
// Using a modification of Bigjim's code to cast the Dictionary:
return new IDictionary<string, NodeBase>().CastDictionary<string, RealNode, NodeBase>();
}
...
}
This worked well. However, I eventually ran into unrelated limitations and ended up creating an abstract FindChild()
method in the base class that would do the lookups instead. As it turned out this eliminated the need for the casted dictionary in the first place. (I was able to replace it with a simple IEnumerable
for my purposes.)
So the question you might ask (especially if performance is an issue prohibiting you from using .Cast<>
or .ConvertAll<>
) is:
"Do I really need to cast the entire collection, or can I use an abstract method to hold the special knowledge needed to perform the task and thereby avoid directly accessing the collection?"
Sometimes the simplest solution is the best.
Is there maybe a way to grab the rendered page from the internet explorer rendering engine and send it to a PDF-Printer tool automatically?
This is how ActivePDF works, which is good means that you know what you'll get, and it actually has reasonable styling support.
It is also one of the few packages I found (when looking a few years back) that actually supports the various page-break CSS commands.
Unfortunately, the ActivePDF software is very frustrating - since it has to launch the IE browser in the background for conversions it can be quite slow, and it is not particularly stable either.
There is a new version currently in Beta which is supposed to be much better, but I've not actually had a chance to try it out, so don't know how much of an improvement it is.
If you are using security annotation from the SensioFrameworkExtraBundle
, you can use a few expressions (that are defined in \Symfony\Component\Security\Core\Authorization\ExpressionLanguageProvider
):
@Security("is_authenticated()")
: to check that the user is authed and not anonymous@Security("is_anonymous()")
: to check if the current user is the anonymous user@Security("is_fully_authenticated()")
: equivalent to is_granted('IS_AUTHENTICATED_FULLY')
@Security("is_remember_me()")
: equivalent to is_granted('IS_AUTHENTICATED_REMEMBERED')
You can simply set the status code of the response to 200 like the following
public ActionResult SomeMethod(parameters...)
{
//others code here
...
Response.StatusCode = 200;
return YourObject;
}
echo file_get_contents('http://localhost/web/a.php'); //Best Example
this
is the DOM element on which the event was hooked. this.id
is its ID. No need to wrap it in a jQuery instance to get it, the id
property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event
object's target
property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
(jQuery ensures that the change
event bubbles, even on IE where it doesn't natively.)
One one line (semi-colons necessary):
for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done
Formatted for legibility (no semi-colons needed):
for i in 0 1 2 3 4 5 6 7 8 9
do
for j in 0 1 2 3 4 5 6 7 8 9
do
echo "$i$j"
done
done
There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do
(saving two lines here).
When Bootstrap Select initializes, it'll build a set of custom divs that run alongside the original <select>
element and will typically synchronize state between the two input mechanisms.
Which is to say that one way to handle events on bootstrap select is to listen for events on the original select that it modifies, regardless of who updated it.
Just listen for a change
event and get the selected value using javascript or jQuery like this:
$('select').on('change', function(e){
console.log(this.value,
this.options[this.selectedIndex].value,
$(this).find("option:selected").val(),);
});
*NOTE: As with any script reliant on the DOM, make sure you wait for the DOM ready event before executing
$(function() {_x000D_
_x000D_
$('select').on('change', function(e){_x000D_
console.log(this.value,_x000D_
this.options[this.selectedIndex].value,_x000D_
$(this).find("option:selected").val(),);_x000D_
});_x000D_
_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
<option val="Must"> Mustard </option>_x000D_
<option val="Cat" > Ketchup </option>_x000D_
<option val="Rel" > Relish </option>_x000D_
</select>
_x000D_
As this answer alludes, Bootstrap Select has their own set of custom events, including changed.bs.select
which:
fires after the select's value has been changed. It passes through event, clickedIndex, newValue, oldValue.
And you can use that like this:
$("select").on("changed.bs.select",
function(e, clickedIndex, newValue, oldValue) {
console.log(this.value, clickedIndex, newValue, oldValue)
});
$(function() {_x000D_
_x000D_
$("select").on("changed.bs.select", _x000D_
function(e, clickedIndex, newValue, oldValue) {_x000D_
console.log(this.value, clickedIndex, newValue, oldValue)_x000D_
});_x000D_
_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
<option val="Must"> Mustard </option>_x000D_
<option val="Cat" > Ketchup </option>_x000D_
<option val="Rel" > Relish </option>_x000D_
</select>
_x000D_
Make a HttpURLConnection to some site like www.whatismyip.com and parse that :-)
Ok i was previously not aware that AngularJS
usually refers to Angular
v1 version and only Angular to Angular v2+
This answer only applies for Angular
Leaving this here for future reference..
Not sure how it works for you guys but on Angular 9 i have to wrap ngStyle in brackets like this:
[ng-style]="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"
Otherwise it doesn't work
I found the answer!! Taking a screenshot interrupts any touches that are on the screen. This is why snapchat requires holding to see the picture. Reference: http://tumblr.jeremyjohnstone.com/post/38503925370/how-to-detect-screenshots-on-ios-like-snapchat
Using the width function:
$('div#somediv').width('70%');
will turn:
<div id="somediv" />
into:
<div id="somediv" style="width: 70%;"/>
$(document).ready(function() {
var CookieSet = $.cookie('cookietitle', 'yourvalue');
if (CookieSet == null) {
// Do Nothing
}
if (jQuery.cookie('cookietitle')) {
// Reactions
}
});
Runtime basically means when program interacts with the hardware and operating system of a machine. C does not have it's own runtime but instead, it requests runtime from an operating system (which is basically a part of ram) to execute itself.
Add this to your main CSS:
table td {
border-top: none !important;
}
Use this for newer versions of bootstrap:
.table th, .table td {
border-top: none !important;
}
script.aculo.us has a slider control that might be worth checking out.
Or, if you know the width of the two "side" images and don't want to deal with floats:
<div class="container">
<div class="left-panel"><img src="myleftimage" /></div>
<div class="center-panel">Content goes here...</div>
<div class="right-panel"><img src="myrightimage" /></div>
</div>
CSS:
.container {
position:relative;
padding-left:50px;
padding-right:50px;
}
.container .left-panel {
width: 50px;
position:absolute;
left:0px;
top:0px;
}
.container .right-panel {
width: 50px;
position:absolute;
right:0px;
top:0px;
}
.container .center-panel {
background: url('mymiddleimage');
}
Notes:
Position:relative on the parent div is used to make absolutely positioned children position themselves relative to that node.
Not to reinvent the wheel, here is my favourite one-liner solution:
/**_x000D_
* Convert milliseconds to time string (hh:mm:ss:mss)._x000D_
*_x000D_
* @param Number ms_x000D_
*_x000D_
* @return String_x000D_
*/_x000D_
function time(ms) {_x000D_
return new Date(ms).toISOString().slice(11, -1);_x000D_
}_x000D_
_x000D_
console.log( time(12345 * 1000) ); // "03:25:45.000"
_x000D_
Method Date.prototype.toISOString()
returns a string in simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ
. This method is supported in all modern browsers (IE9+) and JavaScript engines.
UPDATE: The solution above is always limited to range of one day, which is fine if you use it to format milliseconds up to 24 hours (i.e. ms < 86400000
). To make it working with any input value, I have extended it into a nice universal prototype method:
/**_x000D_
* Convert (milli)seconds to time string (hh:mm:ss[:mss])._x000D_
*_x000D_
* @param Boolean isSec_x000D_
*_x000D_
* @return String_x000D_
*/_x000D_
Number.prototype.toTime = function(isSec) {_x000D_
var ms = isSec ? this * 1e3 : this,_x000D_
lm = ~(4 * !!isSec), /* limit fraction */_x000D_
fmt = new Date(ms).toISOString().slice(11, lm);_x000D_
_x000D_
if (ms >= 8.64e7) { /* >= 24 hours */_x000D_
var parts = fmt.split(/:(?=\d{2}:)/);_x000D_
parts[0] -= -24 * (ms / 8.64e7 | 0);_x000D_
return parts.join(':');_x000D_
}_x000D_
_x000D_
return fmt;_x000D_
};_x000D_
_x000D_
console.log( (12345 * 1000).toTime() ); // "03:25:45.000"_x000D_
console.log( (123456 * 789).toTime() ); // "27:03:26.784"_x000D_
console.log( 12345. .toTime(true) ); // "03:25:45"_x000D_
console.log( 123456789. .toTime(true) ); // "34293:33:09"
_x000D_
To append to this famous question (though a bit too late): You can also do df.groupby('column_name').get_group('column_desired_value').reset_index()
to make a new data frame with specified column having a particular value. E.g.
import pandas as pd
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split()})
print("Original dataframe:")
print(df)
b_is_two_dataframe = pd.DataFrame(df.groupby('B').get_group('two').reset_index()).drop('index', axis = 1)
#NOTE: the final drop is to remove the extra index column returned by groupby object
print('Sub dataframe where B is two:')
print(b_is_two_dataframe)
Run this gives:
Original dataframe:
A B
0 foo one
1 bar one
2 foo two
3 bar three
4 foo two
5 bar two
6 foo one
7 foo three
Sub dataframe where B is two:
A B
0 foo two
1 foo two
2 bar two
You could use String.prototype.indexOf
to accomplish that. Try something like this:
$('.type').keyup(function() {_x000D_
var v = $(this).val();_x000D_
if (v.indexOf('> <') !== -1) {_x000D_
console.log('contains > <');_x000D_
}_x000D_
console.log(v);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="type"></textarea>
_x000D_
Update
Modern browsers also have a String.prototype.includes
method.
This is the issue related to hosts file setup. Add the following line to your hots file In Ububtu: /etc/hosts
127.0.0.1 localhost
In windows: c:\windows\System32\drivers\etc\hosts
127.0.0.1 localhost
There are two ways to do this.
1. providing the SHA of the commit you want to see to git log
git log -p a2c25061
Where -p
is short for patch
2. use git show
git show a2c25061
The output for both commands will be:
Use "attr" method in jquery.
$('.test').click(function(){
var id = $(this).attr('id');
});
Your question is a little unclear, but if what you're doing is trying to get your friend's latest changes, then typically what your friend needs to do is to push those changes up to a remote repo (like one hosted on GitHub), and then you fetch or pull those changes from the remote:
Your friend pushes his changes to GitHub:
git push origin <branch>
Clone the remote repository if you haven't already:
git clone https://[email protected]/abc/theproject.git
Fetch or pull your friend's changes (unnecessary if you just cloned in step #2 above):
git fetch origin
git merge origin/<branch>
Note that git pull
is the same as doing the two steps above:
git pull origin <branch>
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeHere is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.
I think your answer is fine (and it's OK to accept it if you like). This is just "extra".
import numpy as np
a = np.arange(4,10).reshape(2,3)
wh = np.where(a>7)
gt = a>7
x = np.where(gt)
print "wh: ", wh
print "gt: ", gt
print "x: ", x
gives:
wh: (array([1, 1]), array([1, 2]))
gt: [[False False False]
[False True True]]
x: (array([1, 1]), array([1, 2]))
... but:
print "a[wh]: ", a[wh]
print "a[gt] ", a[gt]
print "a[x]: ", a[x]
gives:
a[wh]: [8 9]
a[gt] [8 9]
a[x]: [8 9]
DECLARE @dd VARCHAR(200) = 'Net Operating Loss - 2007';
SELECT SUBSTRING(@dd, 1, CHARINDEX('-', @dd) -1) F1,
SUBSTRING(@dd, CHARINDEX('-', @dd) +1, LEN(@dd)) F2
The easiest way is to use to_datetime
:
df['col'] = pd.to_datetime(df['col'])
It also offers a dayfirst
argument for European times (but beware this isn't strict).
Here it is in action:
In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0 2005-05-23 00:00:00
dtype: datetime64[ns]
You can pass a specific format:
In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0 2005-05-23
dtype: datetime64[ns]
As I just figured, in case you have a model fitted on multiple linear regression, the above mentioned solution won't work.
You have to create your line manually as a dataframe that contains predicted values for your original dataframe (in your case data
).
It would look like this:
# read dataset
df = mtcars
# create multiple linear model
lm_fit <- lm(mpg ~ cyl + hp, data=df)
summary(lm_fit)
# save predictions of the model in the new data frame
# together with variable you want to plot against
predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)
# this is the predicted line of multiple linear regression
ggplot(data = df, aes(x = mpg, y = hp)) +
geom_point(color='blue') +
geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))
# this is predicted line comparing only chosen variables
ggplot(data = df, aes(x = mpg, y = hp)) +
geom_point(color='blue') +
geom_smooth(method = "lm", se = FALSE)
The order of elements in an array ([]
) is maintained. The order of elements (name:value pairs) in an "object" ({}
) is not, and it's usual for them to be "jumbled", if not by the JSON formatter/parser itself then by the language-specific objects (Dictionary, NSDictionary, Hashtable, etc) that are used as an internal representation.
In very simple way. use this code.
// define function
function nextYearDate(date1) {
var date2 = new Date(date1);
var date3 = date2.setDate(date2.getDate() - 1);
var date = new Date(date3);
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear()+1;
var newdate = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
$("#next_date").val(newdate);
}
// call function.
<input type="date" name="current_date" id="current_date" value="" onblur="nextYearDate(this.value);" />
<input type="date" name="next_date" id="next_date" value="" onblur="nextYearDate(this.value);" />
I had the same issue and couldn't get my Nexus 6P to show up as an available device until I changed the connection type from "Charging" to "Photo Transfer(PTP)" and installed the Google USB driver while in PTP mode. Installing the driver prior to that while in Charging mode yielded no results.
"N/A" is not a string it is an error, try this:
=if(ISNA(A1),C1)
you have to place this fomula in cell B1 so it will get the value of your formula
Although it is a late answer, I would say this will help you...
$query = $this->db
->select('user_id, count(user_id) AS num_of_time')
->group_by('user_id')
->order_by('num_of_time', 'desc')
->get('tablename', 10);
print_r($query->result());
I have a decent example in jQuery AJAX and ASMX on using the jQuery AJAX call with asmx web services...
There is a line of code to uncommment in order to have it return JSON.
Remember a string is immutable so you will need to create a new string.
Strings are IEnumerable so you should be able to run a for loop over it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string alpha = "abcdefghijklmnopqrstuvwxyz";
var builder = new StringBuilder();
int count = 0;
foreach (var c in alpha)
{
builder.Append(c);
if ((++count % 5) == 0)
{
builder.Append('-');
}
}
Console.WriteLine("Before: {0}", alpha);
alpha = builder.ToString();
Console.WriteLine("After: {0}", alpha);
}
}
}
Produces this:
Before: abcdefghijklmnopqrstuvwxyz
After: abcde-fghij-klmno-pqrst-uvwxy-z
Just try $('.handle').css('left', '300px');
You can also create shapes directly inside the item
tag, in case you want to add some more details to your view, like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid android:color="#81ba73" />
<corners android:radius="6dp" />
</shape>
<ripple android:color="#c62828"/>
</item>
<item android:state_enabled="false">
<shape>
<solid android:color="#788e73" />
<corners android:radius="6dp" />
</shape>
</item>
<item>
<shape>
<solid android:color="#add8a3" />
<corners android:radius="6dp" />
</shape>
</item>
</selector>
Beware that Android will cycle through the items from top to bottom, therefore, you must place the item
without condition on the bottom of the list (so it acts like a default/fallback).
If you actually want to add a .pdf, I found it necessary to set the position of the memory stream to Zero.
var memStream = new MemoryStream(yourPdfByteArray);
memStream.Position = 0;
var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
var reportAttachment = new Attachment(memStream, contentType);
reportAttachment.ContentDisposition.FileName = "yourFileName.pdf";
mailMessage.Attachments.Add(reportAttachment);
You can add a new source directory with build-helper:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/generated</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
mDatabase.child("token").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot:dataSnapshot.getChildren())
{
String key= snapshot.getKey();
String value=snapshot.getValue().toString();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ListUser.this,databaseError.toString(),Toast.LENGTH_SHORT).show();
}
});
Only work If child have no SubChild
In my case convertor must return string value. I don't why, but it works.
*.xaml (common style file, which is included in another xaml files)
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
</Style>
*.cs
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Color color = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
return "#" + color.Name;
}
Here's how I'd do it:
def distance(a,b):
return sqrt((a.x - b.x)**2 + (a.y - b.y)**2)
def is_between(a,c,b):
return distance(a,c) + distance(c,b) == distance(a,b)
You can define a class constant in php. But your class constant would be accessible from any object instance as well. This is php's functionality.
However, as of php7.1, you can define your class constants with access modifiers (public
, private
or protected
).
A work around would be to define your constant as private
or protected
and then make them readable via a static function
. This function should only return the constant values if called from the static context.
You can also create this static function in your parent class and simply inherit this parent class on all other classes to make it a default functionality.
Credits: http://dwellupper.io/post/48/defining-class-constants-in-php
The easiest way would be to use a library like this one and specifically you want noStrings
to be true
export class CustomValidator{ // Number only validation
static numeric(control: AbstractControl) {
let val = control.value;
const hasError = validate({val: val}, {val: {numericality: {noStrings: true}}});
if (hasError) return null;
return val;
}
}
The problem was that I used MvcRoute.MappUrl
from MvcContrib
to route the context.Routes
.
It seems that MvcContrib
routing mapper was uncomfortable with area routing.
If your PowerShell login script is running after 5 minutes (as mine was) on a 2012 server, there is a GPO setting on a server - 'Configure Login script Delay' the default setting 'not configured' this will leave a 5-minute delay before running the login script.
A build, as Makefile understands it, consists of a lot of targets. For example, to build a project you might need
If you implemented this workflow with makefile, you could make each of the targets separately. For example, if you wrote
make file1.o
it would only build that file, if necessary.
The name of all
is not fixed. It's just a conventional name; all
target denotes that if you invoke it, make will build all what's needed to make a complete build. This is usually a dummy target, which doesn't create any files, but merely depends on the other files. For the example above, building all necessary is building executables, the other files being pulled in as dependencies. So in the makefile it looks like this:
all: executable1 executable2
all
target is usually the first in the makefile, since if you just write make
in command line, without specifying the target, it will build the first target. And you expect it to be all
.
all
is usually also a .PHONY
target. Learn more here.
Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.
Try this.
betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())
Found it at http://www.linuxquestions.org/questions/suse-novell-60/howto-kill-defunct-processes-574612/
2) Here a great tip from another user (Thxs Bill Dandreta): Sometimes
kill -9 <pid>
will not kill a process. Run
ps -xal
the 4th field is the parent process, kill all of a zombie's parents and the zombie dies!
Example
4 0 18581 31706 17 0 2664 1236 wait S ? 0:00 sh -c /usr/bin/gcc -fomit-frame-pointer -O -mfpmat
4 0 18582 18581 17 0 2064 828 wait S ? 0:00 /usr/i686-pc-linux-gnu/gcc-bin/3.3.6/gcc -fomit-fr
4 0 18583 18582 21 0 6684 3100 - R ? 0:00 /usr/lib/gcc-lib/i686-pc-linux-gnu/3.3.6/cc1 -quie
18581
, 18582
, 18583
are zombies -
kill -9 18581 18582 18583
has no effect.
kill -9 31706
removes the zombies.
For Display any subview to main view,Please use following code
UIViewController *yourCurrentViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (yourCurrentViewController.presentedViewController)
{
yourCurrentViewController = yourCurrentViewController.presentedViewController;
}
[yourCurrentViewController presentViewController:composeViewController animated:YES completion:nil];
For Dismiss any subview from main view,Please use following code
UIViewController *yourCurrentViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (yourCurrentViewController.presentedViewController)
{
yourCurrentViewController = yourCurrentViewController.presentedViewController;
}
[yourCurrentViewController dismissViewControllerAnimated:YES completion:nil];
Reinitialising gcloud with proper account and project worked for me.
gcloud init
After this retrying the below command was successful and kubeconfig entry was generated.
gcloud container clusters get-credentials "cluster_name"
check the cluster info with
kubectl cluster-info
Sine you are new to html here are three ready to use examples on how to use CSS together with html. You can simply put them into a file, save it and open it up with the browser of your choice:
This one directly embeds your CSS style into your tags/elements. Generally this is not a very nice approach, because you should always separate the content/html from design.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hi, I'm bold!</title>
</head>
<body>
<p style="font-weight:bold;">Hi, I'm very bold!</p>
</body>
</html>
The next one is a more general approach and works on all "p" (stands for paragraph) tags in your document and additionaly makes them HUGE. Btw. Google uses this approach on his search:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hi, I'm bold!</title>
<style type="text/css">
p {
font-weight:bold;
font-size:26px;
}
</style>
</head>
<body>
<p>Hi, I'm very bold and HUGE!</p>
</body>
</html>
You probably will take a couple of days playing around with the first examples, however here is the last one. In this you finally fully seperate design (css) and content (html) from each other in two different files. stackoverflow takes this approach.
In one file you put all the CSS (call it 'hello_world.css'):
p {
font-weight:bold;
font-size:26px;
}
In another file you should put the html (call it 'hello_world.html'):
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hi, I'm bold!</title>
<link rel="stylesheet" type="text/css" href="hello_world.css" />
</head>
<body>
<p>Hi, I'm very bold and HUGE!</p>
</body>
</html>
Hope this helps a little. To address specific elements in your document and not all tags you should make yourself familiar with the class
, id
and name
attributes. Have fun!
That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)
String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");
or the equivalent:
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)
Or, with Guava:
private static final CharMatcher ALNUM =
CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);
But if you want to turn accented characters into something sensible that's still ascii, look at these questions:
I ran a quick test on SQL Server 2012 on an 8 GB RAM hyper-v box. You can see the results for yourself. I was not running any other windowed application apart from SQL Server Management Studio while running these tests.
My table schema:
CREATE TABLE [dbo].[employee](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_employee] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Total number of records in Employee
table: 178090131 (~ 178 million rows)
First Query:
Set Statistics Time On
Go
Select Count(*) From Employee
Go
Set Statistics Time Off
Go
Result of First Query:
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 35 ms.
(1 row(s) affected)
SQL Server Execution Times:
CPU time = 10766 ms, elapsed time = 70265 ms.
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
Second Query:
Set Statistics Time On
Go
Select Count(1) From Employee
Go
Set Statistics Time Off
Go
Result of Second Query:
SQL Server parse and compile time:
CPU time = 14 ms, elapsed time = 14 ms.
(1 row(s) affected)
SQL Server Execution Times:
CPU time = 11031 ms, elapsed time = 70182 ms.
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
You can notice there is a difference of 83 (= 70265 - 70182) milliseconds which can easily be attributed to exact system condition at the time queries are run. Also I did a single run, so this difference will become more accurate if I do several runs and do some averaging. If for such a huge data-set the difference is coming less than 100 milliseconds, then we can easily conclude that the two queries do not have any performance difference exhibited by the SQL Server Engine.
Note : RAM hits close to 100% usage in both the runs. I restarted SQL Server service before starting both the runs.
Change position:absolute;
to position:fixed;
What I was doing was starting a new activity and then closing the current activity. So, remember this simple rule:
finish()
startActivity<...>()
and not
startActivity<...>()
finish()
When dealing with day-of-week calculations, it's important to take account of the current DATEFIRST
settings. This query will always correctly exclude weekend days, using @@DATEFIRST
to account for any possible setting for the first day of the week.
SELECT *
FROM your_table
WHERE ((DATEPART(dw, date_created) + @@DATEFIRST) % 7) NOT IN (0, 1)
function getRangeDateString($timestamp) {
if ($timestamp) {
$currentTime=strtotime('today');
// Reset time to 00:00:00
$timestamp=strtotime(date('Y-m-d 00:00:00',$timestamp));
$days=round(($timestamp-$currentTime)/86400);
switch($days) {
case '0';
return 'Today';
break;
case '-1';
return 'Yesterday';
break;
case '-2';
return 'Day before yesterday';
break;
case '1';
return 'Tomorrow';
break;
case '2';
return 'Day after tomorrow';
break;
default:
if ($days > 0) {
return 'In '.$days.' days';
} else {
return ($days*-1).' days ago';
}
break;
}
}
}
The difference is in the subsystem that each executable targets.
java.exe
targets the CONSOLE
subsystem.javaw.exe
targets the WINDOWS
subsystem.if result is None:
print "error parsing stream"
elif result:
print "result pass"
else:
print "result fail"
keep it simple and explicit. You can of course pre-define a dictionary.
messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]
If you plan on modifying your simulate
function to include more return codes, maintaining this code might become a bit of an issue.
The simulate
might also raise an exception on the parsing error, in which case you'd either would catch it here or let it propagate a level up and the printing bit would be reduced to a one-line if-else statement.
Here is the alternative command:
gnuplot -p -e 'plot for [file in system("find . -name \\*.txt -depth 1")] file using 1:2 title file with lines'
Must be used convert, not cast:
SELECT
CONVERT(varchar(50), N'æøåáälcçcédnoöruýtžš')
COLLATE Cyrillic_General_CI_AI
Option 2 is correct: The nested <ul>
is a child of the <li>
it belongs in.
If you validate, option 1 comes up as an error in html 5 -- credit: user3272456
<ul>
as child of <li>
The proper way to make HTML nested list is with the nested <ul>
as a child of the <li>
to which it belongs. The nested list should be inside of the <li>
element of the list in which it is nested.
<ul>
<li>Parent/Item
<ul>
<li>Child/Subitem
</li>
</ul>
</li>
</ul>
A list item can contain another entire list — this is known as "nesting" a list. It is useful for things like tables of contents, such as the one at the start of this article:
- Chapter One
- Section One
- Section Two
- Section Three
- Chapter Two
- Chapter Three
The key to nesting lists is to remember that the nested list should relate to one specific list item. To reflect that in the code, the nested list is contained inside that list item. The code for the list above looks something like this:
<ol>
<li>Chapter One
<ol>
<li>Section One</li>
<li>Section Two </li>
<li>Section Three </li>
</ol>
</li>
<li>Chapter Two</li>
<li>Chapter Three </li>
</ol>
Note how the nested list starts after the <li>
and the text of the containing list item (“Chapter One”); then ends before the </li>
of the containing list item. Nested lists often form the basis for website navigation menus, as they are a good way to define the hierarchical structure of the website.
Theoretically you can nest as many lists as you like, although in practice it can become confusing to nest lists too deeply. For very large lists, you may be better off splitting the content up into several lists with headings instead, or even splitting it up into separate pages.
It sounds like you are trying to do something like this:
If that is the case, as previously mentioned, the most efficient way is to let the web server(not Spring) handle HTML requests as static resources. So you'll want the following:
Here is one way to accomplish that...
web.xml - Map servlet to root (/)
<servlet>
<servlet-name>sprung</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
...
<servlet>
<servlet-mapping>
<servlet-name>sprung</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Spring JavaConfig
public class SpringSprungConfig extends DelegatingWebMvcConfiguration {
// Delegate resource requests to default servlet
@Bean
protected DefaultServletHttpRequestHandler defaultServletHttpRequestHandler() {
DefaultServletHttpRequestHandler dsrh = new DefaultServletHttpRequestHandler();
return dsrh;
}
//map static resources by extension
@Bean
public SimpleUrlHandlerMapping resourceServletMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
//make sure static resources are mapped first since we are using
//a slightly different approach
mapping.setOrder(0);
Properties urlProperties = new Properties();
urlProperties.put("/**/*.css", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.js", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.png", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.html", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.woff", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.ico", "defaultServletHttpRequestHandler");
mapping.setMappings(urlProperties);
return mapping;
}
@Override
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
//controller mappings must be evaluated after the static resource requests
handlerMapping.setOrder(1);
handlerMapping.setInterceptors(this.getInterceptors());
handlerMapping.setPathMatcher(this.getPathMatchConfigurer().getPathMatcher());
handlerMapping.setRemoveSemicolonContent(false);
handlerMapping.setUseSuffixPatternMatch(false);
//set other options here
return handlerMapping;
}
}
Additional Considerations
Look at here: http://blog-mstechnology.blogspot.de/2010/06/throw-vs-throw-ex.html
Throw:
try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw;
}
It preserve the Stack information with Exception
This is called as "Rethrow"
If want to throw new exception,
throw new ApplicationException("operation failed!");
Throw Ex:
try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw ex;
}
It Won't Send Stack information with Exception
This is called as "Breaking the Stack"
If want to throw new exception,
throw new ApplicationException("operation failed!",ex);
Make a div and give it a class. Then drop a img in it.
<div class="mydiv">
<img src="location/of/your/image" ></img>
</div>
Set the size of your div and make it relative.
.mydiv {
position: relative;
height:300px;
width: 100%;
overflow: hidden;
}
then style your image
img {
width: 100%;
height: auto;
overflow: hidden;
}
Hope that helps
In Visual Studio 2017, I went to Project Properties -> Configuration Properties -> General, Selected All Platforms (1), then chose the dropdown (2) under Windows SDK Version and updated from 10.0.14393.0 to one that was installed (3). For me, that was 10.0.15063.0.
Additional details: This corrected the error in my case because Windows SDK Version helps VS select the correct paths. VC++ Directories -> Library Directories -> Edit -> Macros -> shows that macro $(WindowsSDK_LibraryPath_x86) has a path with the version number selected above.
Example for replacing LI elements
function (element) {
let li = element.parentElement;
let ul = li.parentNode;
if (li.nextSibling.nodeName === 'LI') {
let li_replaced = ul.replaceChild(li, li.nextSibling);
ul.insertBefore(li_replaced, li);
}
}
SELECT Col.Column_Name from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
Col.Constraint_Name = Tab.Constraint_Name
AND Col.Table_Name = Tab.Table_Name
AND Constraint_Type = 'PRIMARY KEY'
AND Col.Table_Name = '<your table name>'
Try to use <>
instead of !=
.
$_GET['start_date']
is not numeric is my bet, but an date format not supported by strtotime
. You will need to re-format the date to a workable format for strtotime or use combination of explode/mktime.
I could add you an example if you'd be kind enough to post the format you currently receive.
Use CASE
:
SELECT
TABEL1.Id,
CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
THEN 'TRUE'
ELSE 'FALSE'
END AS NewFiled
FROM TABLE1
If TABLE2.ID
is Unique or a Primary Key, you could also use this:
SELECT
TABEL1.Id,
CASE WHEN TABLE2.ID IS NOT NULL
THEN 'TRUE'
ELSE 'FALSE'
END AS NewFiled
FROM TABLE1
LEFT JOIN Table2
ON TABLE2.ID = TABLE1.ID
Not a jQuery way but... Why don't use simpler way. Remove 'c' from following array
var a = ['a','b','c','d']
a.splice(a.indexOf('c'),1);
>["c"]
a
["a", "b", "d"]
You can also use: (Note to myself: Don’t modify objects you don’t own)
Array.prototype.remove = function(v) { this.splice(this.indexOf(v) == -1 ? this.length : this.indexOf(v), 1); }
var a = ['a','b','c'];
a.remove('c'); //value of "a" is now ['a','b']
Adding is simplera.push('c')
Just use Hour
and Minute
properties
var date = DateTime.Now;
date.Hour;
date.Minute;
Or you can easily zero the seconds using
var zeroSecondDate = date.AddSeconds(-date.Second);
Maybe encode them into a known set - something like base 64 is a popular choice.
I think that mergetool.meld.path
should point directly to the meld executable. Thus, the command you want is:
git config --global mergetool.meld.path c:/Progra~2/meld/bin/meld
Although M-x eval-buffer
will work you may run into problems with toggles and other similar things. A better approach might be to "mark" or highlight whats new in your .emacs (or even scratch buffer if your just messing around) and then M-x eval-region
. Hope this helps.
I think there is some default config what is missing in this version of mongoDb client. Try to run:
mongo 127.0.0.1:27017
It's strange, but then I've experienced the issue went away :) (so the simple command 'mongo' w/o any params started to work again for me)
[Ubuntu Linux 11.10 x64 / MongoDB 2.0.1]
Using header file stdio.h
you can easily do it as usual like c. before using %.2lf(set a specific number after % specifier.) using printf().
It simply printf specific digits after decimal point.
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
double total=100;
printf("%.2lf",total);//this prints 100.00 like as C
}
you can save yourself the .strip() fcn by just slicing off the first and last characters from the string representation of the list (see third line below)
>>> mylist=[1,2,3,4,5,'baloney','alfalfa']
>>> strlist=str(mylist)
['1', ' 2', ' 3', ' 4', ' 5', " 'baloney'", " 'alfalfa'"]
>>> mylistfromstring=(strlist[1:-1].split(', '))
>>> mylistfromstring[3]
'4'
>>> for entry in mylistfromstring:
... print(entry)
... type(entry)
...
1
<class 'str'>
2
<class 'str'>
3
<class 'str'>
4
<class 'str'>
5
<class 'str'>
'baloney'
<class 'str'>
'alfalfa'
<class 'str'>
You can use data-*
attribute to embed custom data. The data-*
attributes gives us the ability to embed custom data attributes on all HTML elements.
jQuery .data()
method allows you to get/set data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.
jQuery .attr()
method get/set attribute value for only the first element in the matched set.
Example:
<span id="test" title="foo" data-kind="primary">foo</span>
$("#test").attr("title");
$("#test").attr("data-kind");
$("#test").data("kind");
$("#test").data("value", "bar");
Multiply by 1000, round, and divide back by 1000.
For basic Java: http://download.oracle.com/javase/tutorial/getStarted/index.html and http://download.oracle.com/javase/tutorial/java/index.html
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
Use autocmd CursorMoved * exe printf('match IncSearch /\V\<%s\>/', escape(expand('<cword>'), '/\'))
Make sure you have IncSearch
set to something. e.g call s:Attr('IncSearch', 'reverse')
. Alternatively you can use another highlight group in its place.
This will highlight all occurrences of words under your cursor without a delay. I find that a delay slows me down when I'm wizzing through code. The highlight color will match the color of the word, so it stays consistent with your scheme.
Open notepad and paste this code:
@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/c cd /d %CD% && %*'"
@echo on
Then, save the file as sudo.cmd
. Copy this file and paste it at C:\Windows\System32
or add the path where sudo.cmd
is to your PATH Environment Variable.
When you open command prompt, you can now run something like sudo start .
.
If you want the admin command prompt window to stay open when you run the command, change the code in notepad to this:
@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/k cd /d %CD% && %*'"
@echo on
Explanation:
powershell -Command
runs a powershell command.
Start-Process
is a powershell command that starts a process, in this case, command prompt.
-Verb RunAs
runs the command as admin.
-Argument-List
runs the command with arguments.
Our arguments are '/c cd /d %CD% && %*'
. %*
means all arguments, so if you did sudo foo bar
, it would run in command prompt foo bar
because the parameters are foo and bar, and %*
returns foo bar
. cd /d %CD%
is a command to go to the current directory. This will ensure that when you open the elevated window, the directory will be the same as the normal window. the &&
means that if the first command is successful, run the second command.
The /c
is a cmd parameter for closing the window after the command is finished, and the /k
is a cmd parameter for keeping the window open.
Credit to Adam Plocher for the staying in the current directory code.
The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).
# now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')
The ONESHELL directive allows to write multiple line recipes to be executed in the same shell invocation.
all: foo
SOURCE_FILES = $(shell find . -name '*.c')
.ONESHELL:
foo: ${SOURCE_FILES}
FILES=()
for F in $^; do
FILES+=($${F})
done
gcc "$${FILES[@]}" -o $@
There is a drawback though : special prefix characters (‘@’, ‘-’, and ‘+’) are interpreted differently.
https://www.gnu.org/software/make/manual/html_node/One-Shell.html
"+" does not mutate the list
.append() mutates the old list
This works form me to scroll to when I click next
$('#myTable').on('draw.dt', function() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
});
curl -u username:password http://
curl -u username http://
From the documentation page:
-u, --user <user:password>
Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.
If you simply specify the user name, curl will prompt for a password.
The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.
When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.
When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.
To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.
If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.
http://curl.haxx.se/docs/manpage.html#-u
Note that you do not need --basic
flag as it is the default.
var array = [];
//length array now = 0
array[array.length] = 'hello';
//length array now = 1
// 0
//array = ['hello'];//length = 1
Probably you don't have the service in your manifest, or it does not have an <intent-filter>
that matches your action. Examining LogCat (via adb logcat
, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.
More likely, you should start the service via:
startService(new Intent(this, UpdaterServiceManager.class));
Once the file object is iterated, it is exausted.
>>> f = open('1.txt', 'w')
>>> f.write('1\n2\n3\n')
>>> f.close()
>>> f = open('1.txt', 'r')
>>> for line in f: print line
...
1
2
3
# exausted, another iteration does not produce anything.
>>> for line in f: print line
...
>>>
Use file.seek
(or close/open the file) to rewind the file:
>>> f.seek(0)
>>> for line in f: print line
...
1
2
3
You can use getElementsByClassName()
method for what you want.
var elems = document.getElementsByClassName("a b c");_x000D_
elems[0].style.color = "green";_x000D_
console.log(elems[0]);
_x000D_
<ul>_x000D_
<li class="a">a</li>_x000D_
<li class="a b">a, b</li>_x000D_
<li class="a b c">a, b, c</li>_x000D_
</ul>
_x000D_
This is the fastest solution also. you can see a benchmark about that here.
curl is an extension that needs to be installed, it's got nothing to do with the PHP version.
#include <stdio.h>
#include <string.h>
char isNumber(char *text)
{
int j;
j = strlen(text);
while(j--)
{
if(text[j] > 47 && text[j] < 58)
continue;
return 0;
}
return 1;
}
int main(){
char tmp[16];
scanf("%s", tmp);
if(isNumber(tmp))
return printf("is a number\n");
return printf("is not a number\n");
}
You can also check its stringfied value, which could also work with non Ascii
char isNumber(char *text)
{
int j;
j = strlen(text);
while(j--)
{
if(text[j] >= '0' && text[j] <= '9')
continue;
return 0;
}
return 1;
}
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
SELECT (SELECT COUNT(*) FROM table1) + (SELECT COUNT(*) FROM table2) FROM dual;
Running assembly Code on Mac is just 3 steps away from you. It could be done using XCODE but better is to use NASM Command Line Tool. For My Ease I have already installed Xcode, if you have Xcode installed its good.
But You can do it without XCode as well.
Just Follow:
brew install nasm
nasm -f macho64 myFile.asm
ld -macosx_version_min 10.7.0 -lSystem -o OutPutFile myFile.o && ./64
Simple Text File named myFile.asm is written below for your convenience.
global start
section .text
start:
mov rax, 0x2000004 ; write
mov rdi, 1 ; stdout
mov rsi, msg
mov rdx, msg.len
syscall
mov rax, 0x2000001 ; exit
mov rdi, 0
syscall
section .data
msg: db "Assalam O Alaikum Dear", 10
.len: equ $ - msg
I encountered the same issue (dialog would only open once, after closing, it wouldn't open again), and tried the solutions above which did not fix my problem. I went back to the docs and realized I had a fundamental misunderstanding of how the dialog works.
The $('#myDiv').dialog() command creates/instantiates the dialog, but is not necessarily the proper way to open it. The proper way to open it is to instantiate the dialog with dialog(), then use dialog('open') to display it, and dialog('close') to close/hide it. This means you'll probably want to set the autoOpen option to false.
So the process is: instantiate the dialog on document ready, then listen for the click or whatever action you want to show the dialog. Then it will work, time after time!
<script type="text/javascript">
jQuery(document).ready( function(){
jQuery("#myButton").click( showDialog );
//variable to reference window
$myWindow = jQuery('#myDiv');
//instantiate the dialog
$myWindow.dialog({ height: 350,
width: 400,
modal: true,
position: 'center',
autoOpen:false,
title:'Hello World',
overlay: { opacity: 0.5, background: 'black'}
});
}
);
//function to show dialog
var showDialog = function() {
//if the contents have been hidden with css, you need this
$myWindow.show();
//open the dialog
$myWindow.dialog("open");
}
//function to close dialog, probably called by a button in the dialog
var closeDialog = function() {
$myWindow.dialog("close");
}
</script>
</head>
<body>
<input id="myButton" name="myButton" value="Click Me" type="button" />
<div id="myDiv" style="display:none">
<p>I am a modal dialog</p>
</div>
setInterval(function() {
$('#board').append('.');
}, 1000);
You can use clearInterval if you wanted to stop it at one point.
Check to see if the key-value pair is actually showing up in the request:
In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers
Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like:
F12: Developer Tools > Sources Tab > YourJavascriptSrc.js
and check your code.
But as other answers have said:
xhttp.setRequestHeader(key, value);
should add a key-value pair to your request header, just make sure to place it after your open()
and before your send()
array_slice()
can be used to extract parts of the array, and the union array operator (+
) can recombine the parts.
$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array)-3, true);
This example:
$array = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array) - 1, true) ;
print_r($res);
gives:
Array ( [zero] => 0 [one] => 1 [two] => 2 [my_key] => my_value [three] => 3 )
I think the best approach is just add ".passive"
v-on:scroll.passive='handleScroll'
Use this
unescape(str);
I'm not a great JS programmer, tried all, and this worked awesome!
Generally speaking a schema in oracle is the same as an user. Oracle Database automatically creates a schema when you create a user. A file with the DDL file extension is an SQL Data Definition Language file.
Creating new user (using SQL Plus)
Basic SQL Plus commands:
- connect: connects to a database
- disconnect: logs off but does not exit
- exit: exists
Open SQL Plus and log:
/ as sysdba
The sysdba is a role and is like "root" on unix or "Administrator" on Windows. It sees all, can do all. Internally, if you connect as sysdba, your schema name will appear to be SYS.
Create an user:
SQL> create user johny identified by 1234;
View all users and check if the user johny is there:
SQL> select username from dba_users;
If you try to login as johny now you would get an error:
ERROR:
ORA-01045: user JOHNY lacks CREATE SESSION privilege; logon denied
The user to login needs at least create session priviledge so we have to grant this privileges to the user:
SQL> grant create session to johny;
Now you are able to connect as the user johny:
username: johny
password: 1234
To get rid of the user you can drop it:
SQL> drop user johny;
That was basic example to show how to create an user. It might be more complex. Above we created an user whose objects are stored in the database default tablespace. To have database tidy we should place users objects to his own space (tablespace is an allocation of space in the database that can contain schema objects).
Show already created tablespaces:
SQL> select tablespace_name from dba_tablespaces;
Create tablespace:
SQL> create tablespace johny_tabspace
2 datafile 'johny_tabspace.dat'
3 size 10M autoextend on;
Create temporary tablespace (Temporaty tablespace is an allocation of space in the database that can contain transient data that persists only for the duration of a session. This transient data cannot be recovered after process or instance failure.):
SQL> create temporary tablespace johny_tabspace_temp
2 tempfile 'johny_tabspace_temp.dat'
3 size 5M autoextend on;
Create the user:
SQL> create user johny
2 identified by 1234
3 default tablespace johny_tabspace
4 temporary tablespace johny_tabspace_temp;
Grant some privileges:
SQL> grant create session to johny;
SQL> grant create table to johny;
SQL> grant unlimited tablespace to johny;
Login as johny and check what privileges he has:
SQL> select * from session_privs;
PRIVILEGE
----------------------------------------
CREATE SESSION
UNLIMITED TABLESPACE
CREATE TABLE
With create table privilege the user can create tables:
SQL> create table johny_table
2 (
3 id int not null,
4 text varchar2(1000),
5 primary key (id)
6 );
Insert data:
SQL> insert into johny_table (id, text)
2 values (1, 'This is some text.');
Select:
SQL> select * from johny_table;
ID TEXT
--------------------------
1 This is some text.
To get DDL data you can use DBMS_METADATA package that "provides a way for you to retrieve metadata from the database dictionary as XML or creation DDL and to submit the XML to re-create the object.". (with help from http://www.dba-oracle.com/oracle_tips_dbms_metadata.htm)
For table:
SQL> set pagesize 0
SQL> set long 90000
SQL> set feedback off
SQL> set echo off
SQL> SELECT DBMS_METADATA.GET_DDL('TABLE',u.table_name) FROM USER_TABLES u;
Result:
CREATE TABLE "JOHNY"."JOHNY_TABLE"
( "ID" NUMBER(*,0) NOT NULL ENABLE,
"TEXT" VARCHAR2(1000),
PRIMARY KEY ("ID")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE" ENABLE
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE"
For index:
SQL> set pagesize 0
SQL> set long 90000
SQL> set feedback off
SQL> set echo off
SQL> SELECT DBMS_METADATA.GET_DDL('INDEX',u.index_name) FROM USER_INDEXES u;
Result:
CREATE UNIQUE INDEX "JOHNY"."SYS_C0013353" ON "JOHNY"."JOHNY_TABLE" ("ID")
PCTFREE 10 INITRANS 2 MAXTRANS 255
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE"
More information:
DDL
DBMS_METADATA
Schema objects
Differences between schema and user
Privileges
Creating user/schema
Creating tablespace
SQL Plus commands
Jquery easing plugin renamed their effect function names from version 1.2 on. If you have some javascript depending on easing and it is not calling the right effect name it will throw this error.
Just as a addition. You can find the Catalina Paths in
->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS
In the VM Arguments the Paths are listed and changeable
Brief Description
Use NSCalendar method:
(NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts
"Returns, as an NSDateComponents object using specified components, the difference between two supplied dates". From the API documentation.
Create 2 NSDate whose difference is the NSTimeInterval you want to convert. (If your NSTimeInterval comes from comparing 2 NSDate you don't need to do this step, and you don't even need the NSTimeInterval).
Get your quotes from NSDateComponents
Sample Code
// The time interval
NSTimeInterval theTimeInterval = 326.4;
// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];
// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:date1 toDate:date2 options:0];
NSLog(@"Conversion: %dmin %dhours %ddays %dmoths",[conversionInfo minute], [conversionInfo hour], [conversionInfo day], [conversionInfo month]);
[date1 release];
[date2 release];
Known issues
While working on an enterprise project in STS (heavily Eclipse based) I was crashing constantly and STS plateaued at around 1GB of RAM usage. I couldn't add new .war files to my local tomcat server and after deleting the tomcat folder to re-add it, found I couldn't re-add it either. Essentially almost anything that required a new popup besides the main menus was causing STS to freeze up.
I edited the STS.ini (your Eclipse.ini can be configured similarly) to:
--launcher.XXMaxPermSize 1024M -vmargs -Xms1536m -Xmx2048m -XX:MaxPermSize=1024m
Rebooted STS immediately and saw it plateau at about 1.5 gigs before finally not crashing
if android version is above kitkat you may use this as well
public void onClick(View view) {
Context context = getApplicationContext(); // add this line
if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
((ActivityManager) context.getSystemService(ACTIVITY_SERVICE))
.clearApplicationUserData();
return;
}
The use of extending application just make your application sure for any kind of operation that you want throughout your application running period. Now it may be any kind of variables and suppose if you want to fetch some data from server then you can put your asynctask in application so it will fetch each time and continuously, so that you will get a updated data automatically.. Use this link for more knowledge....
http://www.intridea.com/blog/2011/5/24/how-to-use-application-object-of-android
You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat
I say this because captions are usually applied to floats.
Straight ahead equations (those written with $ ... $
, $$ ... $$
, begin{equation}...
) are in-line objects that do not support \caption
.
This can be done using the following snippet just before \begin{document}
\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}
\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
\let\ORIGINALcaption\caption
\def\caption{%
\addtocounter{equation}{-1}%
\ORIGINALcaption
}%
\ORGeqfloat
}
and when adding an equation use something like
\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}
First thing you should do is go into the logs (Management\SQL Server Logs
) and see if SQL Server successfully registered the Service Principal Name (SPN)
. If you see some sort of error (The SQL Server Network Interface library could not register the Service Principal Name (SPN) for the SQL Server service
) then you know where to start.
We saw this happen when we changed the account SQL Server was running under. Resetting it to Local System Account solved the problem. Microsoft also has a guide on manually configuring the SPN.
You can't POST using JSONP...it simply doesn't work that way, it creates a <script>
element to fetch data...which has to be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.
If this is the problem then go to the place where the javac is present and then type
It will work for sure.
I was having similar issue and I think if we simply ignore the ssl
verification will work like charm as it worked for me. So connecting to server with https
scheme but directing them not to verify the certificate.
Using requests
. Just mention verify=False
instead of None
requests.post(url, data=payload, headers=headers, verify=False)
Hoping this will work for those who needs :).
Additionally, you will see that float
values are rounded.
// e.g: given values 41.0473112,29.0077011 float(11,7) | decimal(11,7) --------------------------- 41.0473099 | 41.0473112 29.0077019 | 29.0077011
Adding following in the page header works for me:
<?php
if($i_wanna_reload_the_full_page_on_top == "yes")
{
$reloadneeded = "1";
}
else
{
$reloadneeded = "0";
}
if($reloadneeded > 0)
{
?>
<script type="text/javascript">
top.window.location='indexframes.php';
</script>
<?php
}else{}
?>