I'm not qualified to comment on logging for .Net, since my bread and butter is Java, but we've had a migration in our logging over the last 8 years you may find a useful analogy to your question.
We started with a Singleton logger that was used by every thread within the JVM, and set the logging level for the entire process. This resulted in huge logs if we had to debug even a very specific part of the system, so lesson number one is to segment your logging.
Our current incarnation of the logger allows multiple instances with one defined as the default. We can instantiate any number of child loggers that have different logging levels, but the most useful facet of this architecture is the ability to create loggers for individual packages and classes by simply changing the logging properties. Lesson number two is to create a flexible system that allows overriding its behavior without changing code.
We are using the Apache commons-logging library wrapped around Log4J.
Hope this helps!
* Edit *
After reading Jeffrey Hantin's post below, I realized that I should have noted what our internal logging wrapper has actually become. It's now essentially a factory and is strictly used to get a working logger using the correct properties file (which for legacy reasons hasn't been moved to the default position). Since you can specify the logging configuration file on command line now, I suspect it will become even leaner and if you're starting a new application, I'd definitely agree with his statement that you shouldn't even bother wrapping the logger.
For even more verbose output use following:
GIT_CURL_VERBOSE=1 GIT_TRACE=1 git pull origin master
DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).
There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.
CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener
shuckc's answer for echoing select lines has a few downsides: you end up with the following set +x
command being echoed as well, and you lose the ability to test the exit code with $?
since it gets overwritten by the set +x
.
Another option is to run the command in a subshell:
echo "getting URL..."
( set -x ; curl -s --fail $URL -o $OUTFILE )
if [ $? -eq 0 ] ; then
echo "curl failed"
exit 1
fi
which will give you output like:
getting URL...
+ curl -s --fail http://example.com/missing -o /tmp/example
curl failed
This does incur the overhead of creating a new subshell for the command, though.
The worst thing of using just
console.log({'some stuff': 2} + '\n' + 'something')
is that all stuff are converted to the string and if you need object to show you may see next:
[object Object]
Thus my variant is the next code:
console.log({'some stuff': 2},'\n' + 'something');
Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:
function blobToDataURL(blob, callback) {
var fileReader = new FileReader();
fileReader.onload = function(e) {callback(e.target.result);}
fileReader.readAsDataURL(blob);
}
<a href="#" id="myAnchor">Click me</a>
<script type="text/javascript">
$(document).ready(function(){
$('#myAnchor').click(function(){
window.location.href = 'index.php';
});
})
</script>
For call from dialer (No permission needed):
fun callFromDailer(mContext: Context, number: String) {
try {
val callIntent = Intent(Intent.ACTION_DIAL)
callIntent.data = Uri.parse("tel:$number")
mContext.startActivity(callIntent)
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(mContext, "No SIM Found", Toast.LENGTH_LONG).show()
}
}
For direct call from app(Permission needed):
fun callDirect(mContext: Context, number: String) {
try {
val callIntent = Intent(Intent.ACTION_CALL)
callIntent.data = Uri.parse("tel:$number")
mContext.startActivity(callIntent)
} catch (e: SecurityException) {
Toast.makeText(mContext, "Need call permission", Toast.LENGTH_LONG).show()
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(mContext, "No SIM Found", Toast.LENGTH_LONG).show()
}
}
Permission:
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
Inaccessible logs: Security
A new event source needs to have a unique name across all logs including Security (which needs admin privilege when it's being read).
So your app will need admin privilege to create a source. But that's probably an overkill.
I wrote this powershell script to create the event source at will. Save it as *.ps1
and run it with any privilege and it will elevate itself.
# CHECK OR RUN AS ADMIN
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
# CHECK FOR EXISTENCE OR CREATE
$source = "My Service Event Source";
$logname = "Application";
if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
[System.Diagnostics.EventLog]::CreateEventSource($source, $logname);
Write-Host $source -f white -nonewline; Write-Host " successfully added." -f green;
}
else
{
Write-Host $source -f white -nonewline; Write-Host " already exists.";
}
# DONE
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
In my case, I was using PDO with php-cli, and it worked fine.
Only when I tried to connect from apache, I got the "missing driver" issue, which I didn't quite understand.
A simple apt-get install php-mysql
solved it. (Ubuntu 16.04 / PHP7. credits go to the selected answer & Ivan's comment)
Hope it can help.
If you want to avoid "drifting", meaning you want the command to execute every N seconds regardless of how long the command takes (assuming it takes less than N seconds), here's some bash that will repeat a command every 5 seconds with one-second accuracy (and will print out a warning if it can't keep up):
PERIOD=5
while [ 1 ]
do
let lastup=`date +%s`
# do command
let diff=`date +%s`-$lastup
if [ "$diff" -lt "$PERIOD" ]
then
sleep $(($PERIOD-$diff))
elif [ "$diff" -gt "$PERIOD" ]
then
echo "Command took longer than iteration period of $PERIOD seconds!"
fi
done
It may still drift a little since the sleep is only accurate to one second. You could improve this accuracy by creative use of the date command.
I had the same issue with Eclipse a couple of months ago when importing my project. Now I had the same with intelliJ. Here is how someone helped me to solve this in IntelliJ:
Menu => View => Tools windows => Maven Project In the spring_user value => Run Configuration, choose clean install. This should do a clean install and after this you should be able to see the classes
You can do this with wget usually. wget --content-disposition
"url" additionally if you add -O /dev/null
you will not be actually saving the file.
wget -O /dev/null --content-disposition example.com
This same Facebook error happened to me in the Production environment. The reason was I had 2 apps registered with Facebook (Local, Production) but I hardcoded the Local app ID into the source code and forgot to switch it out for the Production app ID before deployment.
Best practice dictates you shouldn't have the app ID hardcoded into the source code but if you do, do not mismatch your various Facebook app IDs like I mistakenly did.
For fast, OS-independent search, use scandir
https://github.com/benhoyt/scandir/#readme
Read http://bugs.python.org/issue11406 for details why.
The folks from sqlite.org have taken over the development of the ADO.NET provider:
From their homepage:
This is a fork of the popular ADO.NET 4.0 adaptor for SQLite known as System.Data.SQLite. The originator of System.Data.SQLite, Robert Simpson, is aware of this fork, has expressed his approval, and has commit privileges on the new Fossil repository. The SQLite development team intends to maintain System.Data.SQLite moving forward.
Historical versions, as well as the original support forums, may still be found at http://sqlite.phxsoftware.com, though there have been no updates to this version since April of 2010.
The complete list of features can be found at on their wiki. Highlights include
Released DLLs can be downloaded directly from the site.
I also wanted to combine a DatePicker and a TimePicker. So I create an API to handle both in one interface! :)
https://github.com/Kunzisoft/Android-SwitchDateTimePicker
You can also use SublimePicker
There is a lot of options and they all have their pro and cons.
Pros
Cons
Pros
Cons
Pros
Cons
Pros
Cons
Disclosure: I'm the founder of ApiFlash. I did my best to provide an honest and useful answer.
I don't program in Python, but I came across an FAQ at python.org advocating S.rstrip("\r\n") for python 2.2 or later.
Suppose your project has a package like
package name1.name2.name3.name4
(declared package)
Your package explorer shows
package top level named name1.name2
sub packages named name3.name4
You will have errors because Eclipse extracts the package name from the file directory structure on disk starting at the point you import from.
My case was a bit more involved, perhaps because I was using a symbolic link to a folder outside my workspace.
I first tried Build Path.Java Build Path.Source Tab.Link Source Button.Browse to the folder before name1 in your package.Folder-name as you like (i think). But had issues.
Then I removed the folder from the build path and tried File > Import... > General > File System > click Next > From Directory > Browse... to folder above name1 > click Advanced button > check Create links in workspace > click Finish button.
No, you cannot know when a page was last updated or last changed or uploaded to a server (which might, depending on interpretation, be three different things) just by accessing the page.
A server may, and should (according to the HTTP 1.1 protocol), send a Last-Modified
header, which you can find out in several ways, e.g. using Rex Swain’s HTTP Viewer. However, according to the protocol, this is just
“the date and time at which the origin server believes the variant was last modified”.
And the protocol realistically adds:
“The exact meaning of this header field depends on the implementation of the origin server and the nature of the original resource. For files, it may be just the file system last-modified time. For entities with dynamically included parts, it may be the most recent of the set of last-modify times for its component parts. For database gateways, it may be the last-update time stamp of the record. For virtual objects, it may be the last time the internal state changed.”
In practice, web pages are very often dynamically created from a Content Management System or otherwise, and in such cases, the Last-Modified
header typically shows a data stamp of creating the response, which is normally very close to the time of the request. This means that the header is practically useless in such cases.
Even in the case of a “static” page (the server simply picks up a file matching the request and sends it), the Last-Modified
date stamp normally indicates just the last write access to the file on the server. This might relate to a time when the file was restored from a backup copy, or a time when the file was edited on the server without making any change to the content, or a time when it was uploaded onto the server, possibly replacing an older identical copy. In these cases, assuming that the time stamp is technically correct, it indicates a time after which the page has not been changed (but not necessarily the time of last change).
Another solution is to install Xvfb, and export your display to it. ie:
disp=:8
screen=0
geom=640x480x24
exec Xvfb $disp -screen $screen $geom 2>/tmp/Xvfb.log &
Then
$ export DISPLAY=:8
$ ./example.py
Usually it would be this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>='2010-10-01'
AND yourtimetimefield< '2010-11-01'
But because you have a unix timestamps, you'll need something like this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>=unix_timestamp('2010-10-01')
AND yourtimetimefield< unix_timestamp('2010-11-01')
You can try this before using job_titles
string:
source = unicode(job_titles, 'utf-8')
A simple solution is to install jshon
library :
jshon -l < /tmp/test.json
2
In case of Request to a REST Service:
You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:
@CrossOrigin(origins = "http://localhost:8080")
Very good tutorial: https://spring.io/guides/gs/rest-service-cors/
The Python 2 documentation, 7.6. Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter.
First, you can use special formal parameter syntax *
. If the function definition has a formal parameter preceded by a single *
, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by **
, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.
For instance, here's a function opt_fun
which takes two positional parameters x1
and x2
, and looks for another keyword parameter named "optional".
>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
... if ('optional' in keyword_parameters):
... print 'optional parameter found, it is ', keyword_parameters['optional']
... else:
... print 'no optional parameter, sorry'
...
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry
Second, you can supply a default parameter value of some value like None
which a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.
If you need to join xpath-selected text nodes but can not use string-join
(when you are stuck with XSL 1.0) this might help:
<xsl:variable name="x">
<xsl:apply-templates select="..." mode="string-join-mode"/>
</xsl:variable>
joined and normalized: <xsl:value-of select="normalize-space($x)"/>
<xsl:template match="*" mode="string-join-mode">
<xsl:apply-templates mode="string-join-mode"/>
</xsl:template>
<xsl:template match="text()" mode="string-join-mode">
<xsl:value-of select="."/>
</xsl:template>
WSDL
(Web Service Description Language
) from a Web Service URL.Is possible from SOAP Web Services:
http://www.w3schools.com/xml/tempconvert.asmx
to get the WSDL we have only to add ?WSDL
, for example:
onChange doesn't fire until you lose focus later. If you want to be really strict with instantaneous changes of all sorts, use:
<input
type = "text"
onchange = "myHandler();"
onkeypress = "this.onchange();"
onpaste = "this.onchange();"
oninput = "this.onchange();"
/>
For everyone who felt they want to run away with all the steps and screen shots on the (great!) above answers, this worked for me with android studio 2.2.1
:
Create a new project, name it as you want and take the default (minSdkVersion 15 is fine).
Download the zip file from here: https://sourceforge.net/projects/opencvlibrary/files/opencv-android/ (I downloaded 3.2.0 version, but there may be a newer versions).
Unzip the zip file, the best place is in your workspace folder, but it not really matter.
Inside Android Studio
, click File->New-> Import Module
and navigate to \path_to_your_unzipped_file\OpenCV-android-sdk\sdk\java
and hit Ok, then accept all default dialogs.
In the gradle
file of your app
module, add this to the dependencies block:
dependencies {
compile project(':openCVLibraryXYZ')
//rest of code
}
Where XYZ is the exact version you downloaded, for example in my case:
dependencies {
compile project(':openCVLibrary320')
//rest of code
}
If you have config file transforms then ensure you have the correct config selected within your publish profile. (Publish > Settings > Configuration)
window.load = function(){}
Its fully supported by all browsers, and it will fire an event when all images are fully loaded.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
Here is how to synchronize PHP (>=5.3) and MySQL timezones per session and user settings. Put this where it runs when you need set and synchronized timezones.
date_default_timezone_set($my_timezone);
$n = new \DateTime();
$h = $n->getOffset()/3600;
$i = 60*($h-floor($h));
$offset = sprintf('%+d:%02d', $h, $i);
$this->db->query("SET time_zone='$offset'");
Where $my_timezone is one in the list of PHP timezones: http://www.php.net/manual/en/timezones.php
The PHP timezone has to be converted into the hour and minute offset for MySQL. That's what lines 1-4 do.
Try this.
public function getDownload()
{
//PDF file is stored under project/public/download/info.pdf
$file= public_path(). "/download/info.pdf";
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, 'filename.pdf', $headers);
}
"./download/info.pdf"
will not work as you have to give full physical path.
Update 20/05/2016
Laravel 5, 5.1, 5.2 or 5.* users can use the following method instead of Response
facade. However, my previous answer will work for both Laravel 4 or 5. (the $header
array structure change to associative array =>
- the colon after 'Content-Type' was deleted - if we don't do those changes then headers will be added in wrong way: the name of header wil be number started from 0,1,...)
$headers = [
'Content-Type' => 'application/pdf',
];
return response()->download($file, 'filename.pdf', $headers);
First we need to check if we have enabled mod_headers.c and mod_expires.c.
sudo apache2 -l
If we don't have it, we need to enable them
sudo a2enmod headers
Then we need to restart apache
sudo apache2 restart
At last, add the rules on .htaccess (seen on other answers), for example
ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif|jpe?g|png|ico|css|js|swf)$">
Header set Cache-Control "public"
</FilesMatch>
def transpose_finite_iterable(iterable):
return zip(*iterable) # `itertools.izip` for Python 2 users
works fine for finite iterable (e.g. sequences like list
/tuple
/str
) of (potentially infinite) iterables which can be illustrated like
| |a_00| |a_10| ... |a_n0| |
| |a_01| |a_11| ... |a_n1| |
| |... | |... | ... |... | |
| |a_0i| |a_1i| ... |a_ni| |
| |... | |... | ... |... | |
where
n in N
,a_ij
corresponds to j
-th element of i
-th iterable,and after applying transpose_finite_iterable
we get
| |a_00| |a_01| ... |a_0i| ... |
| |a_10| |a_11| ... |a_1i| ... |
| |... | |... | ... |... | ... |
| |a_n0| |a_n1| ... |a_ni| ... |
Python example of such case where a_ij == j
, n == 2
>>> from itertools import count
>>> iterable = [count(), count()]
>>> result = transpose_finite_iterable(iterable)
>>> next(result)
(0, 0)
>>> next(result)
(1, 1)
But we can't use transpose_finite_iterable
again to return to structure of original iterable
because result
is an infinite iterable of finite iterables (tuple
s in our case):
>>> transpose_finite_iterable(result)
... hangs ...
Traceback (most recent call last):
File "...", line 1, in ...
File "...", line 2, in transpose_finite_iterable
MemoryError
So how can we deal with this case?
deque
After we take a look at docs of itertools.tee
function, there is Python recipe that with some modification can help in our case
def transpose_finite_iterables(iterable):
iterator = iter(iterable)
try:
first_elements = next(iterator)
except StopIteration:
return ()
queues = [deque([element])
for element in first_elements]
def coordinate(queue):
while True:
if not queue:
try:
elements = next(iterator)
except StopIteration:
return
for sub_queue, element in zip(queues, elements):
sub_queue.append(element)
yield queue.popleft()
return tuple(map(coordinate, queues))
let's check
>>> from itertools import count
>>> iterable = [count(), count()]
>>> result = transpose_finite_iterables(transpose_finite_iterable(iterable))
>>> result
(<generator object transpose_finite_iterables.<locals>.coordinate at ...>, <generator object transpose_finite_iterables.<locals>.coordinate at ...>)
>>> next(result[0])
0
>>> next(result[0])
1
Now we can define general function for working with iterables of iterables ones of which are finite and another ones are potentially infinite using functools.singledispatch
decorator like
from collections import (abc,
deque)
from functools import singledispatch
@singledispatch
def transpose(object_):
"""
Transposes given object.
"""
raise TypeError('Unsupported object type: {type}.'
.format(type=type))
@transpose.register(abc.Iterable)
def transpose_finite_iterables(object_):
"""
Transposes given iterable of finite iterables.
"""
iterator = iter(object_)
try:
first_elements = next(iterator)
except StopIteration:
return ()
queues = [deque([element])
for element in first_elements]
def coordinate(queue):
while True:
if not queue:
try:
elements = next(iterator)
except StopIteration:
return
for sub_queue, element in zip(queues, elements):
sub_queue.append(element)
yield queue.popleft()
return tuple(map(coordinate, queues))
def transpose_finite_iterable(object_):
"""
Transposes given finite iterable of iterables.
"""
yield from zip(*object_)
try:
transpose.register(abc.Collection, transpose_finite_iterable)
except AttributeError:
# Python3.5-
transpose.register(abc.Mapping, transpose_finite_iterable)
transpose.register(abc.Sequence, transpose_finite_iterable)
transpose.register(abc.Set, transpose_finite_iterable)
which can be considered as its own inverse (mathematicians call this kind of functions "involutions") in class of binary operators over finite non-empty iterables.
As a bonus of singledispatch
ing we can handle numpy
arrays like
import numpy as np
...
transpose.register(np.ndarray, np.transpose)
and then use it like
>>> array = np.arange(4).reshape((2,2))
>>> array
array([[0, 1],
[2, 3]])
>>> transpose(array)
array([[0, 2],
[1, 3]])
Since transpose
returns iterators and if someone wants to have a tuple
of list
s like in OP -- this can be made additionally with map
built-in function like
>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> tuple(map(list, transpose(original)))
(['a', 'b', 'c', 'd'], [1, 2, 3, 4])
I've added generalized solution to lz
package from 0.5.0
version which can be used like
>>> from lz.transposition import transpose
>>> list(map(tuple, transpose(zip(range(10), range(10, 20)))))
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (10, 11, 12, 13, 14, 15, 16, 17, 18, 19)]
There is no solution (at least obvious) for handling potentially infinite iterable of potentially infinite iterables, but this case is less common though.
If you really want to do this with jQuery (why?) you should get the DOM window.location object to use its functions:
$(window.location)[0].replace("https://www.google.it");
Note that [0] says to jQuery to use directly the DOM object and not the $(window.location) jQuery object incapsulating the DOM object.
This partly depends on what you want to happen if you run into duplicates. For instance, you could do:
var result = dictionaries.SelectMany(dict => dict)
.ToDictionary(pair => pair.Key, pair => pair.Value);
That will throw an exception if you get any duplicate keys.
EDIT: If you use ToLookup then you'll get a lookup which can have multiple values per key. You could then convert that to a dictionary:
var result = dictionaries.SelectMany(dict => dict)
.ToLookup(pair => pair.Key, pair => pair.Value)
.ToDictionary(group => group.Key, group => group.First());
It's a bit ugly - and inefficient - but it's the quickest way to do it in terms of code. (I haven't tested it, admittedly.)
You could write your own ToDictionary2 extension method of course (with a better name, but I don't have time to think of one now) - it's not terribly hard to do, just overwriting (or ignoring) duplicate keys. The important bit (to my mind) is using SelectMany, and realising that a dictionary supports iteration over its key/value pairs.
This has bugged me for some time. What I usually end up doing is rebuilding my external library using debug mode, then copy both .dll and the .pdb file to the bin of my website. This allows me to step into the libarary code.
This issue happens if this project is being used by another project. Make sure you copy the app setting keys to the parent project's app.config or web.config.
What I found was that I needed to drag the distribution_identity.cer file that I downloaded from the "Certificates -> Distribution" page on the developer program portal into the keychain access program, then this error went away.
<td align="center">
or via css, which is the preferred method any more...
<td style="text-align: center;">
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
Another possible case if none works is to see that there is a running Java
application . may be your previous open and close has left unkilled java instances.
Do look for any java instance is running if there are two at least you need to kill one.But ,most of the time i kill any java running :) because that java is using the work space earlier and still will if don't kill it.
Change another work space in case if you want a multiple IDE to use and work on diffrent or same project , but you should import project form workspace after you open your IDE.
There is already a solution provided which allows building a dictionary, (or nested dictionary for more complex data), but if you wish to build an object, then perhaps try 'ObjDict'. This gives much more control over the json to be created, for example retaining order, and allows building as an object which may be a preferred representation of your concept.
pip install objdict first.
from objdict import ObjDict
data = ObjDict()
data.key = 'value'
json_data = data.dumps()
This is for UK landlines without the Country Code
function format_phone_number($number) {
$result = preg_replace('~.*(\d{2})[^\d]{0,7}(\d{4})[^\d]{0,7}(\d{4}).*~', '$1 $2 $3', $number);
return $result;
}
Result:
2012345678
becomes
20 1234 5678
If you are inside a batch script, you can use argument variable tricks to get the filesize:
filesize.bat:
@echo off
echo %~z1
This gives results like the ones you suggest in your question.
Type
help call
at the command prompt for all of the crazy variable manipulation options. Also see this article for more information.
Edit: This only works in Windows 2000 and later
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
<?php
$res = mysql_query('SELECT getTreeNodeName(1) AS result');
if ($res === false) {
echo mysql_errno().': '.mysql_error();
}
while ($obj = mysql_fetch_object($res)) {
echo $obj->result;
}
The best example is
public final class String
which is an immutable class and cannot be extended. Of course, there is more than just making the class final to be immutable.
You should simply apply the following transformation to your input data array.
input_data = input_data.reshape((-1, image_side1, image_side2, channels))
A good information: you don't need to check whether the Bundle object is null into the onCreate() method. Use the onRestoreInstanceState() method, which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null
The $@
and $<
are called automatic variables. The variable $@
represents the name of the target and $<
represents the first prerequisite required to create the output file.
For example:
hello.o: hello.c hello.h
gcc -c $< -o $@
Here, hello.o
is the output file. This is what $@
expands to. The first dependency is hello.c
. That's what $<
expands to.
The -c
flag generates the .o
file; see man gcc
for a more detailed explanation. The -o
specifies the output file to create.
For further details, you can read this article about Linux Makefiles.
Also, you can check the GNU make
manuals. It will make it easier to make Makefiles and to debug them.
If you run this command, it will output the makefile database:
make -p
The javax.servlet dependency is missing in your pom.xml. Add the following to the dependencies-Node:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
Use the ASCII table to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.
I find that this method is nicer compared to the method described where the range of characters is specifically defined within another string.
// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end = 122;
$random_string = "";
$random_string_length = 10;
for ($i = 0; $i < $random_string_length; $i++) {
$ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
// finds the character represented by $ascii_no and adds it to the random string
// study **chr** function for a better understanding
$random_string .= chr( $ascii_no );
}
echo $random_string;
See More:
If you want to access any DOM element simply add ref
attribute and you can directly access that element.
<input type="text" ref="myinput">
And then you can directly:
componentDidMount: function()
{
this.refs.myinput.select();
},
Their is no need of using ReactDOM.findDOMNode()
, if you have added a ref
to any element.
Just create a new array in your dictionary
Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));
Example:
DECLARE @Str NVARCHAR(MAX) = N'
foo bar
Foo Bar
'
PRINT '[' + @Str + ']'
DECLARE @StrPrv NVARCHAR(MAX) = N''
WHILE ((@StrPrv <> @Str) AND (@Str IS NOT NULL)) BEGIN
SET @StrPrv = @Str
-- Beginning
IF EXISTS (SELECT 1 WHERE @Str LIKE '[' + CHAR(13) + CHAR(10) + CHAR(9) + ']%')
SET @Str = LTRIM(RIGHT(@Str, LEN(@Str) - 1))
-- Ending
IF EXISTS (SELECT 1 WHERE @Str LIKE '%[' + CHAR(13) + CHAR(10) + CHAR(9) + ']')
SET @Str = RTRIM(LEFT(@Str, LEN(@Str) - 1))
END
PRINT '[' + @Str + ']'
Result
[
foo bar
Foo Bar
]
[foo bar
Foo Bar]
Source: https://github.com/reduardo7/fnTrim
SELECT dbo.fnTrim(colName)
I use eUML2 plugin from Soyatec, under Eclipse and it works fine for the generation of UML giving the source code. This tool is useful up to Eclipse 4.4.x
You can execute it same as SQL query. first, build your command/Expression and store in a variable and execute/invoke.
$command = ".\yourExternalScriptFile.ps1" + " -param1 '$paramValue'"
It is pretty forward, I don't think it needs explanations. So all set to execute your command now,
Invoke-Expression $command
I would recommend catching the exception here
josh3736's answer is a good one, but to provide a counterpoint 3 years later:
I recommend using rem
units for fonts, if only because it makes it easier for you, the developer, to change sizes. It's true that users very rarely change the default font size in their browsers, and that modern browser zoom will scale up px
units. But what if your boss comes to you and says "don't enlarge the images or icons, but make all the fonts bigger". It's much easier to just change the root font size and let all the other fonts scale relative to that, then to change px
sizes in dozens or hundreds of css rules.
I think it still makes sense to use px
units for some images, or for certain layout elements that should always be the same size regardless of the scale of the design.
Caniuse.com may have said that only 75% of browsers when josh3736 posted his answer in 2012, but as of March 27 they claim 93.78% support. Only IE8 doesn't support it among the browsers they track.
In scripts you have more options and a better shot at rational decomposition. Look into SQLCMD mode (Query Menu -> SQLCMD mode), specifically the :setvar and :r commands.
Within a stored procedure your options are very limited. You can't create define a function directly with the body of a procedure. The best you can do is something like this, with dynamic SQL:
create proc DoStuff
as begin
declare @sql nvarchar(max)
/*
define function here, within a string
note the underscore prefix, a good convention for user-defined temporary objects
*/
set @sql = '
create function dbo._object_name_twopart (@object_id int)
returns nvarchar(517) as
begin
return
quotename(object_schema_name(@object_id))+N''.''+
quotename(object_name(@object_id))
end
'
/*
create the function by executing the string, with a conditional object drop upfront
*/
if object_id('dbo._object_name_twopart') is not null drop function _object_name_twopart
exec (@sql)
/*
use the function in a query
*/
select object_id, dbo._object_name_twopart(object_id)
from sys.objects
where type = 'U'
/*
clean up
*/
drop function _object_name_twopart
end
go
This approximates a global temporary function, if such a thing existed. It's still visible to other users. You could append the @@SPID of your connection to uniqueify the name, but that would then require the rest of the procedure to use dynamic SQL too.
You don't need javascript
to show modal
The simplest way is replace "hide" by "in"
class="modal fade hide"
so
class="modal fade in"
and you need add onclick = "$('.modal').hide()"
on button close;
PS: I think the best way is add jQuery script:
$('.modal').modal('show');
var reverseString = function(str){
let length = str.length - 1;
str = str.split('');
for(let i=0;i<= length;i++){
str[length + i + 1] = str[length - i];
}
return str.splice(length + 1).join('');
}
eric, your code did not seem to work for me when the user enters text then deletes all the text. i created another version if anyone experienced the same problem. here ya go folks:
$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').keyup(function(){
if($('input[type="text"]').val() == ""){
$('input[type="submit"]').attr('disabled','disabled');
}
else{
$('input[type="submit"]').removeAttr('disabled');
}
})
I would like this
from subprocess import call
command = "youtube-dl https://www.youtube.com/watch?v=NG3WygJmiVs -c"
call(command.split(), shell=False)
Try This
CKEDITOR.instances['textareaId'].setData(value);
The ideal way is to use a dictionary that maps a word to it's count. But if you can't use that, you might want to use 2 lists - 1 storing the words, and the other one storing counts of words. Note that order of words and counts matters here. Implementing this would be hard and not very efficient.
It is possible!
This appears to override browser settings. Hope it works for you.
<script type="text/javascript">
// Popup window code
function newPopup(url) {
popupWindow = window.open(url,'popUpWindow1','height=600,width=600,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
</script>
<body>
<a href="JavaScript:newPopup('http://stimsonstopmotion.wordpress.com');">Try me</a>
</body>
To collect more useful resources here:
As mentioned before D3.js is definitely the best visualization library for charts. To use it in AngularJS I developed angular-chart. It is an easy to use directive which connects D3.js with the AngularJS 2-Way-DataBinding. This way the chart gets automatically updated whenever you change the configuration options and at the same time the charts saves its state (zoom level, ...) to make it available in the AngularJS world.
Check out the examples to get convinced.
Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.
You can set your tint color and font as setTitleTextattribute:
UIFont *font= (kUIScreenHeight>KipadHeight)?[UIFont boldSystemFontOfSize:32.0f]:[UIFont boldSystemFontOfSize:16.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,
tintColorLight, NSForegroundColorAttributeName, nil];
[[UINavigationBar appearance] setTitleTextAttributes:attributes];
You should map your virtual network drive in Windows.
net use x: \\vboxsvr\<your_shared_folder_name>
X:
in My Computer
In your case execute net use x: \\vboxsvr\win7
I saw it's solved, but I still want to share a solution which worked for me.
.env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=[your database name]
DB_USERNAME=[your MySQL username]
DB_PASSWORD=[your MySQL password]
MySQL admin:
SELECT user, host FROM mysql.user
Console:
php artisan cache:clear
php artisan config:cache
Now it works for me.
The best working Solution of adding Custom header view in UITableView for section in swift 4 is --
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 50))
let label = UILabel()
label.frame = CGRect.init(x: 5, y: 5, width: headerView.frame.width-10, height: headerView.frame.height-10)
label.text = "Notification Times"
label.font = UIFont().futuraPTMediumFont(16) // my custom font
label.textColor = UIColor.charcolBlackColour() // my custom colour
headerView.addSubview(label)
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
Saul's answer can be better implemented splitting the string like this:
string = string.replaceAll("[\\p{Z}\\s]+", "");
String[] array = string.substring(1, string.length() - 1).split(",");
please try to make it as a character
string str = "Tigger";
//then str[0] will return 'T' not "T"
I had a similar problem with wget to my own live web site returning errors after installing a new SSL certificate. I'd already checked several browsers and they didn't report any errors:
wget --no-cache -O - "https://example.com/..." ERROR: The certificate of ‘example.com’ is not trusted. ERROR: The certificate of ‘example.com’ hasn't got a known issuer.
The problem was I had installed the wrong certificate authority .pem/.crt file from the issuer. Usually they bundle the SSL certificate and CA file as a zip file, but DigiCert email you the certificate and you have to figure out the matching CA on your own. https://www.digicert.com/help/ has an SSL certificate checker which lists the SSL authority and the hopefully matching CA with a nice blue link graphic if they agree:
`SSL Cert: Issuer GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1
CA: Subject GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1 Valid from 16/Jul/2020 to 31/May/2023 Issuer DigiCert Global Root CA`
Since Python 3.5, subprocess.run() is recommended over subprocess.check_output():
>>> int(subprocess.run(["pidof", "-s", "your_process"], stdout=subprocess.PIPE).stdout)
Also, since Python 3.7, you can use the capture_output=true
parameter to capture stdout and stderr:
>>> int(subprocess.run(["pidof", "-s", "your process"], capture_output=True).stdout)
I used ProcessBuilder but had the same issue. The issue was with using command as one String line (like I would type it in cmd) instead of String array. In example from above. If I ran
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar x myjar.jar *.* new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
I got an error. But if I ran
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar", "x", "myjar.jar", "*.*", "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
everything was OK.
Today, you should be representing a folder using its content: URI as obtained from the Storage Access Framework, and opening it should be as simple as:
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
Alas, the Files app currently contains a bug that causes it to crash when you try this using the external storage provider. Folders from third party providers however can be displayed in this way.
CREATE PROCEDURE Get_permission
AS
DECLARE @db_name VARCHAR(200),
@sql_text VARCHAR(max)
SET @sql_text='Create table ##db_name (user_name varchar(max),'
DECLARE db_cursor CURSOR FOR
SELECT name
FROM sys.databases
OPEN db_cursor
FETCH next FROM db_cursor INTO @db_name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql_text=@sql_text + @db_name + ' varchar(max),'
FETCH next FROM db_cursor INTO @db_name
END
CLOSE db_cursor
SET @sql_text=@sql_text + 'Server_perm varchar(max))'
EXEC (@sql_text)
DEALLOCATE db_cursor
DECLARE @RoleName VARCHAR(50)
DECLARE @UserName VARCHAR(50)
DECLARE @CMD VARCHAR(1000)
CREATE TABLE #permission
(
user_name VARCHAR(50),
databasename VARCHAR(50),
role VARCHAR(50)
)
DECLARE longspcur CURSOR FOR
SELECT name
FROM sys.server_principals
WHERE type IN ( 'S', 'U', 'G' )
AND principal_id > 4
AND name NOT LIKE '##%'
AND name <> 'NT AUTHORITY\SYSTEM'
AND name <> 'ONDEMAND\Administrator'
AND name NOT LIKE 'steel%'
OPEN longspcur
FETCH next FROM longspcur INTO @UserName
WHILE @@FETCH_STATUS = 0
BEGIN
CREATE TABLE #userroles_kk
(
databasename VARCHAR(50),
role VARCHAR(50)
)
CREATE TABLE #rolemember_kk
(
dbrole VARCHAR(100),
membername VARCHAR(100),
membersid VARBINARY(2048)
)
SET @CMD = 'use ? truncate table #RoleMember_kk insert into #RoleMember_kk exec sp_helprolemember insert into #UserRoles_kk (DatabaseName, Role) select db_name(), dbRole from #RoleMember_kk where MemberName = ''' + @UserName + ''''
EXEC Sp_msforeachdb
@CMD
INSERT INTO #permission
SELECT @UserName 'user',
b.name,
u.role
FROM sys.sysdatabases b
LEFT OUTER JOIN #userroles_kk u
ON u.databasename = b.name --and u.Role='db_owner'
ORDER BY 1
DROP TABLE #userroles_kk;
DROP TABLE #rolemember_kk;
FETCH next FROM longspcur INTO @UserName
END
CLOSE longspcur
DEALLOCATE longspcur
TRUNCATE TABLE ##db_name
DECLARE @d1 VARCHAR(max),
@d2 VARCHAR(max),
@d3 VARCHAR(max),
@ss VARCHAR(max)
DECLARE perm_cur CURSOR FOR
SELECT *
FROM #permission
ORDER BY 2 DESC
OPEN perm_cur
FETCH next FROM perm_cur INTO @d1, @d2, @d3
WHILE @@FETCH_STATUS = 0
BEGIN
IF NOT EXISTS(SELECT 1
FROM ##db_name
WHERE user_name = @d1)
BEGIN
SET @ss='insert into ##db_name(user_name) values ('''
+ @d1 + ''')'
EXEC (@ss)
SET @ss='update ##db_name set ' + @d2 + '=''' + @d3
+ ''' where user_name=''' + @d1 + ''''
EXEC (@ss)
END
ELSE
BEGIN
DECLARE @var NVARCHAR(max),
@ParmDefinition NVARCHAR(max),
@var1 NVARCHAR(max)
SET @var = N'select @var1=' + @d2
+ ' from ##db_name where USER_NAME=''' + @d1
+ '''';
SET @ParmDefinition = N'@var1 nvarchar(300) OUTPUT';
EXECUTE Sp_executesql
@var,
@ParmDefinition,
@var1=@var1 output;
SET @var1=Isnull(@var1, ' ')
SET @var= ' update ##db_name set ' + @d2 + '=''' + @var1 + ' '
+ @d3 + ''' where user_name=''' + @d1 + ''' '
EXEC (@var)
END
FETCH next FROM perm_cur INTO @d1, @d2, @d3
END
CLOSE perm_cur
DEALLOCATE perm_cur
SELECT *
FROM ##db_name
DROP TABLE ##db_name
DROP TABLE #permission
Swift way to do it, you can call this from anywhere, it returns optional so watch out about that:
/// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups
var topMostVC: UIViewController? {
var presentedVC = UIApplication.sharedApplication().keyWindow?.rootViewController
while let pVC = presentedVC?.presentedViewController {
presentedVC = pVC
}
if presentedVC == nil {
print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
}
return presentedVC
}
Its included as a standard function in:
On Postgres 10:
SELECT to_timestamp(CAST(epoch_ms as bigint)/1000)
Escape the | character using a backtick
get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt
Zero and None both treated as same for if block, below code should work fine.
if number or number==0:
return True
Use show/hide method as below
$("div").show();//To Show
$("div").hide();//To Hide
Use a CipherOutputStream
or CipherInputStream
with a Cipher
and your FileInputStream
/ FileOutputStream
.
I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding")
for creating the Cipher
class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.
Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.
If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.
Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes()
but use String.getBytes(StandardCharsets.UTF_8)
.
To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.
Be warned that CipherInputStream
may not report BadPaddingException
, this includes BadPaddingException
generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.
At, i think Angular 8:
ActivatedRoute.params
has been replaced by ActivatedRoute.paramMap
ActivatedRoute.queryParams
has been replaced by ActivatedRoute.queryParamMap
I have the same issue. I've just run "$ flutter clean"
, then everything is OK.
For a three dimensional array you could try:
for c in array.transpose(1, 0, 2):
do_stuff(c)
See the docs on how array.transpose
works. Basically you are specifying which dimension to shift. In this case we are shifting the second dimension (e.g. columns) to the first dimension.
Not so graceful, but the very much simple in implementation solution - using global variable.
In the "first" file:
window.myApp = angular.module("myApp", [])
....
in the "second" , "third", etc:
myApp.controller('MyController', function($scope) {
....
});
try this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<div name="name" id="name">here</div>
</body>
</html>
In my opinion every programmer has his or her own "words" that is used every time you need an arbitrary word when programming. For some people it's the first words from a childs song, for other it's names and for other its something completely different. Now for the programmer community there are these "words" as well, and these words are 'foo' and 'bar'. The use of this is that if you have to communicate publicly about programming you don't have to say that you would use arbitratry words, you would simply write 'foo' or 'bar' and every programmer knows that this is just arbitrary words.
Your problem is with this line:
number4 = list(cow[n])
It tries to take cow[n]
, which returns an integer, and make it a list. This doesn't work, as demonstrated below:
>>> a = 1
>>> list(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
Perhaps you meant to put cow[n]
inside a list:
number4 = [cow[n]]
See a demonstration below:
>>> a = 1
>>> [a]
[1]
>>>
Also, I wanted to address two things:
:
at the end.input
like that, since it evaluates its input as real Python code. It would be better here to use raw_input
and then convert the input to an integer with int
.To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum
:
>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>
Open up the postgres terminal with the databse you would like:
psql dbname (run this line in a terminal)
then, run this command in the postgres environment
\d
This will describe all tables by name. Basically a list of tables by name ascending.
Then you can try this to describe a table by fields:
\d tablename.
Hope this helps.
Use std::tr1::normal_distribution
.
The std::tr1 namespace is not a part of boost. It's the namespace that contains the library additions from the C++ Technical Report 1 and is available in up to date Microsoft compilers and gcc, independently of boost.
This works i tried it my self i thought i post it here in case someone need it...
document.getElementById("newSkill").options[document.getElementById('newSkill').selectedIndex].text;
You can add:
#div2{
background-image:url(http://s7.static.hootsuite.com/3-0-48/images/themes/classic/streams/message-gradient.png);
background-size: 100% 100%;
height:180px;
width:200px;
border: 1px solid red;
}
You can read more about it here: css3 background-size
As @wirey said appendTo
should work, if not then you can try this:
$("#tblEntAttributes tbody").append(newRowContent);
This is my mix:
overflow-y: scroll;
height: 13em; // Initial height.
resize: vertical; // Allow user to change the vertical size.
max-height: 31em; // If you want to constrain the max size.
You can use querySelectorAll()
like this:
var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');
This translates to:
get all inputs with the attribute "value" and has the attribute "value" that is not blank.
In this demo, it disables the checkbox with a non-blank value.
$http methods return a promise, which can't be iterated, so you have to attach the results to the scope variable through the callbacks:
$scope.documents = [];
$http.get('/Documents/DocumentsList/' + caseId)
.then(function(result) {
$scope.documents = result.data;
});
Now, since this defines the documents
variable only after the results are fetched, you need to initialise the documents
variable on scope beforehand: $scope.documents = []
. Otherwise, your ng-repeat will choke.
This way, ng-repeat will first return an empty list, because documents
array is empty at first, but as soon as results are received, ng-repeat will run again because the `documents``have changed in the success callback.
Also, you might want to alter you ng-repeat expression to:
<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
because if your DisplayDocuments()
function is making a call to the server, than this call will be executed many times over, due to the $digest cycles.
This line should get you the firebase FCM token.
String token = FirebaseInstanceId.getInstance().getToken();
Log.d("MYTAG", "This is your Firebase token" + token);
Do Log.d to print it out to the android monitor.
@Kunigami: I think you may be mistaken about Guava's newArrayList
method. It does not check whether the Iterable is a List type and simply return the given List as-is. It always creates a new list:
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
// Let ArrayList's sizing logic work, if possible
return (elements instanceof Collection)
? new ArrayList<E>(Collections2.cast(elements))
: newArrayList(elements.iterator());
}
In addition to Cody's useful comments it is worth noting that at times you won't know how big your array should be. The two options in this situation are
Redim Preserve
The code below provides an example of a routine that will dimension myArray
in line with the lngSize
variable, then add additional elements (equal to the initial array size) by use of a Mod
test whenever the upper bound is about to be exceeded
Option Base 1
Sub ArraySample()
Dim myArray() As String
Dim lngCnt As Long
Dim lngSize As Long
lngSize = 10
ReDim myArray(1 To lngSize)
For lngCnt = 1 To lngSize*5
If lngCnt Mod lngSize = 0 Then ReDim Preserve myArray(1 To UBound(myArray) + lngSize)
myArray(lngCnt) = "I am record number " & lngCnt
Next
End Sub
you can do it better with two datagridview, you add the same datasource , hide the headers of the second, set the height of the second = to the height of the rows of the first, turn off all resizable atributes of the second, synchronize the scrollbars of both, only horizontal, put the second on the botton of the first etc.
take a look:
dgv3.ColumnHeadersVisible = false;
dgv3.Height = dgv1.Rows[0].Height;
dgv3.Location = new Point(Xdgvx, this.dgv1.Height - dgv3.Height - SystemInformation.HorizontalScrollBarHeight);
dgv3.Width = dgv1.Width;
private void dgv1_Scroll(object sender, ScrollEventArgs e)
{
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
{
dgv3.HorizontalScrollingOffset = e.NewValue;
}
}
I answered a very similar question:
https://stackoverflow.com/a/15982217/1467082
You simply need to iterate over the series' .Points
collection, and then you can assign the points' .Format.Fill.ForeColor.RGB
value based on whatever criteria you need.
UPDATED
The code below will color the chart per the screenshot. This only assumes three colors are used. You can add additional case statements for other color values, and update the assignment of myColor
to the appropriate RGB values for each.
Option Explicit
Sub ColorScatterPoints()
Dim cht As Chart
Dim srs As Series
Dim pt As Point
Dim p As Long
Dim Vals$, lTrim#, rTrim#
Dim valRange As Range, cl As Range
Dim myColor As Long
Set cht = ActiveSheet.ChartObjects(1).Chart
Set srs = cht.SeriesCollection(1)
'## Get the series Y-Values range address:
lTrim = InStrRev(srs.Formula, ",", InStrRev(srs.Formula, ",") - 1, vbBinaryCompare) + 1
rTrim = InStrRev(srs.Formula, ",")
Vals = Mid(srs.Formula, lTrim, rTrim - lTrim)
Set valRange = Range(Vals)
For p = 1 To srs.Points.Count
Set pt = srs.Points(p)
Set cl = valRange(p).Offset(0, 1) '## assume color is in the next column.
With pt.Format.Fill
.Visible = msoTrue
'.Solid 'I commented this out, but you can un-comment and it should still work
'## Assign Long color value based on the cell value
'## Add additional cases as needed.
Select Case LCase(cl)
Case "red"
myColor = RGB(255, 0, 0)
Case "orange"
myColor = RGB(255, 192, 0)
Case "green"
myColor = RGB(0, 255, 0)
End Select
.ForeColor.RGB = myColor
End With
Next
End Sub
Run the command prompt as admin and cd to bin directory of MySQL
Generally it is (C:\Program Files\MySQL\mysql-5.6.36-winx64\bin)
Run command : mysqld --install. (This command will install MySQL services and if services already installed it will prompt.)
Run below commands to start and stop server
To start : net start mysql
To stop : net stop mysql
Run mysql command.
Enjoy !!
It can be done in seven ways:
import com.google.common.primitives.Ints;
import org.apache.commons.lang.math.NumberUtils;
String number = "999";
Ints.tryParse
:
int result = Ints.tryParse(number);
NumberUtils.createInteger
:
Integer result = NumberUtils.createInteger(number);
NumberUtils.toInt
:
int result = NumberUtils.toInt(number);
Integer.valueOf
:
Integer result = Integer.valueOf(number);
Integer.parseInt
:
int result = Integer.parseInt(number);
Integer.decode
:
int result = Integer.decode(number);
Integer.parseUnsignedInt
:
int result = Integer.parseUnsignedInt(number);
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
I have spend all day to solve this error since none of the answers worked for me.
I found out that oracle virtual box doesn't install the network adapter correctly in windows 8.1
Solution:
C:\Program Files\Oracle\VirtualBox\drivers\network\netadp\VBoxNetAdp.inf
)Now that virtual box adapters is installed correctly, it needs to be setup correctly. (the following solution is like many other solution in here)
192.168.56.1
mask 255.255.255.0
192.168.56.100
server Mask: 255.255.255.0
low address bound: 192.168.56.101
upper adress bound 192.168.56.254
The CSS:
div{ overflow-y:scroll; overflow-x:scroll; width:20px; height:30px; } table{ width:50px; height:50px; }
You can make the table and the DIV around the table be any size you want, just make sure that the DIV is smaller than the table. You MUST contain the table inside of the DIV.
Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/
Also v2 can use mobile gesture such as swipe ;)
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
DISPLAY=pygame.display.set_mode((500,400),0,32)
WHITE=(255,255,255)
BLUE=(0,0,255)
DISPLAY.fill(WHITE)
pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
main()
This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect
to go about this, and you add the DISPLAY
constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.
Look up pygame.org for more info
or use map
Results.map(obj=> ({ ...obj, Active: 'false' }))
Edited to reflect comment by @adrianolsk to not mutate the original and instead return a new object for each.
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
For non-servers this requires Remote Server Administration Tools for Windows __
Method __str__ should return string, not print.
def __str__(self):
return 'Memo={0}, Tag={1}'.format(self.memo, self.tags)
I found that I get these a lot when I try to abbreviate, such as:
Table1 t1, Table2 t2
where t1.ID = t2.ID
Changing it to:
Table1, Table2
where Table1.ID = Table2.ID
Makes the query work and not throw the error.
You don't need to add the concat package, you can do this via cssmin like this:
cssmin : {
options: {
keepSpecialComments: 0
},
minify : {
expand : true,
cwd : '/library/css',
src : ['*.css', '!*.min.css'],
dest : '/library/css',
ext : '.min.css'
},
combine : {
files: {
'/library/css/app.combined.min.css': ['/library/css/main.min.css', '/library/css/font-awesome.min.css']
}
}
}
And for js, use uglify like this:
uglify: {
my_target: {
files: {
'/library/js/app.combined.min.js' : ['/app.js', '/controllers/*.js']
}
}
}
In my case, It was from Stored Producers. I was removed a field from table and forgotten to remove it from my SP.
Try this...to select the option with text myText
$("#my-Select option[text=" + myText +"]").prop("selected", true);
For anyone else who wants to set Eclipse style goto definition, you need to create .sublime-mousemap
file in Sublime User
folder.
Windows - create Default (Windows).sublime-mousemap
in %appdata%\Sublime Text 3\Packages\User
Linux - create Default (Linux).sublime-mousemap
in ~/.config/sublime-text-3/Packages/User
Mac - create Default (OSX).sublime-mousemap
in ~/Library/Application Support/Sublime Text 3/Packages/User
Now open that file and put the following configuration inside
[
{
"button": "button1",
"count": 1,
"modifiers": ["ctrl"],
"press_command": "drag_select",
"command": "goto_definition"
}
]
You can change modifiers
key as you like.
Since Ctrl-button1
on Windows and Linux is used for multiple selections, adding a second modifier key like Alt might be a good idea if you want to use both features:
[
{
"button": "button1",
"count": 1,
"modifiers": ["ctrl", "alt"],
"press_command": "drag_select",
"command": "goto_definition"
}
]
Alternatively, you could use the right mouse button (button2
) with Ctrl alone, and not interfere with any built-in functions.
worked for me Thanks
Versions for reference
jquery-3.3.1.js
/1.10.19/js/jquery.dataTables.min.js
/buttons/1.5.2/js/dataTables.buttons.min.js
function copyToClipboard(text) {
var dummy = document.createElement("textarea");
// to avoid breaking orgain page when copying more words
// cant copy when adding below this code
// dummy.style.display = 'none'
document.body.appendChild(dummy);
//Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')
Have you tried looking at your %PATH% variable. That's what Windows uses to find any executable.
Thanks you all! Now it's work. DATAJPA-231
It will be nice if was possible to create count…By… methods just like find…By ones. Example:
public interface UserRepository extends JpaRepository<User, Long> {
public Long /*or BigInteger */ countByActiveTrue();
}
Yes, but don't - escaping forward slashes is a good thing. When using JSON inside <script>
tags it's necessary as a </script>
anywhere - even inside a string - will end the script tag.
Depending on where the JSON is used it's not necessary, but it can be safely ignored.
Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
If pressing the Insert key doesn't work, try doubleclicking the INS/OVR label in the lower right corner of Visual Studio.
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
If $a
is the array that's passed, $a[76][0]['id']
should give '76' and $a[76][1]['id']
should give '81', but I can't test as I don't have PHP installed on this machine.
In my case a WAMP server was installed before on my pc, so when installing the new one some files not overwritten, all you have to do in that case is to go to the C:\ and delete the whole WAMP folder then install it again.
With modern Git versions, the command to use would be:
git push -u origin <branch_name_test>
This will automatically set the branch name to track from remote and push in one go.
you can use ref
to call the function of the child component from the parent
in functional component, you have to use useImperativeHandle
for getting ref into a child like below
import React, { forwardRef, useRef, useImperativeHandle } from 'react';
export default function ParentFunction() {
const childRef = useRef();
return (
<div className="container">
<div>
Parent Component
</div>
<button
onClick={() => { childRef.current.showAlert() }}
>
Call Function
</button>
<Child ref={childRef}/>
</div>
)
}
const Child = forwardRef((props, ref) => {
useImperativeHandle(
ref,
() => ({
showAlert() {
alert("Child Function Called")
}
}),
)
return (
<div>Child Component</div>
)
})
Child.js
import s from './Child.css';
class Child extends Component {
getAlert() {
alert('clicked');
}
render() {
return (
<h1>Hello</h1>
);
}
}
export default Child;
Parent.js
class Parent extends Component {
render() {
onClick() {
this.refs.child.getAlert();
}
return (
<div>
<Child ref="child" />
<button onClick={this.onClick}>Click</button>
</div>
);
}
}
Unfortunately that approach is not portable C++ (so far).
All standard names are in namespace std
and moreover you cannot know which names are NOT defined by including and header (in other words it's perfectly legal for an implementation to declare the name std::string
directly or indirectly when using #include <vector>
).
Despite this however you are required by the language to know and tell the compiler which standard header includes which part of the standard library. This is a source of portability bugs because if you forget for example #include <map>
but use std::map
it's possible that the program compiles anyway silently and without warnings on a specific version of a specific compiler, and you may get errors only later when porting to another compiler or version.
In my opinion there are no valid technical excuses because this is necessary for the general user: the compiler binary could have all standard namespace built in and this could actually increase the performance even more than precompiled headers (e.g. using perfect hashing for lookups, removing standard headers parsing or loading/demarshalling and so on).
The use of standard headers simplifies the life of who builds compilers or standard libraries and that's all. It's not something to help users.
However this is the way the language is defined and you need to know which header defines which names so plan for some extra neurons to be burnt in pointless configurations to remember that (or try to find and IDE that automatically adds the standard headers you use and removes the ones you don't... a reasonable alternative).
Simple fix: Attach a random query string to the image:
<img src="foo.cgi?random=323527528432525.24234" alt="">
What the HTTP RFC says:
Cache-Control: no-cache
But that doesn't work that well :)
The parameter(s) to isset()
must be a variable reference and not an expression (in your case a concatenation); but you can group multiple conditions together like this:
if (isset($_POST['search_term'], $_POST['postcode'])) {
}
This will return true
only if all arguments to isset()
are set and do not contain null
.
Note that isset($var)
and isset($var) == true
have the same effect, so the latter is somewhat redundant.
Update
The second part of your expression uses empty()
like this:
empty ($_POST['search_term'] . $_POST['postcode']) == false
This is wrong for the same reasons as above. In fact, you don't need empty()
here, because by that time you would have already checked whether the variables are set, so you can shortcut the complete expression like so:
isset($_POST['search_term'], $_POST['postcode']) &&
$_POST['search_term'] &&
$_POST['postcode']
Or using an equivalent expression:
!empty($_POST['search_term']) && !empty($_POST['postcode'])
Final thoughts
You should consider using filter
functions to manage the inputs:
$data = filter_input_array(INPUT_POST, array(
'search_term' => array(
'filter' => FILTER_UNSAFE_RAW,
'flags' => FILTER_NULL_ON_FAILURE,
),
'postcode' => array(
'filter' => FILTER_UNSAFE_RAW,
'flags' => FILTER_NULL_ON_FAILURE,
),
));
if ($data === null || in_array(null, $data, true)) {
// some fields are missing or their values didn't pass the filter
die("You did something naughty");
}
// $data['search_term'] and $data['postcode'] contains the fields you want
Btw, you can customize your filters to check for various parts of the submitted values.
To expand on @PhiLho answer, you can center a very large image (or any size image) on a page with:
{
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center;
}
Or you could use a smaller image with a background color that matches the background of the image (if it is a solid color). This may or may not suit your purposes.
{
background-color: green;
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center;
}
You can create Class Person
with fields firstName
and lastName
and define method toString()
. Here I created a util method which returns String presentation of a Person
object.
This is a sample
Main
public class Main {
public static void main(String[] args) {
Person person = generatePerson();
String personStr = personToString(person);
System.out.println(personStr);
}
private static Person generatePerson() {
String firstName = "firstName";//generateFirstName();
String lastName = "lastName";//generateLastName;
return new Person(firstName, lastName);
}
/*
You can even put this method into a separate util class.
*/
private static String personToString(Person person) {
return person.getFirstName() + "\n" + person.getLastName();
}
}
Person
public class Person {
private String firstName;
private String lastName;
//getters, setters, constructors.
}
I prefer a separate util method to toString()
, because toString()
is used for debug.
https://stackoverflow.com/a/3615741/4587961
I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.
Replace
f = open(D\\python\\HW\\2_1 - Copy.cp,"r");
by
f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")
What tutorial are you using?
Give this a try:
success: function(json) {
console.log(JSON.stringify(json.topics));
$.each(json.topics, function(idx, topic){
$("#nav").html('<a href="' + topic.link_src + '">' + topic.link_text + "</a>");
});
},
Okay this code does exactly what you need:
HTML:
<div class="class1">nothing happens hear.</div>
<div class="class1 class2">This element will receive yout code.</div>
<div class="class1">nothing happens hear.</div>
JS:
function getElementMultipleClasses() {
var x = document.getElementsByClassName("class1 class2");
x[0].innerHTML = "This is the element you want";
}
getElementMultipleClasses();
Hope it helps! ;)
The previous answers are all doing more work than they need to. Just use array_diff. This is the simplest way to do it:
$containsAllValues = !array_diff($search_this, $all);
That's all you have to do.
This is a great question and I was surprised at how difficult it was to find a clear and complete answer, most of the answers I found were either sudo-code or not 100% complete.
I was able to create a complete solution to copy and save the data from my DataGridView to an excel file based on Jake's answer so I'm posting my complete solution in the hopes that it can help other new comers to c# like myself :)
First off, you will need the Microsoft.Office.Interop.Excel
reference in your project. See MSDN on how to add it.
My Code:
using Excel = Microsoft.Office.Interop.Excel;
private void btnExportToExcel_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = "Inventory_Adjustment_Export.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
// Copy DataGridView results to clipboard
copyAlltoClipboard();
object misValue = System.Reflection.Missing.Value;
Excel.Application xlexcel = new Excel.Application();
xlexcel.DisplayAlerts = false; // Without this you will get two confirm overwrite prompts
Excel.Workbook xlWorkBook = xlexcel.Workbooks.Add(misValue);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// Format column D as text before pasting results, this was required for my data
Excel.Range rng = xlWorkSheet.get_Range("D:D").Cells;
rng.NumberFormat = "@";
// Paste clipboard results to worksheet range
Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
// For some reason column A is always blank in the worksheet. ¯\_(?)_/¯
// Delete blank column A and select cell A1
Excel.Range delRng = xlWorkSheet.get_Range("A:A").Cells;
delRng.Delete(Type.Missing);
xlWorkSheet.get_Range("A1").Select();
// Save the excel file under the captured location from the SaveFileDialog
xlWorkBook.SaveAs(sfd.FileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlexcel.DisplayAlerts = true;
xlWorkBook.Close(true, misValue, misValue);
xlexcel.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlexcel);
// Clear Clipboard and DataGridView selection
Clipboard.Clear();
dgvItems.ClearSelection();
// Open the newly saved excel file
if (File.Exists(sfd.FileName))
System.Diagnostics.Process.Start(sfd.FileName);
}
}
private void copyAlltoClipboard()
{
dgvItems.SelectAll();
DataObject dataObj = dgvItems.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occurred while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
yum install gcc-c++
on aws ec2 (aws linux),it works
Eclipse has an option to format automatically when saving the file. There is no option for this in IntelliJ although you can configure a macro for the Ctrl+S (Cmd+S on Mac) keys to format the code and save it.
You can use a function which I have created.
def method_finder(classname):
non_magic_class = []
class_methods = dir(classname)
for m in class_methods:
if m.startswith('__'):
continue
else:
non_magic_class.append(m)
return non_magic_class
method_finder(list)
Output:
['append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
You can use new C# 6.0 Language Features:
(s) => { return Convert.ToInt32(s); }
with
corresponding method group Convert.ToInt32
new Converter<string, int>(Convert.ToInt32)
with: Convert.ToInt32
The result will be:
var intList = new List<int>(Array.ConvertAll(sNumbers.Split(','), Convert.ToInt32));
Unfortunately, there doesn't appear to be a magic bullet. Bottom line up front: "context".
Google indeed ignores most punctuation, with the following exceptions:
As such, it is not well suited for these types of searchs. Google Code however does have syntax for searching through their code projects, that includes a robust language/syntax for dealing with "special characters". If looking at someone else's code could help solve a problem, this may be an option.
Unfortunately, this is not a limitation unique to google. You may find that your best successes hinge on providing as much 'context' to the problem as possible. If you are searching to find what $- means, providing information about the problem's domain may yield good results.
For example, searching "special perl variables" quickly yields your answer in the first entry on the results page.
Just a thought, but you may check the influence of a ulimit -v
option.
That is not an actual solution since it would limit address space available for all process, but that would allow you to check the behavior of your application with a limited virtual memory.
Instead of using the built in array function aka:
int x[3] = {0, 1, 2};
you should use the array class and the array template. Try:
#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};
So now if you want to find the length of the array, all you have to do is using the size function in the array class.
Name_of_Array.size();
and that should return the length of elements in the array.
select month(dateField), year(dateField)
I found an easy solution to your question. I also wanted to use an encoded URL but nothing helped me.
http://example.com/query?q=random%20word%20%A3500%20bank%20%24
to use String example = "random word £500 bank $"; you can you below code.
String example = "random word £500 bank $";
String URL = "http://example.com/query?q=" + example.replaceAll(" ","%20");
I had installed Python 32 bit version and psycopg2 64 bit version to get this problem. I installed psycopg2 32 bit version and then it worked.
Use psexec -s
The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.
New Operator for lambda expression added in java 8
Lambda expression is the short way of method writing.
It is indirectly used to implement functional interface
Primary Syntax : (parameters) -> { statements; }
There are some basic rules for effective lambda expressions writting which you should konw.
data = 'data you want inside the file'.
You can use File.write('name of file here', data)
Someone has already made a benchmark: jQuery document.createElement equivalent?
$(document.createElement('div'))
is the big winner.
In my case, I've set a proxy in my emulator. It works back to normal after I removing that proxy.
Actually if you do Ctrl+W W
, you won't need to add that extra Ctrl
. Does the same thing.
This version works better on Windows than the top answer because it understands both /
and path.sep
so that forward slashes work on Windows as they should. Supports absolute and relative paths (relative to the process.cwd
).
/**
* Creates a folder and if necessary, parent folders also. Returns true
* if any folders were created. Understands both '/' and path.sep as
* path separators. Doesn't try to create folders that already exist,
* which could cause a permissions error. Gracefully handles the race
* condition if two processes are creating a folder. Throws on error.
* @param targetDir Name of folder to create
*/
export function mkdirSyncRecursive(targetDir) {
if (!fs.existsSync(targetDir)) {
for (var i = targetDir.length-2; i >= 0; i--) {
if (targetDir.charAt(i) == '/' || targetDir.charAt(i) == path.sep) {
mkdirSyncRecursive(targetDir.slice(0, i));
break;
}
}
try {
fs.mkdirSync(targetDir);
return true;
} catch (err) {
if (err.code !== 'EEXIST') throw err;
}
}
return false;
}
I have had lots of issues with hidden and not visible inputs over the past decade sometimes things are way simpler than we think.
I have had a little wish with IE 5,6,7,8 and 9 for not supporting the opacity and thus the file input would cover the upload image however the following css code has resolved the issue.
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
The following snipped is tested on chrome, IE 5,6,7,8,9,10 the only issue in IE 5 is that it does not support auto margin.
Run the snippet simply copy and paste the CSS and HTML modify the size as you like.
.file-upload{_x000D_
height:100px;_x000D_
width:100px;_x000D_
margin:40px auto;_x000D_
border:1px solid #f0c0d0;_x000D_
border-radius:100px;_x000D_
overflow:hidden;_x000D_
position:relative;_x000D_
}_x000D_
.file-upload input{_x000D_
position:absolute;_x000D_
height:400px;_x000D_
width:400px;_x000D_
left:-200px;_x000D_
top:-200px;_x000D_
background:transparent;_x000D_
opacity:0;_x000D_
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
filter: alpha(opacity=0); _x000D_
}_x000D_
.file-upload img{_x000D_
height:70px;_x000D_
width:70px;_x000D_
margin:15px;_x000D_
}
_x000D_
<div class="file-upload">_x000D_
<!--place upload image/icon first !-->_x000D_
<img src="https://i.stack.imgur.com/dy62M.png" />_x000D_
<!--place input file last !-->_x000D_
<input type="file" name="somename" />_x000D_
</div>
_x000D_
Try print(e.message) this should be able to print your exception.
try:
connection = manager.connect("I2Cx")
except Exception, e:
print(e.message)
Use the constructor: new List<object>(myArray)
"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:
file.py
will be uploaded into your HOME
dir on remote server.
or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:
After connecting to the server pscp will ask for a password.
Try to assign the image that way instead:
imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));
With text type of input you can use this for a better validation,
return (event.keyCode? (event.keyCode == 69 ? false : event.keyCode >= 48 && event.keyCode <= 57) : (event.charCode >= 48 && event.charCode <= 57))? true : event.preventDefault();
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
int[]
and int*
are represented the same way, except int[] allocates (IIRC).
ap
is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.
when you try to access it (x = *ap
), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.
Works for me.
<div ng-show="$scope.showme === true">Hello World</div>
<div ng-repeat="a in $scope.bigdata" ng-init="$scope.showme = true">{{ a.title }}</div>
You can run using the following command. Here I want to run using spring profile local
:
spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=local"
Here's some code. This assumes you are doing this on a form, or a UserControl.
Graphics g = this.CreateGraphics();
SizeF size = g.MeasureString("string to measure");
int nLeft = Convert.ToInt32((this.ClientRectangle.Width / 2) - (size.Width / 2));
int nTop = Convert.ToInt32((this.ClientRectangle.Height / 2) - (size.Height / 2));
From your post, it sounds like the ClientRectangle part (as in, you're not using it) is what's giving you difficulty.
Google has recently made public its internal Collaboratory project (link here). You can start a notebook in the same way as starting a Google Sheet or Google Doc, and then simply share the notebook or add collaborators..
For now, this is the easiest way for me.
Do not use Exceptions to validate your values. Use Util libs instead like apache NumberUtils:
NumberUtils.isNumber(myStringValue);
Edit:
Please notice that, if your string starts with an 0, NumberUtils will interpret your value as hexadecimal.
NumberUtils.isNumber("07") //true
NumberUtils.isNumber("08") //false
Use grep -vc
to ignore grep
in the ps
output and count the lines simultaneously.
if [[ $(ps aux | grep process | grep -vc grep) > 0 ]] ; then echo 1; else echo 0 ; fi
As @wes-floyd and @zpon wrote, add these parameters to SSH to bypass "Are you sure you want to continue connecting (yes/no)?"
-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no
display html form values in same page after clicking on submit button using JS & html codes. After opening it up again it should give that comments in that page.
HTML4 specification states that:
Inline elements may contain only data and other inline elements
Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.
HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.
Since I spent a lot of time on this issue, I thought I'd share my solution. Since spring 3.0.4, there is a configuration parameter that is called <mvc:resources/>
(more about that on the reference documentation website) which can be used to serve static resources while still using the DispatchServlet on your site's root.
In order to use this, use a directory structure that looks like the following:
src/
springmvc/
web/
MyController.java
WebContent/
resources/
img/
image.jpg
WEB-INF/
jsp/
index.jsp
web.xml
springmvc-servlet.xml
The contents of the files should look like:
src/springmvc/web/HelloWorldController.java:
package springmvc.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorldController {
@RequestMapping(value="/")
public String index() {
return "index";
}
}
WebContent/WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
WebContent/WEB-INF/springmvc-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- not strictly necessary for this example, but still useful, see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-controller for more information -->
<context:component-scan base-package="springmvc.web" />
<!-- the mvc resources tag does the magic -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- also add the following beans to get rid of some exceptions -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
<!-- JSTL resolver -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
WebContent/jsp/index.jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1>Page with image</h1>
<!-- use c:url to get the correct absolute path -->
<img src="<c:url value="/resources/img/image.jpg" />" />
Hope this helps :-)
Your Window is not implementing the necessary data binding notifications that the grid requires to use it as a data source, namely the INotifyPropertyChanged interface.
Your "Name2" string needs also to be a property and not a public variable, as data binding is for use with properties.
Implementing the necessary interfaces for using an object as a data source can be found here.
This should be an update/comment to @jquery-guru's answer but as I don't have enough rep it will go here. It fixes the errors that are now generated by the code.
https://jsfiddle.net/vzhrqotw/
The change is basically:
FileUploadCtrl.$inject = ['$scope']
function FileUploadCtrl(scope) {
To:
app.controller('FileUploadCtrl', function($scope)
{
Feel free to move to a more appropriate location if desired.
As to formulas being "updated" in the new row, since all the copying occurs after the shift, the old row (now one index up from the new row) has already had its formula shifted, so copying it to the new row will make the new row reference the old rows cells. A solution would be to parse out the formulas BEFORE the shift, then apply those (a simple String array would do the job. I'm sure you can code that in a few lines).
At start of function:
ArrayList<String> fArray = new ArrayList<String>();
Row origRow = sheet.getRow(sourceRow);
for (int i = 0; i < origRow.getLastCellNum(); i++) {
if (origRow.getCell(i) != null && origRow.getCell(i).getCellType() == Cell.CELL_TYPE_FORMULA)
fArray.add(origRow.getCell(i).getCellFormula());
else fArray.add(null);
}
Then when applying the formula to a cell:
newCell.setCellFormula(fArray.get(i));
Consolidated for quick reference:
public class StringRepeat {
// Java 11 has built-in method - str.repeat(3);
// Apache - StringUtils.repeat(3);
// Google - Strings.repeat("",n);
// System.arraycopy
static String repeat_StringBuilderAppend(String str, int n) {
if (str == null || str.isEmpty())
return str;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(str);
}
return sb.toString();
}
static String repeat_ArraysFill(String str, int n) {
String[] strs = new String[n];
Arrays.fill(strs, str);
return Arrays.toString(strs).replaceAll("\\[|\\]|,| ", "");
}
static String repeat_Recursion(String str, int n) {
if (n <= 0)
return "";
else
return str + repeat_Recursion(str, n - 1);
}
static String repeat_format1(String str, int n) {
return String.format(String.format("%%%ds", n), " ").replace(" ", str);
}
static String repeat_format2(String str, int n) {
return new String(new char[n]).replace("\0", str);
}
static String repeat_format3(String str, int n) {
return String.format("%0" + n + "d", 0).replace("0", str);
}
static String repeat_join(String str, int n) {
return String.join("", Collections.nCopies(n, str));
}
static String repeat_stream(String str, int n) {
return Stream.generate(() -> str).limit(n).collect(Collectors.joining());
}
public static void main(String[] args) {
System.out.println(repeat_StringBuilderAppend("Mani", 3));
System.out.println(repeat_ArraysFill("Mani", 3));
System.out.println(repeat_Recursion("Mani", 3));
System.out.println(repeat_format1("Mani", 3));
System.out.println(repeat_format2("Mani", 3));
System.out.println(repeat_format3("Mani", 3));
System.out.println(repeat_join("Mani", 3));
System.out.println(repeat_stream("Mani", 3));
}
}
I strongly suggest placing this somewhere in your project:
extension String {
func trim() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
func trim(withSet: NSCharacterSet) -> String {
return self.stringByTrimmingCharactersInSet(withSet)
}
}
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
proper example. just create int type field( example mobile number) in the database and submit an blank value for the following database through a form or just insert using SQL. what it will be saved in database 0 because it is int type and cannot be saved as blank or null. therefore it is empty but it will be saved as 0. so when you fetch data through PHP and check for the empty values. it is very useful and logically correct.
0.00, 0.000, 0.0000 .... 0.0...0 is also empty and the above example can also be used for storing different type of values in database like float, double, decimal( decimal have different variants like 0.000 and so on.
Here's how to make all auto-increment sequences match actual data:
Create a procedure to enforce next value as was already described in this thread:
CREATE OR REPLACE PROCEDURE Reset_Sequence(
P_Seq_Name IN VARCHAR2,
P_Val IN NUMBER DEFAULT 0)
IS
L_Current NUMBER := 0;
L_Difference NUMBER := 0;
L_Minvalue User_Sequences.Min_Value%Type := 0;
BEGIN
SELECT Min_Value
INTO L_Minvalue
FROM User_Sequences
WHERE Sequence_Name = P_Seq_Name;
EXECUTE Immediate 'select ' || P_Seq_Name || '.nextval from dual' INTO L_Current;
IF P_Val < L_Minvalue THEN
L_Difference := L_Minvalue - L_Current;
ELSE
L_Difference := P_Val - L_Current;
END IF;
IF L_Difference = 0 THEN
RETURN;
END IF;
EXECUTE Immediate 'alter sequence ' || P_Seq_Name || ' increment by ' || L_Difference || ' minvalue ' || L_Minvalue;
EXECUTE Immediate 'select ' || P_Seq_Name || '.nextval from dual' INTO L_Difference;
EXECUTE Immediate 'alter sequence ' || P_Seq_Name || ' increment by 1 minvalue ' || L_Minvalue;
END Reset_Sequence;
Create another procedure to reconcile all sequences with actual content:
CREATE OR REPLACE PROCEDURE RESET_USER_SEQUENCES_TO_DATA
IS
STMT CLOB;
BEGIN
SELECT 'select ''BEGIN'' || chr(10) || x || chr(10) || ''END;'' FROM (select listagg(x, chr(10)) within group (order by null) x FROM ('
|| X
|| '))'
INTO STMT
FROM
(SELECT LISTAGG(X, ' union ') WITHIN GROUP (
ORDER BY NULL) X
FROM
(SELECT CHR(10)
|| 'select ''Reset_Sequence('''''
|| SEQ_NAME
|| ''''','' || coalesce(max('
|| COL_NAME
|| '), 0) || '');'' x from '
|| TABLE_NAME X
FROM
(SELECT TABLE_NAME,
REGEXP_SUBSTR(WTEXT, 'NEW\.(\S*) IS NULL',1,1,'i',1) COL_NAME,
REGEXP_SUBSTR(BTEXT, '(\.|\s)([a-z_]*)\.nextval',1,1,'i',2) SEQ_NAME
FROM USER_TRIGGERS
LEFT JOIN
(SELECT NAME BNAME,
TEXT BTEXT
FROM USER_SOURCE
WHERE TYPE = 'TRIGGER'
AND UPPER(TEXT) LIKE '%NEXTVAL%'
)
ON BNAME = TRIGGER_NAME
LEFT JOIN
(SELECT NAME WNAME,
TEXT WTEXT
FROM USER_SOURCE
WHERE TYPE = 'TRIGGER'
AND UPPER(TEXT) LIKE '%IS NULL%'
)
ON WNAME = TRIGGER_NAME
WHERE TRIGGER_TYPE = 'BEFORE EACH ROW'
AND TRIGGERING_EVENT = 'INSERT'
)
)
) ;
EXECUTE IMMEDIATE STMT INTO STMT;
--dbms_output.put_line(stmt);
EXECUTE IMMEDIATE STMT;
END RESET_USER_SEQUENCES_TO_DATA;
NOTES:
id
is the method you want to use: to convert it to hex:
hex(id(variable_here))
For instance:
x = 4
print hex(id(x))
Gave me:
0x9cf10c
Which is what you want, right?
(Fun fact, binding two variables to the same int
may result in the same memory address being used.)
Try:
x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))
This gave me identical pairs, even for the large integers.
A different approach:
The vrapper plugin emulates vim
inside the Eclipse editor. One of its features is visual block
mode which works fine inside Eclipse.
It is by default mapped to Ctrl-V
which interferes with the paste command in Eclipse. You can either remap the visual block
mode to a different shortcut, or remap the paste
command to a different key. I chose the latter: remapped the paste
command to Ctrl-Shift-V
to match my terminal's behavior.
A soft git reset will put committed changes back into your index. Next, checkout the branch you had intended to commit on. Then git commit with a new commit message.
git reset --soft <commit>
git checkout <branch>
git commit -m "Commit message goes here"
From git docs:
git reset [<mode>] [<commit>]
This form resets the current branch head to and possibly updates the index (resetting it to the tree of ) and the working tree depending on . If is omitted, defaults to --mixed. The must be one of the following:
--soft
Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.
If you are using Python 3, you can use urllib.parse
url = """example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0"""
import urllib.parse
urllib.parse.unquote(url)
gives:
'example.com?title=????????+??????'
I had the same problem. In my case it arises, because the lookup-table "country" has an existing record with countryId==0 and a primitive primary key and I try to save a User with a countryID==0. Change the primary key of country to Integer. Now Hibernate can identify new records.
For the recommendation of using wrapper classes as primary key see this stackoverflow question
I had similar problem and in my opinion best option is to use just a little bit of javascript or jquery.
You can get wanted divs to be same height by getting highest div value and applying that value to all other divs. If you have many divs and many solutions i suggest to write little advance js code to find out which of all divs is the highest and then use it's value.
With jquery and 2 divs it's very simple, here is example code:
$('.smaller-div').css('height',$('.higher-div').css('height'));
And for the end, there is 1 last thing. Their padding (top and bottom) must be the same ! If one have larger padding you need to eliminate padding difference.
The answer is "nowhere" since the date formatting is proprietary functionality. I don't think the toString functions are intended to conform to a specific format. e.g. in the ECMAScript 5.1 spec (http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, 2/8/2013, page 173), the toString function is documented as follows:
"The contents of the String are implementation-dependent"
Functions such as the samples below could be used to accomplish formatting fairly easily.
function pad(toPad, padWith) {
return (String(padWith) + String(toPad)).slice(-1 * padWith.length);
}
function dateAsInputValue(toFormat) {
if(!(toFormat instanceof Date)) return null;
return toFormat.getFullYear() + "-" + pad(toFormat.getMonth() + 1, "00") + "-" + pad(toFormat.getDate(), "00");
}
function timeAsInputValue(toFormat) {
if(!(toFormat instanceof Date)) return null;
return pad(toFormat.getHours(), "00") + ":" + pad(toFormat.getMinutes(), "00") + ":" + pad(toFormat.getSeconds(), "00");
}
Open up your git bash and type
echo $HOME
This shall be the same folder as you get when you open your command window (cmd) and type
echo %USERPROFILE%
And – of course – the .ssh
folder shall be present on THAT directory.