I'd like to point out that one issues is what if the same resources are in multiple jar files. Let's say you want to read /org/node/foo.txt, but not from one file, but from each and every jar file.
I have run into this same issue several times before. I was hoping in JDK 7 that someone would write a classpath filesystem, but alas not yet.
Spring has the Resource class which allows you to load classpath resources quite nicely.
I wrote a little prototype to solve this very problem of reading resources form multiple jar files. The prototype does not handle every edge case, but it does handle looking for resources in directories that are in the jar files.
I have used Stack Overflow for quite sometime. This is the second answer that I remember answering a question so forgive me if I go too long (it is my nature).
This is a prototype resource reader. The prototype is devoid of robust error checking.
I have two prototype jar files that I have setup.
<pre>
<dependency>
<groupId>invoke</groupId>
<artifactId>invoke</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>node</groupId>
<artifactId>node</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
The jar files each have a file under /org/node/ called resource.txt.
This is just a prototype of what a handler would look like with classpath:// I also have a resource.foo.txt in my local resources for this project.
It picks them all up and prints them out.
package com.foo;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Prototype resource reader.
* This prototype is devoid of error checking.
*
*
* I have two prototype jar files that I have setup.
* <pre>
* <dependency>
* <groupId>invoke</groupId>
* <artifactId>invoke</artifactId>
* <version>1.0-SNAPSHOT</version>
* </dependency>
*
* <dependency>
* <groupId>node</groupId>
* <artifactId>node</artifactId>
* <version>1.0-SNAPSHOT</version>
* </dependency>
* </pre>
* The jar files each have a file under /org/node/ called resource.txt.
* <br />
* This is just a prototype of what a handler would look like with classpath://
* I also have a resource.foo.txt in my local resources for this project.
* <br />
*/
public class ClasspathReader {
public static void main(String[] args) throws Exception {
/* This project includes two jar files that each have a resource located
in /org/node/ called resource.txt.
*/
/*
Name space is just a device I am using to see if a file in a dir
starts with a name space. Think of namespace like a file extension
but it is the start of the file not the end.
*/
String namespace = "resource";
//someResource is classpath.
String someResource = args.length > 0 ? args[0] :
//"classpath:///org/node/resource.txt"; It works with files
"classpath:///org/node/"; //It also works with directories
URI someResourceURI = URI.create(someResource);
System.out.println("URI of resource = " + someResourceURI);
someResource = someResourceURI.getPath();
System.out.println("PATH of resource =" + someResource);
boolean isDir = !someResource.endsWith(".txt");
/** Classpath resource can never really start with a starting slash.
* Logically they do, but in reality you have to strip it.
* This is a known behavior of classpath resources.
* It works with a slash unless the resource is in a jar file.
* Bottom line, by stripping it, it always works.
*/
if (someResource.startsWith("/")) {
someResource = someResource.substring(1);
}
/* Use the ClassLoader to lookup all resources that have this name.
Look for all resources that match the location we are looking for. */
Enumeration resources = null;
/* Check the context classloader first. Always use this if available. */
try {
resources =
Thread.currentThread().getContextClassLoader().getResources(someResource);
} catch (Exception ex) {
ex.printStackTrace();
}
if (resources == null || !resources.hasMoreElements()) {
resources = ClasspathReader.class.getClassLoader().getResources(someResource);
}
//Now iterate over the URLs of the resources from the classpath
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
/* if the resource is a file, it just means that we can use normal mechanism
to scan the directory.
*/
if (resource.getProtocol().equals("file")) {
//if it is a file then we can handle it the normal way.
handleFile(resource, namespace);
continue;
}
System.out.println("Resource " + resource);
/*
Split up the string that looks like this:
jar:file:/Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar!/org/node/
into
this /Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar
and this
/org/node/
*/
String[] split = resource.toString().split(":");
String[] split2 = split[2].split("!");
String zipFileName = split2[0];
String sresource = split2[1];
System.out.printf("After split zip file name = %s," +
" \nresource in zip %s \n", zipFileName, sresource);
/* Open up the zip file. */
ZipFile zipFile = new ZipFile(zipFileName);
/* Iterate through the entries. */
Enumeration entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
/* If it is a directory, then skip it. */
if (entry.isDirectory()) {
continue;
}
String entryName = entry.getName();
System.out.printf("zip entry name %s \n", entryName);
/* If it does not start with our someResource String
then it is not our resource so continue.
*/
if (!entryName.startsWith(someResource)) {
continue;
}
/* the fileName part from the entry name.
* where /foo/bar/foo/bee/bar.txt, bar.txt is the file
*/
String fileName = entryName.substring(entryName.lastIndexOf("/") + 1);
System.out.printf("fileName %s \n", fileName);
/* See if the file starts with our namespace and ends with our extension.
*/
if (fileName.startsWith(namespace) && fileName.endsWith(".txt")) {
/* If you found the file, print out
the contents fo the file to System.out.*/
try (Reader reader = new InputStreamReader(zipFile.getInputStream(entry))) {
StringBuilder builder = new StringBuilder();
int ch = 0;
while ((ch = reader.read()) != -1) {
builder.append((char) ch);
}
System.out.printf("zip fileName = %s\n\n####\n contents of file %s\n###\n", entryName, builder);
} catch (Exception ex) {
ex.printStackTrace();
}
}
//use the entry to see if it's the file '1.txt'
//Read from the byte using file.getInputStream(entry)
}
}
}
/**
* The file was on the file system not a zip file,
* this is here for completeness for this example.
* otherwise.
*
* @param resource
* @param namespace
* @throws Exception
*/
private static void handleFile(URL resource, String namespace) throws Exception {
System.out.println("Handle this resource as a file " + resource);
URI uri = resource.toURI();
File file = new File(uri.getPath());
if (file.isDirectory()) {
for (File childFile : file.listFiles()) {
if (childFile.isDirectory()) {
continue;
}
String fileName = childFile.getName();
if (fileName.startsWith(namespace) && fileName.endsWith("txt")) {
try (FileReader reader = new FileReader(childFile)) {
StringBuilder builder = new StringBuilder();
int ch = 0;
while ((ch = reader.read()) != -1) {
builder.append((char) ch);
}
System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", childFile, builder);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
} else {
String fileName = file.getName();
if (fileName.startsWith(namespace) && fileName.endsWith("txt")) {
try (FileReader reader = new FileReader(file)) {
StringBuilder builder = new StringBuilder();
int ch = 0;
while ((ch = reader.read()) != -1) {
builder.append((char) ch);
}
System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", fileName, builder);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
Depending on your rights, you need sudo at beginning.
With some web hosts including NameCheap, it's not possible to disable ModSecurity using .htaccess
. The only option is to contact tech support and ask them to alter the configuration for you.
Instead of converting each date, you can use the following code:
long difference = (sDt4.getTime() - sDt3.getTime()) / 1000;
System.out.println(difference);
And then see that the result is:
1
I put this forward to help anyone needing something readily practical for giving you a nice, prettified (indented) picture of a JS Node
. None of the other solutions worked for me for a Node
("cyclical error" or whatever...). This walks you through the tree under the DOM Node
(without using recursion) and gives you the depth, tagName
(if applicable) and textContent
(if applicable).
Any other details from the nodes you encounter as you walk the tree under the head node can be added as per your interest...
function printRNode( node ){
// make sort of human-readable picture of the node... a bit like PHP print_r
if( node === undefined || node === null ){
throwError( 'node was ' + typeof node );
}
let s = '';
// NB walkDOM could be made into a utility function which you could
// call with one or more callback functions as parameters...
function walkDOM( headNode ){
const stack = [ headNode ];
const depthCountDowns = [ 1 ];
while (stack.length > 0) {
const node = stack.pop();
const depth = depthCountDowns.length - 1;
// TODO non-text, non-BR nodes could show more details (attributes, properties, etc.)
const stringRep = node.nodeType === 3? 'TEXT: |' + node.nodeValue + '|' : 'tag: ' + node.tagName;
s += ' '.repeat( depth ) + stringRep + '\n';
const lastIndex = depthCountDowns.length - 1;
depthCountDowns[ lastIndex ] = depthCountDowns[ lastIndex ] - 1;
if( node.childNodes.length ){
depthCountDowns.push( node.childNodes.length );
stack.push( ... Array.from( node.childNodes ).reverse() );
}
while( depthCountDowns[ depthCountDowns.length - 1 ] === 0 ){
depthCountDowns.splice( -1 );
}
}
}
walkDOM( node );
return s;
}
Could not commit JPA transaction: Transaction marked as rollbackOnly
This exception occurs when you invoke nested methods/services also marked as @Transactional
. JB Nizet explained the mechanism in detail. I'd like to add some scenarios when it happens as well as some ways to avoid it.
Suppose we have two Spring services: Service1
and Service2
. From our program we call Service1.method1()
which in turn calls Service2.method2()
:
class Service1 {
@Transactional
public void method1() {
try {
...
service2.method2();
...
} catch (Exception e) {
...
}
}
}
class Service2 {
@Transactional
public void method2() {
...
throw new SomeException();
...
}
}
SomeException
is unchecked (extends RuntimeException) unless stated otherwise.
Scenarios:
Transaction marked for rollback by exception thrown out of method2
. This is our default case explained by JB Nizet.
Annotating method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating both method1
and method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating method2
with @Transactional(noRollbackFor = SomeException)
prevents marking transaction for rollback (no exception thrown when exiting from method1
).
Suppose method2
belongs to Service1
. Invoking it from method1
does not go through Spring's proxy, i.e. Spring is unaware of SomeException
thrown out of method2
. Transaction is not marked for rollback in this case.
Suppose method2
is not annotated with @Transactional
. Invoking it from method1
does go through Spring's proxy, but Spring pays no attention to exceptions thrown. Transaction is not marked for rollback in this case.
Annotating method2
with @Transactional(propagation = Propagation.REQUIRES_NEW)
makes method2
start new transaction. That second transaction is marked for rollback upon exit from method2
but original transaction is unaffected in this case (no exception thrown when exiting from method1
).
In case SomeException
is checked (does not extend RuntimeException), Spring by default does not mark transaction for rollback when intercepting checked exceptions (no exception thrown when exiting from method1
).
See all scenarios tested in this gist.
explorer "http://www.google.com/search?client=opera&rls=...."
Alternatively, as long as permissions are not given, the good old <noscript>
tags works. You can cover the page in css and tell them what's wrong, ... without using javascript ofcourse.
After getting some inspiration from Orr Sella's blog post I wrote a pre-commit hook (resides in ~/.git/templates/hooks
) which would set specific usernames and e-mail addresses based on the information inside a local repositorie's ./.git/config
:
You have to place the path to the template directory into your ~/.gitconfig
:
[init]
templatedir = ~/.git/templates
Then each git init
or git clone
will pick up that hook and will apply the user data during the next git commit
. If you want to apply the hook to already exisiting repos then just run a git init
inside the repo in order to reinitialize it.
Here is the hook I came up with (it still needs some polishing - suggestions are welcome). Save it either as
~/.git/templates/hooks/pre_commit
or
~/.git/templates/hooks/post-checkout
and make sure it is executable: chmod +x ./post-checkout || chmod +x ./pre_commit
#!/usr/bin/env bash
# -------- USER CONFIG
# Patterns to match a repo's "remote.origin.url" - beginning portion of the hostname
git_remotes[0]="Github"
git_remotes[1]="Gitlab"
# Adjust names and e-mail addresses
local_id_0[0]="my_name_0"
local_id_0[1]="my_email_0"
local_id_1[0]="my_name_1"
local_id_1[1]="my_email_1"
local_fallback_id[0]="${local_id_0[0]}"
local_fallback_id[1]="${local_id_0[1]}"
# -------- FUNCTIONS
setIdentity()
{
local current_id local_id
current_id[0]="$(git config --get --local user.name)"
current_id[1]="$(git config --get --local user.email)"
local_id=("$@")
if [[ "${current_id[0]}" == "${local_id[0]}" &&
"${current_id[1]}" == "${local_id[1]}" ]]; then
printf " Local identity is:\n"
printf "» User: %s\n» Mail: %s\n\n" "${current_id[@]}"
else
printf "» User: %s\n» Mail: %s\n\n" "${local_id[@]}"
git config --local user.name "${local_id[0]}"
git config --local user.email "${local_id[1]}"
fi
return 0
}
# -------- IMPLEMENTATION
current_remote_url="$(git config --get --local remote.origin.url)"
if [[ "$current_remote_url" ]]; then
for service in "${git_remotes[@]}"; do
# Disable case sensitivity for regex matching
shopt -s nocasematch
if [[ "$current_remote_url" =~ $service ]]; then
case "$service" in
"${git_remotes[0]}" )
printf "\n»» An Intermission\n» %s repository found." "${git_remotes[0]}"
setIdentity "${local_id_0[@]}"
exit 0
;;
"${git_remotes[1]}" )
printf "\n»» An Intermission\n» %s repository found." "${git_remotes[1]}"
setIdentity "${local_id_1[@]}"
exit 0
;;
* )
printf "\n» pre-commit hook: unknown error\n» Quitting.\n"
exit 1
;;
esac
fi
done
else
printf "\n»» An Intermission\n» No remote repository set. Using local fallback identity:\n"
printf "» User: %s\n» Mail: %s\n\n" "${local_fallback_id[@]}"
# Get the user's attention for a second
sleep 1
git config --local user.name "${local_fallback_id[0]}"
git config --local user.email "${local_fallback_id[1]}"
fi
exit 0
EDIT:
So I rewrote the hook as a hook and command in Python. Additionally it's possible to call the script as a Git command (git passport
), too. Also it's possible to define an arbitrary number of IDs inside a configfile (~/.gitpassport
) which are selectable on a prompt. You can find the project at github.com: git-passport - A Git command and hook written in Python to manage multiple Git accounts / user identities.
This refers to the object you’re “in” right now. In other words,this refers to the receiving object. You use this to clarify which variable you’re referring to.Java_whitepaper page :37
class Point extends Object
{
public double x;
public double y;
Point()
{
x = 0.0;
y = 0.0;
}
Point(double x, double y)
{
this.x = x;
this.y = y;
}
}
In the above example code this.x/this.y refers to current class that is Point class x and y variables where (double x,double y) are double values passed from different class to assign values to current class .
display
is not an attribute - it's a CSS property. You need to access the style object for this:
document.getElementById('classRight').style.display = 'none';
to make the string upper case -- just simply type
s.upper()
simple and easy! you can do the same to make it lower too
s.lower()
etc.
find indexes of each double quotes and insert an empty string there.
If you are writing portable code, the answer is "you can't tell", the good news is that you don't need to. Your protocol should involve writing the size as (eg) "8 octets, big-endian format" (Ideally with a check that the actual size fits in 8 octets.)
As Cubbi pointed out in one of the comments, std::wstring_convert
(C++11) provides a neat simple solution (you need to #include
<locale>
and <codecvt>
):
std::wstring string_to_convert;
//setup converter
using convert_type = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_type, wchar_t> converter;
//use converter (.to_bytes: wstr->str, .from_bytes: str->wstr)
std::string converted_str = converter.to_bytes( string_to_convert );
I was using a combination of wcstombs
and tedious allocation/deallocation of memory before I came across this.
http://en.cppreference.com/w/cpp/locale/wstring_convert
update(2013.11.28)
One liners can be stated as so (Thank you Guss for your comment):
std::wstring str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes("some string");
Wrapper functions can be stated as so: (Thank you ArmanSchwarz for your comment)
std::wstring s2ws(const std::string& str)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.from_bytes(str);
}
std::string ws2s(const std::wstring& wstr)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
Note: there's some controversy on whether string
/wstring
should be passed in to functions as references or as literals (due to C++11 and compiler updates). I'll leave the decision to the person implementing, but it's worth knowing.
Note: I'm using std::codecvt_utf8
in the above code, but if you're not using UTF-8 you'll need to change that to the appropriate encoding you're using:
Select
is a transformation, not an action, so it is lazily evaluated (won't actually do the calculations just map the operations). Collect
is an action.
Try:
df.limit(20).collect()
You can use - matplotlib.gridspec.GridSpec
Check - https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html
The below code displays a heatmap on right and an Image on left.
#Creating 1 row and 2 columns grid
gs = gridspec.GridSpec(1, 2)
fig = plt.figure(figsize=(25,3))
#Using the 1st row and 1st column for plotting heatmap
ax=plt.subplot(gs[0,0])
ax=sns.heatmap([[1,23,5,8,5]],annot=True)
#Using the 1st row and 2nd column to show the image
ax1=plt.subplot(gs[0,1])
ax1.grid(False)
ax1.set_yticklabels([])
ax1.set_xticklabels([])
#The below lines are used to display the image on ax1
image = io.imread("https://images-na.ssl-images- amazon.com/images/I/51MvhqY1qdL._SL160_.jpg")
plt.imshow(image)
plt.show()
Are you sure your newline is not CHR(13) + CHR(10)
, in which case, you are ending up with CHR(13) + '_'
, which might still look like a newline?
Try REPLACE(col_name, CHR(13) + CHR(10), '')
Once more a solution... Because there's always one more:
perl -i -pe 's/\r//' filename
It's nice because it's in place and works in every flavor of unix/linux I've worked with.
f'{float(f"{i:.1g}"):g}'
# Or with Python <3.6,
'{:g}'.format(float('{:.1g}'.format(i)))
This solution is different from all of the others because:
For an arbitrary number n
of significant figures, you can use:
print('{:g}'.format(float('{:.{p}g}'.format(i, p=n))))
Test:
a = [1234, 0.12, 0.012, 0.062, 6253, 1999, -3.14, 0., -48.01, 0.75]
b = ['{:g}'.format(float('{:.1g}'.format(i))) for i in a]
# b == ['1000', '0.1', '0.01', '0.06', '6000', '2000', '-3', '0', '-50', '0.8']
Note: with this solution, it is not possible to adapt the number of significant figures dynamically from the input because there is no standard way to distinguish numbers with different numbers of trailing zeros (3.14 == 3.1400
). If you need to do so, then non-standard functions like the ones provided in the to-precision package are needed.
You can use Len(StrFile) > 0
in loop check statement !
Sub openMyfile()
Dim Source As String
Dim StrFile As String
'do not forget last backslash in source directory.
Source = "E:\Planning\03\"
StrFile = Dir(Source)
Do While Len(StrFile) > 0
Workbooks.Open Filename:=Source & StrFile
StrFile = Dir()
Loop
End Sub
You could compare String representations so:
array1.toString() == array2.toString()
array1.toString() !== array3.toString()
but that would also make
array4 = ['1',2,3,4,5]
equal to array1 if that matters to you
Here's a version using template literals. It maps
over the data creating new arrays of strings build from the template literals, and then adds them to the document with insertAdjacentHTML
:
let data = [_x000D_
['Title', 'Artist', 'Duration', 'Created'],_x000D_
['hello', 'me', '2', '2019'],_x000D_
['ola', 'me', '3', '2018'],_x000D_
['Bob', 'them', '4.3', '2006']_x000D_
];_x000D_
_x000D_
function getCells(data, type) {_x000D_
return data.map(cell => `<${type}>${cell}</${type}>`).join('');_x000D_
}_x000D_
_x000D_
function createBody(data) {_x000D_
return data.map(row => `<tr>${getCells(row, 'td')}</tr>`).join('');_x000D_
}_x000D_
_x000D_
function createTable(data) {_x000D_
const [headings, ...rows] = data;_x000D_
return `_x000D_
<table>_x000D_
<thead>${getCells(headings, 'th')}</thead>_x000D_
<tbody>${createBody(rows)}</tbody>_x000D_
</table>_x000D_
`;_x000D_
}_x000D_
_x000D_
document.body.insertAdjacentHTML('beforeend', createTable(data));
_x000D_
table { border-collapse: collapse; }_x000D_
tr { border: 1px solid #dfdfdf; }_x000D_
th, td { padding: 2px 5px 2px 5px;}
_x000D_
I realise this is a little late but you could add the following to your code. This won't work for transparent pngs though, you'd need a cropping mask for that. Which I'm now going to see about.
outerLink {
overflow: hidden;
position: relative;
}
outerLink:hover:after {
background: #000;
content: "";
display: block;
height: 100%;
left: 0;
opacity: 0.5;
position: absolute;
top: 0;
width: 100%;
}
there is indeed an xpath contains function it should look something like:
<xsl:for-each select="item">
<xsl:variable name="hhref" select="link" />
<xsl:variable name="pdate" select="pubDate" />
<xsl:if test="not(contains(hhref,'1234'))">
<li>
<a href="{$hhref}" title="{$pdate}">
<xsl:value-of select="title"/>
</a>
</li>
</xsl:if>
A good style would be to setup some relations and a primary key for permissions (actually, usually it is good style to setup integer primary keys for everything, but whatever):
class User(Base):
__tablename__ = 'users'
email = Column(String, primary_key=True)
name = Column(String)
class Document(Base):
__tablename__ = "documents"
name = Column(String, primary_key=True)
author_email = Column(String, ForeignKey("users.email"))
author = relation(User, backref='documents')
class DocumentsPermissions(Base):
__tablename__ = "documents_permissions"
id = Column(Integer, primary_key=True)
readAllowed = Column(Boolean)
writeAllowed = Column(Boolean)
document_name = Column(String, ForeignKey("documents.name"))
document = relation(Document, backref = 'permissions')
Then do a simple query with joins:
query = session.query(User, Document, DocumentsPermissions).join(Document).join(DocumentsPermissions)
It's better if you create a class that has all the query methods, inclusively, in a different package, so instead of typing all the process in every class, you just call the method from that class.
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
The answer from Constantin is spot on but for more background this behavior is inherited from Matlab.
The Matlab behavior is explained in the Figure Setup - Displaying Multiple Plots per Figure section of the Matlab documentation.
subplot(m,n,i) breaks the figure window into an m-by-n matrix of small subplots and selects the ithe subplot for the current plot. The plots are numbered along the top row of the figure window, then the second row, and so forth.
what if you use
Map<String, ? extends Class<? extends Serializable>> expected = null;
Try passing it directly to the ng-click function:
<div class="col-lg-1 text-center">
<span class="glyphicon glyphicon-trash" data="{{event.id}}"
ng-click="deleteEvent(event.id)"></span>
</div>
Then it should be available in your handler:
$scope.deleteEvent=function(idPassedFromNgClick){
console.log(idPassedFromNgClick);
}
Here's an example
You need to put the last()
indexing on the nodelist result, rather than as part of the selection criteria. Try:
(//element[@name='D'])[last()]
You need to use the CSS3 transform property rotate
- see here for which browsers support it and the prefix you need to use.
One example for webkit browsers is -webkit-transform: rotate(-90deg);
Edit: The question was changed substantially so I have added a demo that works in Chrome/Safari (as I only included the -webkit-
CSS prefixed rules). The problem you have is that you do not want to rotate the title div, but simply the text inside it. If you remove your rotation, the <div>
s are in the correct position and all you need to do is wrap the text in an element and rotate that instead.
There already exists a more customisable widget as part of the jQuery UI - see the accordion demo page. I am sure with some CSS cleverness you should be able to make the accordion vertical and also rotate the title text :-)
Edit 2: I had anticipated the text center problem and have already updated my demo. There is a height/width constraint though, so longer text could still break the layout.
Edit 3: It looks like the horizontal version was part of the original plan but I cannot see any way of configuring it on the demo page. I was incorrect… the new accordion is part of the upcoming jQuery UI 1.9! So you could try the development builds if you want the new functionality.
Hope this helps!
Returning the function name without ()
returns a reference to the function, which can be assigned as you've done with var s = a()
. s
now contains a reference to the function b()
, and calling s()
is functionally equivalent to calling b()
.
// Return a reference to the function b().
// In your example, the reference is assigned to var s
return b;
Calling the function with ()
in a return statement executes the function, and returns whatever value was returned by the function. It is similar to calling var x = b();
, but instead of assigning the return value of b()
you are returning it from the calling function a()
. If the function b()
itself does not return a value, the call returns undefined
after whatever other work is done by b()
.
// Execute function b() and return its value
return b();
// If b() has no return value, this is equivalent to calling b(), followed by
// return undefined;
Let’s try to keep this least technical.
Let’s say you are sending a html form data to node-js server i.e. you made a request to the server. The server file would receive your request under a request object. Now by logic, if you console log this request object in your server file you should see your form data some where in it, which could be extracted then, but whoa ! you actually don’t !
So, where is our data ? How will we extract it if its not only present in my request.
Simple explanation to this is http sends your form data in bits and pieces which are intended to get assembled as they reach their destination. So how would you extract your data.
But, why take this pain of every-time manually parsing your data for chunks and assembling it. Use something called “body-parser” which would do this for you.
body-parser parses your request and converts it into a format from which you can easily extract relevant information that you may need.
For example, let’s say you have a sign-up form at your frontend. You are filling it, and requesting server to save the details somewhere.
Extracting username and password from your request goes as simple as below if you use body-parser.
var loginDetails = {
username : request.body.username,
password : request.body.password
};
So basically, body-parser parsed your incoming request, assembled the chunks containing your form data, then created this body object for you and filled it with your form data.
As of Chrome 80, none of the current answers work. There is no visible "Pause" button - you need to long-click the "Play" button to access the Stop icon:
You can get unicode for that junk character from charactermap tool in window pc and add \u e.g. \u00a9 for copyright symbol. Now you can use that string with that particular junk caharacter, don't remove any junk character but replace with proper unicode.
You can do
jQuery.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
followed by
$(selector).reverse().each(...)
I have done it like this and it seems to work:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
}
}
Even if this can somehow be done it is a terrible idea since it would be possible to get a sequence that then gets used by another record!
A much better idea is to save the record and then retrieve the sequence afterwards.
As others have mentioned, perhaps the main advantage of matrix
was that it provided a convenient notation for matrix multiplication.
However, in Python 3.5 there is finally a dedicated infix operator for matrix multiplication: @
.
With recent NumPy versions, it can be used with ndarray
s:
A = numpy.ones((1, 3))
B = numpy.ones((3, 3))
A @ B
So nowadays, even more, when in doubt, you should stick to ndarray
.
You are using RxJS 6. Just replace
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
by
import { Observable, of } from 'rxjs';
can use command:
:g/^/move 0
reference: https://vi.stackexchange.com/questions/2105/how-to-reverse-the-order-of-lines
Yes, I found MySQL also cannot edit result tables. Usually results tables joining other tables don't have primary keys. I heard other suggested put the result table in another table, but the better solution is to use Dbeaver which can edit result tables.
I had the same issue, I found most of the answers here out dated. I ended up writing a wrapper on FFMPEG to access from Android with a single line of code.
Please click on this link it should work ..
http://www.php-guru.in/2013/html-to-pdf-conversion-in-codeigniter/
Or you can see below
There are number of PHP libraries on the web to convert HTML page to PDF file. They are easy to implement and deploy when you are working on any web application in core PHP. But when we try to integrate this libraries with any framework or template, then it becomes very tedious work if the framework which we are using does not have its own library to integrate it with any PDF library. The same situation came in front of me when there was one requirement to convert HTML page to PDF file and the framework I was using was codeigniter.
I searched on web and got number of PHP libraries to convert HTML page to PDF file. After lot of research and googling I decided to go with TCPDF PHP library to convert HTML page to PDF file for my requirement. I found TCPDf PHP library quite easy to integrate with codeigniter and stated working on it. After successfully completing my integration of codeigniter and TCPDF, I thought of sharing this script on web.
Now, let’s start with implimentation of the code.
Download the TCPDF library code, you can download it from TCPDF website http://www.tcpdf.org/.
Now create “tcpdf” folder in “application/helpers/” directory of your web application which is developed in codeigniter. Copy all TCPDF library files and paste it in “application/helpers/tcpdf/” directory. Update the configuration file “tcpdf_config.php” of TCPDF, which is located in “application/helpers/tcpdf/config” directory, do changes according to your applicatoin requirements. We can set logo, font, font size, with, height, header etc in the cofing file. Give read, write permissions to “cache” folder which is there in tcpdf folder. After defining your directory structure, updating configuration file and assigning permissions, here starts your actual coding part.
Create one PHP helper file in “application/helpers/” directory of codeigniter, say “pdf_helper.php”, then copy below given code and paste it in helper file
Helper: application/helpers/pdf_helper.php
function tcpdf()
{
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');
}
Then in controller file call the above helper, suppose our controller file is “createpdf.php” and it has method as pdf(), so the method pdf() will load the “pdf_helper” helper and will also have any other code.
Controller: application/controllers/createpdf.php
function pdf()
{
$this->load->helper('pdf_helper');
/*
---- ---- ---- ----
your code here
---- ---- ---- ----
*/
$this->load->view('pdfreport', $data);
}
Now create one view file, say “pdfreport.php” in “application/views/” directory, which is also loaded in pdf() method in controller. So in view file we can directly call the tcpdf() function which we have defined in “pdf_helper” helper, which will load all required TCPDF classes, functions, variable etc. Then we can directly use the TCPDF example codes as it is in our current controller or view. Now in out current view “pdfreport” copy the given code below:
View: application/views/pdfreport.php
tcpdf();
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$obj_pdf->SetCreator(PDF_CREATOR);
$title = "PDF Report";
$obj_pdf->SetTitle($title);
$obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING);
$obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$obj_pdf->SetDefaultMonospacedFont('helvetica');
$obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$obj_pdf->SetFont('helvetica', '', 9);
$obj_pdf->setFontSubsetting(false);
$obj_pdf->AddPage();
ob_start();
// we can have any view part here like HTML, PHP etc
$content = ob_get_contents();
ob_end_clean();
$obj_pdf->writeHTML($content, true, false, true, false, '');
$obj_pdf->Output('output.pdf', 'I');
Thus our HTML page will be converted to PDF using TCPDF in CodeIgniter. We can also embed images,css,modifications in PDF file by using TCPDF library.
private void PDFExport(LocalReport report)
{
string[] streamids;
string minetype;
string encod;
string fextension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>EMF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.25in</MarginTop>" +
" <MarginLeft>0.25in</MarginLeft>" +
" <MarginRight>0.25in</MarginRight>" +
" <MarginBottom>0.25in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
byte[] rpbybe = report.Render("PDF", deviceInfo, out minetype, out encod, out fextension, out streamids,
out warnings);
using(FileStream fs=new FileStream("E:\\newwwfg.pdf",FileMode.Create))
{
fs.Write(rpbybe , 0, rpbybe .Length);
}
}
I also had the "Missing or insufficient permissions" error after specifying security rules. Turns out that the the rules are not recursive by default! i.e. if you wrote a rule like
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
The rule will not apply to any subcollections under /users/{userId}
. This was the reason for my error.
I fixed it by specifying the rule as:
match /users/{userId}/{document=**} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
Read more at the relevant section of the documentation.
Integer.parseInt(str) throws NumberFormatException
if the string does not contain a parsable integer. You can hadle the same as below.
int a;
String str = "N/A";
try {
a = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
// Handle the condition when str is not a number.
}
CASE WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%'
THEN 'BP Medication' ELSE '' END AS [BP Medication]
The leading ', '
and trailing ','
are added so that you can handle the match regardless of where it is in the string (first entry, last entry, or anywhere in between).
That said, why are you storing data you want to search on as a comma-separated string? This violates all kinds of forms and best practices. You should consider normalizing your schema.
In addition: don't use 'single quotes'
as identifier delimiters; this syntax is deprecated. Use [square brackets]
(preferred) or "double quotes"
if you must. See "string literals as column aliases" here: http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx
EDIT If you have multiple values, you can do this (you can't short-hand this with the other CASE
syntax variant or by using something like IN()
):
CASE
WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%'
WHEN ', ' + dbo.Table.Column +',' LIKE '%, amlodipine,%'
THEN 'BP Medication' ELSE '' END AS [BP Medication]
If you have more values, it might be worthwhile to use a split function, e.g.
USE tempdb;
GO
CREATE FUNCTION dbo.SplitStrings(@List NVARCHAR(MAX))
RETURNS TABLE
AS
RETURN ( SELECT DISTINCT Item FROM
( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
FROM ( SELECT [XML] = CONVERT(XML, '<i>'
+ REPLACE(@List,',', '</i><i>') + '</i>').query('.')
) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
WHERE Item IS NOT NULL
);
GO
CREATE TABLE dbo.[Table](ID INT, [Column] VARCHAR(255));
GO
INSERT dbo.[Table] VALUES
(1,'lactulose, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(2,'lactulite, Lasix (furosemide), lactulose, propranolol, rabeprazole, sertraline,'),
(3,'lactulite, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(4,'lactulite, Lasix (furosemide), lactulose, amlodipine, rabeprazole, sertraline,');
SELECT t.ID
FROM dbo.[Table] AS t
INNER JOIN dbo.SplitStrings('lactulose,amlodipine') AS s
ON ', ' + t.[Column] + ',' LIKE '%, ' + s.Item + ',%'
GROUP BY t.ID;
GO
Results:
ID
----
1
2
4
I just combined the HTML, JS and CSS suggestions in the answers here
HTML:
<input type="checkbox" readonly>
jQuery:
(function(){
// Raj: https://stackoverflow.com/a/14753503/260665
$(document).on('click', 'input[type="checkbox"][readonly]', function(e){
e.preventDefault();
});
})();
CSS:
input[type="checkbox"][readonly] {
cursor: not-allowed;
opacity: 0.5;
}
Since the element is not 'disabled' it still goes through the POST.
If your img is exactly first element inside div then try
$(this.firstChild);
$( "#box" ).click( function() {_x000D_
let img = $(this.firstChild);_x000D_
console.log({img});_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="box"><img src="https://picsum.photos/seed/picsum/300/150"></div>
_x000D_
I find using the pipe character with some top and bottom padding works well. Using a div with a border will require more CSS to vertically align it and get the horizontal spacing even with the other elements.
.divider-vertical {
padding-top: 14px;
padding-bottom: 14px;
}
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li class="divider-vertical">|</li>
<li><a href="#">Faq</a></li>
<li class="divider-vertical">|</li>
<li><a href="#">News</a></li>
<li class="divider-vertical">|</li>
<li><a href="#">Contact</a></li>
</ul>
All the answers here, including the accepted one, will give you the total amount of RAM available for use. And that may have been what OP wanted.
But if you are interested in getting the amount of installed RAM, then you'll want to make a call to the GetPhysicallyInstalledSystemMemory function.
From the link, in the Remarks section:
The GetPhysicallyInstalledSystemMemory function retrieves the amount of physically installed RAM from the computer's SMBIOS firmware tables. This can differ from the amount reported by the GlobalMemoryStatusEx function, which sets the ullTotalPhys member of the MEMORYSTATUSEX structure to the amount of physical memory that is available for the operating system to use. The amount of memory available to the operating system can be less than the amount of memory physically installed in the computer because the BIOS and some drivers may reserve memory as I/O regions for memory-mapped devices, making the memory unavailable to the operating system and applications.
Sample code:
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);
static void Main()
{
long memKb;
GetPhysicallyInstalledSystemMemory(out memKb);
Console.WriteLine((memKb / 1024 / 1024) + " GB of RAM installed.");
}
You can use the expandable list view explained in API demos to show groups
To animate the list items motion, you will have to override the getView method and apply translate animation on each list item. The values for animation depend on the position of each list item. This was something which i tried on a simple list view long time back.
The quintessential example of this is an array of pointers to structs or objects (that are mutable).
A shallow copy copies the array and maintains references to the original objects.
A deep copy will copy (clone) the objects too so they bear no relation to the original. Implicit in this is that the object themselves are deep copied. This is where it gets hard because there's no real way to know if something was deep copied or not.
The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.
In order to read the details with complete examples and explanations you could see the article Constructors and destructors.
The default copy constructor is shallow. You can make your own copy constructors deep or shallow, as appropriate. See C++ Notes: OOP: Copy Constructors.
You need to use JSON.stringify
to first serialize your object to JSON, and then specify the contentType
so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON
object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
If you want to manually count it, the size of a struct is just the size of each of its data members after accounting for alignment. There's no magic overhead bytes for a struct.
String str, str1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String : ");
str = sc.nextLine();
str1 = str.replaceAll("[aeiouAEIOU]", "");
System.out.print(str1);
The function expects a string.
file_exists()
does not work properly with HTTP URLs.
simple query would be, just set a variable to some number you want. then update the column you need by incrementing 1 from that number. for all the rows it'll update each row id by incrementing 1
SET @a = 50000835 ;
UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1
WHERE external_identifier IS NULL;
How about:
function changeText() {
$("#demoTable td").each(function () {
$(this).html().replace("8: Tap on APN and Enter <B>www</B>", "");
}
}
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
I had a similar issue so I found a workaround (remove hyperlink tags thanks to regular expressions so that only a paragraph tag remains). I posted this solution on https://github.com/python-openxml/python-docx/issues/85 BP
I might be a bit late to answer this but this will be useful for new people looking for this answer.
The answers above are good, but to have a perfect video background you have to check at the aspect ratio as the video might cut or the canvas around get deformed when resizing the screen or using it on different screen sizes.
I got into this issue not long ago and I found the solution using media queries.
Here is a tutorial that I wrote on how to create a Fullscreen Video Background with only CSS
I will add the code here as well:
HTML:
<div class="videoBgWrapper">
<video loop muted autoplay poster="img/videoframe.jpg" class="videoBg">
<source src="videosfolder/video.webm" type="video/webm">
<source src="videosfolder/video.mp4" type="video/mp4">
<source src="videosfolder/video.ogv" type="video/ogg">
</video>
</div>
CSS:
.videoBgWrapper {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
z-index: -100;
}
.videoBg{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
@media (min-aspect-ratio: 16/9) {
.videoBg{
width: 100%;
height: auto;
}
}
@media (max-aspect-ratio: 16/9) {
.videoBg {
width: auto;
height: 100%;
}
}
I hope you find it useful.
The installation procedure creates a user account called postgres
that is associated with the default Postgres role. In order to use Postgres, you can log into that account. But if not explicitly specified the rails app looks for a different role, more particularly the role having your unix username which might not be created in the postgres roles.
To overcome that, you can create a new role, first by switching over to the default role postgres which was created during installation
sudo -i -u postgres
After you are logged in to the postgres account, you can create a new user by the command:
createuser --interactive
This will prompt you with some choices and, based on your responses, execute the correct Postgres commands to create a user.
Pass over a role name and some permissions and the role is created, you can then migrate your db
Use characterAtIndex:
. If the first character is an asterisk, use substringFromIndex:
to get the string sans '*'.
driver.find_element_by_xpath("path").send_keys(Keys.CONTROL + u'\ue003')
worked great with FireFox
If you have more than one column to be converted you can do the following:
df[["col1", "col2", "col3"]] = df[["col1", "col2", "col3"]].apply(pd.to_datetime)
You can do something like this:
HTML:
<div class='div'>
<label>Something</label>
<input type='text' class='input'/>
<div>
CSS:
.div{
margin-bottom: 10px;
display: grid;
grid-template-columns: 1fr 4fr;
}
.input{
width: 50%;
}
Hope this helps ! :)
You can use read_csv
from pandas
to skip these lines.
import pandas as pd
data_df = pd.read_csv('data.csv', error_bad_lines=False)
The org.json library is easy to use.
Just remember (while casting or using methods like getJSONObject
and getJSONArray
) that in JSON notation
[ … ]
represents an array, so library will parse it to JSONArray
{ … }
represents an object, so library will parse it to JSONObject
Example code below:
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
}
You may find more examples from: Parse JSON in Java
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
You can use inline styles but you will have some limitations if you are using them in all of your stylings, some known limitations are you can't use CSS pseudo selectors and media queries in there.
You can use Radium to solve this but still, I feel has the project grows its gonna get cumbersome.
I would recommend using CSS modules.
using CSS Modules you will have the freedom of writing CSS in CSS file and don't have to worry about the naming clashes, it will be taken care by CSS Modules.
An advantage of this method is that it gives you styling functionality to the specific component. This will create much more maintainable code and readable project architecture for the next developer to work on your project.
In the config file, change the "host" variable to point to the external server. The config file is called config.inc.php
and it will be in the main phpMyAdmin folder. There should be a line like this:
$cfg['Servers'][$i]['host'] = 'localhost';
Just change localhost
to your server's IP address.
Note: you may have to configure the external server to allow remote connections, but I've done this several times on shared hosting so it should be fine.
npm install bootstrap jquery --save
You don't have to install popper.js with npm as it comes with npm Bootstrap in bootstrap.bundle.js
.
Bundled JS files (bootstrap.bundle.js and minified bootstrap.bundle.min.js) include Popper, but not jQuery.
Source to Verify: Link
Now you only have to do this in your HTML file:
<script src="node_modules/jquery/dist/jquery.slim.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
I followed the solution by poke with a minor adjustment in the end. My steps follow
- git fetch --prune
;
- git branch -a
printing the following
master
branch
remotes/origin/HEAD -> origin/master
remotes/origin/master
remotes/origin/branch
(remote branch to remove)
- git push origin --delete branch
.
Here, the branch to remove is not named as remotes/origin/branch
but simply branch
. And the branch is removed.
Ed: phpMyAdmin is for MySQL, but the asker needs something for Microsoft SQL Server.
Most solutions that I found involve using an ODBC Driver and then whatever client application you use. For example, Gorilla SQL claims to be able to do that, even though the project seems abandoned.
Most good solutions are either using Remote Desktop or VMware/Parallels.
In Java, static methods belong to the class rather than the instance. This means that you cannot call other instance methods from static methods unless they are called in an instance that you have initialized in that method.
Here's something you might want to do:
public class Foo
{
public void fee()
{
//do stuff
}
public static void main (String[]arg)
{
Foo foo = new Foo();
foo.fee();
}
}
Notice that you are running an instance method from an instance that you've instantiated. You can't just call call a class instance method directly from a static method because there is no instance related to that static method.
$('.close').click(function() {
//Code to be executed when close is clicked
$('#result').html('yes,result');
});
The closest I can get to the answer is by adding an extension method into a System.Type
object. Not pretty, but still interesting.
public static class Foo
{
public static void Bar()
{
var now = DateTime.Now;
var tomorrow = typeof(DateTime).Tomorrow();
}
public static DateTime Tomorrow(this System.Type type)
{
if (type == typeof(DateTime)) {
return DateTime.Now.AddDays(1);
} else {
throw new InvalidOperationException();
}
}
}
Otherwise, IMO Andrew and ShuggyCoUk has a better implementation.
I tend to find this neat
sudo mkdir -p /etc/paths.d # was optional in my case
echo /usr/local/git/bin | sudo tee /etc/paths.d/mypath1
In KOTLIN:- If you want to save Token into DB or shared preferences then override onNewToken in FirebaseMessagingService
override fun onNewToken(token: String) {
super.onNewToken(token)
}
Get token at run-time,use
FirebaseInstanceId.getInstance().instanceId
.addOnSuccessListener(this@SplashActivity) { instanceIdResult ->
val mToken = instanceIdResult.token
println("printing fcm token: $mToken")
}
Default usage
el.addEventListener('input', function () {
fn();
});
But, if you want to fire event when you change inputs value manualy via JS you should use custom event(any name, like 'myEvent' \ 'ev' etc.) IF you need to listen forms 'change' or 'input' event and you change inputs value via JS - you can name your custom event 'change' \ 'input' and it will work too.
var event = new Event('input');
el.addEventListener('input', function () {
fn();
});
form.addEventListener('input', function () {
anotherFn();
});
el.value = 'something';
el.dispatchEvent(input);
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
Just adding a bit of extra information here in case someone has the same issue as me.
I use namespaces in my code and I had a class with a function that throws an Exception.
However my try/catch code in another class file was completely ignored and the normal PHP error for an uncatched exception was thrown.
Turned out I forgot to add "use \Exception;" at the top, adding that solved the error.
$('#list option').each(function(index){
//do stuff
console.log(index);
});
logs the index :)
a more detailed example is below.
function run_each() {_x000D_
_x000D_
var $results = $(".results");_x000D_
_x000D_
$results.empty();_x000D_
_x000D_
$results.append("==================== START 1st each ====================");_x000D_
console.log("==================== START 1st each ====================");_x000D_
_x000D_
$('#my_select option').each(function(index, value) {_x000D_
$results.append("<br>");_x000D_
// log the index_x000D_
$results.append("index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log("index: " + index);_x000D_
// logs the element_x000D_
// $results.append(value); this would actually remove the element_x000D_
$results.append("<br>");_x000D_
console.log(value);_x000D_
// logs element property_x000D_
$results.append(value.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(value.innerHTML);_x000D_
// logs element property_x000D_
$results.append(this.text);_x000D_
$results.append("<br>");_x000D_
console.log(this.text);_x000D_
// jquery_x000D_
$results.append($(this).text());_x000D_
$results.append("<br>");_x000D_
console.log($(this).text());_x000D_
_x000D_
// BEGIN just to see what would happen if nesting an .each within an .each_x000D_
$('p').each(function(index) {_x000D_
$results.append("==================== nested each");_x000D_
$results.append("<br>");_x000D_
$results.append("nested each index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log(index);_x000D_
});_x000D_
// END just to see what would happen if nesting an .each within an .each_x000D_
_x000D_
});_x000D_
_x000D_
$results.append("<br>");_x000D_
$results.append("==================== START 2nd each ====================");_x000D_
console.log("");_x000D_
console.log("==================== START 2nd each ====================");_x000D_
_x000D_
_x000D_
$('ul li').each(function(index, value) {_x000D_
$results.append("<br>");_x000D_
// log the index_x000D_
$results.append("index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log(index);_x000D_
// logs the element_x000D_
// $results.append(value); this would actually remove the element_x000D_
$results.append("<br>");_x000D_
console.log(value);_x000D_
// logs element property_x000D_
$results.append(value.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(value.innerHTML);_x000D_
// logs element property_x000D_
$results.append(this.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(this.innerHTML);_x000D_
// jquery_x000D_
$results.append($(this).text());_x000D_
$results.append("<br>");_x000D_
console.log($(this).text());_x000D_
});_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(document).on("click", ".clicker", function() {_x000D_
_x000D_
run_each();_x000D_
_x000D_
});
_x000D_
.results {_x000D_
background: #000;_x000D_
height: 150px;_x000D_
overflow: auto;_x000D_
color: lime;_x000D_
font-family: arial;_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.one,_x000D_
.two,_x000D_
.three {_x000D_
width: 33.3%;_x000D_
}_x000D_
_x000D_
.one {_x000D_
background: yellow;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.two {_x000D_
background: pink;_x000D_
}_x000D_
_x000D_
.three {_x000D_
background: darkgray;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<div class="one">_x000D_
<select id="my_select">_x000D_
<option>apple</option>_x000D_
<option>orange</option>_x000D_
<option>pear</option>_x000D_
</select>_x000D_
</div>_x000D_
_x000D_
<div class="two">_x000D_
<ul id="my_list">_x000D_
<li>canada</li>_x000D_
<li>america</li>_x000D_
<li>france</li>_x000D_
</ul>_x000D_
</div>_x000D_
_x000D_
<div class="three">_x000D_
<p>do</p>_x000D_
<p>re</p>_x000D_
<p>me</p>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<button class="clicker">run_each()</button>_x000D_
_x000D_
_x000D_
<div class="results">_x000D_
_x000D_
_x000D_
</div>
_x000D_
Yes, use the rendered
attribute.
<h:form rendered="#{some boolean condition}">
You usually tie it to the model rather than letting the model grab the component and manipulate it.
E.g.
<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
Note the importance of keyword based EL operators such as gt
, ge
, le
and lt
instead of >
, >=
, <=
and <
as angle brackets <
and >
are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.
As to your specific use case, let's assume that the link is passing a parameter like below:
<a href="page.xhtml?form=1">link</a>
You can then show the form as below:
<h:form rendered="#{param.form eq '1'}">
(the #{param}
is an implicit EL object referring to a Map
representing the request parameters)
In the context of the repository pattern, aggregate roots are the only objects your client code loads from the repository.
The repository encapsulates access to child objects - from a caller's perspective it automatically loads them, either at the same time the root is loaded or when they're actually needed (as with lazy loading).
For example, you might have an Order
object which encapsulates operations on multiple LineItem
objects. Your client code would never load the LineItem
objects directly, just the Order
that contains them, which would be the aggregate root for that part of your domain.
Below is an example of a script which implements try/catch/finally
in bash.
Like other answers to this question, exceptions must be caught after exiting a subprocess.
The example scripts start by creating an anonymous fifo, which is used to pass string messages from a command exception
or throw
to end of the closest try
block. Here the messages are removed from the fifo and placed in an array variable. The status is returned through return
and exit
commands and placed in a different variable. To enter a catch
block, this status must not be zero. Other requirements to enter a catch
block are passed as parameters. If the end of a catch
block is reached, then the status is set to zero. If the end of the finally
block is reached and the status is still nonzero, then an implicit throw containing the messages and status is executed. The script requires the calling of the function trycatchfinally
which contains an unhandled exception handler.
The syntax for the trycatchfinally
command is given below.
trycatchfinally [-cde] [-h ERR_handler] [-k] [-o debug_file] [-u unhandled_handler] [-v variable] fifo function
The -c
option adds the call stack to the exception messages.
The -d
option enables debug output.
The -e
option enables command exceptions.
The -h
option allows the user to substitute their own command exception handler.
The -k
option adds the call stack to the debug output.
The -o
option replaces the default output file which is /dev/fd/2
.
The -u
option allows the user to substitute their own unhandled exception handler.
The -v
option allows the user the option to pass back values though the use of Command Substitution.
The fifo
is the fifo filename.
The function function
is called by trycatchfinally
as a subprocess.
Note: The
cdko
options were removed to simplify the script.
The syntax for the catch
command is given below.
catch [[-enoprt] list ...] ...
The options are defined below. The value for the first list is the status. Subsquent values are the messages. If the there are more messages than lists, then the remaining messages are ignored.
-e
means [[ $value == "$string" ]]
(the value has to match at least one string in the list)
-n
means [[ $value != "$string" ]]
(the value can not match any of the strings in the list)
-o
means [[ $value != $pattern ]]
(the value can not match any of the patterns in the list)
-p
means [[ $value == $pattern ]]
(the value has to match at least one pattern in the list)
-r
means [[ $value =~ $regex ]]
(the value has to match at least one extended regular expression in the list)
-t
means [[ ! $value =~ $regex ]]
(the value can not match any of the extended regular expressions in the list)
The try/catch/finally
script is given below. To simplify the script for this answer, most of the error checking was removed. This reduced the size by 64%. A complete copy of this script can be found at my other answer.
shopt -s expand_aliases
alias try='{ common.Try'
alias yrt='EchoExitStatus; common.yrT; }'
alias catch='{ while common.Catch'
alias hctac='common.hctaC; done; }'
alias finally='{ common.Finally'
alias yllanif='common.yllaniF; }'
DefaultErrHandler() {
echo "Orginal Status: $common_status"
echo "Exception Type: ERR"
}
exception() {
let "common_status = 10#$1"
shift
common_messages=()
for message in "$@"; do
common_messages+=("$message")
done
}
throw() {
local "message"
if [[ $# -gt 0 ]]; then
let "common_status = 10#$1"
shift
for message in "$@"; do
echo "$message" >"$common_fifo"
done
elif [[ ${#common_messages[@]} -gt 0 ]]; then
for message in "${common_messages[@]}"; do
echo "$message" >"$common_fifo"
done
fi
chmod "0400" "$common_fifo"
exit "$common_status"
}
common.ErrHandler() {
common_status=$?
trap ERR
if [[ -w "$common_fifo" ]]; then
if [[ $common_options != *e* ]]; then
common_status="0"
return
fi
eval "${common_errHandler:-} \"${BASH_LINENO[0]}\" \"${BASH_SOURCE[1]}\" \"${FUNCNAME[1]}\" >$common_fifo <$common_fifo"
chmod "0400" "$common_fifo"
fi
if [[ common_trySubshell -eq BASH_SUBSHELL ]]; then
return
else
exit "$common_status"
fi
}
common.Try() {
common_status="0"
common_subshell="$common_trySubshell"
common_trySubshell="$BASH_SUBSHELL"
common_messages=()
}
common.yrT() {
local "status=$?"
if [[ common_status -ne 0 ]]; then
local "message=" "eof=TRY_CATCH_FINALLY_END_OF_MESSAGES_$RANDOM"
chmod "0600" "$common_fifo"
echo "$eof" >"$common_fifo"
common_messages=()
while read "message"; do
[[ $message != *$eof ]] || break
common_messages+=("$message")
done <"$common_fifo"
fi
common_trySubshell="$common_subshell"
}
common.Catch() {
[[ common_status -ne 0 ]] || return "1"
local "parameter" "pattern" "value"
local "toggle=true" "compare=p" "options=$-"
local -i "i=-1" "status=0"
set -f
for parameter in "$@"; do
if "$toggle"; then
toggle="false"
if [[ $parameter =~ ^-[notepr]$ ]]; then
compare="${parameter#-}"
continue
fi
fi
toggle="true"
while "true"; do
eval local "patterns=($parameter)"
if [[ ${#patterns[@]} -gt 0 ]]; then
for pattern in "${patterns[@]}"; do
[[ i -lt ${#common_messages[@]} ]] || break
if [[ i -lt 0 ]]; then
value="$common_status"
else
value="${common_messages[i]}"
fi
case $compare in
[ne]) [[ ! $value == "$pattern" ]] || break 2;;
[op]) [[ ! $value == $pattern ]] || break 2;;
[tr]) [[ ! $value =~ $pattern ]] || break 2;;
esac
done
fi
if [[ $compare == [not] ]]; then
let "++i,1"
continue 2
else
status="1"
break 2
fi
done
if [[ $compare == [not] ]]; then
status="1"
break
else
let "++i,1"
fi
done
[[ $options == *f* ]] || set +f
return "$status"
}
common.hctaC() {
common_status="0"
}
common.Finally() {
:
}
common.yllaniF() {
[[ common_status -eq 0 ]] || throw
}
caught() {
[[ common_status -eq 0 ]] || return 1
}
EchoExitStatus() {
return "${1:-$?}"
}
EnableThrowOnError() {
[[ $common_options == *e* ]] || common_options+="e"
}
DisableThrowOnError() {
common_options="${common_options/e}"
}
GetStatus() {
echo "$common_status"
}
SetStatus() {
let "common_status = 10#$1"
}
GetMessage() {
echo "${common_messages[$1]}"
}
MessageCount() {
echo "${#common_messages[@]}"
}
CopyMessages() {
if [[ ${#common_messages} -gt 0 ]]; then
eval "$1=(\"\${common_messages[@]}\")"
else
eval "$1=()"
fi
}
common.GetOptions() {
local "opt"
let "OPTIND = 1"
let "OPTERR = 0"
while getopts ":cdeh:ko:u:v:" opt "$@"; do
case $opt in
e) [[ $common_options == *e* ]] || common_options+="e";;
h) common_errHandler="$OPTARG";;
u) common_unhandled="$OPTARG";;
v) common_command="$OPTARG";;
esac
done
shift "$((OPTIND - 1))"
common_fifo="$1"
shift
common_function="$1"
chmod "0600" "$common_fifo"
}
DefaultUnhandled() {
local -i "i"
echo "-------------------------------------------------"
echo "TryCatchFinally: Unhandeled exception occurred"
echo "Status: $(GetStatus)"
echo "Messages:"
for ((i=0; i<$(MessageCount); i++)); do
echo "$(GetMessage "$i")"
done
echo "-------------------------------------------------"
}
TryCatchFinally() {
local "common_errHandler=DefaultErrHandler"
local "common_unhandled=DefaultUnhandled"
local "common_options="
local "common_fifo="
local "common_function="
local "common_flags=$-"
local "common_trySubshell=-1"
local "common_subshell"
local "common_status=0"
local "common_command="
local "common_messages=()"
local "common_handler=$(trap -p ERR)"
[[ -n $common_handler ]] || common_handler="trap ERR"
common.GetOptions "$@"
shift "$((OPTIND + 1))"
[[ -z $common_command ]] || common_command+="=$"
common_command+='("$common_function" "$@")'
set -E
set +e
trap "common.ErrHandler" ERR
try
eval "$common_command"
yrt
catch; do
"$common_unhandled" >&2
hctac
[[ $common_flags == *E* ]] || set +E
[[ $common_flags != *e* ]] || set -e
[[ $common_flags != *f* || $- == *f* ]] || set -f
[[ $common_flags == *f* || $- != *f* ]] || set +f
eval "$common_handler"
}
Below is an example, which assumes the above script is stored in the file named simple
. The makefifo
file contains the script described in this answer. The assumption is made that the file named 4444kkkkk
does not exist, therefore causing an exception to occur. The error message output from the ls 4444kkkkk
command is automatically suppressed until inside the appropriate catch
block.
#!/bin/bash
#
if [[ $0 != ${BASH_SOURCE[0]} ]]; then
bash "${BASH_SOURCE[0]}" "$@"
return
fi
source simple
source makefifo
MyFunction3() {
echo "entered MyFunction3" >&4
echo "This is from MyFunction3"
ls 4444kkkkk
echo "leaving MyFunction3" >&4
}
MyFunction2() {
echo "entered MyFunction2" >&4
value="$(MyFunction3)"
echo "leaving MyFunction2" >&4
}
MyFunction1() {
echo "entered MyFunction1" >&4
local "flag=false"
try
(
echo "start of try" >&4
MyFunction2
echo "end of try" >&4
)
yrt
catch "[1-3]" "*" "Exception\ Type:\ ERR"; do
echo 'start of catch "[1-3]" "*" "Exception\ Type:\ ERR"'
local -i "i"
echo "-------------------------------------------------"
echo "Status: $(GetStatus)"
echo "Messages:"
for ((i=0; i<$(MessageCount); i++)); do
echo "$(GetMessage "$i")"
done
echo "-------------------------------------------------"
break
echo 'end of catch "[1-3]" "*" "Exception\ Type:\ ERR"'
hctac >&4
catch "1 3 5" "*" -n "Exception\ Type:\ ERR"; do
echo 'start of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"'
echo "-------------------------------------------------"
echo "Status: $(GetStatus)"
[[ $(MessageCount) -le 1 ]] || echo "$(GetMessage "1")"
echo "-------------------------------------------------"
break
echo 'end of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"'
hctac >&4
catch; do
echo 'start of catch' >&4
echo "failure"
flag="true"
echo 'end of catch' >&4
hctac
finally
echo "in finally"
yllanif >&4
"$flag" || echo "success"
echo "leaving MyFunction1" >&4
} 2>&6
ErrHandler() {
echo "EOF"
DefaultErrHandler "$@"
echo "Function: $3"
while read; do
[[ $REPLY != *EOF ]] || break
echo "$REPLY"
done
}
set -u
echo "starting" >&2
MakeFIFO "6"
TryCatchFinally -e -h ErrHandler -o /dev/fd/4 -v result /dev/fd/6 MyFunction1 4>&2
echo "result=$result"
exec >&6-
The above script was tested using GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin17)
. The output, from running this script, is shown below.
starting
entered MyFunction1
start of try
entered MyFunction2
entered MyFunction3
start of catch "[1-3]" "*" "Exception\ Type:\ ERR"
-------------------------------------------------
Status: 1
Messages:
Orginal Status: 1
Exception Type: ERR
Function: MyFunction3
ls: 4444kkkkk: No such file or directory
-------------------------------------------------
start of catch
end of catch
in finally
leaving MyFunction1
result=failure
Another example which uses a throw
can be created by replacing function MyFunction3
with the script shown below.
MyFunction3() {
echo "entered MyFunction3" >&4
echo "This is from MyFunction3"
throw "3" "Orginal Status: 3" "Exception Type: throw"
echo "leaving MyFunction3" >&4
}
The syntax for the throw
command is given below. If no parameters are present, then status and messages stored in the variables are used instead.
throw [status] [message ...]
The output, from executing the modified script, is shown below.
starting
entered MyFunction1
start of try
entered MyFunction2
entered MyFunction3
start of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"
-------------------------------------------------
Status: 3
Exception Type: throw
-------------------------------------------------
start of catch
end of catch
in finally
leaving MyFunction1
result=failure
Since the quickest, shortest answer is in a comment (from Jeff) and has a typo, here it is corrected and in full:
sales['time_hour'] = pd.DatetimeIndex(sales['timestamp']).hour
Yes, you can. I have a 64-bit Debian running in VMware on Windows XP 32-Bit. As long as you set the Guest to use two processors, it will work just fine.
Yet another approach is ISNULL().
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = ISNULL(@ABC, [ABC]),
[ABCD] = ISNULL(@ABCD, [ABCD])
The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.
select COALESCE(null, null, 1, 'two') --returns 1
select COALESCE(null, null, null, 'two') --returns 'two'
You could use AsyncTask
, you'll have to customize to fit your needs, but something like the following
Async task has three primary methods:
onPreExecute()
- most commonly used for setting up and starting a progress dialog
doInBackground()
- Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).
onPostExecute()
- Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.First we will start the class, initialize a String
to hold the results outside of the methods but inside the class, then run the onPreExecute()
method setting up a simple progress dialog.
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
Then we need to set up the connection and how we want to handle the response:
@Override
protected Void doInBackground(String... params) {
String url_select = "http://yoururlhere.com";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
} // protected Void doInBackground(String... params)
Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
for(i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String name = jObject.getString("name");
String tab1_text = jObject.getString("tab1_text");
int active = jObject.getInt("active");
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
For parsing do this-
$http.jsonp(url).
success(function(data, status, headers, config) {
//what do I do here?
$scope.data=data;
}).
Or you can use `$scope.data=JSON.Stringify(data);
In Angular template you can use it as
{{data}}
From: http://nginx.org/r/large_client_header_buffers
Syntax:
large_client_header_buffers
number
size
;
Default:large_client_header_buffers 4 8k;
Context: http, serverSets the maximum
number
andsize
of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.
so you need to change the size parameter at the end of that line to something bigger for your needs.
This was the only code that worked for me:
element.removeProp('disabled')
Note that it's removeProp
and not removeAttr
.
I'm using jQuery 2.1.3
here.
You can use jQuery’s show()
and hide()
methods. Like below:
JQuery:
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var val = $(this).attr("value");
var target = $("." + val);
$(".msg").not(target).hide();
$(target).show();
});
});
HTML:
<input type="radio" name="color" value="yellow"> Yellow
<input type="radio" name="color" value="red"> Red
<input type="radio" name="color" value="green"> Green
<div class="yellow msg">You have selected Yellow</div>
<div class="red msg">You have selected Red</div>
<div class="green msg">You have selected Green</div>
Here is an example: Show/hide DIV based on Radio Button click
This is great for creating sample data. Example: put all testing data in a directory called "test-create-volume-123", then after your test is done, zap the entire directory. By generating exactly three digits, you don't have weird sorting issues.
printf '%02d\n' $((1 + RANDOM % 100))
This scales down, e.g. to one digit:
printf '%01d\n' $((1 + RANDOM % 10))
It scales up, but only to four digits. See above as to why :)
perl -e 'map { $on=$_; s/ /_/; rename($on, $_) or warn $!; } <*>;'
Match et replace space > underscore of all files in current directory
Use this :
List<String> splitString = (List<String>) Arrays.asList(jobtype.split(","));
According to protocol documentation there are at least three options website designers can use to inform sitemap.xml location to search engines:
So, unless they have chosen to publish the sitemap location on their robots.txt file, you cannot really know where they have put their sitemap.xml files.
I had similar issue where local build was working fine however when I push my branch onto heroku it would fail to build. Issue was that I had some devDependencies in my package.json which were not installed during npm install which was causing my build to fail.
If you need access to packages declared under devDependencies in a different buildpack or at runtime, then you can set NPM_CONFIG_PRODUCTION=false or YARN_PRODUCTION=false
to skip the pruning step.
Also you can move you devDependencies into dependencies...
Good guestion! -- where I have not yet found a satisfying answer for my case, the answer I provide here works for me, but may not be future proof...
If one uses gcc (clang?) and have -Werror
and -Wbad-function-cast
defined,
int val = (int)pow(10,9);
will result:
error: cast from function call of type 'double' to non-matching type 'int' [-Werror=bad-function-cast]
(for a good reason, overflow and where values are rounded needs to be thought out)
EDIT: 2020-08-30: So, my use case casting the value from function returning double to int, and chose pow() to represent that in place of a private function somewhere. Then I sidestepped thinking pow() more. (See comments more why pow() used below could be problematic...).
After properly thought out (that parameters to pow() are good), int val = pow(10,9);
seems to work with gcc 9.2 x86-64 ...
but note:
printf("%d\n", pow(10,4));
may output e.g.
-1121380856
(did for me) where
int i = pow(10,4); printf("%d\n", i);
printed
10000
in one particular case I tried.
Using Future described in above answers does the job, but a bit less significantly as f.get(), blocks the thread until it gets the result, which violates concurrency.
Best solution is to use Guava's ListenableFuture. An example :
ListenableFuture<Void> future = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1, new NamedThreadFactory).submit(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
someBackgroundTask();
}
});
Futures.addCallback(future, new FutureCallback<Long>()
{
@Override
public void onSuccess(Long result)
{
doSomething();
}
@Override
public void onFailure(Throwable t)
{
}
};
I've encountered string, which had mixings of English, Russian and some other alphabets, which caused exception. I need only Russian and English, and this currently works for me:
ec1 = Encoding::Converter.new "UTF-8","Windows-1251",:invalid=>:replace,:undef=>:replace,:replace=>""
ec2 = Encoding::Converter.new "Windows-1251","UTF-8",:invalid=>:replace,:undef=>:replace,:replace=>""
t = ec2.convert ec1.convert t
You tried:
sudo apt-get install oracle-java6-installer --reinstall
and:
sudo update-alternatives --config keytool
I am using a UISplitViewController with a navigationcontroller and a tableviewcontroller. This worked for me in the master view after trying many solutions here:
float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if (systemVersion >= 7.0f) {
// Move the view down 20 pixels
CGRect bounds = self.view.bounds;
bounds.origin.y -= 20.0;
[self.navigationController.view setBounds:bounds];
// Create a solid color background for the status bar
CGRect statusFrame = CGRectMake(0.0, -20.0, bounds.size.width, 20);
UIView* statusBar = [[UIView alloc] initWithFrame:statusFrame];
statusBar.backgroundColor = [UIColor whiteColor];
[statusBar setAlpha:1.0f];
[statusBar setOpaque:YES];
[self.navigationController.view addSubview:statusBar];
}
It's similar to Hot Licks' solution but applies the subview to the navigationController.
Not a complete answer, but one specific situation where I've received this is when trying to access an object that 'died' because I tried to use autorelease:
netObjectDefinedInMyHeader = [[[MyNetObject alloc] init] autorelease];
So for example, I was actually passing this as an object to 'notify' (registered it as a listener, observer, whatever idiom you like) but it had already died once the notification was sent and I'd get the EXC_BAD_ACCESS. Changing it to [[MyNetObject alloc] init]
and releasing it later as appropriate solved the error.
Another reason this may happen is for example if you pass in an object and try to store it:
myObjectDefinedInHeader = aParameterObjectPassedIn;
Later when trying to access myObjectDefinedInHeader you may get into trouble. Using:
myObjectDefinedInHeader = [aParameterObjectPassedIn retain];
may be what you need. Of course these are just a couple of examples of what I've ran into and there are other reasons, but these can prove elusive so I mention them. Good luck!
You can use DateTime::createFromFormat()
for this purpose:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
return $d && $d->format($format) === $date;
}
[Function taken from this answer. Also on php.net. Originally written by Glavic.]
Test cases:
var_dump(validateDate('2013-13-01')); // false
var_dump(validateDate('20132-13-01')); // false
var_dump(validateDate('2013-11-32')); // false
var_dump(validateDate('2012-2-25')); // false
var_dump(validateDate('2013-12-01')); // true
var_dump(validateDate('1970-12-01')); // true
var_dump(validateDate('2012-02-29')); // true
var_dump(validateDate('2012', 'Y')); // true
var_dump(validateDate('12012', 'Y')); // false
Thanks @Kit Ho for your answer. I used your code and found that I kept running into errors where my InputStream was always null and ClassNotFound exceptions when the JSONObject was being created. Here's my version of your code which does the trick for me:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
public class JSONParsing {
public static void main(String[] args) throws Exception {
File f = new File("file.json");
if (f.exists()){
InputStream is = new FileInputStream("file.json");
String jsonTxt = IOUtils.toString(is, "UTF-8");
System.out.println(jsonTxt);
JSONObject json = new JSONObject(jsonTxt);
String a = json.getString("1000");
System.out.println(a);
}
}
}
I found this answer to be enlightening about the difference between FileInputStream and getResourceAsStream. Hope this helps someone else too.
The function :getargc
below may be what you're looking for.
@echo off
setlocal enableextensions enabledelayedexpansion
call :getargc argc %*
echo Count is %argc%
echo Args are %*
endlocal
goto :eof
:getargc
set getargc_v0=%1
set /a "%getargc_v0% = 0"
:getargc_l0
if not x%2x==xx (
shift
set /a "%getargc_v0% = %getargc_v0% + 1"
goto :getargc_l0
)
set getargc_v0=
goto :eof
It basically iterates once over the list (which is local to the function so the shifts won't affect the list back in the main program), counting them until it runs out.
It also uses a nifty trick, passing the name of the return variable to be set by the function.
The main program just illustrates how to call it and echos the arguments afterwards to ensure that they're untouched:
C:\Here> xx.cmd 1 2 3 4 5
Count is 5
Args are 1 2 3 4 5
C:\Here> xx.cmd 1 2 3 4 5 6 7 8 9 10 11
Count is 11
Args are 1 2 3 4 5 6 7 8 9 10 11
C:\Here> xx.cmd 1
Count is 1
Args are 1
C:\Here> xx.cmd
Count is 0
Args are
C:\Here> xx.cmd 1 2 "3 4 5"
Count is 3
Args are 1 2 "3 4 5"
Navigate to settings and locate the base.py file Set the allowed hosts to ALLOWED_HOSTS = ['*']
After a fair amount of work, I was able to get it to build on Ubuntu 12.04 x86 and Debian 7.4 x86_64. I wrote up a guide below. Can you please try following it to see if it resolves the issue?
If not please let me know where you get stuck.
Install Common Dependencies
sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev
Install NumArray 1.5.2
wget http://goo.gl/6gL0q3 -O numarray-1.5.2.tgz
tar xfvz numarray-1.5.2.tgz
cd numarray-1.5.2
sudo python setup.py install
Install Numeric 23.8
wget http://goo.gl/PxaHFW -O numeric-23.8.tgz
tar xfvz numeric-23.8.tgz
cd Numeric-23.8
sudo python setup.py install
Install HDF5 1.6.5
wget ftp://ftp.hdfgroup.org/HDF5/releases/hdf5-1.6/hdf5-1.6.5.tar.gz
tar xfvz hdf5-1.6.5.tar.gz
cd hdf5-1.6.5
./configure --prefix=/usr/local
sudo make
sudo make install
Install Nanoengineer
git clone https://github.com/kanzure/nanoengineer.git
cd nanoengineer
./bootstrap
./configure
make
sudo make install
Troubleshooting
On Debian Jessie, you will receive the error message that cant pants mentioned. There seems to be an issue in the automake scripts. x86_64-linux-gnu-gcc
is inserted in CFLAGS
and gcc
will interpret that as a name of one of the source files. As a workaround, let's create an empty file with that name. Empty so that it won't change the program and that very name so that compiler picks it up. From the cloned nanoengineer directory, run this command to make gcc happy (it is a hack yes, but it does work) ...
touch sim/src/x86_64-linux-gnu-gcc
If you receive an error message when attemping to compile HDF5 along the lines of: "error: call to ‘__open_missing_mode’ declared with attribute error: open with O_CREAT in second argument needs 3 arguments", then modify the file perform/zip_perf.c, line 548 to look like the following and then rerun make...
output = open(filename, O_RDWR | O_CREAT, S_IRUSR|S_IWUSR);
If you receive an error message about Numeric/arrayobject.h not being found when building Nanoengineer, try running
export CPPFLAGS=-I/usr/local/include/python2.7
./configure
make
sudo make install
If you receive an error message similar to "TRACE_PREFIX undeclared", modify the file sim/src/simhelp.c lines 38 to 41 to look like this and re-run make:
#ifdef DISTUTILS
static char tracePrefix[] = "";
#else
static char tracePrefix[] = "";
If you receive an error message when trying to launch NanoEngineer-1 that mentions something similar to "cannot import name GL_ARRAY_BUFFER_ARB", modify the lines in the following files
/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/setup_draw.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/GLPrimitiveBuffer.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/prototype/test_drawing.py
that look like this:
from OpenGL.GL import GL_ARRAY_BUFFER_ARB
from OpenGL.GL import GL_ELEMENT_ARRAY_BUFFER_ARB
to look like this:
from OpenGL.GL.ARB.vertex_buffer_object import GL_ARRAY_BUFFER_AR
from OpenGL.GL.ARB.vertex_buffer_object import GL_ELEMENT_ARRAY_BUFFER_ARB
I also found an additional troubleshooting text file that has been removed, but you can find it here
some resources:
ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:
arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]
or using fromELF utility(built in most IDEs such as ADS though):
fromelf -bin -o [binary-output-file] [elf-input-file]
First is correct way of checking whether a field value is null
while later won't work the way you expect it to because null
is special value which does not equal anything, so you can't use equality comparison using =
for it.
So when you need to check if a field value is null
or not, use:
where x is null
instead of:
where x = null
Is your link to another web page? If so, perhaps you could put the variable in the query string and set the session variable when the page being linked to is loaded.
So the link looks like this:
<a href="home.php?variable=value" name="home">home</a>
And the homge page would parse the query string and set the session variable.
You have to actually call some method to create the directories. Just creating a file
object will not create the corresponding file or directory on the file system.
You can use File#mkdirs()
method to create the directory: -
theFile.mkdirs();
Difference between File#mkdir()
and File#mkdirs()
is that, the later will create any intermediate directory if it does not exist.
While many of the above answers are completely valid, no one seems to answer your question completely, specifically the part:
I don't know if I am right, but to determine probabilities I think I need to fit my data to a theoretical distribution that is the most suitable to describe my data. I assume that some kind of goodness of fit test is needed to determine the best model.
This is the process you're describing of using some theoretical distribution and fitting the parameters to your data and there's some excellent answers how to do this.
However, it's also possible to use a non-parametric approach to your problem, which means you do not assume any underlying distribution at all.
By using the so-called Empirical distribution function which equals: Fn(x)= SUM( I[X<=x] ) / n. So the proportion of values below x.
As was pointed out in one of the above answers is that what you're interested in is the inverse CDF (cumulative distribution function), which is equal to 1-F(x)
It can be shown that the empirical distribution function will converge to whatever 'true' CDF that generated your data.
Furthermore, it is straightforward to construct a 1-alpha confidence interval by:
L(X) = max{Fn(x)-en, 0}
U(X) = min{Fn(x)+en, 0}
en = sqrt( (1/2n)*log(2/alpha)
Then P( L(X) <= F(X) <= U(X) ) >= 1-alpha for all x.
I'm quite surprised that PierrOz answer has 0 votes, while it's a completely valid answer to the question using a non-parametric approach to estimating F(x).
Note that the issue you mention of P(X>=x)=0 for any x>47 is simply a personal preference that might lead you to chose the parametric approach above the non-parametric approach. Both approaches however are completely valid solutions to your problem.
For more details and proofs of the above statements I would recommend having a look at 'All of Statistics: A Concise Course in Statistical Inference by Larry A. Wasserman'. An excellent book on both parametric and non-parametric inference.
EDIT: Since you specifically asked for some python examples it can be done using numpy:
import numpy as np
def empirical_cdf(data, x):
return np.sum(x<=data)/len(data)
def p_value(data, x):
return 1-empirical_cdf(data, x)
# Generate some data for demonstration purposes
data = np.floor(np.random.uniform(low=0, high=48, size=30000))
print(empirical_cdf(data, 20))
print(p_value(data, 20)) # This is the value you're interested in
Windows XP has the Windows Firewall which can interfere with network traffic if not configured properly. You can turn off the Windows Firewall, if you have administrator privileges, by accessing the Windows Firewall applet through the Control Panel. If your application works with the Windows Firewall turned off then the problem is probably due to the settings of the firewall.
We have an application which runs on multiple PCs communicating using UDP/IP and we have been doing experiments so that the application can run on a PC with a user who does not have administrator privileges. In order for our application to communicate between multiple PCs we have had to use an administrator account to modify the Windows Firewall settings.
In our application, one PC is designated as the server and the others are clients in a server/client group and there may be several groups on the same subnet.
The first change was to use the functionality of the Exceptions tab of the Windows Firewall applet to create an exception for the port that we use for communication.
We are using host name lookup so that the clients can locate their assigned server by using the computer name which is composed of a mnemonic prefix with a dash followed by an assigned terminal number (for instance SERVER100-1). This allows several servers with their assigned clients to coexist on the same subnet. The client uses its prefix to generate the computer name for the assigned server and to then use host name lookup to discover the IP address of the assigned server.
What we found is that the host name lookup using the computer name (assigned through the Computer Name tab of the System Properties dialog) would not work unless the server PC's Windows Firewall had the File and Printer Sharing Service port enabled.
So we had to make two changes: (1) setup an exception for the port we used for communication and (2) enable File and Printer Service in the Exceptions tab to allow for the host name lookup.
** EDIT **
You may also find this Microsoft Knowledge Base article on helpful on Windows XP networking.
And see this article on NETBIOS name resolution in Windows.
No, it is not okay to put a link
element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):
“This element defines a link. Unlike
A
, it may only appear in theHEAD
section of a document, although it may appear any number of times.”
Try following code in KeyPress event of textbox
if (char.IsLetter(e.KeyChar) == false &
Convert.ToString(e.KeyChar) != Microsoft.VisualBasic.Constants.vbBack)
e.Handled = true
Be sure to stringify
before sending. I leaned on the libraries too much and thought they would encode properly based on the contentType I was posting, but they do not seem to.
Works:
$.ajax({
url: _saveAllDevicesUrl
, type: 'POST'
, contentType: 'application/json'
, data: JSON.stringify(postData) //stringify is important
, success: _madeSave.bind(this)
});
I prefer this method to using a plugin like $.toJSON, although that does accomplish the same thing.
Unlike classes, case classes are just used to hold data.
Case classes are flexible for data-centric applications, which means you can define data fields in case class and define business logic in a companion object. In this way, you are separating the data from the business logic.
With the copy method, you can inherit any or all required properties from the source and can change them as you like.
SELECT CONVERT(date, GETDATE())
This SQL query gives output similar to \dx
:
SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", c.description AS "Description"
FROM pg_catalog.pg_extension e
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace
LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass
ORDER BY 1;
Thanks to https://blog.dbi-services.com/listing-the-extensions-available-in-postgresql/
You have to select and send the form data as well:
$("#post-btn").click(function(){
$.post("process.php", $("#reg-form").serialize(), function(data) {
alert(data);
});
});
Take a look at the documentation for the jQuery serialize
method, which encodes the data from the form fields into a data-string to be sent to the server.
Use the Task manager to find the Service and kill it from there using End Task. Always does the trick for me.
If you have made the service yourself, consider removing Long running operations from the OnStart event, usually that is what causes the Service to be non responsive.
Heredoc syntax can be very useful:
// start the string with 3 <'s and then a word
// it doesn't have to be any particular string or length
// but it's common to make it in all caps.
echo <<< EOT
in here is your string
it has the same variable substitution rules
as a double quoted string.
when you end it, put the indicator word at the
start of the line (no spaces before it)
and put a semicolon after it
EOT;
All of this works for me:
@Echo Off
Echo Directory = %~dp0
Echo Object Name With Quotations=%0
Echo Object Name Without Quotes=%~0
Echo Bat File Drive = %~d0
Echo Full File Name = %~n0%~x0
Echo File Name Without Extension = %~n0
Echo File Extension = %~x0
Pause>Nul
Output:
Directory = D:\Users\Thejordster135\Desktop\Code\BAT\
Object Name With Quotations="D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat"
Object Name Without Quotes=D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat
Bat File Drive = D:
Full File Name = Path.bat
File Name Without Extension = Path
File Extension = .bat
In addition to what @inkedmn has pointed out, a static member is at the class level. Therefore, the said member is loaded into memory by the JVM once for that class (when the class is loaded). That is, there aren't n instances of a static member loaded for n instances of the class to which it belongs.
in scss
&::after{
content: url(images/RelativeProjectsArr.png);
margin-left:30px;
}
&:hover{
background-color:$turkiz;
color:#e5e7ef;
&::after{
content: url(images/RelativeProjectsArrHover.png);
}
}
If you install using bundler as suggested by gryzzly and the gem creates a binary then make sure you run it with bundle exec mygembinary
as the gem is stored in a bundler directory which is not visible on the normal gem path.
One really easy option which is often overlooked is to create a .rdlc report using Microsoft Reporting and export it to excel format. You can design it in visual studio and generate the file using:
localReport.Render("EXCELOPENXML", null, ((name, ext, encoding, mimeType, willSeek) => stream = new FileStream(name, FileMode.CreateNew)), out warnings);
You can also export it do .doc or .pdf, using "WORDOPENXML"
and "PDF"
respectively, and it's supported on many different platforms such as ASP.NET and SSRS.
It's much easier to make changes in a visual designer where you can see the results, and trust me, once you start grouping data, formatting group headers, adding new sections, you don't want to mess with dozens of XML nodes.
This is one approach:
from xlrd import open_workbook
class Arm(object):
def __init__(self, id, dsp_name, dsp_code, hub_code, pin_code, pptl):
self.id = id
self.dsp_name = dsp_name
self.dsp_code = dsp_code
self.hub_code = hub_code
self.pin_code = pin_code
self.pptl = pptl
def __str__(self):
return("Arm object:\n"
" Arm_id = {0}\n"
" DSPName = {1}\n"
" DSPCode = {2}\n"
" HubCode = {3}\n"
" PinCode = {4} \n"
" PPTL = {5}"
.format(self.id, self.dsp_name, self.dsp_code,
self.hub_code, self.pin_code, self.pptl))
wb = open_workbook('sample.xls')
for sheet in wb.sheets():
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
items = []
rows = []
for row in range(1, number_of_rows):
values = []
for col in range(number_of_columns):
value = (sheet.cell(row,col).value)
try:
value = str(int(value))
except ValueError:
pass
finally:
values.append(value)
item = Arm(*values)
items.append(item)
for item in items:
print item
print("Accessing one single value (eg. DSPName): {0}".format(item.dsp_name))
print
You don't have to use a custom class, you can simply take a dict()
. If you use a class however, you can access all values via dot-notation, as you see above.
Here is the output of the script above:
Arm object:
Arm_id = 1
DSPName = JaVAS
DSPCode = 1
HubCode = AGR
PinCode = 282001
PPTL = 1
Accessing one single value (eg. DSPName): JaVAS
Arm object:
Arm_id = 2
DSPName = JaVAS
DSPCode = 1
HubCode = AGR
PinCode = 282002
PPTL = 3
Accessing one single value (eg. DSPName): JaVAS
Arm object:
Arm_id = 3
DSPName = JaVAS
DSPCode = 1
HubCode = AGR
PinCode = 282003
PPTL = 5
Accessing one single value (eg. DSPName): JaVAS
I don't know why the first answer is the best one, I tried it and not working in fact, as @kalys.osmonov said, you can give text-align:center
to header
, but you have to make ul
as inline-block
rather than inline
, and also you have to notice that text-align
can be inherited which is not good to some degree, so the better way (not working below IE 9) is using margin
and transform
. Just remove float right
and margin;0 auto
from ul
, like below:
#header ul {
/* float: right; */
/* margin: 0 auto; */
display: inline-block;
margin-left: 50%; /* From parent width */
transform: translateX(-50%); /* use self width which can be unknown */
-ms-transform: translateX(-50%); /* For IE9 */
}
This way can fix the problem that making dynamic width of ul
center if you don't care IE8 etc.
For me I had a typo and my remote branch didn't exist
Use git branch -a
to list remote branches
I have a trouble may proof gradlew clean is not equal to ADT build clean. And Now I am struggling to get it fixed.
Here is what I got: I set a configProductID=11111 from my gradle.properties, from my build.gradle, I add
resValue "string", "ProductID", configProductID
If I do a build clean from ADT, the resource R.string.ProductID can be generated. Then I can do bellow command successfully.
gradlew assembleDebug
But, as I am trying to setup build server, I don't want help from ADT IDE, so I need to avoid using ADT build clean. Here comes my problem. Now I change my resource name from "ProductID" to "myProductID", I do:
gradlew clean
I get error
PS D:\work\wctposdemo> .\gradlew.bat clean
FAILURE: Build failed with an exception.
* Where:
Build file 'D:\work\wctposdemo\app\build.gradle'
* What went wrong:
Could not compile build file 'D:\work\wctposdemo\app\build.gradle'.
> startup failed:
General error during semantic analysis: Unsupported class file major version 57
If I try with:
.\gradlew.bat --recompile-scripts
I just get error of
Unknown command-line option '--recompile-scripts'.
in this code data
is a two dimensional array of table data
let oTable = document.getElementById('datatable-id');
let data = [...oTable.rows].map(t => [...t.children].map(u => u.innerText))
The shortest way! it's working for me, Where NA is my default value.
<td th:text="${ins.eValue!=null}? ${ins.eValue}:'NA'" />
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
$('#myId').val()
should do it, failing that I would try:
$('#myId option:selected').val()
objects are passed by reference, primitives are passed by value.
String is not a primitive, it is an object, and it is a special case of object.
This is for memory-saving purpose. In JVM, there is a string pool. For every string created, JVM will try to see if the same string exist in the string pool, and point to it if there were already one.
public class TestString
{
private static String a = "hello world";
private static String b = "hello world";
private static String c = "hello " + "world";
private static String d = new String("hello world");
private static Object o1 = new Object();
private static Object o2 = new Object();
public static void main(String[] args)
{
System.out.println("a==b:"+(a == b));
System.out.println("a==c:"+(a == c));
System.out.println("a==d:"+(a == d));
System.out.println("a.equals(d):"+(a.equals(d)));
System.out.println("o1==o2:"+(o1 == o2));
passString(a);
passString(d);
}
public static void passString(String s)
{
System.out.println("passString:"+(a == s));
}
}
/* OUTPUT */
a==b:true
a==c:true
a==d:false
a.equals(d):true
o1==o2:false
passString:true
passString:false
the == is checking for memory address (reference), and the .equals is checking for contents (value)
Another good approach and one that is a bit more elegant is as follows:
watch:{
'item.someOtherProp': function (newVal, oldVal){
//to work with changes in someOtherProp
},
'item.prop': function(newVal, oldVal){
//to work with changes in prop
}
}
(I learned this approach from @peerbolte in the comment here)
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
I had this problem since updating to the iOS 9 SDK when I was calling a block that did UI updates within an NSURLConnection async request completion handler. Putting the block call in a dispatch_async using dispatch_main_queue solved the issue.
It worked fine in iOS 8.
In the shell, you can't execute more than one statement at a time:
>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement
You need to execute them one by one:
>>> x = 5
>>> y = 6
>>>
When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.
One way is to: (Assumes index column begins at A1)
MsgBox Range("A1").End(xlDown).Row
Which is looking for the 1st unoccupied cell downwards from A1 and showing you its ordinal row number.
You can select the next empty cell with:
Range("A1").End(xlDown).Offset(1, 0).Select
If you need the end of a dataset (including blanks), try: Range("A:A").SpecialCells(xlLastCell).Row
To expand on Konrad's comment:
As a consequence, a purely functional program always yields the same value for an input, and the order of evaluation is not well-defined;
Because of this, functional code is generally easier to parallelize. Since there are (generally) no side effects of the functions, and they (generally) just act on their arguments, a lot of concurrency issues go away.
Functional programming is also used when you need to be capable of proving your code is correct. This is much harder to do with procedural programming (not easy with functional, but still easier).
Disclaimer: I haven't used functional programming in years, and only recently started looking at it again, so I might not be completely correct here. :)
I had the same issues as Tyler Sheaffer.
I implemented his solution in Swift and it solved my problems.
Swift 3.0:
final class UITableViewWithReloadCompletion: UITableView {
private var reloadDataCompletionBlock: (() -> Void)?
override func layoutSubviews() {
super.layoutSubviews()
reloadDataCompletionBlock?()
reloadDataCompletionBlock = nil
}
func reloadDataWithCompletion(completion: @escaping () -> Void) {
reloadDataCompletionBlock = completion
self.reloadData()
}
}
Swift 2:
class UITableViewWithReloadCompletion: UITableView {
var reloadDataCompletionBlock: (() -> Void)?
override func layoutSubviews() {
super.layoutSubviews()
self.reloadDataCompletionBlock?()
self.reloadDataCompletionBlock = nil
}
func reloadDataWithCompletion(completion:() -> Void) {
reloadDataCompletionBlock = completion
self.reloadData()
}
}
Example Usage:
tableView.reloadDataWithCompletion() {
// reloadData is guaranteed to have completed
}
Any - boolean function that returns true when any of object in list satisfies condition set in function parameters. For example:
List<string> strings = LoadList();
boolean hasNonEmptyObject = strings.Any(s=>string.IsNullOrEmpty(s));
Where - function that returns list with all objects in list that satisfy condition set in function parameters. For example:
IEnumerable<string> nonEmptyStrings = strings.Where(s=> !string.IsNullOrEmpty(s));
Exists - basically the same as any but it's not generic - it's defined in List class, while Any is defined on IEnumerable interface.
I think the best and simplest solution is (KISS):
double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;
METLIFE ENGLISH LANGUAGE (MEL)!
I worked for a company that wrote tools to automatically find and fix Y2K problems in Cobol and PL/I. MetLife approached us with 2m lines of code they'd written in MEL, a language they developed in the late 50's or early 60's. MEL was a language that helped inspire Cobol, and its procedural code would look reasonably familiar to any modern Cobol programmer.
We had a strong developer take a crack at writing a translator to rip through MEL programs and correct identified dates. He actually got a demo going in a couple weeks, and he thought that another 3-4 weeks of work were all that would be needed to get it into shape for production. Great, we thought, and decided to take on the work.
Unfortunately, he hadn't really studied MEL's very primitive equivalent of the Cobol DATA DIVISION (where declarations go). It turned out each MEL program provided its own view of each input or output file, and it only declared those fields it was interested in. There might be 30 or 40 different takes on what an input file with variant records looked like. Talk about blind men and the elephant!
An exceptionally bright and driven guy then took over and worked out the semantics of identifying which record definitions described what file, a process made much harder by the presence of variant records in many files. He then wrote the algorighms to unify each set of alternate record definitions into a common record definition, and then mapping everything from old emulated Honeywell data types into new IBM mainframe types. It took two person years to get it all working.
I am on Mac Os. In my case, my host file was black. I added following entries (these entries should be there by default, but they weren't).
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
After re-running android studio, it prompted the sdk download.
The recommended way from Apple is to change the contentInset
of the UIScrollView
. It is a very elegant solution, because you do not have to mess with the contentSize
.
Following code is copied from the Keyboard Programming Guide, where the handling of this issue is explained. You should have a look into it.
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);
[scrollView setContentOffset:scrollPoint animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
Swift version:
func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardAppear(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardDisappear(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}
// Don't forget to unregister when done
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}
@objc func onKeyboardAppear(_ notification: NSNotification) {
let info = notification.userInfo!
let rect: CGRect = info[UIKeyboardFrameBeginUserInfoKey] as! CGRect
let kbSize = rect.size
let insets = UIEdgeInsetsMake(0, 0, kbSize.height, 0)
scrollView.contentInset = insets
scrollView.scrollIndicatorInsets = insets
// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
var aRect = self.view.frame;
aRect.size.height -= kbSize.height;
let activeField: UITextField? = [addressTextView, servicePathTextView, usernameTextView, passwordTextView].first { $0.isFirstResponder }
if let activeField = activeField {
if !aRect.contains(activeField.frame.origin) {
let scrollPoint = CGPoint(x: 0, y: activeField.frame.origin.y-kbSize.height)
scrollView.setContentOffset(scrollPoint, animated: true)
}
}
}
@objc func onKeyboardDisappear(_ notification: NSNotification) {
scrollView.contentInset = UIEdgeInsets.zero
scrollView.scrollIndicatorInsets = UIEdgeInsets.zero
}
Renew the certificate. This can be done for free using Greenlock which issues certificates via Let's Encrypt™ v2
'use strict';
var request = require('request');
var agentOptions;
var agent;
agentOptions = {
host: 'www.example.com'
, port: '443'
, path: '/'
, rejectUnauthorized: false
};
agent = new https.Agent(agentOptions);
request({
url: "https://www.example.com/api/endpoint"
, method: 'GET'
, agent: agent
}, function (err, resp, body) {
// ...
});
By using an agent
with rejectUnauthorized
you at least limit the security vulnerability to the requests that deal with that one site instead of making your entire node process completely, utterly insecure.
If you were using a self-signed cert you would add this option:
agentOptions.ca = [ selfSignedRootCaPemCrtBuffer ];
For trusted-peer connections you would also add these 2 options:
agentOptions.key = clientPemKeyBuffer;
agentOptions.cert = clientPemCrtSignedBySelfSignedRootCaBuffer;
It's unfortunate that process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
is even documented. It should only be used for debugging and should never make it into in sort of code that runs in the wild. Almost every library that runs atop https
has a way of passing agent options through. Those that don't should be fixed.
Perhaps not in the context that you have it, but you could use
SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA
You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.
This is related to multiple versions of same depenendency in the local repository .m2
go to ur eclipse > problems tab > see the errors > go the local .m2 folder
delete all the non relevant versions of the the dependency which you have added recently.
then try to rebuild the project.
If the structs only contain primitives or if you are interested in strict equality then you can do something like this:
int my_struct_cmp(const struct my_struct * lhs, const struct my_struct * rhs) { return memcmp(lhs, rsh, sizeof(struct my_struct)); }
However, if your structs contain pointers to other structs or unions then you will need to write a function that compares the primitives properly and make comparison calls against the other structures as appropriate.
Be aware, however, that you should have used memset(&a, sizeof(struct my_struct), 1) to zero out the memory range of the structures as part of your ADT initialization.
import java.text.DateFormatSymbols;
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month-1];
}
The output is actually dependent on the content type being requested. However, at minimum you should put the resource that was created in Location. Just like the Post-Redirect-Get pattern.
In my case I leave it blank until requested otherwise. Since that is the behavior of JAX-RS when using Response.created().
However, just note that browsers and frameworks like Angular do not follow 201's automatically. I have noted the behaviour in http://www.trajano.net/2013/05/201-created-with-angular-resource/
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xlsx"');
header('Cache-Control: max-age=0');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate');
header ('Pragma: public');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24'
- it is a performance killer:
DATE()
for all rows, including those, that don't matchIt is much faster to use
SELECT * FROM tablename
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'
as this will allow index use without calculation.
EDIT
As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read
SELECT * FROM tablename
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'
The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.
<customErrors defaultRedirect="~/404.aspx" mode="On">
<error statusCode="404" redirect="~/404.aspx"/>
</customErrors>
Code above is only for "Page Not Found Error-404" if file extension is known(.html,.aspx etc)
Beside it you also have set Customer Errors for extension not known or not correct as
.aspwx
or .vivaldo
. You have to add httperrors
settings in web.config
<httpErrors errorMode="Custom">
<error statusCode="404" prefixLanguageFilePath="" path="/404.aspx" responseMode="Redirect" />
</httpErrors>
<modules runAllManagedModulesForAllRequests="true"/>
it must be inside the <system.webServer>
</system.webServer>
The reason might be because the IPython module is not in your PYTHONPATH.
If you donwload IPython and then do python setup.py install
The setup doesn't add the module IPython to your python path. You might want to add it to your PYTHONPATH manually. It should work after you do :
export PYTHONPATH=/pathtoIPython:$PYTHONPATH
Add this line in your .bashrc or .profile to make it permanent.
Increase the Windows process limit to 3gb. (via boot.ini or Vista boot manager)
Typical Java programs compile into .jar files, which can be executed like .exe files provided the target machine has Java installed and that Java is in its PATH. From Eclipse you use the Export menu item from the File menu.
You can use following technique to dynamically load JS scripts and libraries on demand in your Angular project.
script.store.ts will contain the path of the script either locally or on a remote server and a name that will be used to load the script dynamically
interface Scripts {
name: string;
src: string;
}
export const ScriptStore: Scripts[] = [
{name: 'filepicker', src: 'https://api.filestackapi.com/filestack.js'},
{name: 'rangeSlider', src: '../../../assets/js/ion.rangeSlider.min.js'}
];
script.service.ts is an injectable service that will handle the loading of script, copy script.service.ts
as it is
import {Injectable} from "@angular/core";
import {ScriptStore} from "./script.store";
declare var document: any;
@Injectable()
export class ScriptService {
private scripts: any = {};
constructor() {
ScriptStore.forEach((script: any) => {
this.scripts[script.name] = {
loaded: false,
src: script.src
};
});
}
load(...scripts: string[]) {
var promises: any[] = [];
scripts.forEach((script) => promises.push(this.loadScript(script)));
return Promise.all(promises);
}
loadScript(name: string) {
return new Promise((resolve, reject) => {
//resolve if already loaded
if (this.scripts[name].loaded) {
resolve({script: name, loaded: true, status: 'Already Loaded'});
}
else {
//load script
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = this.scripts[name].src;
if (script.readyState) { //IE
script.onreadystatechange = () => {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
this.scripts[name].loaded = true;
resolve({script: name, loaded: true, status: 'Loaded'});
}
};
} else { //Others
script.onload = () => {
this.scripts[name].loaded = true;
resolve({script: name, loaded: true, status: 'Loaded'});
};
}
script.onerror = (error: any) => resolve({script: name, loaded: false, status: 'Loaded'});
document.getElementsByTagName('head')[0].appendChild(script);
}
});
}
}
Inject this ScriptService
wherever you need it and load js libs like this
this.script.load('filepicker', 'rangeSlider').then(data => {
console.log('script loaded ', data);
}).catch(error => console.log(error));
In a google script project you can create html files (example: index.html) or gs files (example:code.gs). The .gs files are executed on the server and you can use Logger.log as @Peter Herrman describes. However if the function is created in a .html file it is being executed on the user's browser and you can use console.log. The Chrome browser console can be viewed by Ctrl Shift J on Windows/Linux or Cmd Opt J on Mac
If you want to use Logger.log on an html file you can use a scriptlet to call the Logger.log function from the html file. To do so you would insert <? Logger.log(something) ?> replacing something with whatever you want to log. Standard scriptlets, which use the syntax <? ... ?>, execute code without explicitly outputting content to the page.
alternatively in c or c++ after including stdio.h
char d=(char)(7);
printf("%c\n",d);
(char)7 is called the bell character.
The problem you have is caused that you use the same ArrayList NodeList over all iterations in main for loop. Each iterations NodeList is enlarged by new elements.
After first loop, NodeList has 5 elements (PropertyStart,a,b,c,PropertyEnd) and list has 1 element (NodeList: (PropertyStart,a,b,c,PropertyEnd))
After second loop NodeList has 10 elements (PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd) and list has 2 elements (NodeList (with 10 elements), NodeList (with 10 elements))
To get you expectations you must replace
NodeList.addAll(nodes);
list.add(NodeList)
by
List childrenList = new ArrayList(nodes);
list.add(childrenList);
PS. Your code is not readable, keep Java code conventions to have readble code. For example is hard to recognize if NodeList is a class or object
You can use a CROSS JOIN
:
SELECT *
FROM ( SELECT SUM(Fdays) AS fDaysSum
FROM tblFieldDays
WHERE tblFieldDays.NameCode=35
AND tblFieldDays.WeekEnding=1) A -- use you real query here
CROSS JOIN (SELECT SUM(CHdays) AS hrsSum
FROM tblChargeHours
WHERE tblChargeHours.NameCode=35
AND tblChargeHours.WeekEnding=1) B -- use you real query here
This works for me in the current version 2.7.1
:
function colorizePercentageChart(myObjBar) {
var bars = myObjBar.data.datasets[0].data;
console.log(myObjBar.data.datasets[0]);
for (i = 0; i < bars.length; i++) {
var color = "green";
if(parseFloat(bars[i]) < 95){
color = "yellow";
}
if(parseFloat(bars[i]) < 50){
color = "red";
}
console.log(color);
myObjBar.data.datasets[0].backgroundColor[i] = color;
}
myObjBar.update();
}
Try -
Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)
As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?
You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.
In TorpedoQuery it look like this
Entity from = from(Entity.class);
where(from.getCode()).in("Joe", "Bob");
Query<Entity> select = select(from);
maybe you can try using
SELECT user_name
FROM user_master
WHERE upper(user_name) LIKE '%ME%'
The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use
yournumber.ToString("0.00");
What I want to say here is like some kind of add-on on @Suciu Lucian's answer.
The weird situation I ran into is that when I apply the solution of @Suciu Lucian in my file, it works in Chrome but not in Safari (and did not try in Firefox). After I studied the guide of styling table border published by w3.org, I found something alternative:
table.myTable{
border-spacing: 0;
}
table.myTable td{
border-bottom:1px solid red;
}
Yes you have to style the td
instead of the tr
.
Open Terminal and execute commands given below.
cd /etc
subl bashrc
subl denotes Sublime editor. You can replace subl with vi to open bashrc file in default editor. This will workout only if you have bashrc file, created earlier.
I've updated Bryan's code for my Sierra iMac:
# this version was tested OK vith macOs Sierra 10.12.5 (16F73) on oct 0th, 2017
# original ipa file must be store in current working directory
IPA="ipa-filename.ipa"
PROVISION="path-to.mobileprovision"
CERTIFICATE="hexadecimal-certificate-identifier" # must be in keychain
# identifier maybe retrieved by running: security find-identity -v -p codesigning
# unzip the ipa
unzip -q "$IPA"
# remove the signature
rm -rf Payload/*.app/_CodeSignature
# replace the provision
cp "$PROVISION" Payload/*.app/embedded.mobileprovision
# generate entitlements for current app
cd Payload/
codesign -d --entitlements - *.app > entitlements.plist
cd ..
mv Payload/entitlements.plist entitlements.plist
# sign with the new certificate and entitlements
/usr/bin/codesign -f -s "$CERTIFICATE" '--entitlements' 'entitlements.plist' Payload/*.app
# zip it back up
zip -qr resigned.ipa Payload
In PostgreSQL the system determines which table is meant by following a search path, which is a list of schemas to look in.
The first matching table in the search path is taken to be the one wanted, otherwise, if there is no match a error is raised, even if matching table names exist in other schemas in the database.
To show the current search path you can use the following command:
SHOW search_path;
And to put the new schema in the path, you could use:
SET search_path TO myschema;
Or if you want multiple schemas:
SET search_path TO myschema, public;
Reference: https://www.postgresql.org/docs/current/static/ddl-schemas.html
What do I do wrong?
The source code of ToastDisplay is OK (mine is similar and works), but it will only receive something, if it is currently in foreground (you register receiver in onResume). But it can not receive anything if a different activity (in this case SendBroadcast activity) is shown.
Instead you probably want to startActivity ToastDisplay from the first activity?
BroadcastReceiver and Activity make sense in a different use case. In my application I need to receive notifications from a background GPS tracking service and show them in the activity (if the activity is in the foreground).
There is no need to register the receiver in the manifest. It would be even harmful in my use case - my receiver manipulates the UI of the activity and the UI would not be available during onReceive if the activity is not currently shown. Instead I register and unregister the receiver for activity in onResume and onPause as described in BroadcastReceiver documentation:
You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml.
You can use a heredoc, which supports variable interpolation, making it look fairly neat:
function TestBlockHTML ($replStr) {
return <<<HTML
<html>
<body><h1>{$replStr}</h1>
</body>
</html>
HTML;
}
Pay close attention to the warning in the manual though - the closing line must not contain any whitespace, so can't be indented.
Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.
thread apply all bt
I noticed that you can also get errors if you don't specify the angles correctly, even when using glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z))
you still might run into problems. The fix I found for this was specifying the type as glm::rotate(Model, (glm::mediump_float)90, glm::vec3(x, y, z))
instead of just saying glm::rotate(Model, 90, glm::vec3(x, y, z))
Or just write the second argument, the angle in radians (previously in degrees), as a float with no cast needed such as in:
glm::mat4 rotationMatrix = glm::rotate(glm::mat4(1.0f), 3.14f, glm::vec3(1.0));
You can add glm::radians() if you want to keep using degrees. And add the includes:
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
This is Perfect. try this one :)
<form name="test" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
/* Html Input Fields */
</form>
The answer of David Taiaroa is correct, but doesn’t work because the time to "fade in" the modal doesn’t let you set focus on input. You need to create a delay:
$('#myModal').on('shown.bs.modal', function () {
...
setTimeout(function (){
$('#textareaID').focus();
}, 1000);
})
The following functions are available to obtain the current date and/or time in PostgreSQL:
CURRENT_TIME
CURRENT_DATE
CURRENT_TIMESTAMP
Example
SELECT CURRENT_TIME;
08:05:18.864750+05:30
SELECT CURRENT_DATE;
2020-05-14
SELECT CURRENT_TIMESTAMP;
2020-05-14 08:04:51.290498+05:30
In C#
8.0 and later you can use [^5..]
to get the last five characters combined with a ?
operator to avoid a potential ArgumentOutOfRangeException
.
string input1 = "0123456789";
string input2 = "0123";
Console.WriteLine(input1.Length >= 5 ? input1[^5..] : input1); //returns 56789
Console.WriteLine(input2.Length >= 5 ? input2[^5..] : input2); //returns 0123
Use:
call msbuild.bat
call unit-tests.bat
call deploy.bat
When not using CALL, the current batch file stops and the called batch file starts executing. It's a peculiar behavior dating back to the early MS-DOS days.
numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)
This would work, if your are trying to Sum up a list.
I've been searching for a simple way to make the sticky footer works.
I just applied a class="navbar-fixed-bottom
" and it worked instantly
Only thing to keep in mind it's to adjust the settings of the footer for mobile devices.
Cheers!
For debian/ubuntu install
sudo apt-get install php-pgsql
You need to stop all tracks (from webcam, microphone):
localStream.getTracks().forEach(track => track.stop());
There is a method setText()
which takes 3 arguments :
public void setText(String text, String charset, String subtype)
throws MessagingException
Parameters:
text - the text content to set
charset - the charset to use for the text
subtype - the MIME subtype to use (e.g., "html")
NOTE: the subtype takes text after / in MIME types so for ex.
The return statements should place in one line. Or the other option is to remove the curly brackets that bound the HTML statement.
example:
return posts.map((post, index) =>
<div key={index}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
);