In my case, it was just because there were no source file in the target. All of my library was template with source code in the header. Adding an empty file.cpp solved the problem.
I'll answer the more general question of how to have a canvas dynamically adapt in size upon window resize. The accepted answer appropriately handles the case where width and height are both supposed to be 100%, which is what was asked for, but which also will change the aspect ratio of the canvas. Many users will want the canvas to resize on window resize, but while keeping the aspect ratio untouched. It's not the exact question, but it "fits in", just putting the question into a slightly more general context.
The window will have some aspect ratio (width / height), and so will the canvas object. How you want these two aspect ratios to relate to each other is one thing you'll have to be clear about, there is no "one size fits all" answer to that question - I'll go through some common cases of what you might want.
Most important thing you have to be clear about: the html canvas object has a width attribute and a height attribute; and then, the css of the same object also has a width and a height attribute. Those two widths and heights are different, both are useful for different things.
Changing the width and height attributes is one method with which you can always change the size of your canvas, but then you'll have to repaint everything, which will take time and is not always necessary, because some amount of size change you can accomplish via the css attributes, in which case you do not redraw the canvas.
I see 4 cases of what you might want to happen on window resize (all starting with a full screen canvas)
1: you want the width to remain 100%, and you want the aspect ratio to stay as it was. In that case, you do not need to redraw the canvas; you don't even need a window resize handler. All you need is
$(ctx.canvas).css("width", "100%");
where ctx is your canvas context. fiddle: resizeByWidth
2: you want width and height to both stay 100%, and you want the resulting change in aspect ratio to have the effect of a stretched-out image. Now, you still don't need to redraw the canvas, but you need a window resize handler. In the handler, you do
$(ctx.canvas).css("height", window.innerHeight);
fiddle: messWithAspectratio
3: you want width and height to both stay 100%, but the answer to the change in aspect ratio is something different from stretching the image. Then you need to redraw, and do it the way that is outlined in the accepted answer.
fiddle: redraw
4: you want the width and height to be 100% on page load, but stay constant thereafter (no reaction to window resize.
fiddle: fixed
All fiddles have identical code, except for line 63 where the mode is set. You can also copy the fiddle code to run on your local machine, in which case you can select the mode via a querystring argument, as ?mode=redraw
In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.
The class Integer represents an int value, but it can hold a null value. Depending on your check
method, you could be returning an int or an Integer.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
For BIFF .xls files
application/vnd.ms-excel
For Excel2007 and above .xlsx files
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.
When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).
Remember to call wait() on the child process to prevent any lingering zombies.
jsonIssues = [...jsonIssues,{ID:'3',Name:'name 3',Notes:'NOTES 3'}]
CSS is not a programming language, so the question of turing-completeness is a meaningless one. If programming extensions are added to CSS such as was the case in IE6 then that new synthesis is a whole different thing.
CSS is merely a description of styles; it does not have any logic, and its structure is flat.
1) In Laravel 5 , form helper is removed .You need to first install laravel collective .
Refer link: https://laravelcollective.com/docs/5.1/html
{!! Form::open(array('route' => 'log_in')) !!}
OR
{!! Form::open(array('route' => '/')) !!}
2) For laravel 4, form helper is already there
{{ Form::open(array('url' => '/')) }}
You can add a reference to System.Configuration
in your project and then:
using System.Configuration;
then
string sValue = ConfigurationManager.AppSettings["BatchFile"];
with an app.config
file like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="BatchFile" value="blah.bat" />
</appSettings>
</configuration>
--EDIT-- It looks like I took his question heading too literally - he was asking for an array of ints rather than a List --EDIT ENDS--
Yet another helper method...
private static int[] StringToIntArray(string myNumbers)
{
List<int> myIntegers = new List<int>();
Array.ForEach(myNumbers.Split(",".ToCharArray()), s =>
{
int currentInt;
if (Int32.TryParse(s, out currentInt))
myIntegers.Add(currentInt);
});
return myIntegers.ToArray();
}
quick test code for it, too...
static void Main(string[] args)
{
string myNumbers = "1,2,3,4,5";
int[] myArray = StringToIntArray(myNumbers);
Console.WriteLine(myArray.Sum().ToString()); // sum is 15.
myNumbers = "1,2,3,4,5,6,bad";
myArray = StringToIntArray(myNumbers);
Console.WriteLine(myArray.Sum().ToString()); // sum is 21
Console.ReadLine();
}
I also got this error (within the Eclipse-based STM32CubeIDE on Windows).
After double-clicking on the "multiple target patterns" error it showed a path to a .ld
file. It turns out to be another "illegal character" problem. The offending character was the (wait for it): =
Heuristic of the week: use only [a..z] in your paths, as there are bound to be other illegal characters </vomit>.
The GNU make manual doesn't explicitly document this.
tl;dr What to do in modern (2018) times? Assume tel:
is supported, use it and forget about anything else.
The tel:
URI scheme RFC5431 (as well as sms:
but also feed:
, maps:
, youtube:
and others) is handled by protocol handlers (as mailto:
and http:
are).
They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto:
protocol handler with same meaning and behaviour of tel:
but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.
What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler()
and related functions) simplifying also the check for their support through isProtocolHandlerRegistered()
function.
There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).
In general what I suggest is:
tel:
is supported (yes, it's not true for very old devices but IMO you can ignore them).tel:
isn't supported then change links to use callto:
and repeat check desctibed in 3.tel:
and callto:
aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href
with javascript:void(0)
and (if number isn't repeated in text span) putting, telephone number in title
. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto:
and tel:
.Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:
tel:
is supported.tel:
with callto:
.tel:
or leave it as is (assuming there are good chances Skype is installed).Andrew's answer is good.
And just to help you out a bit more, here's how you use multiple formatting in one string
"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".
If you are using ints instead of string, use %d instead of %s.
"My name is %s and i'm %d" % ('john', 12) #My name is john and i'm 12
ListenForClients
is getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in Main
. When two instances of the TcpListener
try to listen on the same port, you get that error.
Addition after very useful comment of mhand at the end
Although most solutions might work, I think they are not very efficiently. Suppose if you only want the first few items of the first few chunks. Then you wouldn't want to iterate over all (zillion) items in your sequence.
The following will at utmost enumerate twice: once for the Take and once for the Skip. It won't enumerate over any more elements than you will use:
public static IEnumerable<IEnumerable<TSource>> ChunkBy<TSource>
(this IEnumerable<TSource> source, int chunkSize)
{
while (source.Any()) // while there are elements left
{ // still something to chunk:
yield return source.Take(chunkSize); // return a chunk of chunkSize
source = source.Skip(chunkSize); // skip the returned chunk
}
}
Suppose you divide your source into chunks of chunkSize
. You enumerate only the first N chunks. From every enumerated chunk you'll only enumerate the first M elements.
While(source.Any())
{
...
}
the Any will get the Enumerator, do 1 MoveNext() and returns the returned value after Disposing the Enumerator. This will be done N times
yield return source.Take(chunkSize);
According to the reference source this will do something like:
public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count)
{
return TakeIterator<TSource>(source, count);
}
static IEnumerable<TSource> TakeIterator<TSource>(IEnumerable<TSource> source, int count)
{
foreach (TSource element in source)
{
yield return element;
if (--count == 0) break;
}
}
This doesn't do a lot until you start enumerating over the fetched Chunk. If you fetch several Chunks, but decide not to enumerate over the first Chunk, the foreach is not executed, as your debugger will show you.
If you decide to take the first M elements of the first chunk then the yield return is executed exactly M times. This means:
After the first chunk has been yield returned, we skip this first Chunk:
source = source.Skip(chunkSize);
Once again: we'll take a look at reference source to find the skipiterator
static IEnumerable<TSource> SkipIterator<TSource>(IEnumerable<TSource> source, int count)
{
using (IEnumerator<TSource> e = source.GetEnumerator())
{
while (count > 0 && e.MoveNext()) count--;
if (count <= 0)
{
while (e.MoveNext()) yield return e.Current;
}
}
}
As you see, the SkipIterator
calls MoveNext()
once for every element in the Chunk. It doesn't call Current
.
So per Chunk we see that the following is done:
Take():
If the content is enumerated: GetEnumerator(), one MoveNext and one Current per enumerated item, Dispose enumerator;
Skip(): for every chunk that is enumerated (NOT the contents of the chunk): GetEnumerator(), MoveNext() chunkSize times, no Current! Dispose enumerator
If you look at what happens with the enumerator, you'll see that there are a lot of calls to MoveNext(), and only calls to Current
for the TSource items you actually decide to access.
If you take N Chunks of size chunkSize, then calls to MoveNext()
If you decide to enumerate only the first M elements of every fetched chunk, then you need to call MoveNext M times per enumerated Chunk.
The total
MoveNext calls: N + N*M + N*chunkSize
Current calls: N*M; (only the items you really access)
So if you decide to enumerate all elements of all chunks:
MoveNext: numberOfChunks + all elements + all elements = about twice the sequence
Current: every item is accessed exactly once
Whether MoveNext is a lot of work or not, depends on the type of source sequence. For lists and arrays it is a simple index increment, with maybe an out of range check.
But if your IEnumerable is the result of a database query, make sure that the data is really materialized on your computer, otherwise the data will be fetched several times. DbContext and Dapper will properly transfer the data to local process before it can be accessed. If you enumerate the same sequence several times it is not fetched several times. Dapper returns an object that is a List, DbContext remembers that the data is already fetched.
It depends on your Repository whether it is wise to call AsEnumerable() or ToLists() before you start to divide the items in Chunks
setTimeout(function () { _x000D_
swal({_x000D_
title: "Wow!",_x000D_
text: "Message!",_x000D_
type: "success",_x000D_
confirmButtonText: "OK"_x000D_
},_x000D_
function(isConfirm){_x000D_
if (isConfirm) {_x000D_
window.location.href = "//stackoverflow.com";_x000D_
}_x000D_
}); }, 1000);
_x000D_
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css">
_x000D_
Or you can use the build-in function timer
, i.e.:
swal({_x000D_
title: "Success!",_x000D_
text: "Redirecting in 2 seconds.",_x000D_
type: "success",_x000D_
timer: 2000,_x000D_
showConfirmButton: false_x000D_
}, function(){_x000D_
window.location.href = "//stackoverflow.com";_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css">
_x000D_
If the application is running in the foreground, iOS won't show a notification banner/alert. That's by design. But we can achieve it by using UILocalNotification
as follows
Check whether application is in active state on receiving a remote
notification. If in active state fire a UILocalNotification.
if (application.applicationState == UIApplicationStateActive ) {
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.userInfo = userInfo;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = message;
localNotification.fireDate = [NSDate date];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
SWIFT:
if application.applicationState == .active {
var localNotification = UILocalNotification()
localNotification.userInfo = userInfo
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.alertBody = message
localNotification.fireDate = Date()
UIApplication.shared.scheduleLocalNotification(localNotification)
}
From oracle documentation page:
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword
super
.
You can also use super
to refer to a hidden field (although hiding fields is discouraged).
Use of super
in constructor of subclasses:
Invocation of a superclass constructor must be the first line in the subclass constructor.
The syntax for calling a superclass constructor is
super();
or:
super(parameter list);
With super()
, the superclass no-argument constructor is called. With super(parameter list)
, the superclass constructor with a matching parameter list is called.
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Related post:
I have same issue. Error message for me is not complete. But in my case, I've added generation jar with sources. By placing this code in pom.xml:
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
<executions>
<execution>
<phase>deploy</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
So in deploy phase I execute source:jar goal which produces jar with sources. And deploy ends with BUILD SUCCESS
stat appears to do this with the fewest system calls:
$ set debian-live-8.2.0-amd64-xfce-desktop.iso
$ strace stat --format %s $1 | wc
282 2795 27364
$ strace wc --bytes $1 | wc
307 3063 29091
$ strace du --bytes $1 | wc
437 4376 41955
$ strace find $1 -printf %s | wc
604 6061 64793
U can use this Edittext....This will help you.
<EditText
android:id="@+id/EditText02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="5"
android:gravity="top|left"
android:inputType="textMultiLine" />
Since 2019 you can now use the new functionality called Github package registry.
Basically the process is:
settings.xml
deploy using
mvn deploy -Dregistry=https://maven.pkg.github.com/yourusername -Dtoken=yor_token
I am not sure I got you but this might be what you are looking for:
SELECT i.invoiceid, sum(case when i.amount is not null then i.amount else 0 end), sum(case when i.amount is not null then i.amount else 0 end) - sum(case when p.amount is not null then p.amount else 0 end) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN payments p ON ip.paymentid = p.paymentid
LEFT JOIN customers c ON p.customerid = c.customerid
WHERE c.customernumber = '100'
GROUP BY i.invoiceid
This would get you the amounts sums in case there are multiple payment rows for each invoice
NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];
Java's String
implements hashCode like this:
public int hashCode()
Returns a hash code for this string. The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)
So something like this:
int HashTable::hash (string word) {
int result = 0;
for(size_t i = 0; i < word.length(); ++i) {
result += word[i] * pow(31, i);
}
return result;
}
Using python 64 bit solves lot of problems.
If you want to install requests directly you can use the "-m" (module) option available to python.
python.exe -m pip install requests
You can do this directly in PowerShell, though you may need to use the full python path (eg. C:\Python27\python.exe
) instead of just python.exe
.
As mentioned in the comments, if you have added Python to your path you can simply do:
python -m pip install requests
With coming in of Java NIO, below is a possible solution too
With Java 9:
private static void copyDir(String src, String dest, boolean overwrite) {
try {
Files.walk(Paths.get(src)).forEach(a -> {
Path b = Paths.get(dest, a.toString().substring(src.length()));
try {
if (!a.toString().equals(src))
Files.copy(a, b, overwrite ? new CopyOption[]{StandardCopyOption.REPLACE_EXISTING} : new CopyOption[]{});
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
//permission issue
e.printStackTrace();
}
}
With Java 7:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
Path sourceParentFolder = Paths.get("/sourceParent");
Path destinationParentFolder = Paths.get("/destination/");
try {
Stream<Path> allFilesPathStream = Files.walk(sourceParentFolder);
Consumer<? super Path> action = new Consumer<Path>(){
@Override
public void accept(Path t) {
try {
String destinationPath = t.toString().replaceAll(sourceParentFolder.toString(), destinationParentFolder.toString());
Files.copy(t, Paths.get(destinationPath));
}
catch(FileAlreadyExistsException e){
//TODO do acc to business needs
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
allFilesPathStream.forEach(action );
} catch(FileAlreadyExistsException e) {
//file already exists and unable to copy
} catch (IOException e) {
//permission issue
e.printStackTrace();
}
}
}
Here is a rough but more declarative solution. I haven't been able to get it down to a single annotation, but this seems to work well. Also not sure about performance on large data sets.
Given this JSON:
{
"list": [
{
"wrapper": {
"name": "Jack"
}
},
{
"wrapper": {
"name": "Jane"
}
}
]
}
And these model objects:
public class RootObject {
@JsonProperty("list")
@JsonDeserialize(contentUsing = SkipWrapperObjectDeserializer.class)
@SkipWrapperObject("wrapper")
public InnerObject[] innerObjects;
}
and
public class InnerObject {
@JsonProperty("name")
public String name;
}
Where the Jackson voodoo is implemented like:
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface SkipWrapperObject {
String value();
}
and
public class SkipWrapperObjectDeserializer extends JsonDeserializer<Object> implements
ContextualDeserializer {
private Class<?> wrappedType;
private String wrapperKey;
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException {
SkipWrapperObject skipWrapperObject = property
.getAnnotation(SkipWrapperObject.class);
wrapperKey = skipWrapperObject.value();
JavaType collectionType = property.getType();
JavaType collectedType = collectionType.containedType(0);
wrappedType = collectedType.getRawClass();
return this;
}
@Override
public Object deserialize(JsonParser parser, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.readTree(parser);
JsonNode wrapped = objectNode.get(wrapperKey);
Object mapped = mapIntoObject(wrapped);
return mapped;
}
private Object mapIntoObject(JsonNode node) throws IOException,
JsonProcessingException {
JsonParser parser = node.traverse();
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(parser, wrappedType);
}
}
Hope this is useful to someone!
If somebody comes looking it should look like this:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/domains/example.com/html
ErrorLog /var/www/domains/example.com/apache.error.log
CustomLog /var/www/domains/example.com/apache.access.log common
php_flag log_errors on
php_flag display_errors on
php_value error_reporting 2147483647
php_value error_log /var/www/domains/example.com/php.error.log
</VirtualHost>
This is for development only since display_error
is turned on. You will notice that the Apache error log is separate from the PHP error log. The good stuff is in php.error.log
.
Take a look here for the error_reporting
key http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting
Rather than using javscript/jquery the easiest way I found is:
<iframe style="min-height:98vh" src="http://yourdomain.com" width="100%"></iframe>
_x000D_
Here 1vh = 1% of Browser window height. So the theoretical value of height to be set is 100vh but practically 98vh did the magic.
From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):
Android and iOS devices respect the following
<meta>
tag:<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this
<meta>
tag be included within the page's<head>
element.
JavaScript code using ng-controller:
$scope.checkkey = function (event) {
alert(event.keyCode); //this will show the ASCII value of the key pressed
}
In HTML:
<input type="text" ng-keypress="checkkey($event)" />
You can now place your checks and other conditions using the keyCode method.
this works....
<script language="javascript">
(function($) {
$.fn.MessageBox = function(msg) {
return this.each(function(){
alert(msg);
})
};
})(jQuery);?
</script>
.
<body>
<div class="Title">Welcome!</div>
<input type="button" value="ahaha" onclick="$(this).MessageBox('msg');" />
</body>
edit
you are using a failsafe jQuery code using the $ alias... it should be written like:
(function($) {
// plugin code here, use $ as much as you like
})(jQuery);
or
jQuery(function($) {
// your code using $ alias here
});
note that it has a 'jQuery' word in each of it....
On mac, open the terminal and type:
cd /usr/local/mysql/bin
then type:
./mysql -u root -p
It will ask you for the mysql root password. Enter your password and use mysql database in the terminal.
In MSVC to suppress a particular warning it is enough to specify the it's number to compiler as /wd#. My CMakeLists.txt contains such the block:
If (MSVC)
Set (CMAKE_EXE_LINKER_FLAGS "$ {CMAKE_EXE_LINKER_FLAGS} / NODEFAULTLIB: LIBCMT")
Add_definitions (/W4 /wd4512 /wd4702 /wd4100 /wd4510 /wd4355 /wd4127)
Add_definitions (/D_CRT_SECURE_NO_WARNINGS)
Elseif (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_GNUC)
Add_definitions (-Wall -W -pedantic)
Else ()
Message ("Unknown compiler")
Endif ()
Now I can not say what exactly /wd4512 /wd4702 /wd4100 /wd4510 /wd4355 /wd4127 mean, because I do not pay any attention to MSVC for three years, but they suppress superpedantic warnings that does not influence the result.
What could help you is a watchdog. Watchdogs were used extensively in industrial computing in the 1980s. Hardware failures were much more common then - another answer also refers to that period.
A watchdog is a combined hardware/software feature. The hardware is a simple counter that counts down from a number (say 1023) to zero. TTL or other logic could be used.
The software has been designed as such that one routine monitors the correct operation of all essential systems. If this routine completes correctly = finds the computer running fine, it sets the counter back to 1023.
The overall design is so that under normal circumstances, the software prevents that the hardware counter will reach zero. In case the counter reaches zero, the hardware of the counter performs its one-and-only task and resets the entire system. From a counter perspective, zero equals 1024 and the counter continues counting down again.
This watchdog ensures that the attached computer is restarted in a many, many cases of failure. I must admit that I'm not familiar with hardware that is able to perform such a function on today's computers. Interfaces to external hardware are now a lot more complex than they used to be.
An inherent disadvantage of the watchdog is that the system is not available from the time it fails until the watchdog counter reaches zero + reboot time. While that time is generally much shorter than any external or human intervention, the supported equipment will need to be able to proceed without computer control for that timeframe.
To move a file you could also use Jakarta Commons IOs FileUtils.moveFile
On error it throws an IOException
, so when no exception is thrown you know that that the file was moved.
I chose to tackle this on the oninput
event in order to handle the issue for keyboard pasting, mouse pasting and key strokes. Pass true or false to indicate decimal or integer validation.
It's basically three steps in three one liners. If you don't want to truncate the decimals comment the third step. Adjustments for rounding can be made in the third step as well.
// Example Decimal usage;
// <input type="text" oninput="ValidateNumber(this, true);" />
// Example Integer usage:
// <input type="text" oninput="ValidateNumber(this, false);" />
function ValidateNumber(elm, isDecimal) {
try {
// For integers, replace everything except for numbers with blanks.
if (!isDecimal)
elm.value = elm.value.replace(/[^0-9]/g, '');
else {
// 1. For decimals, replace everything except for numbers and periods with blanks.
// 2. Then we'll remove all leading ocurrences (duplicate) periods
// 3. Then we'll chop off anything after two decimal places.
// 1. replace everything except for numbers and periods with blanks.
elm.value = elm.value.replace(/[^0-9.]/g, '');
//2. remove all leading ocurrences (duplicate) periods
elm.value = elm.value.replace(/\.(?=.*\.)/g, '');
// 3. chop off anything after two decimal places.
// In comparison to lengh, our index is behind one count, then we add two for our decimal places.
var decimalIndex = elm.value.indexOf('.');
if (decimalIndex != -1) { elm.value = elm.value.substr(0, decimalIndex + 3); }
}
}
catch (err) {
alert("ValidateNumber " + err);
}
}
In the beginning there was sh, sed, and awk (and find, and grep, and...). It was good. But awk can be an odd little beast and hard to remember if you don't use it often. Then the great camel created Perl. Perl was a system administrator's dream. It was like shell scripting on steroids. Text processing, including regular expressions were just part of the language. Then it got ugly... People tried to make big applications with Perl. Now, don't get me wrong, Perl can be an application, but it can (can!) look like a mess if you're not really careful. Then there is all this flat data business. It's enough to drive a programmer nuts.
Enter Python, Ruby, et al. These are really very good general purpose languages. They support text processing, and do it well (though perhaps not as tightly entwined in the basic core of the language). But they also scale up very well, and still have nice looking code at the end of the day. They also have developed pretty hefty communities with plenty of libraries for most anything.
Now, much of the negativeness towards Perl is a matter of opinion, and certainly some people can write very clean Perl, but with this many people complaining about it being too easy to create obfuscated code, you know some grain of truth is there. The question really becomes then, are you ever going to use this language for more than simple bash script replacements. If not, learn some more Perl.. it is absolutely fantastic for that. If, on the other hand, you want a language that will grow with you as you want to do more, may I suggest Python or Ruby.
Either way, good luck!
Since XAMPP went through some modifications, the file is now at xampp/php/php.ini
.
With little php is very easy.
HTML part:
<input type="text" name="some_name">
JavaScript
<script type="text/javascript">
some_variable = "<?php echo $_POST['some_name']?>";
</script>
You can put custom image in radiobutton like normal button. for that create one XML file in drawable folder e.g
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sub_screens_aus_hl"
android:state_pressed="true"/>
<item android:drawable="@drawable/sub_screens_aus"
android:state_checked="true"/>
<item android:drawable="@drawable/sub_screens_aus"
android:state_focused="true" />
<item android:drawable="@drawable/sub_screens_aus_dis" />
</selector>
Here you can use 3 different images for radiobutton
and use this file to RadioButton like:
android:button="@drawable/aus"
android:layout_height="120dp"
android:layout_width="wrap_content"
To compile you could just initiate a shell call to the csc compiler. You may have a headache trying to keep your paths and switches straight but it certainly can be done.
EDIT: Or better yet, use the CodeDOM as Noldorin suggested...
Your string is wider than your format width of 2. So there's no padding to be done.
You can access multiple columns by passing a list of column indices to dataFrame.ix.
For example:
>>> df = pandas.DataFrame({
'a': np.random.rand(5),
'b': np.random.rand(5),
'c': np.random.rand(5),
'd': np.random.rand(5)
})
>>> df
a b c d
0 0.705718 0.414073 0.007040 0.889579
1 0.198005 0.520747 0.827818 0.366271
2 0.974552 0.667484 0.056246 0.524306
3 0.512126 0.775926 0.837896 0.955200
4 0.793203 0.686405 0.401596 0.544421
>>> df.ix[:,[1,3]]
b d
0 0.414073 0.889579
1 0.520747 0.366271
2 0.667484 0.524306
3 0.775926 0.955200
4 0.686405 0.544421
Looking for another great simple solution?
var img=document.createElement('img');
img.src=canvas.toDataURL();
$(img).css("background", backgroundColor);
$(img).width(settings.width);
$(img).height(settings.height);
This solution will use the resize algorith of browser! :)
In scikit-learn 0.22.0 you can pass mean_squared_error()
the argument squared=False
to return the RMSE.
from sklearn.metrics import mean_squared_error
mean_squared_error(y_actual, y_predicted, squared=False)
I was facing the same problems and found a easy solution now.
Using pathman.
pathman /as %M2%
Adds for example %M2% to the system path. Nothing more and nothing less. No more problems getting a mixture of user PATH and system PATH. No more hardly trying to get the correct values from registry...
Tried at Windows 10
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
End if
The error indicates that the compiler thinks you want to do a bitwise OR
on a Boolean and a string. Which of course won't work.
setState()
has an optional callback parameter that you can use for this. You only need to change your code slightly, to this:
// Form Input
this.setState(
{
originId: input.originId,
destinationId: input.destinationId,
radius: input.radius,
search: input.search
},
this.findRoutes // here is where you put the callback
);
Notice the call to findRoutes
is now inside the setState()
call,
as the second parameter.
Without ()
because you are passing the function.
b = a[a>threshold]
this should do
I tested as follows:
import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()
t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0
t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0
I got
$ python test.py
0:00:00.028000
0:00:02.461000
http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays
The Best Command for changing branch
git branch -M YOUR_BRANCH
Click app/manifests/AndroidManifest.xml
You see android:icon="@mipmap/your image name"
Also change android:roundicon="@mipmap/your image name"
Example:
android:icon="@mipmap/image"
that's all
Hi - I want to write a test to establish that an Exception is not raised in a given circumstance.
That's the default assumption -- exceptions are not raised.
If you say nothing else, that's assumed in every single test.
You don't have to actually write an any assertion for that.
Complete instruction is as follow:
openssl pkcs12 -in myfile.pfx -nocerts -out private-key.pem -nodes
openssl pkcs12 -in myfile.pfx -nokeys -out certificate.pem
yum install -y ca-certificates
,
cp your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem
,
update-ca-trust
,
update-ca-trust force-enable
Hope to be useful
One of the advantages of the static factory methods with private constructor(object creation must have been restricted for external classes to ensure instances are not created externally) is that you can create instance-controlled classes. And instance-controlled classes guarantee that no two equal distinct instances exist(a.equals(b) if and only if a==b) during your program is running that means you can check equality of objects with == operator instead of equals method, according to Effective java.
The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time. Classes that do this are said to be instance-controlled. There are several reasons to write instance-controlled classes. Instance control allows a class to guarantee that it is a singleton (Item 3) or noninstantiable (Item 4). Also, it allows an immutable class (Item 15) to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the == operator instead of the equals(Object) method, which may result in improved performance. Enum types (Item 30) provide this guarantee.
From Effective Java, Joshua Bloch(Item 1,page 6)
I added this answer to clarify that the accepted answer shows CPU time which may not be the time you want. Because according to the reference, there are CPU time and wall clock time. Wall clock time is the time which shows the actual elapsed time regardless of any other conditions like CPU shared by other processes. For example, I used multiple processors to do a certain task and the CPU time was high 18s where it actually took 2s in actual wall clock time.
To get the actual time you do,
#include <chrono>
auto t_start = std::chrono::high_resolution_clock::now();
// the work...
auto t_end = std::chrono::high_resolution_clock::now();
double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end-t_start).count();
document.getElementById("email").validity.valid
seems to be true when field is either empty or valid. This also has some other interesting flags:
Tested in Chrome.
I have noticed that when using type="image/vnd.microsoft.icon"
, the favicon fails to appear when the browser is not connected to the internet.
But type="image/x-icon"
works whether the browser can connect to the internet, or not.
When developing, at times I am not connected to the internet.
You can use this site: https://cachedviews.com/ . Cache View or Cached Pages of Any Website - Google Cached Pages of Any Website
Here's some swift-code for you to set the line spacing programmatically
let label = UILabel()
let attributedText = NSMutableAttributedString(string: "Your string")
let paragraphStyle = NSMutableParagraphStyle()
//SET THIS:
paragraphStyle.lineSpacing = 4
//OR SET THIS:
paragraphStyle.lineHeightMultiple = 4
//Or set both :)
let range = NSMakeRange(0, attributedText.length)
attributedText.addAttributes([NSParagraphStyleAttributeName : paragraphStyle], range: range)
label.attributedText = attributedText
I'm using macOS Sierra (v10.12.1) Xcode v8.1 Swift 3.0.1 and here's what worked for me in ViewController.swift:
//
// ViewController.swift
// UIWebViewExample
//
// Created by Scott Maretick on 1/2/17.
// Copyright © 2017 Scott Maretick. All rights reserved.
//
import UIKit
import WebKit
class ViewController: UIViewController {
//added this code
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Your webView code goes here
let url = URL(string: "https://www.google.com")
if UIApplication.shared.canOpenURL(url!) {
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
//If you want handle the completion block than
UIApplication.shared.open(url!, options: [:], completionHandler: { (success) in
print("Open url : \(success)")
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
};
For anyone going through this error and you've tried updating versions and making sure effects core is present etc and still scratching your head. Check the documentation for animate() and other syntax.
All I did was write "Linear" instead of "linear" and got the [this.easing] is not a function
$("#main").animate({ scrollLeft: '187px'}, 'slow', 'Linear'); //bad
$("#main").animate({ scrollLeft: '187px'}, 'slow', 'linear'); //good
So, I solved this by going to my website in IIS Manager and changing the host name in site bindings from localhost to *. Started working immediately.
Be aware that random.shuffle()
should not be used on multi-dimensional arrays as it causes repetitions.
Imagine you want to shuffle an array along its first dimension, we can create the following test example,
import numpy as np
x = np.zeros((10, 2, 3))
for i in range(10):
x[i, ...] = i*np.ones((2,3))
so that along the first axis, the i-th element corresponds to a 2x3 matrix where all the elements are equal to i.
If we use the correct shuffle function for multi-dimensional arrays, i.e. np.random.shuffle(x)
, the array will be shuffled along the first axis as desired. However, using random.shuffle(x)
will cause repetitions. You can check this by running len(np.unique(x))
after shuffling which gives you 10 (as expected) with np.random.shuffle()
but only around 5 when using random.shuffle()
.
How about...
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
//Optionally for time zone conversions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
//unless ARC is active
[formatter release];
Swift 4.2 :
func stringFromDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
return formatter.string(from: date)
}
I think this suits perfect for any color you have:
a {
color: inherit;
}
Listview lv = (ListView) findViewById(R.id.previewlist);
final BaseAdapter adapter = new PreviewAdapter(this, name, age);
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
View view = null;
String value;
for (int i = 0; i < adapter.getCount(); i++) {
view = adapter.getView(i, view, lv);
Textview et = (TextView) view.findViewById(R.id.passfare);
value=et.getText().toString();
Toast.makeText(getApplicationContext(), value,
Toast.LENGTH_SHORT).show();
}
}
});
This is an old topic and I'd like to add my understanding here to expand the knowledge of this interesting topic.
The key difference between REM and :: is:
REM is a command itself, while :: is NOT.
We can treat :: as a token that as soon as CMD parser encounters the first non-blank space in a line is this :: token, it will just skip the whole line and read next line. That's why REM should be followed by at least a blank space to be able to function as a comment for the line, while :: does not need any blank space behind it.
That REM is a command itself can be best understood from the following FOR syntax
The basic FOR syntax is as follows
FOR %v in (set) DO <Command> [command param]
here <Command>
can be any valid command
So we can write the following valid command line as rem
is a command
FOR %i in (1,2,3) DO rem echo %i
However, we CANNOT write the following line as ::
is not a command
FOR %i in (1,2,3) DO :: echo %i
Below works (in my limited testing) by doing deep compare between two object hierarchies. In handles various cases including the cases when objects themselves or their attributes are dictionaries.
def deep_comp(o1:Any, o2:Any)->bool:
# NOTE: dict don't have __dict__
o1d = getattr(o1, '__dict__', None)
o2d = getattr(o2, '__dict__', None)
# if both are objects
if o1d is not None and o2d is not None:
# we will compare their dictionaries
o1, o2 = o1.__dict__, o2.__dict__
if o1 is not None and o2 is not None:
# if both are dictionaries, we will compare each key
if isinstance(o1, dict) and isinstance(o2, dict):
for k in set().union(o1.keys() ,o2.keys()):
if k in o1 and k in o2:
if not deep_comp(o1[k], o2[k]):
return False
else:
return False # some key missing
return True
# mismatched object types or both are scalers, or one or both None
return o1 == o2
This is a very tricky code so please add any cases that might not work for you in comments.
If you are going to be adding lots of items, consider deriving your own class from ObservableCollection and adding items to the protected Items member - this won't raise events in observers. When you are done you can raise the appropriate events:
public class BulkUpdateObservableCollection<T> : ObservableCollection<T>
{
public void AddRange(IEnumerable<T> collection)
{
foreach (var i in collection) Items.Add(i);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
}
}
When adding many items to an ObservableCollection that is already bound to a UI element (such as LongListSelector) this can make a massive performance difference.
Prior to adding the items, you could also ensure you have enough space, so that the list isn't continually being expanded by implementing this method in the BulkObservableCollection class and calling it prior to calling AddRange:
public void IncreaseCapacity(int increment)
{
var itemsList = (List<T>)Items;
var total = itemsList.Count + increment;
if (itemsList.Capacity < total)
{
itemsList.Capacity = total;
}
}
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
I found this in the navbar example, and simplified it.
<ul class="nav">
<li><a>Default</a></li>
<li><a>Static top</a></li>
<li><b><a>Fixed top <span class="sr-only">(current)</span></a></b></li>
</ul>
You see which one is selected (sr-only
part is hidden):
You hear which one is selected if you use screen reader:
As a result of this technique blind people supposed to navigate easier on your website.
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
In VSCode 1.24 you can do that.
Right click on EXPLORER
on the side bar and checked Outline
.
Don't BULK INSERT into your real tables directly.
I would always
dbo.Employee_Staging
(without the IDENTITY
column) from the CSV fileand then copy the data across to the real table with a T-SQL statement like:
INSERT INTO dbo.Employee(Name, Address)
SELECT Name, Address
FROM dbo.Employee_Staging
You can use combination of baseUrl
and paths
docs.
Assuming root is on the topmost src
dir(and I read your image properly) use
// tsconfig.json
{
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"lib/*": [
"src/org/global/lib/*"
]
}
}
}
For webpack
you might also need to add module resolution. For webpack2
this could look like
// webpack.config.js
module.exports = {
resolve: {
...
modules: [
...
'./src/org/global'
]
}
}
Yes, it is possible.
There is a perfect open-source Python (.PYC) decompiler, called Decompyle++ https://github.com/zrax/pycdc/
Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python.
There are no HTTP headers that will report the clients timezone so far although it has been suggested to include it in the HTTP specification.
If it was me, I would probably try to fetch the timezone using clientside JavaScript and then submit it to the server using Ajax or something.
Here's an answer in Kotlin and androidX
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager
class DeactivatedViewPager @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : ViewPager(context, attrs) {
var isPagingEnabled = true
override fun onTouchEvent(ev: MotionEvent?): Boolean {
return isPagingEnabled && super.onTouchEvent(ev)
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
return isPagingEnabled && super.onInterceptTouchEvent(ev)
}
}
You can add a header parameter to your request, and Swagger-UI will show it as an editable text box:
swagger: "2.0"
info:
version: 1.0.0
title: TaxBlaster
host: taxblaster.com
basePath: /api
schemes:
- http
paths:
/taxFilings/{id}:
get:
parameters:
- name: id
in: path
description: ID of the requested TaxFiling
required: true
type: string
- name: auth
in: header
description: an authorization header
required: true
type: string
responses:
200:
description: Successful response, with a representation of the Tax Filing.
schema:
$ref: "#/definitions/TaxFilingObject"
404:
description: The requested tax filing was not found.
definitions:
TaxFilingObject:
type: object
description: An individual Tax Filing record.
properties:
filingID:
type: string
year:
type: string
period:
type: integer
currency:
type: string
taxpayer:
type: object
You can also add a security definition with type apiKey
:
swagger: "2.0"
info:
version: 1.0.0
title: TaxBlaster
host: taxblaster.com
basePath: /api
schemes:
- http
securityDefinitions:
api_key:
type: apiKey
name: api_key
in: header
description: Requests should pass an api_key header.
security:
- api_key: []
paths:
/taxFilings/{id}:
get:
parameters:
- name: id
in: path
description: ID of the requested TaxFiling
required: true
type: string
responses:
200:
description: Successful response, with a representation of the Tax Filing.
schema:
$ref: "#/definitions/TaxFilingObject"
404:
description: The requested tax filing was not found.
definitions:
TaxFilingObject:
type: object
description: An individual Tax Filing record.
properties:
filingID:
type: string
year:
type: string
period:
type: integer
currency:
type: string
taxpayer:
type: object
The securityDefinitions
object defines security schemes.
The security
object (called "security requirements" in Swagger–OpenAPI), applies a security scheme to a given context. In our case, we're applying it to the entire API by declaring the security requirement a top level. We can optionally override it within individual path items and/or methods.
This would be the preferred way to specify your security scheme; and it replaces the header parameter from the first example. Unfortunately, Swagger-UI doesn't offer a text box to control this parameter, at least in my testing so far.
let signUpVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SignUp")
// self.present(signUpVC, animated: false, completion: nil)
self.navigationController?.pushViewController(signUpVC, animated: true)
RETURNING
Since PostgreSQL 8.2, that's possible with a single round-trip to the database:
INSERT INTO tbl(filename)
VALUES ('my_filename')
RETURNING tbl_id;
tbl_id
would typically be a serial
or IDENTITY
(Postgres 10 or later) column. More in the manual.
If filename
needs to include tbl_id
(redundantly), you can still use a single query.
Use lastval()
or the more specific currval()
:
INSERT INTO tbl (filename)
VALUES ('my_filename' || currval('tbl_tbl_id_seq') -- or lastval()
RETURNING tbl_id;
See:
If multiple sequences may be advanced in the process (even by way of triggers or other side effects) the sure way is to use currval('tbl_tbl_id_seq')
.
The string literal 'tbl_tbl_id_seq'
in my example is supposed to be the actual name of the sequence and is cast to regclass
, which raises an exception if no sequence of that name can be found in the current search_path
.
tbl_tbl_id_seq
is the automatically generated default for a table tbl
with a serial column tbl_id
. But there are no guarantees. A column default can fetch values from any sequence if so defined. And if the default name is taken when creating the table, Postgres picks the next free name according to a simple algorithm.
If you don't know the name of the sequence for a serial
column, use the dedicated function pg_get_serial_sequence()
. Can be done on the fly:
INSERT INTO tbl (filename)
VALUES ('my_filename' || currval(pg_get_serial_sequence('tbl', 'tbl_id'))
RETURNING tbl_id;
The code yo have provided runs fine. Remember that if you have your code in the header, you need to wait for the dom to be loaded first. In jQuery it would just be as simple as putting your code inside $(function(e){...});
In normal javascript use window.onLoad(..) or the like... or have the script after the table defnition (yuck!). The snippet you provided runs fine when I have it that way for the following:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<table id='ddReferences'>
<tr>
<td>dfsdf</td>
<td>sdfs</td>
<td>frtyr</td>
<td>hjhj</td>
</tr>
</table>
<script>
var refTab = document.getElementById("ddReferences")
var ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; row = refTab.rows[i]; i++ ) {
row = refTab.rows[i];
for ( var j = 0; col = row.cells[j]; j++ ) {
alert(col.firstChild.nodeValue);
}
}
</script>
</body>
</html>
Add z-index:-9999;
to this method, or it will cover your top bar if you have 1
.
you can use custom gallery control.. check this https://github.com/kilaka/ImageViewZoom use galleryTouch class from this..
This issue is caused by SELinux. After setting file ownership just as you did, I hit this issue. The audit2why(1)
tool can be used to diagnose SELinux denials from the log:
(django)[f22-4:www/django/demo] ftweedal% sudo audit2why -a
type=AVC msg=audit(1437490152.208:407): avc: denied { write }
for pid=20330 comm="httpd" name="db.sqlite3" dev="dm-1" ino=52036
scontext=system_u:system_r:httpd_t:s0
tcontext=unconfined_u:object_r:httpd_sys_content_t:s0
tclass=file permissive=0
Was caused by:
The boolean httpd_unified was set incorrectly.
Description:
Allow httpd to unified
Allow access by executing:
# setsebool -P httpd_unified 1
Sure enough, running sudo setsebool -P httpd_unified 1
resolved the issue.
Looking into what httpd_unified
is for, I came across a fedora-selinux-list post which explains:
This Boolean is off by default, turning it on will allow all httpd executables to have full access to all content labeled with a http file context. Leaving it off makes sure that one httpd service can not interfere with another.
So turning on httpd_unified
lets you circumvent the default behaviour that prevents multiple httpd
instances on the same server - all running as user apache
- messing with each others' stuff.
In my case, I am only running one httpd
, so it was fine for me to turn on httpd_unified
. If you cannot do this, I suppose some more fine-grained labelling is needed.
Look into python wheels to solve your problem. The best part of python wheels is that they let you install C extensions with no compilers. I just installed numpy and scipy using pip in a clean python install and they both worked fine.
You could always use sorted
>>> sorted(numbers)[-2]
74
Your problem is that class B is not declared as a "new-style" class. Change it like so:
class B(object):
and it will work.
super()
and all subclass/superclass stuff only works with new-style classes. I recommend you get in the habit of always typing that (object)
on any class definition to make sure it is a new-style class.
Old-style classes (also known as "classic" classes) are always of type classobj
; new-style classes are of type type
. This is why you got the error message you saw:
TypeError: super() argument 1 must be type, not classobj
Try this to see for yourself:
class OldStyle:
pass
class NewStyle(object):
pass
print type(OldStyle) # prints: <type 'classobj'>
print type(NewStyle) # prints <type 'type'>
Note that in Python 3.x, all classes are new-style. You can still use the syntax from the old-style classes but you get a new-style class. So, in Python 3.x you won't have this problem.
We can add the following to a particular tag in CSS:
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
In case of half rotation change 90
to 45
.
To expound on cletus' answer, at runtime all record of the generic types is removed. Generics are processed only in the compiler and are used to provide additional type safety. They are really just shorthand that allows the compiler to insert typecasts at the appropriate places. For example, previously you'd have to do the following:
List x = new ArrayList();
x.add(new SomeClass());
Iterator i = x.iterator();
SomeClass z = (SomeClass) i.next();
becomes
List<SomeClass> x = new ArrayList<SomeClass>();
x.add(new SomeClass());
Iterator<SomeClass> i = x.iterator();
SomeClass z = i.next();
This allows the compiler to check your code at compile-time, but at runtime it still looks like the first example.
A binary search tree uses the definition: that for every node,the node to the left of it has a less value(key) and the node to the right of it has a greater value(key).
Where as the heap,being an implementation of a binary tree uses the following definition:
If A and B are nodes, where B is the child node of A,then the value(key) of A must be larger than or equal to the value(key) of B.That is, key(A) = key(B).
http://wiki.answers.com/Q/Difference_between_binary_search_tree_and_heap_tree
I ran in the same question today for my exam and I got it right. smile ... :)
Here's what you can do using font-awesome library.
button.btn.add::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
Yes, it is possible. One of the solutions is below (jsfiddle as a proof).
HTML:
<a id="fire" href="#" title="submit form">Submit form</a>
(see, above there is no form)
JavaScript:
jQuery('#fire').click(function(event){
event.preventDefault();
var newForm = jQuery('<form>', {
'action': 'http://www.google.com/search',
'target': '_top'
}).append(jQuery('<input>', {
'name': 'q',
'value': 'stack overflow',
'type': 'hidden'
}));
newForm.submit();
});
The above example shows you how to create form, how to add inputs and how to submit. Sometimes display of the result is forbidden by X-Frame-Options
, so I have set target
to _top
, which replaces the main window's content. Alternatively if you set _blank
, it can show within new window / tab.
In my case I accidentally wrote:
app:displayViewTitle="@string/instructions_defineExtract_confirm_email"
Interestingly, Android Studio were able to navigate the string via CTRL+click. It was just giving Build Time error. Changing to standard "dot seperation" did the trick
app:displayViewTitle="@string/instructions.defineExtract.confirm.email"
If you're dealing with fixed number of keys that you know in advance, use Python's inbuilt namedtuples instead. A possible use-case is when you want to store some constant data and access it throughout the program by both indexing and specifying keys.
import collections
ordered_keys = ['foo', 'bar']
D = collections.namedtuple('D', ordered_keys)
d = D(foo='python', bar='spam')
d[0] # result: python
d[1] # result: spam
d.foo # result: python
d.bar # result: spam
Or better:
getattr(d, 'foo') # result: python
getattr(d, 'bar') # result: spam
I use shortlog for this:
$ git shortlog master..
Username (3):
Write something
Add something
Bump to 1.3.8
You can try with Directory.GetFiles and fix your pattern
string[] files = Directory.GetFiles(@"c:\", "*.txt");
foreach (string file in files)
{
File.Copy(file, "....");
}
Or Move
foreach (string file in files)
{
File.Move(file, "....");
}
There are several correct ways to display a down-pointing and upward-pointing triangle.
HTML :
▲
▼
HTML :
▲
▼
HTML :
?
?
HTML :
<span class='icon-up'></span>
<span class='icon-down'></span>
CSS :
.icon-up:before {
content: "\25B2";
}
.icon-down:before {
content: "\25BC";
}
Each of these three methods should have the same output. For other symbols, the same three options exist. Some even have a fourth option, allowing you to use a string based reference (eg. ♥
to display ?).
You can use a reference website like Unicode-table.com to find which icons are supported in UNICODE and which codes they correspond with. For example, you find the values for the down-pointing triangle at http://unicode-table.com/en/25BC/.
Note that these methods are sufficient only for icons that are available by default in every browser. For symbols like ?,?,?,?,?,? or ?, this is far less likely to be the case. While it is possible to provide cross-browser support for other UNICODE symbols, the procedure is a bit more complicated.
If you want to know how to add support for less common UNICODE characters, see Create webfont with Unicode Supplementary Multilingual Plane symbols for more info on how to do this.
A totally different strategy is the use of background-images instead of fonts. For optimal performance, it's best to embed the image in your CSS file by base-encoding it, as mentioned by eg. @weasel5i2 and @Obsidian. I would recommend the use of SVG rather than GIF, however, is that's better both for performance and for the sharpness of your symbols.
This following code is the base64 for and SVG version of the icon :
/* size: 0.9kb */
url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iMTYiIGhlaWdodD0iMjgiIHZpZXdCb3g9IjAgMCAxNiAyOCI+PGcgaWQ9Imljb21vb24taWdub3JlIj48L2c+PHBhdGggZD0iTTE2IDE3cTAgMC40MDYtMC4yOTcgMC43MDNsLTcgN3EtMC4yOTcgMC4yOTctMC43MDMgMC4yOTd0LTAuNzAzLTAuMjk3bC03LTdxLTAuMjk3LTAuMjk3LTAuMjk3LTAuNzAzdDAuMjk3LTAuNzAzIDAuNzAzLTAuMjk3aDE0cTAuNDA2IDAgMC43MDMgMC4yOTd0MC4yOTcgMC43MDN6TTE2IDExcTAgMC40MDYtMC4yOTcgMC43MDN0LTAuNzAzIDAuMjk3aC0xNHEtMC40MDYgMC0wLjcwMy0wLjI5N3QtMC4yOTctMC43MDMgMC4yOTctMC43MDNsNy03cTAuMjk3LTAuMjk3IDAuNzAzLTAuMjk3dDAuNzAzIDAuMjk3bDcgN3EwLjI5NyAwLjI5NyAwLjI5NyAwLjcwM3oiIGZpbGw9IiMwMDAwMDAiPjwvcGF0aD48L3N2Zz4=
For many use cases, SVG-based background images and icon fonts are largely equivalent with regards to performance and flexibility. To decide which to pick, consider the following differences:
SVG images
color
, font-size
, line-height
, background-color
or other font related styling rules to change the display of your icon, but you can reference different components of the icon as shapes individually.Icon fonts
color
, font-size
, line-height
, background-color
or other font related styling rules to change the display of your iconPersonally, I would recommend the use of background-images only when you need multiple colors and those color can't be achieved by means of color
, background-color
and other color-related CSS rules for fonts.
The main benefit of using SVG images is that you can give different components of a symbol their own styling. If you embed your SVG XML code in the HTML document, this is very similar to styling the HTML. This would, however, result in a web page that uses both HTML tags and SVG tags, which could significantly reduce the readability of a webpage. It also adds extra bloat if the symbol is repeated across multiple pages and you need to consider that old versions of IE have no or limited support for SVG.
On Windows Powershell I run this:
git stash apply "stash@{1}"
If you want to turn off the warnings about the specific strings, you can use the following:
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--suppress MissingTranslation -->
<string name="some_string">ignore my translation</string>
...
</resources>
If you want to warn on specific strings instead of an error, you will need to build a custom Lint rule to adjust the severity status for a specific thing.
Try these
String appDirectoryName = getResources().getString(R.string.app_name);
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getResources().getString(R.string.app_name));
directory.mkdirs();
File[] fList = directory.listFiles();
int a = 1;
for (int x = 0; x < fList.length; x++) {
//txt.setText("You Have Capture " + String.valueOf(a) + " Photos");
a++;
}
//get all the files from a directory
for (File file : fList) {
if (file.isFile()) {
list.add(new ModelClass(file.getName(), file.getAbsolutePath()));
}
}
See: http://predef.sourceforge.net/index.php
This project provides a reasonably comprehensive listing of pre-defined #defines
for many operating systems, compilers, language and platform standards, and standard libraries.
If you are working on a machine where it doesn't have permissions to all the files and moreover you have two versions such as default 2.7 & latest 3.6 then while running the command use the python version with the command. If the latest python is installed with sudo then run the command with sudo.
exp:
sudo python3.6 manage.py runserver
Take a look at the library I wrote: https://github.com/tachyons-css/react-native-style-tachyons
It allows you to specify a root-fontSize (rem
) upon start, which you can make dependent of your PixelRatio
or other device-characteristics.
Then you get styles relative to your rem
, not only fontSize, but paddings etc. as well:
<Text style={[s.f5, s.pa2, s.tc]}>
Something
</Text>
Expanation:
f5
is always your base-fontsizepa2
gives you padding relative to your base-fontsize.At the first site is a dropdown field to select the language of phpmyadmin.
In the config.inc.php you can set:
$cfg['Lang'] = '';
More details you can find in the documentation: http://www.phpmyadmin.net/documentation/
You don't need anything special for adding paramaters. Just like you had it.
Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups@show'));
class Groups_Controller extends Base_Controller {
public $restful = true;
public function get_show($groupID) {
return 'I am group id ' . $groupID;
}
}
I've made an example without jQuery here : http://codepen.io/sorinnn/pen/ovzdq
/**
by Nemes Ioan Sorin - not an jQuery big fan
therefore this script is for those who love the old clean coding style
@id = the id of the element who need to bring into view
Note : this demo scrolls about 12.700 pixels from Link1 to Link3
*/
(function()
{
window.setTimeout = window.setTimeout; //
})();
var smoothScr = {
iterr : 30, // set timeout miliseconds ..decreased with 1ms for each iteration
tm : null, //timeout local variable
stopShow: function()
{
clearTimeout(this.tm); // stopp the timeout
this.iterr = 30; // reset milisec iterator to original value
},
getRealTop : function (el) // helper function instead of jQuery
{
var elm = el;
var realTop = 0;
do
{
realTop += elm.offsetTop;
elm = elm.offsetParent;
}
while(elm);
return realTop;
},
getPageScroll : function() // helper function instead of jQuery
{
var pgYoff = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
return pgYoff;
},
anim : function (id) // the main func
{
this.stopShow(); // for click on another button or link
var eOff, pOff, tOff, scrVal, pos, dir, step;
eOff = document.getElementById(id).offsetTop; // element offsetTop
tOff = this.getRealTop(document.getElementById(id).parentNode); // terminus point
pOff = this.getPageScroll(); // page offsetTop
if (pOff === null || isNaN(pOff) || pOff === 'undefined') pOff = 0;
scrVal = eOff - pOff; // actual scroll value;
if (scrVal > tOff)
{
pos = (eOff - tOff - pOff);
dir = 1;
}
if (scrVal < tOff)
{
pos = (pOff + tOff) - eOff;
dir = -1;
}
if(scrVal !== tOff)
{
step = ~~((pos / 4) +1) * dir;
if(this.iterr > 1) this.iterr -= 1;
else this.itter = 0; // decrease the timeout timer value but not below 0
window.scrollBy(0, step);
this.tm = window.setTimeout(function()
{
smoothScr.anim(id);
}, this.iterr);
}
if(scrVal === tOff)
{
this.stopShow(); // reset function values
return;
}
}
}
Sorting by C and D needs to be put into number form for the corresponding column, ie 3 and 4, respectively. Eg Order By 2 asc")
You can get this error if you use wrong mode when opening the file. For example:
with open(output, 'wb') as output_file:
print output_file.read()
In that code, I want to read the file, but I use mode wb
instead of r
or r+
By today's standards and web terminology, I'd say Bootstrap is actually not a framework, although that's what their website claims. Most developers consider Angular, Vue and React frameworks, while Bootstrap is commonly referred to as a "library".
But, to be exact and correct, Bootstrap is an open-source, mobile-first collection of CSS, JavaScript and HTML design utilities aimed at providing means to develop commonly used web elements considerably faster (and smarter) than having to code them from scratch.
A few core principles which contributed to Bootstrap's success:
It contains design templates and functionality for: layout, typography, forms, navigation, menus (including dropdowns), buttons, panels, badges, modals, alerts, tabs, collapsible, accordions, carousels, lists, tables, pagination, media utilities (including embeds, images and image replacement), responsiveness utilities, color-based utilities (primary, secondary, danger, warning, info, light, dark, muted, white), other utilities (position, margin, padding, sizing, spacing, alignment, visibility), scrollspy, affix, tooltips, popovers.
By default it relies on jQuery, but you'll find jQuery free variants powered by each of the modern popular progressive JavaScript frameworks:
Working with Bootstrap relies heavily on applying certain classes (or, depending on JS framework: directives, methods or attributes/props) and on using particular markup structures.
Documentation typically contains generic examples which can be easily copy-pasted and used as starter templates.
Another advantage of developing with Bootstrap is its vibrant community, translated into an abundance of themes, templates and plugins available for it, most of which are open-source (i.e: calendars, date/time-pickers, plugins for tabular content management, as well as libraries/component collections built on top of Bootstrap, such as MDB, portfolio templates, admin templates, etc...)
Last, but not least, Bootstrap has been well maintained over the years, which makes it a solid choice for production-ready applications/websites.
The answer to this is CSS Specificity. You need to be more "specific" in your CSS so that it can override bootstrap css properties.
For example you have a sample code for a bootstrap menu here:
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div id="home-menu-container" class="collapse navbar-collapse">
<ul id="home-menu" class="nav navbar-nav">
<li><a class="navbar-brand" href="#"><img src="images/xd_logo.png" /></a></li>
<li><a href="#intro">Home</a></li>
<li><a href="#about">About Us</a></li>
<li><a href="#services">What We Do</a></li>
<li><a href="#process">Our Process</a><br /></li>
<li><a href="#portfolio">Portfolio</a></li>
<li><a href="#contact">Contact Us</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
Here, you need to remember the hierarchy of the specificity. It goes like this:
So, for the above if your css has something like this:
.navbar ul li a { color: red; } /* 10(.navbar) + 1(ul) + 1(li) + 1(a) = 13 points */
.navbar a { color: green; } /* 10(.navbar) + 1(a) = 11 points */
So, even if you have defined the .navbar a
after .navbar ul li a
it is still going to override with a red colour, instead of a green since the specificity is more (13 points).
So, basically all you need to do is calculate the points for the element you are wanting to change the css for, via inspect element on your browser. Here, bootstrap has specified its css for the element as
.navbar-inverse .navbar-nav>li>a { /* Total = 22 points */
color: #999;
}
So, even if your css is loading is being loaded after bootstrap.css which has the following line:
.navbar-nav li a {
color: red;
}
it's still going to be rendered as #999. In order to solve this, bootstrap has 22 points (calculate it yourself). So all we need is something more than that. Thus, I have added custom IDs to the elements i.e. home-menu-container and home-menu. Now the following css will work:
#home-menu-container #home-menu li a { color: red; } /* 100 + 100 + 1 + 1 = 202 points :) */
Done.
You can refer to this MDN link.
you could submit all parameters with such naming:
params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]
then later you do something like this:
foreach ($_REQUEST['params'] as $item) {
echo $item['topdiameter'];
echo $item['bottomdiameter'];
}
Use this: $newDate = $dateInDB->format('Y-m-d');
The filter option filters only the first level subkey below ansible_facts
Assuming we are talking about web applications and building APIs:
One approach is to categorize files by feature, much like what a micro service architecture would look like. The biggest win in my opinion is that it is super easy to see which files relate to a feature of the application.
The best way to illustrate is through an example:
We are developing a library application. In the first version of the application, a user can:
In a second version, users can also:
In a third version, users can also:
First we have the following structure:
books
+- controllers
¦ +- booksController.js
¦ +- authorsController.js
¦
+- entities
+- book.js
+- author.js
We then add on the user and loan features:
user
+- controllers
¦ +- userController.js
+- entities
¦ +- user.js
+- middleware
+- authentication.js
loan
+- controllers
¦ +- loanController.js
+- entities
+- loan.js
And then the favorites functionality:
favorites
+- controllers
¦ +- favoritesController.js
+- entities
+- favorite.js
For any new developer that gets handed the task to add on that the books search should also return information if any book have been marked as favorite, it's really easy to see where in the code he/she should look.
Then when the product owner sweeps in and exclaims that the favorites feature should be removed completely, it's easy to remove it.
You can use the following methods to update the value of a reactive form control. Any of the following method will suit for your need.
Methods using setValue()
this.form.get("dept").setValue(selected.id);
this.form.controls["dept"].setValue(selected.id);
Methods using patchValue()
this.form.get("dept").patchValue(selected.id);
this.form.controls['dept'].patchValue(selected.id);
this.form.patchValue({"dept": selected.id});
Last method will loop thorough all the controls in the form so it is not preferred when updating single control
You can use any of the method inside the event handler
deptSelected(selected: { id: string; text: string }) {
// any of the above method can be added here
}
You can update multiple controls in the form group if required using the
this.form.patchValue({"dept": selected.id, "description":"description value"});
Either way, when the using block is exited (either by successful completion or by error) it is closed.
Although I think it would be better to organize like this because it's a lot easier to see what is going to happen, even for the new maintenance programmer who will support it later:
using (SqlConnection connection = new SqlConnection(connectionString))
{
int employeeID = findEmployeeID();
try
{
connection.Open();
SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
command.CommandTimeout = 5;
command.ExecuteNonQuery();
}
catch (Exception)
{
/*Handle error*/
}
}
Composition is just as it sounds - you create an object by plugging in parts.
EDIT the rest of this answer is erroneously based on the following premise.
This is accomplished with Interfaces.
For example, using the Car
example above,
Car implements iDrivable, iUsesFuel, iProtectsOccupants
Motorbike implements iDrivable, iUsesFuel, iShortcutThroughTraffic
House implements iProtectsOccupants
Generator implements iUsesFuel
So with a few standard theoretical components you can build up your object. It's then your job to fill in how a House
protects its occupants, and how a Car
protects its occupants.
Inheritance is like the other way around. You start off with a complete (or semi-complete) object and you replace or Override the various bits you want to change.
For example, MotorVehicle
may come with a Fuelable
method and Drive
method. You may leave the Fuel method as it is because it's the same to fill up a motorbike and a car, but you may override the Drive
method because the Motorbike drives very differently to a Car
.
With inheritance, some classes are completely implemented already, and others have methods that you are forced to override. With Composition nothing's given to you. (but you can Implement the interfaces by calling methods in other classes if you happen to have something laying around).
Composition is seen as more flexible, because if you have a method such as iUsesFuel, you can have a method somewhere else (another class, another project) that just worries about dealing with objects that can be fueled, regardless of whether it's a car, boat, stove, barbecue, etc. Interfaces mandate that classes that say they implement that interface actually have the methods that that interface is all about. For example,
iFuelable Interface:
void AddSomeFuel()
void UseSomeFuel()
int percentageFull()
then you can have a method somewhere else
private void FillHerUp(iFuelable : objectToFill) {
Do while (objectToFill.percentageFull() <= 100) {
objectToFill.AddSomeFuel();
}
Strange example, but it's shows that this method doesn't care what it's filling up, because the object implements iUsesFuel
, it can be filled. End of story.
If you used Inheritance instead, you would need different FillHerUp
methods to deal with MotorVehicles
and Barbecues
, unless you had some rather weird "ObjectThatUsesFuel" base object from which to inherit.
We could call startActivityForResult()
directly from Fragment
So You should call this.startActivityForResult(i, 1);
instead of getActivity().startActivityForResult(i, 1);
Intent i = new Intent(getActivity(), SecondActivity.class);
i.putExtra("helloString", helloString);
this.startActivityForResult(i, 1);
Activity will send the Activity Result to your Fragment.
Just add an ID tag to the input element... ie:
and check the value of the element in you javascript:
document.getElementById("question").value
Oh ya, get get firefox/firebug. It's the only way to do javascript.
class KeyStatisticCollection(DataDownloadUtilities.DataDownloadCollection):
def GenerateAddressStrings(self):
pass
def worker(self):
pass
def DownloadProc(self):
pass
Both tools are meant to work with text and there are tasks both tools can be used for.
For me the rule to separate them is: Use sed
to automate tasks you would do otherwise in a text editor manually. That's why it is called stream editor. (You can use the same commands to edit text in vim). Use awk
if you want to analyze text, meaning counting fields, calculate totals, extract and reorganize structures etc.
Also you should not forget about grep
. Use grep
if you only want to search/extract something in a text (file)
I got the same issue. My solution was a foreach of radio buttons, with the image at the right of it. Since you can only choose a single option at radio, it works (like) a select.
Worket well for me. Hope it can help someone else.
The prompt command will echo text to the output:
prompt A useful comment.
select(*) from TableA;
Will be displayed as:
SQL> A useful comment.
SQL>
COUNT(*)
----------
0
For this, you would use a goto statement. Such as:
switch(value){
case 1:
goto case 3;
case 2:
goto case 3;
case 3:
DoCase123();
//This would work too, but I'm not sure if it's slower
case 4:
goto case 5;
case 5:
goto case 6;
case 6:
goto case 7;
case 7:
DoCase4567();
}
For those that still have problems, you have to download the language file your want from here:
and then include it in your page like this for example(italian language):
<script type="text/javascript" src="/scripts/jquery.ui.datepicker-it.js"></script>
then use zilverdistel's code :D
You shouldn't really worry about undefined being renamed. If someone renames undefined, you will be in a lot more trouble than just a few if checks failing. If you really want to protect your code, wrap it in an IFFE (immediately invoked function expression) like this:
(function($, Backbone, _, undefined) {
//undefined is undefined here.
})(jQuery, Backbone, _);
If you're working with global variables (which is wrong already) in a browser enviroment, I'd check for undefined like this:
if(window.neverDefined === undefined) {
//Code works
}
Since global variables are a part of the window object, you can simply check against undefined instead of casting to a string and comparing strings.
On top of that, why are your variables not defined? I've seen a lot of code where they check a variables existence and perform some action based on that. Not once have I seen where this approach has been correct.
When you give id as a primary key then a pop up is come and those aske you to how many size of this primary key. So you just leave blank because by default int value is set 11. Click then ok on those pop up without any enter a number. in this type of error never will you face in future. Thank you
I've taken Anas Nakawa's idea and improved it. First of all, there is no reason to actually run the function being declared. We want to know whether it parses correctly, not whether the code works. Second, a literal object is a better context for our purpose than var XXX
as it's harder to break out of.
function isValidVarName( name ) {
try {
return name.indexOf('}') === -1 && eval('(function() { a = {' + name + ':1}; a.' + name + '; var ' + name + '; }); true');
} catch( e ) {
return false;
}
return true;
}
// so we can see the test code
var _eval = eval;
window.eval = function(s) {
console.log(s);
return _eval(s);
}
console.log(isValidVarName('name'));
console.log(isValidVarName('$name'));
console.log(isValidVarName('not a name'));
console.log(isValidVarName('a:2,b'));
console.log(isValidVarName('"a string"'));
console.log(isValidVarName('xss = alert("I\'m in your vars executin mah scrip\'s");;;;;'));
console.log(isValidVarName('_;;;'));
console.log(isValidVarName('_=location="#!?"'));
console.log(isValidVarName('?'));
console.log(isValidVarName('HELLO'));
console.log(isValidVarName('????'));
console.log(isValidVarName('?????????????'));
console.log(isValidVarName('KingGeorge?'));
console.log(isValidVarName('}; }); alert("I\'m in your vars executin\' mah scripts"); true; // yeah, super valid'));
console.log(isValidVarName('if'));
I liked Levit's answer and ended up using it. But I just wanted to point out, just in case, that there is an official Google PHP library for new reCAPTCHA: https://github.com/google/recaptcha
The latest version (right now 1.1.2) supports Composer and contains an example that you can run to see if you have configured everything correctly.
Below you can see part of the example that comes with this official library (with my minor modifications for clarity):
// Make the call to verify the response and also pass the user's IP address
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if ($resp->isSuccess()) {
// If the response is a success, that's it!
?>
<h2>Success!</h2>
<p>That's it. Everything is working. Go integrate this into your real project.</p>
<p><a href="/">Try again</a></p>
<?php
} else {
// If it's not successful, then one or more error codes will be returned.
?>
<h2>Something went wrong</h2>
<p>The following error was returned: <?php
foreach ($resp->getErrorCodes() as $code) {
echo '<tt>' , $code , '</tt> ';
}
?></p>
<p>Check the error code reference at <tt><a href="https://developers.google.com/recaptcha/docs/verify#error-code-reference">https://developers.google.com/recaptcha/docs/verify#error-code-reference</a></tt>.
<p><strong>Note:</strong> Error code <tt>missing-input-response</tt> may mean the user just didn't complete the reCAPTCHA.</p>
<p><a href="/">Try again</a></p>
<?php
}
Hope it helps someone.
The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:
File > Preferences > Settings > Encoding > Choose your option
This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.
Set dynamic content size like this.
self.scroll_view.contentSize = CGSizeMake(screen_width,CGRectGetMaxY(self.controlname.frame)+20);
This is working for me, Writing(creating as well) and/or appending content in the same mode.
$fp = fopen("MyFile.txt", "a+")
this is my solution for clean empty fields.
Start from fees object: get only avail attribute (with map) filter empty fields (with filter) parse results to integer (with map)
fees.map( ( e ) => e.avail ).filter( v => v!== '').map( i => parseInt( i ) );
the app domain is your domain name.
Before you enter your domain, first click on Add Platform, select website, enter your site URL and mobile site url. Save the settings.
Thereafter, you can enter the domain name in the App domains field.
See more at my blog: http://www.ogbongeblog.com/2014/03/unable-to-add-app-domains-to-new.html
For the cut(1)
man page:
Use one, and only one of -b, -c or -f. Each LIST is made up of one range, or many ranges separated by commas. Selected input is written in the same order that it is read, and is written exactly once.
It reaches field 1 first, so that is printed, followed by field 2.
Use awk
instead:
awk '{ print $2 " " $1}' file.txt
You could use Type.GetMember Method, then get the attribute info using reflection:
// display attribute of "currentPromotion"
var type = typeof(UserPromotion);
var memberInfo = type.GetMember(currentPromotion.ToString());
var attributes = memberInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
var description = ((DisplayAttribute)attributes[0]).Name;
There were a few similar posts here:
Getting attributes of Enum's value
How to make MVC3 DisplayFor show the value of an Enum's Display-Attribute?
In Java, single quotes can only take one character, with escape if necessary. You need to use full quotation marks as follows for strings:
y = "hello";
You also used
System.out.println(g);
which I assume should be
System.out.println(y);
Note: When making char
values (you'll likely use them later) you need single quotes. For example:
char foo='m';
A lot answers here recommends $@
or $*
with and without quotes, however none seems to explain what these really do and why you should that way. So let me steal this excellent summary from this answer:
+--------+---------------------------+
| Syntax | Effective result |
+--------+---------------------------+
| $* | $1 $2 $3 ... ${N} |
+--------+---------------------------+
| $@ | $1 $2 $3 ... ${N} |
+--------+---------------------------+
| "$*" | "$1c$2c$3c...c${N}" |
+--------+---------------------------+
| "$@" | "$1" "$2" "$3" ... "${N}" |
+--------+---------------------------+
Notice that quotes makes all the difference and without them both have identical behavior.
For my purpose, I needed to pass parameters from one script to another as-is and for that the best option is:
# file: parent.sh
# we have some params passed to parent.sh
# which we will like to pass on to child.sh as-is
./child.sh $*
Notice no quotes and $@
should work as well in above situation.
This won't work, yet void * can help a lot in defining generic pointer to functions and passing it as an argument to another function (similar to callback in Java) or define it a structure similar to oop.
Just want to summarize the answers and comments. There are a number of ways doing a pagination.
Prior to oracle 12c there were no OFFSET/FETCH functionality, so take a look at whitepaper as the @jasonk suggested. It's the most complete article I found about different methods with detailed explanation of advantages and disadvantages. It would take a significant amount of time to copy-paste them here, so I won't do it.
There is also a good article from jooq creators explaining some common caveats with oracle and other databases pagination. jooq's blogpost
Good news, since oracle 12c we have a new OFFSET/FETCH functionality. OracleMagazine 12c new features. Please refer to "Top-N Queries and Pagination"
You may check your oracle version by issuing the following statement
SELECT * FROM V$VERSION
You could use java-aes-crypto or Facebook's Conceal
java-aes-crypto
Quoting from the repo
A simple Android class for encrypting & decrypting strings, aiming to avoid the classic mistakes that most such classes suffer from.
Facebook's conceal
Quoting from the repo
Conceal provides easy Android APIs for performing fast encryption and authentication of data
You are dividing integers then converting to float. Divide by floats instead.
As a bonus, use the awesome string formatting methods described here: http://docs.python.org/library/string.html#format-specification-mini-language
To specify a percent conversion and precision.
>>> float(1) / float(3)
[Out] 0.33333333333333331
>>> 1.0/3.0
[Out] 0.33333333333333331
>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'
>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'
A great gem!
You can use HTML5 autofocus
for this. You don't need jQuery or other JavaScript.
<input type="text" name="some_field" autofocus>
Note this will not work on IE9 and lower.
Here are a few options:
In Perl, you can choose alternate delimiters. You're not confined to m//
. You could choose another, such as m{}
. Then escaping isn't necessary. As a matter of fact, Damian Conway in "Perl Best Practices" asserts that m{}
is the only alternate delimiter that ought to be used, and this is reinforced by Perl::Critic (on CPAN). While you can get away with using a variety of alternate delimiter characters, //
and {}
seem to be the clearest to decipher later on. However, if either of those choices result in too much escaping, choose whichever one lends itself best to legibility. Common examples are m(...)
, m[...]
, and m!...!
.
In cases where you either cannot or prefer not to use alternate delimiters, you can escape the forward slashes with a backslash: m/\/[^/]+$/
for example (using an alternate delimiter that could become m{/[^/]+$}
, which may read more clearly). Escaping the slash with a backslash is common enough to have earned a name and a wikipedia page: Leaning Toothpick Syndrome. In regular expressions where there's just a single instance, escaping a slash might not rise to the level of being considered a hindrance to legibility, but if it starts to get out of hand, and if your language permits alternate delimiters as Perl does, that would be the preferred solution.
This question was linked from this blog post and an alternative solution was proposed for the newer versions of Git:
git branch -m master old_master
git checkout --orphan master
git branch -D old_master
This solution assumes that:
master
branchold_master
so I'm free to use that nameIt will rename the existing branch to old_master
and create a new, orphaned, branch master
(like it is created for new repositories) after which you can freely delete old_master
... or not. Up to you.
Note: Moving or copying a git branch preserves its reflog (see this code) while deleting and then creating a new branch destroys it. Since you want to get back to the original state with no history you probably want to delete the branch, but others may want to consider this small note.
sed -n ':pre
1,4 {N;b pre
}
:cycle
$!{P;N;D;b cycle
}' YourFile
posix version
This might help someone like me that finds this answer when searching for solutions to how Rails handles the class loading ... I found that I had to define a module
whose name matched my filename appropriately, rather than just defining a class:
In file lib/development_mail_interceptor.rb (Yes, I'm using code from a Railscast :))
module DevelopmentMailInterceptor
class DevelopmentMailInterceptor
def self.delivering_email(message)
message.subject = "intercepted for: #{message.to} #{message.subject}"
message.to = "[email protected]"
end
end
end
works, but it doesn't load if I hadn't put the class inside a module.
Make sure the folder with the standard header files is in the projects path.
I don't know where this is in Turbo C, but I would think there's a way of doing this.
Bascailly, "a b" selects all b's inside a, while "a>b" selects b's what are only children to the a, it will not select b what is child of b what is child of a.
This example illustrates the difference:
div span{background:red}
div>span{background:green}
<div><span>abc</span><span>def<span>ghi</span></span></div>
Background color of abc and def will be green, but ghi will have red background color.
IMPORTANT: If you change order of the rules to:
div>span{background:green}
div span{background:red}
All letters will have red background, because descendant selector selects child's too.
Note the Argparse Tutorial in Python HOWTOs. It starts from most basic examples, like this one:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
args = parser.parse_args()
print(args.square**2)
and progresses to less basic ones.
There is an example with predefined choice for an option, like what is asked:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
print("{}^2 == {}".format(args.square, answer))
else:
print(answer)
I did it with css, ie: adding classes for arrows, but you can use images as well.
Bellow is an example with fontAwesome:
JS:
owl.owlCarousel({
...
// should be empty otherwise you'll still see prev and next text,
// which is defined in js
navText : ["",""],
rewindNav : true,
...
});
CSS
.owl-carousel .owl-nav .owl-prev,
.owl-carousel .owl-nav .owl-next,
.owl-carousel .owl-dot {
font-family: 'fontAwesome';
}
.owl-carousel .owl-nav .owl-prev:before{
// fa-chevron-left
content: "\f053";
margin-right:10px;
}
.owl-carousel .owl-nav .owl-next:after{
//fa-chevron-right
content: "\f054";
margin-right:10px;
}
Using images:
.owl-carousel .owl-nav .owl-prev,
.owl-carousel .owl-nav .owl-next,
.owl-carousel .owl-dot {
//width, height
width:30px;
height:30px;
...
}
.owl-carousel .owl-nav .owl-prev{
background: url('left-icon.png') no-repeat;
}
.owl-carousel .owl-nav .owl-next{
background: url('right-icon.png') no-repeat;
}
Maybe someone will find this helpful :)
According to the Apple Human Interface Guidelines:
@1x : about 25 x 25 (max: 48 x 32)
@2x : about 50 x 50 (max: 96 x 64)
@3x : about 75 x 75 (max: 144 x 96)
let JSONData = jsonString.data(using: .utf8)!
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
guard let userDictionary = jsonResult as? Dictionary<String, AnyObject> else {
throw NSError()}
I re-wrote an answer above and made it better:
CREATE FUNCTION [dbo].[CSVParser]
(
@s VARCHAR(255),
@idx NUMERIC
)
RETURNS VARCHAR(12)
BEGIN
DECLARE @comma int
SET @comma = CHARINDEX(',', @s)
WHILE 1=1
BEGIN
IF @comma=0
IF @idx=1
RETURN @s
ELSE
RETURN ''
IF @idx=1
BEGIN
DECLARE @word VARCHAR(12)
SET @word=LEFT(@s, @comma - 1)
RETURN @word
END
SET @s = RIGHT(@s,LEN(@s)-@comma)
SET @comma = CHARINDEX(',', @s)
SET @idx = @idx - 1
END
RETURN 'not used'
END
Example usage:
SELECT dbo.CSVParser(COLUMN, 1),
dbo.CSVParser(COLUMN, 2),
dbo.CSVParser(COLUMN, 3)
FROM TABLE
If your collection gets too big, I have found that Xml serialization gets quite slow. Another option to serialize your dictionary would be "roll your own" using a BinaryReader and BinaryWriter.
Here's some sample code just to get you started. You can make these generic extension methods to handle any type of Dictionary, and it works quite well, but is too verbose to post here.
class Account
{
public string AccountName { get; set; }
public int AccountNumber { get; set; }
internal void Serialize(BinaryWriter bw)
{
// Add logic to serialize everything you need here
// Keep in synch with Deserialize
bw.Write(AccountName);
bw.Write(AccountNumber);
}
internal void Deserialize(BinaryReader br)
{
// Add logic to deserialize everythin you need here,
// Keep in synch with Serialize
AccountName = br.ReadString();
AccountNumber = br.ReadInt32();
}
}
class Program
{
static void Serialize(string OutputFile)
{
// Write to disk
using (Stream stream = File.Open(OutputFile, FileMode.Create))
{
BinaryWriter bw = new BinaryWriter(stream);
// Save number of entries
bw.Write(accounts.Count);
foreach (KeyValuePair<string, List<Account>> accountKvp in accounts)
{
// Save each key/value pair
bw.Write(accountKvp.Key);
bw.Write(accountKvp.Value.Count);
foreach (Account account in accountKvp.Value)
{
account.Serialize(bw);
}
}
}
}
static void Deserialize(string InputFile)
{
accounts.Clear();
// Read from disk
using (Stream stream = File.Open(InputFile, FileMode.Open))
{
BinaryReader br = new BinaryReader(stream);
int entryCount = br.ReadInt32();
for (int entries = 0; entries < entryCount; entries++)
{
// Read in the key-value pairs
string key = br.ReadString();
int accountCount = br.ReadInt32();
List<Account> accountList = new List<Account>();
for (int i = 0; i < accountCount; i++)
{
Account account = new Account();
account.Deserialize(br);
accountList.Add(account);
}
accounts.Add(key, accountList);
}
}
}
static Dictionary<string, List<Account>> accounts = new Dictionary<string, List<Account>>();
static void Main(string[] args)
{
string accountName = "Bob";
List<Account> newAccounts = new List<Account>();
newAccounts.Add(AddAccount("A", 1));
newAccounts.Add(AddAccount("B", 2));
newAccounts.Add(AddAccount("C", 3));
accounts.Add(accountName, newAccounts);
accountName = "Tom";
newAccounts = new List<Account>();
newAccounts.Add(AddAccount("A1", 11));
newAccounts.Add(AddAccount("B1", 22));
newAccounts.Add(AddAccount("C1", 33));
accounts.Add(accountName, newAccounts);
string saveFile = @"C:\accounts.bin";
Serialize(saveFile);
// clear it out to prove it works
accounts.Clear();
Deserialize(saveFile);
}
static Account AddAccount(string AccountName, int AccountNumber)
{
Account account = new Account();
account.AccountName = AccountName;
account.AccountNumber = AccountNumber;
return account;
}
}
You cannot write data's to asset/Raw folder, since it is packed(.apk) and not expandable in size.
If your application need to download dependency files from server, you can go for APK Expansion Files provided by android (http://developer.android.com/guide/market/expansion-files.html).
All of the suggestions above work, but if you want your computations to by more efficient, you should take advantage of numpy vector operations (as pointed out here).
import pandas as pd
import numpy as np
df = pd.DataFrame ({'a' : np.random.randn(6),
'b' : ['foo', 'bar'] * 3,
'c' : np.random.randn(6)})
Example 1: looping with pandas.apply()
:
%%timeit
def my_test2(row):
return row['a'] % row['c']
df['Value'] = df.apply(my_test2, axis=1)
The slowest run took 7.49 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 481 µs per loop
Example 2: vectorize using pandas.apply()
:
%%timeit
df['a'] % df['c']
The slowest run took 458.85 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 70.9 µs per loop
Example 3: vectorize using numpy arrays:
%%timeit
df['a'].values % df['c'].values
The slowest run took 7.98 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 6.39 µs per loop
So vectorizing using numpy arrays improved the speed by almost two orders of magnitude.
If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time
with the ability to do arithmetic. When you go past midnight, it wraps around zero. Now, "What time will it be, 24 hours from now" has a lot of corner cases, including daylight savings time, leap seconds, historical timezone changes, and so on. But sometimes you really do need the simple case, and that's what this will do.
Your example would be written:
>>> import datetime
>>> import nptime
>>> nptime.nptime(11, 34, 59) + datetime.timedelta(0, 3)
nptime(11, 35, 2)
nptime
inherits from datetime.time
, so any of those methods should be usable, too.
It's available from PyPi as nptime
("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime
Put them inside btn-toolbar
or some other container, not btn-group
. btn-group
joins them together. More info on Bootstrap documentation.
Edit: The original question was for Bootstrap 2.x, but the same is still valid for Bootstrap 3 and Bootstrap 4.
In Bootstrap 4 you will need to add appropriate margin to your groups using utility classes, such as mx-2.
<div id='myInputF2'> YES ITS DIV TEXT TO COPY </div>
<script>
function myFunctionF2() {
str = document.getElementById('myInputF2').innerHTML;
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
alert('Copied the text:' + el.value);
};
</script>
more info: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f
string ImagePath = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
string a = "";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
if (receiveStream.CanRead)
{ a = "OK"; }
}
catch { }
Under "Settings -> Editor -> General -> Auto Import"
there are several options regarding automatic imports. Only unambiguous imports may be added automatically; this is one of the options.
EDIT: I wrote this answer up in haste, before realizing that your question is about sending values to a chan inside a goroutine. The approach below can be used either with an additional chan as suggested above, or using the fact that the chan you have already is bi-directional, you can use just the one...
If your goroutine exists solely to process the items coming out of the chan, you can make use of the "close" builtin and the special receive form for channels.
That is, once you're done sending items on the chan, you close it. Then inside your goroutine you get an extra parameter to the receive operator that shows whether the channel has been closed.
Here is a complete example (the waitgroup is used to make sure that the process continues until the goroutine completes):
package main
import "sync"
func main() {
var wg sync.WaitGroup
wg.Add(1)
ch := make(chan int)
go func() {
for {
foo, ok := <- ch
if !ok {
println("done")
wg.Done()
return
}
println(foo)
}
}()
ch <- 1
ch <- 2
ch <- 3
close(ch)
wg.Wait()
}
google the javascript same origin policy
in a nutshell, the url you are trying to use must have the same root and protocol. so http://yoursite.com cannot access https://yoursite.com or http://anothersite.com
is you absolutely MUST bypass this protection (which is at the browser level, as galimy pointed out), consider the ProxyPass module for your favorite web server.
As of July, 2020 the following dependencies in pom.xml worked for me:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.1</version>
</dependency>
With this 4.13 junit library and hamcrest, it uses hamcrest.MatcherAssert when asserting and throws exception- enter image description here
In java spark dataset it can be used as
Dataset userfilter = user.filter(col("gender").isin("male","female"));
As stated by many here, I am writing the same thing but with an additional point!
At first we need to make sure that our R Studio has these two packages installed:
In order to load a package in R you can use the below function:
install.packages("readxl/XLConnect")
library(XLConnect)
search()
search will display the list of current packages being available in your R Studio.
Now another catch, even though you might have these two packages but still you may encounter problem while reading "xlsx" file and the error could be like "error: more columns than column name"
To solve this issue you can simply resave your excel sheet "xlsx" in to
"CSV (Comma delimited)"
and your life will be super easy....
Have fun!!
Linux Mint 20 Ulyana users need to change "ulyana" to "bionic" in
/etc/apt/sources.list.d/additional-repositories.list
like so:
deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable
As it was mentioned above CasperJS is the best tool to fill and send forms. Simplest possible example of how to fill & submit form using fill() function:
casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
this.fill('form#loginForm', {
'login': 'admin',
'password': '12345678'
}, true);
this.evaluate(function(){
//trigger click event on submit button
document.querySelector('input[type="submit"]').click();
});
});
I got it with:
import console
console.clear()
if you want to do it in your script, or if you are in the console just tap clear() and press enter. That works on Pyto on iPhone. It may depend on the console though.
I have faced the similar issue and fixed by copying the missing Jar files in to .M2 Path,
For example: if you see the error message as Missing artifact tws:axis-client:jar:8.7
then you have to download "axis-client-8.7.jar" file and paste the same in to below location will resolve the issue.
C:\Users\UsernameXXX.m2\repository\tws\axis-client\8.7(Paste axis-client-8.7.jar).
finally, right click on project->Maven->Update Project...Thats it.
happy coding.
try changing that line-height change to a margin-top or padding-top change instead
#btnhome:active{
margin-top : 25px;
}
Edit: You could also try adding a span inside the button
<div id="header">
<button id="btnhome"><span>Home</span></button>
<button id="btnabout">About</button>
<button id="btncontact">Contact</button>
<button id="btnsup">Help Us</button>
</div>
Then style that
#btnhome span:active { padding-top:25px;}
Thanks all. I took bits of each of your solutions and made my own.
The final working solution is:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
success: function(data) {
$('#twitter-loader').remove();
$('#twitter-container').html(data);
}
});
});
</script>
Pickle uses different protocols
to convert your data to a binary stream.
In python 2 there are 3 different protocols (0
, 1
, 2
) and the default is 0
.
In python 3 there are 5 different protocols (0
, 1
, 2
, 3
, 4
) and the default is 3
.
You must specify in python 3 a protocol lower than 3
in order to be able to load the data in python 2. You can specify the protocol
parameter when invoking pickle.dump
.
echo "echo "we are now going to work with ${ser}" " >> $servfile
Escape all " within quotes with \. Do this with variables like \$servicetest too:
echo "echo \"we are now going to work with \${ser}\" " >> $servfile
echo "read -p \"Please enter a service: \" ser " >> $servfile
echo "if [ \$servicetest > /dev/null ];then " >> $servfile
In my case this was happening with a Laravel queue worker. The system logs did not mention any killing so I looked further and it turned out that the worker was basically killing itself because of a job that exceeded the memory limit (which is set to 128M by default).
Running the queue worker with --timeout=600
and --memory=1024
fixed the problem for me.
I realize this is an old thread, but @alex 's answer needs to be marked as the correct answer
element.getBoundingClientRect()
is an exact match to jQuery's $(element).offset()
And it's compatible with IE4+ ... https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
Using Android Studio newest version
and update Android Plugin to 'newest alpha version`, I can disable Instant Run:
Try to update Android Studio.
If you use Bootstrap, try to assign margin-bottom 0 to the paragraph and after assign the property align-items-center to container, for example, like this:
<div class="row align-items-center">
<p class="col-sm-1 mb-0">
....
</p>
</div>
Bootstrap by default assign a calculate margin bottom, so mb-0 disabled this.
I hope it helps
//user113716 code is working but i altered as below. it will work if your URL contain "?" mark or not
//replace URL in browser
if(window.location.href.indexOf("?") > -1) {
var newUrl = refineUrl();
window.history.pushState("object or string", "Title", "/"+newUrl );
}
function refineUrl()
{
//get full url
var url = window.location.href;
//get url after/
var value = url = url.slice( 0, url.indexOf('?') );
//get the part after before ?
value = value.replace('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]','');
return value;
}
The top answer is equivalent to doing:
let text = find.reduce((acc, item, i) => {
const regex = new RegExp(item, "g");
return acc.replace(regex, replace[i]);
}, textarea);
Given this:
var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["<", ">", "<br/>"];
In this case, no imperative programming is going on.
The simpliest way is to add a hidden timestamp before the date in every TD tag of the column, for example:
<td class="sorting_1">
<span class="d-none">1547022615</span>09/01/2019 09:30
</td>
With the default string ordering, a timestamp would order the column the way you want and it will not be shown when rendered in the browser.
new[,2]
is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
ipcs -s | grep $USERNAME | perl -e 'while (<STDIN>) { @a=split(/\s+/); print `ipcrm sem $a[1]`}'
or
ipcs -s | grep $USERNAME | awk ' { print $2 } ' | xargs ipcrm sem
Change $USERNAME to a real username.
Make sure it's within a document ready tagAlternatively, try using .live
$(document).ready(function(){
$('#content').live('click', function(e) {
alert(1);
});
});
Example:
$(document).ready(function() {_x000D_
$('#content').click(function(e) { _x000D_
alert(1);_x000D_
});_x000D_
});
_x000D_
#content {_x000D_
padding: 20px;_x000D_
background: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id="content">Hello world</div>
_x000D_
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
$('#content').on( "click", function() {
alert(1);
});
All objects in Java are references and you can use them like pointers.
abstract class Animal
{...
}
class Lion extends Animal
{...
}
class Tiger extends Animal
{
public Tiger() {...}
public void growl(){...}
}
Tiger first = null;
Tiger second = new Tiger();
Tiger third;
Dereferencing a null:
first.growl(); // ERROR, first is null.
third.growl(); // ERROR, third has not been initialized.
Aliasing Problem:
third = new Tiger();
first = third;
Losing Cells:
second = third; // Possible ERROR. The old value of second is lost.
You can make this safe by first assuring that there is no further need of the old value of second or assigning another pointer the value of second.
first = second;
second = third; //OK
Note that giving second a value in other ways (NULL, new...) is just as much a potential error and may result in losing the object that it points to.
The Java system will throw an exception (OutOfMemoryError
) when you call new and the allocator cannot allocate the requested cell. This is very rare and usually results from run-away recursion.
Note that, from a language point of view, abandoning objects to the garbage collector are not errors at all. It is just something that the programmer needs to be aware of. The same variable can point to different objects at different times and old values will be reclaimed when no pointer references them. But if the logic of the program requires maintaining at least one reference to the object, It will cause an error.
Novices often make the following error.
Tiger tony = new Tiger();
tony = third; // Error, the new object allocated above is reclaimed.
What you probably meant to say was:
Tiger tony = null;
tony = third; // OK.
Improper Casting:
Lion leo = new Lion();
Tiger tony = (Tiger)leo; // Always illegal and caught by compiler.
Animal whatever = new Lion(); // Legal.
Tiger tony = (Tiger)whatever; // Illegal, just as in previous example.
Lion leo = (Lion)whatever; // Legal, object whatever really is a Lion.
Pointers in C:
void main() {
int* x; // Allocate the pointers x and y
int* y; // (but not the pointees)
x = malloc(sizeof(int)); // Allocate an int pointee,
// and set x to point to it
*x = 42; // Dereference x to store 42 in its pointee
*y = 13; // CRASH -- y does not have a pointee yet
y = x; // Pointer assignment sets y to point to x's pointee
*y = 13; // Dereference y to store 13 in its (shared) pointee
}
Pointers in Java:
class IntObj {
public int value;
}
public class Binky() {
public static void main(String[] args) {
IntObj x; // Allocate the pointers x and y
IntObj y; // (but not the IntObj pointees)
x = new IntObj(); // Allocate an IntObj pointee
// and set x to point to it
x.value = 42; // Dereference x to store 42 in its pointee
y.value = 13; // CRASH -- y does not have a pointee yet
y = x; // Pointer assignment sets y to point to x's pointee
y.value = 13; // Deference y to store 13 in its (shared) pointee
}
}
UPDATE: as suggested in the comments one must note that C has pointer arithmetic. However, we do not have that in Java.
TRY THIS CODE
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
MessageBox.Show("Please enter number only...");
e.Handled = true;
}
}
Source is http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx
Dates are stored in their timestamp format. If you want everything that belongs to a specific month, query for the start and the end of the month.
var start = new Date(2010, 11, 1);
var end = new Date(2010, 11, 30);
db.posts.find({created_on: {$gte: start, $lt: end}});
//taken from http://cookbook.mongodb.org/patterns/date_range/
I know that you're currently using jQuery, but what if you defined the onclick handler inline. Then you could do:
<a href='/link/for/non-js-users.htm' onclick='loadContent(5);return false;'>
Article 5</a>
Or for fun:
>>> ast.literal_eval('[%s]'%','.join(map(repr,s.split())))
['QH', 'QD', 'JC', 'KD', 'JS']
>>>
ast.literal_eval
I would suggest the P: drive is not mapped for the account that sql server has started as.
Similar to unutbu's answer, you can use numpy's arange function, which is analog to Python's intrinsic function range
. Notice that the end point is not included, as in range
:
>>> import numpy as np
>>> a = np.arange(0,5, 0.5)
>>> a
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
>>> a = np.arange(0,5, 0.5) # returns a numpy array
>>> a
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
>>> a.tolist() # if you prefer it as a list
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]