My solution for this problem came after reading and trying all of the above.
In my case I tried to downgrade Java to use printouts in Apache ActiveMQ
. After uninstalling all Java versions and cleaning the registry I was getting the same error
Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' has value '1.7', but '1.8' is required."
In my case I needed to go to environment variables, edit path, open the javapath location (C:\ProgramData\Oracle\Java\javapath
) and there it was - three files (java.exe
, javaw.exe
, javaws.exe
) that remained from the JRE8 version.
After establishing this fact I simply switched them with the same files from C:\Windows\SysWOW64
directory (those were from the JRE7
version) and it all worked perfectly.
The Basics:
String
is an immutable class, it can't be changed.
StringBuilder
is a mutable class that can be appended to, characters replaced or removed and ultimately converted to a String
StringBuffer
is the original synchronized version of StringBuilder
You should prefer StringBuilder
in all cases where you have only a single thread accessing your object.
The Details:
Also note that StringBuilder/Buffers
aren't magic, they just use an Array as a backing object and that Array has to be re-allocated when ever it gets full. Be sure and create your StringBuilder/Buffer
objects large enough originally where they don't have to be constantly re-sized every time .append()
gets called.
The re-sizing can get very degenerate. It basically re-sizes the backing Array to 2 times its current size every time it needs to be expanded. This can result in large amounts of RAM getting allocated and not used when StringBuilder/Buffer
classes start to grow large.
In Java String x = "A" + "B";
uses a StringBuilder
behind the scenes. So for simple cases there is no benefit of declaring your own. But if you are building String
objects that are large, say less than 4k, then declaring StringBuilder sb = StringBuilder(4096);
is much more efficient than concatenation or using the default constructor which is only 16 characters. If your String
is going to be less than 10k then initialize it with the constructor to 10k to be safe. But if it is initialize to 10k then you write 1 character more than 10k, it will get re-allocated and copied to a 20k array. So initializing high is better than to low.
In the auto re-size case, at the 17th character the backing Array gets re-allocated and copied to 32 characters, at the 33th character this happens again and you get to re-allocated and copy the Array into 64 characters. You can see how this degenerates to lots of re-allocations and copies which is what you really are trying to avoid using StringBuilder/Buffer
in the first place.
This is from the JDK 6 Source code for AbstractStringBuilder
void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}
A best practice is to initialize the StringBuilder/Buffer
a little bit larger than you think you are going to need if you don't know right off hand how big the String
will be but you can guess. One allocation of slightly more memory than you need is going to be better than lots of re-allocations and copies.
Also beware of initializing a StringBuilder/Buffer
with a String
as that will only allocated the size of the String + 16 characters, which in most cases will just start the degenerate re-allocation and copy cycle that you are trying to avoid. The following is straight from the Java 6 source code.
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
If you by chance do end up with an instance of StringBuilder/Buffer
that you didn't create and can't control the constructor that is called, there is a way to avoid the degenerate re-allocate and copy behavior. Call .ensureCapacity()
with the size you want to ensure your resulting String
will fit into.
The Alternatives:
Just as a note, if you are doing really heavy String
building and manipulation, there is a much more performance oriented alternative called Ropes.
Another alternative, is to create a StringList
implemenation by sub-classing ArrayList<String>
, and adding counters to track the number of characters on every .append()
and other mutation operations of the list, then override .toString()
to create a StringBuilder
of the exact size you need and loop through the list and build the output, you can even make that StringBuilder
an instance variable and 'cache' the results of .toString()
and only have to re-generate it when something changes.
Also don't forget about String.format()
when building fixed formatted output, which can be optimized by the compiler as they make it better.
mysqldump
will backup by default all the triggers but NOT the stored procedures/functions. There are 2 mysqldump parameters that control this behavior:
--routines
– FALSE by default--triggers
– TRUE by defaultso in mysqldump
command , add --routines
like :
mysqldump <other mysqldump options> --routines > outputfile.sql
Use below method, just pass the subject and body as arguments of the method
public static void shareText(String subject,String body) {
Intent txtIntent = new Intent(android.content.Intent.ACTION_SEND);
txtIntent .setType("text/plain");
txtIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
txtIntent .putExtra(android.content.Intent.EXTRA_TEXT, body);
startActivity(Intent.createChooser(txtIntent ,"Share"));
}
This has to do with contiguous memory.
Here's some info I found online for somebody asking that before, supposedly from a "VM god":
The reason we need a contiguous memory region for the heap is that we have a bunch of side data structures that are indexed by (scaled) offsets from the start of the heap. For example, we track object reference updates with a "card mark array" that has one byte for each 512 bytes of heap. When we store a reference in the heap we have to mark the corresponding byte in the card mark array. We right shift the destination address of the store and use that to index the card mark array. Fun addressing arithmetic games you can't do in Java that you get to (have to :-) play in C++.
Usually we don't have trouble getting modest contiguous regions (up to about 1.5GB on Windohs, up to about 3.8GB on Solaris. YMMV.). On Windohs, the problem is mostly that there are some libraries that get loaded before the JVM starts up that break up the address space. Using the /3GB switch won't rebase those libraries, so they are still a problem for us.
We know how to make chunked heaps, but there would be some overhead to using them. We have more requests for faster storage management than we do for larger heaps in the 32-bit JVM. If you really want large heaps, switch to the 64-bit JVM. We still need contiguous memory, but it's much easier to get in a 64-bit address space.
Use .attr
$("current_month").attr("month")
$("current_month").attr("year")
And change the labels id to
<label year="2010" month="6" id="current_month"> June 2010</label>
If you want the node_modules
folder available to the host during development, you could install the dependencies when you start the container instead of during build-time. I do this to get syntax highlighting working in my editor.
# We're using a multi-stage build so that we can install dependencies during build-time only for production.
# dev-stage
FROM node:14-alpine AS dev-stage
WORKDIR /usr/src/app
COPY package.json ./
COPY . .
# `yarn install` will run every time we start the container. We're using yarn because it's much faster than npm when there's nothing new to install
CMD ["sh", "-c", "yarn install && yarn run start"]
# production-stage
FROM node:14-alpine AS production-stage
WORKDIR /usr/src/app
COPY package.json ./
RUN yarn install
COPY . .
Add node_modules
to .dockerignore
to prevent it from being copied when the Dockerfile
runs COPY . .
. We use volumes to bring in node_modules
.
**/node_modules
node_app:
container_name: node_app
build:
context: ./node_app
target: dev-stage # `production-stage` for production
volumes:
# For development:
# If node_modules already exists on the host, they will be copied
# into the container here. Since `yarn install` runs after the
# container starts, this volume won't override the node_modules.
- ./node_app:/usr/src/app
# For production:
#
- ./node_app:/usr/src/app
- /usr/src/app/node_modules
Summary from Angular docs:
Best answers from SO:
https://stackoverflow.com/a/26924234/165673 (<-- GOOD)
https://stackoverflow.com/a/27263882/165673
https://stackoverflow.com/a/16566144/165673
Yes , Its easy to way we call the function inside the store procedure.
for e.g. create user define Age function and use in select query.
select dbo.GetRegAge(R.DateOfBirth, r.RegistrationDate) as Age,R.DateOfBirth,r.RegistrationDate from T_Registration R
If you are using windows and are interested in clearing the screen before running the program, you can compile the file call it from a .bat file. for example:
cls
java "what ever the name of the compiles class is"
Save as "etc".bat and then running by calling it in the command prompt or double clicking the file
Ran into this same issue myself. For me, the issue was that my product name ($TARGET_NAME) was not capitalized the same way presented in the certificate provided by apple. For example, i had com.companyid.APNDemo whereas the Apple cert was using com.companyid.apndemo.
I changed my target to be lowercase and it worked. Note: The clue for me was the codesigning setting in Build Settings was set to my default developer certificate; not the APNTest provisioning profile.
You need to instantiate the class it is contained within, or make the method static.
So if it is contained within class Foo:
Foo x = new Foo();
List<Integer> stuff = x.myNumbers();
or alternatively shorthand:
List<Integer> stuff = new Foo().myNumbers();
or if you make it static like so:
public static List<Integer> myNumbers() {
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(11);
numbers.add(3);
return(numbers);
}
you can call it like so:
List<Integer> stuff = Foo.myNumbers();
And it's maybe also handy to know that BigTable is not a relational database (like MySQL) but a huge (distributed) hash table which has very different characteristics. You can play around with (a limited version) of BigTable yourself on the Google AppEngine platform.
Next to Hadoop mentioned above there are many other implementations that try to solve the same problems as BigTable (scalability, availability). I saw a nice blog post yesterday listing most of them here.
Set the z-index
of the :before
or :after
pseudo element to -1 and give it a position
that honors the z-index
property (absolute
, relative
, or fixed
). This works because the pseudo element's z-index
is relative to its parent element, rather than <html>
, which is the default for other elements. Which makes sense because they are child elements of <html>
.
The problem I was having (that lead me to this question and the accepted answer above) was that I was trying to use a :after
pseudo element to get fancy with a background to an element with z-index
of 15, and even when set with a z-index
of 14, it was still being rendered on top of its parent. This is because, in that stacking context, it's parent has a z-index
of 0.
Hopefully that helps clarify a little what's going on.
In C++, use no-argument constructors. In C you can't have constructors, so use either memset
or - the interesting solution - designated initializers:
struct Snapshot s = { .x = 0.0, .y = 0.0 };
It is a bit old, this post. But this is my code to show/hide the columns. I use the built in function to display the columns and just mark them.
Function that displays columns shown/hidden columns. The #jqGrid is the name of my grid, and the columnChooser is the jqGrid column chooser.
function showHideColumns() {
$('#jqGrid').jqGrid('columnChooser', {
width: 250,
dialog_opts: {
modal: true,
minWidth: 250,
height: 300,
show: 'blind',
hide: 'explode',
dividerLocation: 0.5
} });
It is a sort of format specifier for formatting numeric results. There are additional specifiers on the link.
What N
does is that it separates numbers into thousand decimal places according to your CultureInfo and represents only 2 decimal digits in floating part as is N2
by rounding right-most digit if necessary.
N0
does not represent any decimal place but rounding is applied to it.
Let's exemplify.
using System;
using System.Globalization;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
double x = 567892.98789;
CultureInfo someCulture = new CultureInfo("da-DK", false);
// 10 means left-padded = right-alignment
Console.WriteLine(String.Format(someCulture, "{0:N} denmark", x));
Console.WriteLine("{0,10:N} us", x);
// watch out rounding 567,893
Console.WriteLine(String.Format(someCulture, "{0,10:N0}", x));
Console.WriteLine("{0,10:N0}", x);
Console.WriteLine(String.Format(someCulture, "{0,10:N5}", x));
Console.WriteLine("{0,10:N5}", x);
Console.ReadKey();
}
}
}
It yields,
567.892,99 denmark
567,892.99 us
567.893
567,893
567.892,98789
567,892.98789
You are looking for the cp
command. You need to change directories so that you are outside of the directory you are trying to copy.
If the directory you're copying is called dir1
and you want to copy it to your /home/Pictures
folder:
cp -r dir1/ ~/Pictures/
Linux is case-sensitive and also needs the /
after each directory to know that it isn't a file. ~
is a special character in the terminal that automatically evaluates to the current user's home directory. If you need to know what directory you are in, use the command pwd
.
When you don't know how to use a Linux command, there is a manual page that you can refer to by typing:
man [insert command here]
at a terminal prompt.
Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you've started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.
Use this css code for all four sides: box-shadow: 0px 1px 7px 0px rgb(106, 111, 109);
<button type="submit" formnovalidate="formnovalidate">submit</button>
also working
I once wrote this function for ksh on Solaris (uses Perl for base64 encoding):
# usage: email_attachment to cc subject body attachment_filename
email_attachment() {
to="$1"
cc="$2"
subject="$3"
body="$4"
filename="${5:-''}"
boundary="_====_blah_====_$(date +%Y%m%d%H%M%S)_====_"
{
print -- "To: $to"
print -- "Cc: $cc"
print -- "Subject: $subject"
print -- "Content-Type: multipart/mixed; boundary=\"$boundary\""
print -- "Mime-Version: 1.0"
print -- ""
print -- "This is a multi-part message in MIME format."
print -- ""
print -- "--$boundary"
print -- "Content-Type: text/plain; charset=ISO-8859-1"
print -- ""
print -- "$body"
print -- ""
if [[ -n "$filename" && -f "$filename" && -r "$filename" ]]; then
print -- "--$boundary"
print -- "Content-Transfer-Encoding: base64"
print -- "Content-Type: application/octet-stream; name=$filename"
print -- "Content-Disposition: attachment; filename=$filename"
print -- ""
print -- "$(perl -MMIME::Base64 -e 'open F, shift; @lines=<F>; close F; print MIME::Base64::encode(join(q{}, @lines))' $filename)"
print -- ""
fi
print -- "--${boundary}--"
} | /usr/lib/sendmail -oi -t
}
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(void)
{
int i = 0;
char *a = (char *) malloc(sizeof(char) * 1024);
while (1) {
scanf("%c", &a[i]);
if (a[i] == '\n') {
break;
}
else {
i++;
}
}
a[i] = '\0';
i = 0;
printf("\n");
while (a[i] != '\0') {
printf("%c", a[i]);
i++;
}
free(a);
getch();
return 0;
}
A sub class is a small file of a program that extends from some other class. For example you make a class about cars in general and have basic information that holds true for all cars with your constructors and stuff then you have a class that extends from that on a more specific car or line of cars that would have new variables/methods. I see you already have plenty of examples of code from above by the time I get to post this but I hope this description helps.
As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2))
.
Just access the Priority
property of the object returned from the pipeline:
$var = (Get-WSManInstance -enumerate wmicimv2/win32_process).Priority
(This won't work if Get-WSManInstance
returns multiple objects.2)
For the second question: to get two properties there are several options, problably the simplest is to have have one variable* containing an object with two separate properties:
$var = (Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)
and then use, assuming only one process:
$var.Priority
and
$var.ProcessID
If there are multiple processes $var
will be an array which you can index, so to get the properties of the first process (using the array literal syntax @(...)
so it is always a collection1):
$var = @(Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)
and then use:
$var[0].Priority
$var[0].ProcessID
1 PowerShell helpfully for the command line, but not so helpfully in scripts has some extra logic when assigning the result of a pipeline to a variable: if no objects are returned then set $null
, if one is returned then that object is assigned, otherwise an array is assigned. Forcing an array returns an array with zero, one or more (respectively) elements.
2 This changes in PowerShell V3 (at the time of writing in Release Candidate), using a member property on an array of objects will return an array of the value of those properties.
ENV PYTHONWARNINGS="ignore::DeprecationWarning"
Use Json
class instead of Content
as shown following:
// When I want to return an error:
if (!isFileSupported)
{
Response.StatusCode = (int) HttpStatusCode.BadRequest;
return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
}
else
{
// When I want to return sucess:
Response.StatusCode = (int)HttpStatusCode.OK;
return Json("Message sent!", MediaTypeNames.Text.Plain);
}
Also set contentType:
contentType: 'application/json; charset=utf-8',
Why are the 500 Internal Server Errors not being logged into your apache error logs?
The errors that cause your 500 Internal Server Error are coming from a PHP module. By default, PHP does NOT log these errors. Reason being you want web requests go as fast as physically possible and it's a security hazard to log errors to screen where attackers can observe them.
These instructions to enable Internal Server Error Logging are for Ubuntu 12.10
with PHP 5.3.10
and Apache/2.2.22
.
Make sure PHP logging is turned on:
Locate your php.ini file:
el@apollo:~$ locate php.ini
/etc/php5/apache2/php.ini
Edit that file as root:
sudo vi /etc/php5/apache2/php.ini
Find this line in php.ini:
display_errors = Off
Change the above line to this:
display_errors = On
Lower down in the file you'll see this:
;display_startup_errors
; Default Value: Off
; Development Value: On
; Production Value: Off
;error_reporting
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT
; Production Value: E_ALL & ~E_DEPRECATED
The semicolons are comments, that means the lines don't take effect. Change those lines so they look like this:
display_startup_errors = On
; Default Value: Off
; Development Value: On
; Production Value: Off
error_reporting = E_ALL
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT
; Production Value: E_ALL & ~E_DEPRECATED
What this communicates to PHP is that we want to log all these errors. Warning, there will be a large performance hit, so you don't want this enabled on production because logging takes work and work takes time, time costs money.
Restarting PHP and Apache should apply the change.
Do what you did to cause the 500 Internal Server error again, and check the log:
tail -f /var/log/apache2/error.log
You should see the 500 error at the end, something like this:
[Wed Dec 11 01:00:40 2013] [error] [client 192.168.11.11] PHP Fatal error:
Call to undefined function Foobar\\byob\\penguin\\alert() in /yourproject/
your_src/symfony/Controller/MessedUpController.php on line 249, referer:
https://nuclearreactor.com/abouttoblowup
#This adds 10 seconds from now.
from datetime import datetime
import commands
date_string_command="date +%s"
utc = commands.getoutput(date_string_command)
a_date=datetime.fromtimestamp(float(int(utc))).strftime('%Y-%m-%d %H:%M:%S')
print('a_date:'+a_date)
utc = int(utc)+10
b_date=datetime.fromtimestamp(float(utc)).strftime('%Y-%m-%d %H:%M:%S')
print('b_date:'+b_date)
This is a little more wordy but it comes from date command in unix.
Try:
<xsl:value-of select="count(preceding-sibling::*) + 1" />
Edit - had a brain freeze there, position() is more straightforward!
For me, the way it worked is I have to kill the parent process. Figure the parent process out and kill it
taskkill /IM "parent_process_name.exe" /T /F
You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink
Assuming you have foo.conf in sites-available
Try
cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l
Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf
Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.
If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.
ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf
Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:
lrwxrwxrwx 1 root root 26 Jun 24 21:06 000-default -> ../sites-available/default
See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).
Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.
You need to subscribe to the KeyDown
event on the text box. Then something like this:
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != '+' && e.KeyChar != '-'
&& e.KeyChar != '(' && e.KeyChar != ')' && e.KeyChar != '*'
&& e.KeyChar != '/')
{
e.Handled = true;
return;
}
e.Handled=false;
return;
}
The important thing to know is that if you changed the Handled
property to true
, it will not process the keystroke. Setting it to false
will.
You can also set the TMPDIR
environment variable.
In some situations (Docker in my case) it's more convenient to set an environment variable than to update a config file.
I got this error when I tried to install pymssql even though Visual C++ 2015 (14.0) is installed in my system.
I resolved this error by downloading the .whl file of pymssql from here.
Once downloaded, it can be installed by the following command :
pip install python_package.whl
Hope this helps
function validate(){
var re = /^[A-Za-z]+$/;
if(re.test(document.getElementById("textboxID").value))
alert('Valid Name.');
else
alert('Invalid Name.');
}
Though this question is rather old and has already been answered, I just want to add a note on how to do proper exception handling in C++11:
std::nested_exception
and std::throw_with_nested
Using these, in my opinion, leads to cleaner exception design and makes it unnecessary to create an exception class hierarchy.
Note that this enables you to get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging. It is described on StackOverflow here and here, how to write a proper exception handler which will rethrow nested exceptions.
Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:
Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"
This worked for me on Ubuntu 12.04 and R version 3.0
cd /usr/lib/jvm/java-6-sun-1.6.0.26/include
this is the directory that has jni.h
Next create a soft link to another required header file (I'm too lazy to find out how to include more than one directory in the JAVA_CPPFLAGS option below):
sudo ln -s linux/jni_md.h .
Finally
sudo R CMD javareconf JAVA_CPPFLAGS=-I/usr/lib/jvm/java-6-sun-1.6.0.26/include
Since PHP >= 5.2.2 you can use the DateTime
class as such:
if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
# current time is greater than 2010-05-15 16:00:00
# in other words, 2010-05-15 16:00:00 has passed
}
The string passed to the DateTime constructor is parsed according to these rules.
Note that it is also possible to use time
and strtotime
functions. See original answer.
Delete your .git folder, and reinitialize the git with git init, in my case that's work , because git add command staging the folder and the files in .git folder, if you close CLI after the commit , there will be double folder in staging area that make git system throw this issue.
ADT is a set of objects and operations, no where in an ADT’s definitions is there any mention of how the set of operations is implemented. Programmers who use collections only need to know how to instantiate and access data in some pre-determined manner, without concerns for the details of the collections implementations. In other words, from a user’s perspective, a collection is an abstraction, and for this reason, in computer science, some collections are referred to as abstract data types (ADTs). The user is only concern with learning its interface, or the set of operations its performs...more
Further to Cody Gray's answer, there's a third way (everything there applies her as well):
You can also use a dynamic array that's resized on the fly:
Dim test() as String
Dim arraySize as Integer
Do While someCondition
'...whatever
arraySize = arraySize + 1
ReDim Preserve test(arraySize)
test(arraySize) = newStringValue
Loop
Note the Preserve
keyword. Without it, redimensioning an array also initializes all the elements.
Use ?'%*%'
to get the documentation.
%*%
is matrix multiplication. For matrix multiplication, you need an m x n
matrix times an n x p
matrix.
None of the many answers with Application.CutCopyMode
or .Select
worked for me.
But I did find a solution not posted here, which worked fantastically for me!
From StackExchange SuperUser: Excel VBA “Unselect” wanted
If you are really wanting 'nothing selected`, you can use VBA to protect the sheet at the end of your code execution, which will cause nothing to be selected. You can either add this to a macro or put it into your VBA directly.
Sub NoSelect()
With ActiveSheet
.EnableSelection = xlNoSelection
.Protect
End With
End Sub
As soon as the sheet is unprotected, the cursor will activate a cell.
Hope this helps someone with the same problem!
This will give you what you want:
eg2011cleaned <- eg2011[!eg2011$ID %in% bg2011missingFromBeg, ]
The error in your second attempt is because you forgot the ,
In general, for convenience, the specification object[index]
subsets columns for a 2d object
. If you want to subset rows and keep all columns you have to use the specification
object[index_rows, index_columns]
, while index_cols
can be left blank, which will use all columns by default.
However, you still need to include the ,
to indicate that you want to get a subset of rows instead of a subset of columns.
If start
can't find what it's looking for, it does what you describe.
Since what you're doing should work, it's very likely you're leaving out some quotes (or putting extras in).
Using following single line code you can get status bar height in any orientation and also if it is visible or not
#define STATUS_BAR_HIGHT (
[UIApplicationsharedApplication].statusBarHidden ? 0 : (
[UIApplicationsharedApplication].statusBarFrame.size.height > 100 ?
[UIApplicationsharedApplication].statusBarFrame.size.width :
[UIApplicationsharedApplication].statusBarFrame.size.height
)
)
It just a simple but very useful macro just try this you don't need to write any extra code
It's a matter of preference, but I prefer to see scripts that consistently use the slash - this way all "units" of work (creating a PL/SQL object, running a PL/SQL anonymous block, and executing a DML statement) can be picked out more easily by eye.
Also, if you eventually move to something like Ant for deployment it will simplify the definition of targets to have a consistent statement delimiter.
In my Impression, the GDI approach and the DX approach are different in its nature. painting using GDI applies the FLUSH method, the FLUSH approach draws the frame then clear it and redraw another frame in the same buffer, this will result in flickering in games require high frame rate.
I think what you really need is a replay system, which I totally agree with what people discussed.
Other way of doing this: Assuming that you have a TextBox input type, Create a Form, and have the textbox value as a public property.
public partial class TextPrompt : Form
{
public string Value
{
get { return tbText.Text.Trim(); }
}
public TextPrompt(string promptInstructions)
{
InitializeComponent();
lblPromptText.Text = promptInstructions;
}
private void BtnSubmitText_Click(object sender, EventArgs e)
{
Close();
}
private void TextPrompt_Load(object sender, EventArgs e)
{
CenterToParent();
}
}
In the main form, this will be the code:
var t = new TextPrompt(this, "Type the name of the settings file:");
t.ShowDialog()
;
This way, the code looks cleaner:
Use continue statement instead of return to skip an iteration in JS loops.
Have you set up a python interpreter facet?
Open Project Structure CTRL+ALT+SHIFT+S
Project settings -> Facets -> expand Python click on child -> Python Interpreter
Then:
Project settings -> Modules -> Expand module -> Python -> Dependencies -> select Python module SDK
$("input:checkbox:not(:checked)")
Will get you the unchecked boxes.
Works for me-
function querySt(Key) {
var url = window.location.href;
KeysValues = url.split(/[\?&]+/);
for (i = 0; i < KeysValues.length; i++) {
KeyValue= KeysValues[i].split("=");
if (KeyValue[0] == Key) {
return KeyValue[1];
}
}
}
function GetQString(Key) {
if (querySt(Key)) {
var value = querySt(Key);
return value;
}
}
Your Service/ Application might already be running. In Search enter Services and you will get list of services. Stop yours and then try again.
You cannot delete a variable if you declared it (with var x;
) at the time of first use.
However, if your variable x
first appeared in the script without a declaration, then you can use the delete
operator (delete x;
) and your variable will be deleted, very similar to deleting an element of an array or deleting a property of an object.
long
and long int
are identical. So are long long
and long long int
. In both cases, the int
is optional.
As to the difference between the two sets, the C++ standard mandates minimum ranges for each, and that long long
is at least as wide as long
.
The controlling parts of the standard (C++11, but this has been around for a long time) are, for one, 3.9.1 Fundamental types
, section 2 (a later section gives similar rules for the unsigned integral types):
There are five standard signed integer types : signed char, short int, int, long int, and long long int. In this list, each type provides at least as much storage as those preceding it in the list.
There's also a table 9 in 7.1.6.2 Simple type specifiers
, which shows the "mappings" of the specifiers to actual types (showing that the int
is optional), a section of which is shown below:
Specifier(s) Type
------------- -------------
long long int long long int
long long long long int
long int long int
long long int
Note the distinction there between the specifier and the type. The specifier is how you tell the compiler what the type is but you can use different specifiers to end up at the same type.
Hence long
on its own is neither a type nor a modifier as your question posits, it's simply a specifier for the long int
type. Ditto for long long
being a specifier for the long long int
type.
Although the C++ standard itself doesn't specify the minimum ranges of integral types, it does cite C99, in 1.2 Normative references
, as applying. Hence the minimal ranges as set out in C99 5.2.4.2.1 Sizes of integer types <limits.h>
are applicable.
In terms of long double
, that's actually a floating point value rather than an integer. Similarly to the integral types, it's required to have at least as much precision as a double
and to provide a superset of values over that type (meaning at least those values, not necessarily more values).
I recommended an experimental new attribute CSS I tested on latest browser and it's good:
image-rendering: optimizeSpeed; /* */
image-rendering: -moz-crisp-edges; /* Firefox */
image-rendering: -o-crisp-edges; /* Opera */
image-rendering: -webkit-optimize-contrast; /* Chrome (and Safari) */
image-rendering: optimize-contrast; /* CSS3 Proposed */
-ms-interpolation-mode: nearest-neighbor; /* IE8+ */
With this the browser will know the algorithm for rendering
In case you have some parameters to pass to a function and want a value in return. Here I am passing "12345" as an argument to a function and after processing returning variable XYZ which will be assigned to VALUE
#!/bin/bash
getValue()
{
ABC=$1
XYZ="something"$ABC
echo $XYZ
}
VALUE=$( getValue "12345" )
echo $VALUE
Output:
something12345
Following steps has fixed my issue.
(1) Moved the website to a Dedicated application pool.
(2) Changed the Managed Pipeline Mode from integrated to Classic.
(3) Set Enable 32-Bit Applications from false to true.
ASP pages are working fine now!
public static Bitmap decodeFile(String path) {
Bitmap b = null;
File f = new File(path);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int IMAGE_MAX_SIZE = 1024; // maximum dimension limit
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
public static Bitmap showBitmapFromFile(String file_path)
{
try {
File imgFile = new File(file_path);
if(imgFile.exists()){
Bitmap pic_Bitmap = decodeFile(file_path);
return pic_Bitmap;
}
} catch (Exception e) {
MyLog.e("Exception showBitmapFromFile");
return null;
}
return null;
}
if you are using image loading in List view then use Aquery concept .
https://github.com/AshishPsaini/AqueryExample
AQuery aq= new AQuery((Activity) activity, convertView);
//load image from file, down sample to target width of 250 pixels .gi
File file=new File("//pic/path/here/aaaa.jpg");
if(aq!=null)
aq.id(holder.pic_imageview).image(file, 250);
I would not recommend you to start session just to get some unique id. Instead, use such things as uniqid()
because it's intended to return unique id.
However, if you already have session, then, of course, use session_id()
to get your session id - but do not rely on that, because "unique id" isn't same as "session id" in common sense: for example, multiple tabs in most browsers will use same process, thus, use same session identifier in result - and, therefore, different connections will have same id. It's your decision about desired behavior, I've mentioned this just to show the difference between session id and unique id.
above my knowledge it is possible in 4 ways
<button style="display:none;"></button>
#buttonId{ display:none; }
$('#buttonId').prop('display':'none');
& $("#buttonId").css('opacity', 0);
('very long string'.slice(0,10))+'...'
// "very long ..."
what is the exec function and its family.
The exec
function family is all functions used to execute a file, such as execl
, execlp
, execle
, execv
, and execvp
.They are all frontends for execve
and provide different methods of calling it.
why is this function used
Exec functions are used when you want to execute (launch) a file (program).
and how does it work.
They work by overwriting the current process image with the one that you launched. They replace (by ending) the currently running process (the one that called the exec command) with the new process that has launched.
For more details: see this link.
SELECT COUNT(*), table1.category_id, table2.category_name
FROM table1
INNER JOIN table2 ON table1.category_id=table2.category_id
WHERE table1.colour <> 'red'
GROUP BY table1.category_id, table2.category_name
create a filter.js and you can make this as reusable
angular.module('yourmodule').filter('date', function($filter)
{
return function(input)
{
if(input == null){ return ""; }
var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
return _date.toUpperCase();
};
});
view
<span>{{ d.time | date }}</span>
or in controller
var filterdatetime = $filter('date')( yourdate );
If you are getting an error with the other MemoryStream examples here, then you need to set the Position to 0.
public static Stream ToStream(this bytes[] bytes)
{
return new MemoryStream(bytes)
{
Position = 0
};
}
I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop.
If you used the Visual Studio 2012 ASP.NET Web Forms Application template then you would have gotten that reference. I'm assuming it's the one you would get via Nuget instead of the framework System.Data.Entity reference.
Yes, It is required to add libraries after the source files/objects files. This command will solve the problem:
gcc -static -L/usr/lib -I/usr/lib main.c -ltommath
FWIW, if you don't want to use custom function or extension, you can:
let array = [ .... ]
if let found = find(array.map({ $0.name }), "Foo") {
let obj = array[found]
}
This generates name
array first, then find
from it.
If you have huge array, you might want to do:
if let found = find(lazy(array).map({ $0.name }), "Foo") {
let obj = array[found]
}
or maybe:
if let found = find(lazy(array).map({ $0.name == "Foo" }), true) {
let obj = array[found]
}
When I tried the suggested solution I realized that my app name was truncated. I read up on process.title
in the nodejs documentation (https://nodejs.org/docs/latest/api/process.html#process_process_title) and it says
On Linux and OS X, it's limited to the size of the binary name plus the length of the command line arguments because it overwrites the argv memory.
My app does not use any arguments, so I can add this line of code to my app.js
process.title = process.argv[2];
and then add these few lines to my package.json
file
"scripts": {
"start": "node app.js this-name-can-be-as-long-as-it-needs-to-be",
"stop": "killall -SIGINT this-name-can-be-as-long-as-it-needs-to-be"
},
to use really long process names. npm start
and npm stop
work, of course npm stop
will always terminate all running processes, but that is ok for me.
EDIT:
The info below is only applicable to VS2008 and the 3.5 framework. VS2010 has a new registry location. Further details can be found on MSDN: How to Add or Remove References in Visual Studio.
ORIGINAL
It should be listed in the .NET tab of the Add Reference dialog. Assemblies that appear there have paths in registry keys under:
HKLM\Software\Microsoft\.NETFramework\AssemblyFolders\
I have a key there named Microsoft .NET Framework 3.5 Reference Assemblies with a string value of:
C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\
Navigating there I can see the actual System.Web.Extensions dll.
EDIT:
I found my .NET 4.0 version in:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Web.Extensions.dll
I'm running Win 7 64 bit, so if you're on a 32 bit OS drop the (x86).
Use the time package to work with time information in Go.
Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.
Play example:
package main
import (
"fmt"
"time"
)
func inTimeSpan(start, end, check time.Time) bool {
return check.After(start) && check.Before(end)
}
func main() {
start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC")
end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC")
in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC")
out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC")
if inTimeSpan(start, end, in) {
fmt.Println(in, "is between", start, "and", end, ".")
}
if !inTimeSpan(start, end, out) {
fmt.Println(out, "is not between", start, "and", end, ".")
}
}
Please make sure you have downloaded the sqldump fully, this problem is very common when we try to import half/incomplete downloaded sqldump. Please check size of your sqldump file.
( child selector) was introduced in css2. div p{ } select all p elements decedent of div elements, whereas div > p selects only child p elements, not grand child, great grand child on so on.
<style>
div p{ color:red } /* match both p*/
div > p{ color:blue } /* match only first p*/
</style>
<div>
<p>para tag, child and decedent of p.</p>
<ul>
<li>
<p>para inside list. </p>
</li>
</ul>
</div>
For more information on CSS Ce[lectors and their use, check my blog, css selectors and css3 selectors
Swift 5
// Get the document directory url
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
print(directoryContents)
// if you want to filter the directory contents you can do like this:
let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
print("mp3 urls:",mp3Files)
let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent }
print("mp3 list:", mp3FileNames)
} catch {
print(error)
}
Instead of relying on a persistent drive, you could set the script to map/unmap the drive each time you use it:
net use Q: \\share.domain.com\share
forfiles /p Q:\myfolder /s /m *.txt /d -0 /c "cmd /c del @path"
net use Q: /delete
This works for me.
Specify all fields but your ID field.
INSERT INTO MyTable (FIELD2, FIELD3, ..., FIELD529, PreviousId)
SELECT FIELD2, NULL, ..., FIELD529, FIELD1
FROM MyTable
WHERE FIELD1 = @Id;
T(n) = 2T(n/2)+ c
T(n/2) = 2T(n/4) + c => T(n) = 4T(n/4) + 2c + c
similarly T(n) = 8T(n/8) + 4c+ 2c + c
....
....
last step ... T(n) = nT(1) + c(sum of powers of 2 from 0 to h(height of tree))
so Complexity is O(2^(h+1) -1)
but h = log(n)
so, O(2n - 1) = O(n)
Your product
class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.
As a side note: You should use Pascal casing for your class names. That is Product
, and not product
.
You should use CSS to align the textbox. The reason your code above does not work is because by default a div's width is the same as the container it's in, therefore in your example it is pushed below.
The following would work.
<td colspan="2" class="cell">
<asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server" CssClass="righttextbox"></asp:TextBox>
</td>
In your CSS file:
.cell
{
text-align:left;
}
.righttextbox
{
float:right;
}
For anybody reading this in 2019, after React 16.8 was released, take a look at the React Hooks. It really simplifies handling states in components. The docs are very well written with an example of exactly what you need.
Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:
import datetime
print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())
today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))
schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)
The output:
Timestamp: 2014-10-18 21:31:12
Timestamp: 2014-Oct-18 21:31:12
Date now: 2014-10-18 21:31:12.318340
Date today: 2014-10-18
Today's date is Oct, 18 2014
Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific
Maintenance: October, 18 2014 - 1 PM to 6 PM Central
Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior
Steps to resolve conflict:
"git checkout "MAIN_BRANCH"
"git merge origin/BRANCH_NAME_TO_BE_MERGED"
Auto-merging src/file1.py
CONFLICT (content): Merge conflict in src/file1.py
Auto-merging src/services/docker/filexyz.py
Auto-merging src/cache.py
Auto-merging src/props.py
CONFLICT (content): Merge conflict in src/props.py
Auto-merging src/app.py
CONFLICT (content): Merge conflict in src/app.py
Auto-merging file3
CONFLICT (content): Merge conflict in file3
Automatic merge failed; fix conflicts and then commit the result.
Now you can see it is showing "CONFLICT (content)", to those file which is having "CONFLICT", see your code and resolve them
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: file3
both modified: src/app.py
both modified: src/props.py
both modified: src/utils/file1.py
git add file3
git add src/app.py
git add src/props.py
git add src/utils/file1.py
On branch MAIN_BRANCH
Your branch is ahead of 'origin/MAIN_BRANCH' by 10 commits.
(use "git push" to publish your local commits)
7."git push"
Add a Dependency in
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.3</version>
</dependency>
Try using scrolling=no
attribute on the iframe tag. Mozilla also has an overflow-x
and overflow-y
CSS property you may look into.
In terms of the height, you could also try height=100%
on the iframe tag.
You can separate your commands using a semi colon:
cd /my_folder;rm *.jar;svn co path to repo;mvn compile package install
Was that what you mean?
This URL format worked like a charm:
http://maps.google.com/maps?&z={INSERT_MAP_ZOOM}&mrt={INSERT_TYPE_OF_SEARCH}&t={INSERT_MAP_TYPE}&q={INSERT_MAP_LAT_COORDINATES}+{INSERT_MAP_LONG_COORDINATES}
Example for Mount Everest:
http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=27.9879012+86.9253141
Full reference here:
https://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
-- EDIT --
Apparently the zoom parameter stopped working, here's the updated format.
Format
https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite¢er={LAT},{LONG}&zoom={ZOOM}
Example
Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.
Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe
, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.
The correct format for passing variables in a GET request is
?variable1=value1&variable2=value2&variable3=value3...
^ ---notice &--- ^
But essentially, you have the right idea.
pyringe is a debugger that can interact with running python processes, print stack traces, variables, etc. without any a priori setup.
While I've often used the signal handler solution in the past, it can still often be difficult to reproduce the issue in certain environments.
For pandas 0.17 and above, use this :
test = df.sort_values('one', ascending=False)
Since 'one' is a series in the pandas data frame, hence pandas will not accept the arguments in the form of a list.
In addition, since info locals
does not display the arguments to the function you're in, use
(gdb) info args
For example:
int main(int argc, char *argv[]) {
argc = 6*7; //Break here.
return 0;
}
argc
and argv
won't be shown by info locals
. The message will be "No locals."
Reference: info locals command.
Run the below query against the database
select distinct local_net_address, local_tcp_port from sys.dm_exec_connections where local_net_address is not null
The above query shows the local IP as well as the listening Port number
You can check to see if a module is installed for python by running:
pip uninstall moduleName
If it is installed, it will ask you if you want to delete it or not. My issue was that it was installed for python, but not for python3. To check to see if a module is installed for python3, run:
python3 -m pip uninstall moduleName
After doing this, if you find that a module is not installed for one or both versions, use these two commands to install the module.
To say that something "is null" means that it is a reference to the null value. Primitives (int, double, float, etc) are by definition not reference types, so they cannot have null values. You will need to find out what your database wrapper will do in this case.
This error can also show up if there are parts in your string that json.loads()
does not recognize. An in this example string, an error will be raised at character 27 (char 27)
.
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
My solution to this would be to use the string.replace()
to convert these items to a string:
import json
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
string = string.replace("False", '"False"')
dict_list = json.loads(string)
Try This, It's working for me .
Single line of code
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
I had the same issue. Rather than figure out the MVC code, I opted for a cheap hack that seems to work. In my Global.asax class:
member x.Application_EndRequest() =
if x.Response.StatusCode = 401 then
let redir = "?redirectUrl=" + Uri.EscapeDataString x.Request.Url.PathAndQuery
if x.Request.Url.LocalPath.ToLowerInvariant().Contains("admin") then
x.Response.Redirect("/Login/Admin/" + redir)
else
x.Response.Redirect("/Login/Login/" + redir)
Dim RowNumber As Integer
RowNumber = ActiveSheet.Range("A65536").End(xlUp).Row
In your case it should return #9
For those using bash installed on their windows system (known as Windows Subsystem for Linux (WSL)), attempting xclip will give an error:
Error: Can't open display: (null)
Instead, recall that linux subsystem has access to windows executables. It's possible to use clip.exe like
echo hello | clip.exe
which allows you to use the paste command (ctrl-v).
Try using mongoose function for pagination. Limit is the number of records per page and number of the page.
var limit = parseInt(body.limit);
var skip = (parseInt(body.page)-1) * parseInt(limit);
db.Rankings.find({})
.sort('-id')
.limit(limit)
.skip(skip)
.exec(function(err,wins){
});
I follow this way to append a new line in a .csv file:
pose_x = 1
pose_y = 2
with open('path-to-your-csv-file.csv', mode='a') as file_:
file_.write("{},{}".format(pose_x, pose_y))
file_.write("\n")
Right now, I'm using twinsplay to organize my windows side by side.
I tried Winsplit before, but I couldn't get it to work because the default hotkeys ( Ctrl-Alt-Left, Ctrl-Alt-Right ) clashed with the graphics card hotkeys for rotating my screen and setting different hotkeys just didn't work. Twinsplay just worked for me out of the box.
Another nice thing about twinsplay is that it also allows me to save and restore windows "sessions" - so I can save my work environment ( eclipse, total commander, visual studio, msdn, outlook, firefox ) before turning off the computer at night and then quickly get back to it in the morning.
In case it helps anyone I had the same error. It turns out my page had not been scrapped by Facebook in awhile and it was an old error. There was a scrape again button on the page that fixed it.
If you want a certain message, use this:
String phoneNo = "";//The phone number you want to text
String sms= "";//The message you want to text to the phone
Intent smsIntent = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", phoneNo, null));
smsIntent.putExtra("sms_body",sms);
startActivity(smsIntent);
To iterate over a multidimensional array, you can use RecursiveArrayIterator
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Output:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
I would probably use setInteval
. Like this,
var period = 1000; // ms
var endTime = 10000; // ms
var counter = 0;
var sleepyAlert = setInterval(function(){
alert('Hello');
if(counter === endTime){
clearInterval(sleepyAlert);
}
counter += period;
}, period);
Another trick to get the link color working correctly inside the <button>
markup
<button type="button" class="btn btn-outline-success and-all-other-classes">
<a href="#" style="color:inherit"> Button text with correct colors </a>
</button>
Please keep in mind that in bs4 beta e.g. btn-primary-outline
changed to btn-outline-primary
While you have to checkout a repository, you can skip checking out any files with --no-checkout
and --depth 1
:
$ time git clone --no-checkout --depth 1 https://github.com/torvalds/linux .
Cloning into '.'...
remote: Enumerating objects: 75646, done.
remote: Counting objects: 100% (75646/75646), done.
remote: Compressing objects: 100% (71197/71197), done.
remote: Total 75646 (delta 6176), reused 22237 (delta 3672), pack-reused 0
Receiving objects: 100% (75646/75646), 201.46 MiB | 7.27 MiB/s, done.
Resolving deltas: 100% (6176/6176), done.
real 0m46.117s
user 0m13.412s
sys 0m19.641s
And while there is only a .git
directory:
$ ls -al
total 0
drwxr-xr-x 3 root staff 96 Dec 26 23:57 .
drwxr-xr-x+ 71 root staff 2272 Dec 27 00:03 ..
drwxr-xr-x 12 root staff 384 Dec 26 23:58 .git
you can get a directory listing via:
$ git ls-tree --full-name --name-only -r HEAD | head
.clang-format
.cocciconfig
.get_maintainer.ignore
.gitattributes
.gitignore
.mailmap
COPYING
CREDITS
Documentation/.gitignore
Documentation/ABI/README
or get the number of files via:
$ git ls-tree -r HEAD | wc -l
71259
or get the total file size via:
$ git ls-tree -l -r HEAD | awk '/^[^-]/ {s+=$4} END {print s}'
1006679487
After becoming frustrated with the too many limitations of cut
, I wrote my own replacement, which I called cuts
for "cut on steroids".
cuts provides what is likely the most minimalist solution to this and many other related cut/paste problems.
One example, out of many, addressing this particular question:
$ cat text.txt
0 1 2 3
0 1 2 3 4
$ cuts 2 text.txt
2
2
cuts
supports:
paste
separately)and much more. None of which is provided by standard cut
.
See also: https://stackoverflow.com/a/24543231/1296044
Source and documentation (free software): http://arielf.github.io/cuts/
curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.
do you mean a method?
$('div.foo').attr('id', 'foo123');
Just be careful that you don't set multiple elements to the same ID.
Joseph forgot to add the value in his example with withDefault
.
Here is the code I ended up using:
Map map = [:].withDefault { key -> return [] }
listOfObjects.each { map.get(it.myKey).add(it.myValue) }
Before connecting WIFI network you need to check security type of the WIFI network ScanResult class has a capabilities. This field gives you type of network
Refer: https://developer.android.com/reference/android/net/wifi/ScanResult.html#capabilities
There are three types of WIFI networks.
First, instantiate a WifiConfiguration object and fill in the network’s SSID (note that it has to be enclosed in double quotes), set the initial state to disabled, and specify the network’s priority (numbers around 40 seem to work well).
WifiConfiguration wfc = new WifiConfiguration();
wfc.SSID = "\"".concat(ssid).concat("\"");
wfc.status = WifiConfiguration.Status.DISABLED;
wfc.priority = 40;
Now for the more complicated part: we need to fill several members of WifiConfiguration to specify the network’s security mode. For open networks.
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedAuthAlgorithms.clear();
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
For networks using WEP; note that the WEP key is also enclosed in double quotes.
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
if (isHexString(password)) wfc.wepKeys[0] = password;
else wfc.wepKeys[0] = "\"".concat(password).concat("\"");
wfc.wepTxKeyIndex = 0;
For networks using WPA and WPA2, we can set the same values for either.
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wfc.preSharedKey = "\"".concat(password).concat("\"");
Finally, we can add the network to the WifiManager’s known list
WifiManager wfMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int networkId = wfMgr.addNetwork(wfc);
if (networkId != -1) {
// success, can call wfMgr.enableNetwork(networkId, true) to connect
}
You just need to change directories to your app, THEN run bundle install
:)
Got it to work by transitioning the padding as well as the width.
JSFiddle: http://jsfiddle.net/tuybk748/1/
<div class='label gray'>+
</div><!-- must be connected to prevent gap --><div class='contents-wrapper'>
<div class="gray contents">These are the contents of this div</div>
</div>
.gray {
background: #ddd;
}
.contents-wrapper, .label, .contents {
display: inline-block;
}
.label, .contents {
overflow: hidden; /* must be on both divs to prevent dropdown behavior */
height: 20px;
}
.label {
padding: 10px 10px 15px;
}
.contents {
padding: 10px 0px 15px; /* no left-right padding at beginning */
white-space: nowrap; /* keeps text all on same line */
width: 0%;
-webkit-transition: width 1s ease-in-out, padding-left 1s ease-in-out,
padding-right 1s ease-in-out;
-moz-transition: width 1s ease-in-out, padding-left 1s ease-in-out,
padding-right 1s ease-in-out;
-o-transition: width 1s ease-in-out, padding-left 1s ease-in-out,
padding-right 1s ease-in-out;
transition: width 1s ease-in-out, padding-left 1s ease-in-out,
padding-right 1s ease-in-out;
}
.label:hover + .contents-wrapper .contents {
width: 100%;
padding-left: 10px;
padding-right: 10px;
}
If you have opened the command prompt(cmd) to run the jar on current folder,then the error will come as above.so close the command prompt and try maven clean and install,it will work definitely.
You are viewing your decimal or double values in Visual Studio. That doesn't respect the culture settings you have on your code.
Change the Region and Language settings on your Control Panel if you want to see decimal
and double
values having the comma as the decimal separator.
Use BigDecimal
:
new BigDecimal(theInputString);
It retains all decimal digits. And you are sure of the exact representation since it uses decimal base, not binary base, to store the precision/scale/etc.
And it is not subject to precision loss like float
or double
are, unless you explicitly ask it to.
The reason Herb said what he said is because of cases like this.
Let's say I have function A
which calls function B
, which calls function C
. And A
passes a string through B
and into C
. A
does not know or care about C
; all A
knows about is B
. That is, C
is an implementation detail of B
.
Let's say that A is defined as follows:
void A()
{
B("value");
}
If B and C take the string by const&
, then it looks something like this:
void B(const std::string &str)
{
C(str);
}
void C(const std::string &str)
{
//Do something with `str`. Does not store it.
}
All well and good. You're just passing pointers around, no copying, no moving, everyone's happy. C
takes a const&
because it doesn't store the string. It simply uses it.
Now, I want to make one simple change: C
needs to store the string somewhere.
void C(const std::string &str)
{
//Do something with `str`.
m_str = str;
}
Hello, copy constructor and potential memory allocation (ignore the Short String Optimization (SSO)). C++11's move semantics are supposed to make it possible to remove needless copy-constructing, right? And A
passes a temporary; there's no reason why C
should have to copy the data. It should just abscond with what was given to it.
Except it can't. Because it takes a const&
.
If I change C
to take its parameter by value, that just causes B
to do the copy into that parameter; I gain nothing.
So if I had just passed str
by value through all of the functions, relying on std::move
to shuffle the data around, we wouldn't have this problem. If someone wants to hold on to it, they can. If they don't, oh well.
Is it more expensive? Yes; moving into a value is more expensive than using references. Is it less expensive than the copy? Not for small strings with SSO. Is it worth doing?
It depends on your use case. How much do you hate memory allocations?
Use the array_count_values function.
$countValues = array_count_values($myArray);
echo $countValues["Ben"];
Use the Calendar-API:
// get Calendar instance
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
// substract 7 days
// If we give 7 there it will give 8 days back
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-6);
// convert to date
Date myDate = cal.getTime();
Hope this helps. Have Fun!
Remove Quote. and use innerText instead of text
function toggleText(button_id)
{ //-----\/ 'button_id' - > button_id
if (document.getElementById(button_id).innerText == "Lock")
{
document.getElementById(button_id).innerText = "Unlock";
}
else
{
document.getElementById(button_id).innerText = "Lock";
}
}
IntelliJ IDEA does not have an action to add imports. Rather it has the ability to do such as you type. If you enable the "Add unambiguous imports on the fly" in Settings > Editor > General > Auto Import, IntelliJ IDEA will add them as you type without the need for any shortcuts. You can also add classes and packages to exclude from auto importing to make a class you use heavily, that clashes with other classes of the same name, unambiguous.
For classes that are ambiguous (or is you prefer to have the "Add unambiguous imports on the fly" option turned off), just type the name of the class (just the name is OK, no need to fully qualify). Use code completion and select the particular class you want:
Notice the fully qualified names to the right. When I select the one I want and hit enter, IDEA will automatically add the import statement. This works the same if I was typing the name of a constructor. For static methods, you can even just keep typing the method you want. In the following screenshot, no "StringUtils" class is imported yet.
Alternatively, type the class name and then hit Alt+Enter or ?+Enter to "Show intention actions and quick-fixes" and then select the import option.
Although I've never used it, I think the Eclipse Code Formatter third party plug-in will do what you want. It lists "emulates Eclipse's imports optimizing" as a feature. See its instructions for more information. But in the end, I suspect you'll find the built in IDEA features work fine once you get use to their paradigm. In general, IDEA uses a "develop by intentions" concept. So rather than interrupting my development work to add an import statement, I just type the class I want (my intention) and IDEA automatically adds the import statement for the class for me.
desc 'an updated version'
task :task_name, [:arg1, :arg2] => [:dependency1, :dependency2] do |t, args|
puts args[:arg1]
end
Xcode 10.1 • Swift 4.2
import UIKit
class ProgressHUD: UIVisualEffectView {
var title: String?
var theme: UIBlurEffect.Style = .light
let strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
let activityIndicator = UIActivityIndicatorView()
init(title: String, theme: UIBlurEffect.Style = .light) {
super.init(effect: UIBlurEffect(style: theme))
self.title = title
self.theme = theme
[activityIndicator, strLabel].forEach(contentView.addSubview(_:))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
if let superview = self.superview {
frame = CGRect(x: superview.frame.midX - strLabel.frame.width / 2,
y: superview.frame.midY - strLabel.frame.height / 2, width: 160, height: 46)
layer.cornerRadius = 15.0
layer.masksToBounds = true
activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
activityIndicator.startAnimating()
strLabel.text = title
strLabel.font = .systemFont(ofSize: 14, weight: UIFont.Weight.medium)
switch theme {
case .dark:
strLabel.textColor = .white
activityIndicator.style = .white
default:
strLabel.textColor = .gray
activityIndicator.style = .gray
}
}
}
func show() {
self.isHidden = false
}
func hide() {
self.isHidden = true
}
}
Use:
let progress = ProgressHUD(title: "Authorization", theme: .dark)
[progress].forEach(view.addSubview(_:))
conda
doesn't support this directly because it installs from binaries, whereas git install would be from source. conda build
does support recipes that are built from git. On the other hand, if all you want to do is keep up-to-date with the latest and greatest of a package, using pip inside of Anaconda is just fine, or alternately, use setup.py develop
against a git clone.
I may get bitten by this one but I think that it's personal preference. I can't find any reference in the docs to each() being different than keys() or values() (other than the obvious "they return different things" answer. In fact the docs state the use the same iterator and they all return actual list values instead of copies of them, and that modifying the hash while iterating over it using any call is bad.
All that said, I almost always use keys() because to me it is usually more self documenting to access the key's value via the hash itself. I occasionally use values() when the value is a reference to a large structure and the key to the hash was already stored in the structure, at which point the key is redundant and I don't need it. I think I've used each() 2 times in 10 years of Perl programming and it was probably the wrong choice both times =)
var month = mydate.getMonth(); // month (in integer 0-11)
var year = mydate.getFullYear(); // year
Then all you would need to have is an array of months:
var months = ['Jan', 'Feb', 'Mar', ...];
And then to show it:
alert(months[month] + " " + year);
Encountered a similar problem today. Did not see my fix listed here, so I thought I'd share.
Root could not erase a file.
I did my research. Turns out there's something called an immutable bit.
# lsattr /path/file
----i-------- /path/file
#
This bit being configured prevents even root from modifying/removing it.
To remove this I did:
# chattr -i /path/file
After that I could rm the file.
In reverse, it's a neat trick to know if you have something you want to keep from being gone.
:)
firstly you need to import the Select class and then you need to create the instance of Select class. After creating the instance of Select class, you can perform select methods on that instance to select the options from dropdown list. Here is the code
from selenium.webdriver.support.select import Select
select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)
Look at the Subfloats section of http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions.
\begin{figure}[htp]
\centering
\label{figur}\caption{equation...}
\subfloat[Subcaption 1]{\label{figur:1}\includegraphics[width=60mm]{explicit3185.eps}}
\subfloat[Subcaption 2]{\label{figur:2}\includegraphics[width=60mm]{explicit3183.eps}}
\\
\subfloat[Subcaption 3]{\label{figur:3}\includegraphics[width=60mm]{explicit1501.eps}}
\subfloat[Subcaption 4]{\label{figur:4}\includegraphics[width=60mm]{explicit23185.eps}}
\\
\subfloat[Subcaption 5]{\label{figur:5}\includegraphics[width=60mm]{explicit23183.eps}}
\subfloat[Subcaption 6]{\label{figur:6}\includegraphics[width=60mm]{explicit21501.eps}}
\end{figure}
If you want to trim the whitespace off just the beginning and end of the string, you can do something like this:
some_string = " Hello, world!\n "
new_string = some_string.strip()
# new_string is now "Hello, world!"
This works a lot like Qt's QString::trimmed() method, in that it removes leading and trailing whitespace, while leaving internal whitespace alone.
But if you'd like something like Qt's QString::simplified() method which not only removes leading and trailing whitespace, but also "squishes" all consecutive internal whitespace to one space character, you can use a combination of .split()
and " ".join
, like this:
some_string = "\t Hello, \n\t world!\n "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"
In this last example, each sequence of internal whitespace replaced with a single space, while still trimming the whitespace off the start and end of the string.
One another way is to use the same thing what firebase uses.
For example when user logs in, firebase stores below details in local storage. When user comes back to the page, firebase uses the same method to identify if user should be logged in automatically.
ATTN: As this is neither listed or recommended by firebase. You can call this method un-official way of doing this. Which means later if firebase changes their inner working, this method may not work. Or in short. Use at your own risk! :)
Props to George Walters II above, I just took his answer and extended it a bit to support rounding individual corners differently. This could be optimized a bit further (some of the target rects overlap), but not a whole lot.
I know this thread is a bit old, but its one of the top results for queries on Google for how to round corners of ImageViews on Android.
/**
* Use this method to scale a bitmap and give it specific rounded corners.
* @param context Context object used to ascertain display density.
* @param bitmap The original bitmap that will be scaled and have rounded corners applied to it.
* @param upperLeft Corner radius for upper left.
* @param upperRight Corner radius for upper right.
* @param lowerRight Corner radius for lower right.
* @param lowerLeft Corner radius for lower left.
* @param endWidth Width to which to scale original bitmap.
* @param endHeight Height to which to scale original bitmap.
* @return Scaled bitmap with rounded corners.
*/
public static Bitmap getRoundedCornerBitmap(Context context, Bitmap bitmap, float upperLeft,
float upperRight, float lowerRight, float lowerLeft, int endWidth,
int endHeight) {
float densityMultiplier = context.getResources().getDisplayMetrics().density;
// scale incoming bitmap to appropriate px size given arguments and display dpi
bitmap = Bitmap.createScaledBitmap(bitmap,
Math.round(endWidth * densityMultiplier),
Math.round(endHeight * densityMultiplier), true);
// create empty bitmap for drawing
Bitmap output = Bitmap.createBitmap(
Math.round(endWidth * densityMultiplier),
Math.round(endHeight * densityMultiplier), Config.ARGB_8888);
// get canvas for empty bitmap
Canvas canvas = new Canvas(output);
int width = canvas.getWidth();
int height = canvas.getHeight();
// scale the rounded corners appropriately given dpi
upperLeft *= densityMultiplier;
upperRight *= densityMultiplier;
lowerRight *= densityMultiplier;
lowerLeft *= densityMultiplier;
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
// fill the canvas with transparency
canvas.drawARGB(0, 0, 0, 0);
// draw the rounded corners around the image rect. clockwise, starting in upper left.
canvas.drawCircle(upperLeft, upperLeft, upperLeft, paint);
canvas.drawCircle(width - upperRight, upperRight, upperRight, paint);
canvas.drawCircle(width - lowerRight, height - lowerRight, lowerRight, paint);
canvas.drawCircle(lowerLeft, height - lowerLeft, lowerLeft, paint);
// fill in all the gaps between circles. clockwise, starting at top.
RectF rectT = new RectF(upperLeft, 0, width - upperRight, height / 2);
RectF rectR = new RectF(width / 2, upperRight, width, height - lowerRight);
RectF rectB = new RectF(lowerLeft, height / 2, width - lowerRight, height);
RectF rectL = new RectF(0, upperLeft, width / 2, height - lowerLeft);
canvas.drawRect(rectT, paint);
canvas.drawRect(rectR, paint);
canvas.drawRect(rectB, paint);
canvas.drawRect(rectL, paint);
// set up the rect for the image
Rect imageRect = new Rect(0, 0, width, height);
// set up paint object such that it only paints on Color.WHITE
paint.setXfermode(new AvoidXfermode(Color.WHITE, 255, AvoidXfermode.Mode.TARGET));
// draw resized bitmap onto imageRect in canvas, using paint as configured above
canvas.drawBitmap(bitmap, imageRect, imageRect, paint);
return output;
}
This is caused by Security settings for internet explorer. You can fix this,by changing internet explorer settings.Go To Settings->Internet Options->Security Tabs. You will see different zones:i)Internet ii)Local Intranet iii)Trusted Sites iv)Restricted Sites. Depending on your requirement select one zone. I am running my application in localhost so i selected Local intranet and then click Custom Level button. It opens security settings window. Please enable Initialize and script Activex controls not marked as safe for scripting option.It should work.
This worked for me when I got the same error message...
mvn install deploy
Well it is just a 4 step easy proceess,
I hope it helps
Step 1.
Store the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
Step 2.
Retrieve the XMLHttpRequest object
function createXmlHttpRequestObject() {
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
Step 3.
Make asynchronous HTTP request using the XMLHttpRequest object
function process() {
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
// retrieve the name typed by the user on the form
item = encodeURIComponent(document.getElementById("input_item").value);
// execute the your_file.php page from the server
xmlHttp.open("GET", "your_file.php?item=" + item, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
}
Step 4.
Executed automatically when a message is received from the server
function handleServerResponse() {
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4) {
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200) {
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseText;
document.getElementById("put_response").innerHTML = xmlResponse;
// restart sequence
}
// a HTTP status different than 200 signals an error
else {
alert("There was a problem accessing the server: " + xmlHttp.statusText);
}
}
}
This might help
def digit_sum(n):
num_str = str(n)
sum = 0
for i in range(0, len(num_str)):
sum += int(num_str[i])
return sum
This is how to use chai to deeply test associative arrays.
I had an issue trying to assert that two associative arrays were equal. I know that these shouldn't really be used in javascript but I was writing unit tests around legacy code which returns a reference to an associative array. :-)
I did it by defining the variable as an object (not array) prior to my function call:
var myAssocArray = {}; // not []
var expectedAssocArray = {}; // not []
expectedAssocArray['myKey'] = 'something';
expectedAssocArray['differentKey'] = 'something else';
// legacy function which returns associate array reference
myFunction(myAssocArray);
assert.deepEqual(myAssocArray, expectedAssocArray,'compare two associative arrays');
Following configuration, you need to set:
To open the port 5432 edit your /etc/postgresql/9.1/main/postgresql.conf
and change
# Connection Settings -
listen_addresses = '*' # what IP address(es) to listen on;
In /etc/postgresql/10/main/pg_hba.conf
# IPv4 local connections:
host all all 0.0.0.0/0 md5
Now restart your DBMS
sudo service postgresql restart
Now you can connect with
psql -h hostname(IP) -p port -U username -d database
TimeSpan.FromTicks(28000000000).TotalMinutes;
No that is wrong. Arrays are special objects in Java. So it is like passing other objects where you pass the value of the reference, but not the reference itself. Meaning, changing the reference of an array in the called routine will not be reflected in the calling routine.
In order to set the value of integer variable we simply assign the value to it.
eg g1val = 0
where as set keyword is used to assign value to object.
Sub test()
Dim g1val, g2val As Integer
g1val = 0
g2val = 0
For i = 3 To 18
If g1val > Cells(33, i).Value Then
g1val = g1val
Else
g1val = Cells(33, i).Value
End If
Next i
For j = 32 To 57
If g2val > Cells(31, j).Value Then
g2val = g2val
Else
g2val = Cells(31, j).Value
End If
Next j
End Sub
I've been struggling with this for awhile too. It actually occurred due to some Microsoft Office updates via Windows Update starting in December. It has caused quite a bit of a headache, not to mention hours of lost productivity due to this issue.
One of the updates breaks the forms, and you need to clear the Office cache as stated by UHsoccer
Additionally, another answer thread here: Suddenly several VBA macro errors, mostly 32809 has a link to the MS blog with details.
Another of the updates causes another error where if you create or modify one of these forms (even as simple as saving the form data) it will update the internals of the spreadsheet, which, when given to another person without the updates, will cause the error above.
The solution (if you are working with others on the same spreadsheet)? Sadly, either have everyone you deal with use the office updates, then have them clear the office cache, or revert back to pre Dec '14 updates via a system restore (or by manually removing them).
I know, not much of a solution, right? I'm not happy either.
Just as a back-story, I updated my machine, keeping up with updates, and one of the companies I dealt with did not. I was pulling out my hair just before Christmas trying to figure out the issue, and without any restore points, I finally relented and reformatted.
Now, a month later, the company's IT department updated their workstations. And, without surprise, they began having issues similar to this as well (not to mention when I received their spreadsheets, I had the same issue).
Now, we are all up on the same updates, and everything is well as can be.
This returns an absolute difference in days between some Date
and today:
extension Date {
func daysFromToday() -> Int {
return abs(Calendar.current.dateComponents([.day], from: self, to: Date()).day!)
}
}
and then use it:
if someDate.daysFromToday() >= 7 {
// at least a week from today
}
ORDER BY article_rating, article_time DESC
will sort by article_time only if there are two articles with the same rating. From all I can see in your example, this is exactly what happens.
? primary sort secondary sort ?
1. 50 | This article rocks | Feb 4, 2009 3.
2. 35 | This article is pretty good | Feb 1, 2009 2.
3. 5 | This Article isn't so hot | Jan 25, 2009 1.
but consider:
? primary sort secondary sort ?
1. 50 | This article rocks | Feb 2, 2009 3.
1. 50 | This article rocks, too | Feb 4, 2009 4.
2. 35 | This article is pretty good | Feb 1, 2009 2.
3. 5 | This Article isn't so hot | Jan 25, 2009 1.
Activity.getResources().getConfiguration().orientation
Unfortunately, as mmyers said, File.list() is about as fast as you are going to get using Java. If speed is as important as you say, you may want to consider doing this particular operation using JNI. You can then tailor your code to your particular situation and filesystem.
If they are in the same controller class, it would be:
foreach ( $characters as $character) {
$num += $this->getFactorial($index) * $index;
$index ++;
}
Otherwise you need to create a new instance of the class, and call the method, ie:
$controller = new MyController();
foreach ( $characters as $character) {
$num += $controller->getFactorial($index) * $index;
$index ++;
}
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
For passing a single integer I agree with Reed Copsey's answer. If in the future you are going to pass more complicated constucts I personally like to pass all my variables as an Anonymous Type. It will look something like this:
foreach(int id in myIdsToCheck)
{
Task.Factory.StartNew( (Object obj) =>
{
var data = (dynamic)obj;
CheckFiles(data.id, theBlockingCollection,
cancelCheckFile.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}, new { id = id }); // Parameter value
}
You can learn more about it in my blog
If it echoing out to a browser, you should use CSS. This would require also having the comment wrapped in an HTML tag. Something like:
echo '<p style="color: red; text-align: center">
Request has been sent. Please wait for my reply!
</p>';
If you want to run it @build time :
CMD /bin/bash /file.sh arg1
if you want to run it @run time :
ENTRYPOINT ["/bin/bash"]
CMD ["/file.sh", "arg1"]
Then in the host shell
docker build -t test .
docker run -i -t test
The easiest way to do is so...
You set the name and value.
<input type="checkbox" name="selectedProducts" value="@item.ProductId" />@item.Name
Then on submitting grab the values of checkboxes and save in an int array. then the appropriate LinQ Function. That's it..
[HttpPost]
public ActionResult Checkbox(int[] selectedObjects)
{
var selected = from x in selectedObjects
from y in db
where y.ObjectId == x
select y;
return View(selected);
}
You need to specify the std::
namespace:
std::cout << .... << std::endl;;
Alternatively, you can use a using
directive:
using std::cout;
using std::endl;
cout << .... << endl;
I should add that you should avoid these using
directives in headers, since code including these will also have the symbols brought into the global namespace. Restrict using directives to small scopes, for example
#include <iostream>
inline void foo()
{
using std::cout;
using std::endl;
cout << "Hello world" << endl;
}
Here, the using
directive only applies to the scope of foo()
.
Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference - https://en.wikipedia.org/wiki/Carriage_return#Computers
To formalize some of the approaches laid out above:
Create a function that operates on the rows of your dataframe like so:
def f(row):
if row['A'] == row['B']:
val = 0
elif row['A'] > row['B']:
val = 1
else:
val = -1
return val
Then apply it to your dataframe passing in the axis=1
option:
In [1]: df['C'] = df.apply(f, axis=1)
In [2]: df
Out[2]:
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
Of course, this is not vectorized so performance may not be as good when scaled to a large number of records. Still, I think it is much more readable. Especially coming from a SAS background.
Edit
Here is the vectorized version
df['C'] = np.where(
df['A'] == df['B'], 0, np.where(
df['A'] > df['B'], 1, -1))
You can try this function (PHP 7 required)
function getDirectories(string $path) : array
{
$directories = [];
$items = scandir($path);
foreach ($items as $item) {
if($item == '..' || $item == '.')
continue;
if(is_dir($path.'/'.$item))
$directories[] = $item;
}
return $directories;
}
In case you have multiple SDKs locations (might happen if you play around with multiple Android Studio versions and create new location for SDK, what I did), make sure to check the local.properties file (both of the project and of your module, if you have such structure) and check if the line sdk.dir=/home/yourSdkLocation points indeed to the SDK you want to use.
This was the reason it wasn't working for me and it has fixed this.
There's the more general but perhaps not as helpful to you Wireshark.
One of the SO server sites might be better suited for your question. In fact, it's already been asked on SuperUser.
In order to get the value of the selected item you can do the following:
this.options[this.selectedIndex].text
Here the different options
of the select are accessed, and the SelectedIndex
is used to choose the selected one, then its text
is being accessed.
Read more about the select DOM here.
2 files with the same name but different case might be the issue.
You can Delete one on these files or rename it. Ex:
Pdf.html.twig (The GOOD one)
pdf.html.twig (The one I deleted)
Do you know View.getViewTreeObserver().addOnGlobalLayoutListener()
By this you can calculate the sizes.
I achieve your UI effect by GridView:
GridView g;
g.setNumColumns(2);
g.setStretchMode(GridView.STRETCH_SPACING_UNIFORM);
I installed php-soap to CentOS Linux release 7.1.1503 (Core) using following way.
1) yum install php-soap
================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
php-soap x86_64 5.4.16-36.el7_1 base 157 k
Updating for dependencies:
php x86_64 5.4.16-36.el7_1 base 1.4 M
php-cli x86_64 5.4.16-36.el7_1 base 2.7 M
php-common x86_64 5.4.16-36.el7_1 base 563 k
php-devel x86_64 5.4.16-36.el7_1 base 600 k
php-gd x86_64 5.4.16-36.el7_1 base 126 k
php-mbstring x86_64 5.4.16-36.el7_1 base 503 k
php-mysql x86_64 5.4.16-36.el7_1 base 99 k
php-pdo x86_64 5.4.16-36.el7_1 base 97 k
php-xml x86_64 5.4.16-36.el7_1 base 124 k
Transaction Summary
================================================================================
Install 1 Package
Upgrade ( 9 Dependent packages)
Total download size: 6.3 M
Is this ok [y/d/N]: y
Downloading packages:
------
------
------
Installed:
php-soap.x86_64 0:5.4.16-36.el7_1
Dependency Updated:
php.x86_64 0:5.4.16-36.el7_1 php-cli.x86_64 0:5.4.16-36.el7_1
php-common.x86_64 0:5.4.16-36.el7_1 php-devel.x86_64 0:5.4.16-36.el7_1
php-gd.x86_64 0:5.4.16-36.el7_1 php-mbstring.x86_64 0:5.4.16-36.el7_1
php-mysql.x86_64 0:5.4.16-36.el7_1 php-pdo.x86_64 0:5.4.16-36.el7_1
php-xml.x86_64 0:5.4.16-36.el7_1
Complete!
2) yum search php-soap
============================ N/S matched: php-soap =============================
php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
3) service httpd restart
To verify run following
4) php -m | grep -i soap
soap
The following link gives information on launching the app (if installed) directly from browser. Otherwise it directly opens up the app in play store so that user can seamlessly download.
Or you could use the "correct" method, similar to your original atoi approach, but with std::stringstream instead. That should work with chars as input as well as strings. (boost::lexical_cast is another option for a more convenient syntax)
(atoi is an old C function, and it's generally recommended to use the more flexible and typesafe C++ equivalents where possible. std::stringstream covers conversion to and from strings)
I solved this in my env, without modify hadoop-env.sh
You'd be better using /bin/bash
as default shell not /bin/sh
Check these before:
echo $JAVA_HOME
)echo $SHELL
in every node, check if print /bin/bash
if not, vi /etc/passwd
, add /bin/bash
at tail of your username
ref
The default colours in Gecko, assuming the user hasn't changed their preferences, are:
#0000EE
(blue)#551A8B
(purple)#EE0000
(red)Gecko also provides names for the user's colours; they are -moz-hyperlinktext
-moz-visitedhyperlinktext
and -moz-activehyperlinktext
and they also provide -moz-nativehyperlinktext
which is the system link colour.
Apparently with Laravel 5.2, the closure in DB::listen
only receives a single parameter.
So, if you want to use DB::listen
in Laravel 5.2, you should do something like:
DB::listen(
function ($sql) {
// $sql is an object with the properties:
// sql: The query
// bindings: the sql query variables
// time: The execution time for the query
// connectionName: The name of the connection
// To save the executed queries to file:
// Process the sql and the bindings:
foreach ($sql->bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$sql->bindings[$i] = "'$binding'";
}
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
$query = vsprintf($query, $sql->bindings);
// Save the query to file
$logFile = fopen(
storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'),
'a+'
);
fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $query . PHP_EOL);
fclose($logFile);
}
);
An undocumented feature of the formData
field that request
implements is the ability to pass options to the form-data
module it uses:
request({
url: 'http://example.com',
method: 'POST',
formData: {
'regularField': 'someValue',
'regularFile': someFileStream,
'customBufferFile': {
value: fileBufferData,
options: {
filename: 'myfile.bin'
}
}
}
}, handleResponse);
This is useful if you need to avoid calling requestObj.form()
but need to upload a buffer as a file. The form-data
module also accepts contentType
(the MIME type) and knownLength
options.
This change was added in October 2014 (so 2 months after this question was asked), so it should be safe to use now (in 2017+). This equates to version v2.46.0
or above of request
.
The simplest way to add empty "option" before all.
<option></option>
Example:
<select class="select2" lang="ru" tabindex="-1">
<option></option>
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</select>
Also js code, if you need:
$(document).ready(function() {
$(".select2").select2({
placeholder: "Select a state",
allowClear: true
});
});
}
It's worked fine in server
composer install --no-dev
A very hacky solution would be to loop through the class you want to inherit from adding the functions one by one to the new parent class
class ChildA {
public static x = 5
}
class ChildB {
public static y = 6
}
class Parent {}
for (const property in ChildA) {
Parent[property] = ChildA[property]
}
for (const property in ChildB) {
Parent[property] = ChildB[property]
}
Parent.x
// 5
Parent.y
// 6
All properties of ChildA
and ChildB
can now be accessed from the Parent
class, however they will not be recognised meaning that you will receive warnings such as Property 'x' does not exist on 'typeof Parent'
As noted earlier, there is an option to turn on or off History provided you open up task manager under the elevated "Administrator" mode (right click on the Task Scheduler program/shortcut and choose "Run As Administrator"). Then under "Tasks" is your spot to stop or start History.
try using -U
(aka --update-snapshots
) when you run maven
And make sure the dependency definition is correct
try something like this :
$.ajax({
type: 'POST',
url: 'loginCheck',
data: $(formLogin).serialize(),
dataType: 'json',
success: function (textStatus, status) {
console.log(textStatus);
console.log(status);
},
error: function(xhr, textStatus, error) {
console.log(xhr.responseText);
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
after struggling with this for a couple of hours, I've found that you can only use one db helper object per db execution. For example,
for(int x = 0; x < someMaxValue; x++)
{
db = new DBAdapter(this);
try
{
db.addRow
(
NamesStringArray[i].toString(),
StartTimeStringArray[i].toString(),
EndTimeStringArray[i].toString()
);
}
catch (Exception e)
{
Log.e("Add Error", e.toString());
e.printStackTrace();
}
db.close();
}
as apposed to:
db = new DBAdapter(this);
for(int x = 0; x < someMaxValue; x++)
{
try
{
// ask the database manager to add a row given the two strings
db.addRow
(
NamesStringArray[i].toString(),
StartTimeStringArray[i].toString(),
EndTimeStringArray[i].toString()
);
}
catch (Exception e)
{
Log.e("Add Error", e.toString());
e.printStackTrace();
}
}
db.close();
creating a new DBAdapter each time the loop iterates was the only way I could get my strings into a database through my helper class.
The lack of a Linux-like backtick/backquote facility is a major annoyance of the pre-PowerShell world. Using backquotes via for-loops is not at all cosy. So we need kinda of setvar myvar cmd-line
command.
In my %path%
I have a dir with a number of bins and batches to cope with those Win shortcomings.
One batch I wrote is:
:: setvar varname cmd
:: Set VARNAME to the output of CMD
:: Triple escape pipes, eg:
:: setvar x dir c:\ ^^^| sort
:: -----------------------------
@echo off
SETLOCAL
:: Get command from argument
for /F "tokens=1,*" %%a in ("%*") do set cmd=%%b
:: Get output and set var
for /F "usebackq delims=" %%a in (`%cmd%`) do (
ENDLOCAL
set %1=%%a
)
:: Show results
SETLOCAL EnableDelayedExpansion
echo %1=!%1!
So in your case, you would type:
> setvar text echo Hello
text=Hello
The script informs you of the results, which means you can:
> echo text var is now %text%
text var is now Hello
You can use whatever command:
> setvar text FIND "Jones" names.txt
What if the command you want to pipe to some variable contains itself a pipe?
Triple escape it, ^^^|
:
> setvar text dir c:\ ^^^| find "Win"
CREATE OR REPLACE PACKAGE BODY TEST AS
FUNCTION GET_UPS(
TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY',
STARTING_DATE_IN DATE,
ENDING_DATE_IN DATE
)RETURN MEASURE_TABLE IS
T MEASURE_TABLE;
BEGIN
**SELECT MEASURE_RECORD(L4_ID , L6_ID ,L8_ID ,YEAR ,
PERIOD,VALUE ) BULK COLLECT INTO T
FROM ...**
;
RETURN T;
END GET_UPS;
END TEST;
For me doesnt put jars to lib directory and set to Build path enought.
The right thing was add it to Deployment Assembly.
You can also simply set your pandas column as list of id values with length same as of dataframe.
df['New_ID'] = range(880, 880+len(df))
Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html
I use this query
SELECT id FROM table_name WHERE field_name REGEXP '"key_name":"([^"])key_word([^"])"';
or
SELECT id FROM table_name WHERE field_name RLIKE '"key_name":"[[:<:]]key_word[[:>:]]"';
The first query I use it to search partial value. The second query I use it to search exact word.
The latest PowerShell version as of Sept 2015 is PowerShell 4.0. It's bundled with Windows Management Framework 4.0.
Here's the download page for PowerShelll 4.0 for all versions of Windows. For Windows 7, there are 2 links on that page, 1 for x64 and 1 for x86.
$("#button_id").click(function() {
$('#button_id').attr('disabled', 'true');
$('#myDiv').hide(function() { $('#button_id').removeAttr('disabled'); });
});
Don't use .attr()
to do the disabled, use .prop()
, it's better.
txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\\Tasks";
Put a double backslash instead of a single backslash...
I think in this case they are the same, but here is an example where order matters:
const int* cantChangeTheData;
int* const cantChangeTheAddress;
For route controller method we have to define only one route. In get or post method we have to define the route separately.
And the resources method is used to creates multiple routes to handle a variety of Restful actions.
Here the Laravel documentation about this.
My error was also related to not finding the required .so
file by a service.
I used LD_LIBRARY_PATH
variable to priorities the path picked up by the linker to search the required lib.
I copied both service and .so
file in a folder and fed it to LD_LIBRARY_PATH
variable as
LD_LIBRARY_PATH=. ./service
being in the same folder I have given the above command and it worked.
Sharing this as I've recently encountered issues similar to this thread
For a long time, my script worked well (basic payment form) and returned the POST variables to my success.php page and the IPN data as POST variables also. However, lately, I noticed the return page (success.php) was no longer receiving any POST vars. I tested in Sandbox and live and I'm pretty sure PayPal have changed something !
The notify_url still receives the correct IPN data allowing me to update DB, but I've not been able to display a success message on my return URL (success.php) page.
Despite trying many combinations to switch options on and off in PayPal website payment preferences and IPN, I've had to make some changes to my script to ensure I can still process a message. I've accomplished this by turning on PDT and Auto Return, after following this excellent guide.
Now it all works fine, but the only issue is the return URL contains all of the PDT variables which is ugly!
You may also find this helpful
You can get a similar result by creating scalar-valued functions that return the variable values. Of course, function calls can be expensive if you use them in queries that return a large number of results, but if you're limiting the result-set you should be fine. Here I'm using a database created just to hold these semi-static values, but you can create them on a per-database basis, too. As you can see, there are no input variables, just a well-named function that returns a static value: if you change that value in the function, it will instantly change anywhere it's used (the next time it's called).
USE [globalDatabase]
GO
CREATE FUNCTION dbo.global_GetStandardFonts ()
RETURNS NVARCHAR(255)
AS
BEGIN
RETURN 'font-family:"Calibri Light","sans-serif";'
END
GO
-- Usage:
SELECT '<html><head><style>body{' + globalDatabase.dbo.global_GetStandardFonts() + '}</style></head><body>...'
-- Result: <html><head><style>body{font-family:"Calibri Light","sans-serif";}</style></head><body>...
You can use another overload of the DropDownList
method. Pick the one you need and pass in
a object with your html attributes.
@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })
If you have 32-bit Windows, this method is not working without following settings.
- Run prompt cmd.exe (important : Run As Administrator)
- type bcdedit.exe and run
- Look at the "increaseuserva" params and there is no then write following statement
- bcdedit /set increaseuserva 3072
- and again step 2 and check params
We added this settings and this block started.
if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
call "$(DevEnvDir)..\tools\vsvars32.bat"
editbin /largeaddressaware "$(TargetPath)"
)
More info - command increaseuserva
: https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/bcdedit--set
Well, for just getting the filename of your batch the easiest way would be to just use %~n0
.
@echo %~n0
will output the name (without the extension) of the currently running batch file (unless executed in a subroutine called by call
). The complete list of such “special” substitutions for path names can be found with help for
, at the very end of the help:
In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only %~nxI - expands %I to a file name and extension only %~fsI - expands %I to a full path name with short names only
To precisely answer your question, however: Substrings are done using the :~start,length
notation:
%var:~10,5%
will extract 5 characters from position 10 in the environment variable %var%
.
NOTE: The index of the strings is zero based, so the first character is at position 0, the second at 1, etc.
To get substrings of argument variables such as %0
, %1
, etc. you have to assign them to a normal environment variable using set
first:
:: Does not work:
@echo %1:~10,5
:: Assign argument to local variable first:
set var=%1
@echo %var:~10,5%
The syntax is even more powerful:
%var:~-7%
extracts the last 7 characters from %var%
%var:~0,-4%
would extract all characters except the last four which would also rid you of the file extension (assuming three characters after the period [.
]).See help set
for details on that syntax.