OR is slightly tricky, but not overly so. Here is an example
set var1=%~1
set var2=%~2
::
set or_=
if "%var1%"=="Stack" set or_=true
if "%var2%"=="Overflow" set or_=true
if defined or_ echo Stack OR Overflow
This can simply also mean you are missing or have too many parentheses. For example this has too many, and will result in unexpected EOF
:
print(9, not (a==7 and b==6)
Here is a complete solution to your question using Python's built-in functions:
# Create the List
numbers = input("Enter the elements of the list. Separate each value with a comma. Do not put a comma at the end.\n").split(",")
# Convert the elements in the list (treated as strings) to integers
numberL = [int(element) for element in numbers]
# Loop through the list with a for-loop
for elements in numberL:
maxEle = max(numberL)
indexMax = numberL.index(maxEle)
print(maxEle)
print(indexMax)
Do you need the second batch file to run asynchronously? Typically one batch file runs another synchronously with the call
command, and the second one would share the first one's window.
You can use start /b
second.bat to launch a second batch file asynchronously from your first that shares your first one's window. If both batch files write to the console simultaneously, the output will be overlapped and probably indecipherable. Also, you'll want to put an exit
command at the end of your second batch file, or you'll be within a second cmd
shell once everything is done.
Why not iterate through your DataRow array and add (using DataRow.ImportRow, if necessary, to get a copy of the DataRow), something like:
foreach (DataRow row in rowArray) {
dataTable.ImportRow(row);
}
Make sure your dataTable has the same schema as the DataRows in your DataRow array.
I was annoyed by the lack of proper coloring in cmd too, so I went ahead and created cmdcolor. It's just an stdout proxy, which looks for a limited set of ANSI/VT100 control sequences (in other words, like in bash), i.e. echo \033[31m RED \033[0m DEFAULT | cmdcolor.exe
.
From http://msdn.microsoft.com/en-us/library/ms176089.aspx
varchar [ ( n | max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.
1 character = 1 byte. And don't forget 2 bytes for the termination. So, 2^31-3 characters.
Scenario A: If your large files were only added to a branch, you don't need to run git filter-branch
. You just need to delete the branch and run garbage collection:
git branch -D mybranch
git reflog expire --expire-unreachable=all --all
git gc --prune=all
Scenario B: However, it looks like based on your bash history, that you did merge the changes into master. If you haven't shared the changes with anyone (no git push
yet). The easiest thing would be to reset master back to before the merge with the branch that had the big files. This will eliminate all commits from your branch and all commits made to master after the merge. So you might lose changes -- in addition to the big files -- that you may have actually wanted:
git checkout master
git log # Find the commit hash just before the merge
git reset --hard <commit hash>
Then run the steps from the scenario A.
Scenario C: If there were other changes from the branch or changes on master after the merge that you want to keep, it would be best to rebase master and selectively include commits that you want:
git checkout master
git log # Find the commit hash just before the merge
git rebase -i <commit hash>
In your editor, remove lines that correspond to the commits that added the large files, but leave everything else as is. Save and quit. Your master branch should only contain what you want, and no large files. Note that git rebase
without -p
will eliminate merge commits, so you'll be left with a linear history for master after <commit hash>
. This is probably okay for you, but if not, you could try with -p
, but git help rebase
says combining -p with the -i option explicitly is generally not a good idea unless you know what you are doing
.
Then run the commands from scenario A.
What I ideally want to do is call LogTable.DeleteItem(user_id) - Without supplying the range, and have it delete everything for me.
An understandable request indeed; I can imagine advanced operations like these might get added over time by the AWS team (they have a history of starting with a limited feature set first and evaluate extensions based on customer feedback), but here is what you should do to avoid the cost of a full scan at least:
Use Query rather than Scan to retrieve all items for user_id
- this works regardless of the combined hash/range primary key in use, because HashKeyValue and RangeKeyCondition are separate parameters in this API and the former only targets the Attribute value of the hash component of the composite primary key..
Primary key of the item from which to continue an earlier query. An earlier query might provide this value as the LastEvaluatedKey if that query operation was interrupted before completing the query; either because of the result set size or the Limit parameter. The LastEvaluatedKey can be passed back in a new query request to continue the operation from that point.
Loop over all returned items and either facilitate DeleteItem as usual
As highlighted by ivant, the BatchWriteItem operation enables you to put or delete several items across multiple tables in a single API call [emphasis mine]:
To upload one item, you can use the PutItem API and to delete one item, you can use the DeleteItem API. However, when you want to upload or delete large amounts of data, such as uploading large amounts of data from Amazon Elastic MapReduce (EMR) or migrate data from another database in to Amazon DynamoDB, this API offers an efficient alternative.
Please note that this still has some relevant limitations, most notably:
Maximum operations in a single request — You can specify a total of up to 25 put or delete operations; however, the total request size cannot exceed 1 MB (the HTTP payload).
Not an atomic operation — Individual operations specified in a BatchWriteItem are atomic; however BatchWriteItem as a whole is a "best-effort" operation and not an atomic operation. That is, in a BatchWriteItem request, some operations might succeed and others might fail. [...]
Nevertheless this obviously offers a potentially significant gain for use cases like the one at hand.
One possible reason is JAVA_HOME is not set because java is not installed.
I encountered the same issue. It says
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/spark/launcher/Main : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:643)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:296)
at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:406)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/spark/python/pyspark/conf.py", line 104, in __init__
SparkContext._ensure_initialized()
File "/opt/spark/python/pyspark/context.py", line 243, in _ensure_initialized
SparkContext._gateway = gateway or launch_gateway()
File "/opt/spark/python/pyspark/java_gateway.py", line 94, in launch_gateway
raise Exception("Java gateway process exited before sending the driver its port number")
Exception: Java gateway process exited before sending the driver its port number
at sc = pyspark.SparkConf()
. I solved it by running
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
which is from https://www.digitalocean.com/community/tutorials/how-to-install-java-with-apt-get-on-ubuntu-16-04
This is for future readers. I found that the simplest method for me was to use Visual Studio -> Tools -> External Tools. More details in this answer.
Easier to use and good debugging tools.
usually __iter__()
just return self if you have already define the next() method (generator object):
here is a Dummy example of a generator :
class Test(object):
def __init__(self, data):
self.data = data
def next(self):
if not self.data:
raise StopIteration
return self.data.pop()
def __iter__(self):
return self
but __iter__()
can also be used like this:
http://mail.python.org/pipermail/tutor/2006-January/044455.html
First of all, you should be aware of the fact that CUDA will not automagically make computations faster. On the one hand, because GPU programming is an art, and it can be very, very challenging to get it right. On the other hand, because GPUs are well-suited only for certain kinds of computations.
This may sound confusing, because you can basically compute anything on the GPU. The key point is, of course, whether you will achieve a good speedup or not. The most important classification here is whether a problem is task parallel or data parallel. The first one refers, roughly speaking, to problems where several threads are working on their own tasks, more or less independently. The second one refers to problems where many threads are all doing the same - but on different parts of the data.
The latter is the kind of problem that GPUs are good at: They have many cores, and all the cores do the same, but operate on different parts of the input data.
You mentioned that you have "simple math but with huge amount of data". Although this may sound like a perfectly data-parallel problem and thus like it was well-suited for a GPU, there is another aspect to consider: GPUs are ridiculously fast in terms of theoretical computational power (FLOPS, Floating Point Operations Per Second). But they are often throttled down by the memory bandwidth.
This leads to another classification of problems. Namely whether problems are memory bound or compute bound.
The first one refers to problems where the number of instructions that are done for each data element is low. For example, consider a parallel vector addition: You'll have to read two data elements, then perform a single addition, and then write the sum into the result vector. You will not see a speedup when doing this on the GPU, because the single addition does not compensate for the efforts of reading/writing the memory.
The second term, "compute bound", refers to problems where the number of instructions is high compared to the number of memory reads/writes. For example, consider a matrix multiplication: The number of instructions will be O(n^3) when n is the size of the matrix. In this case, one can expect that the GPU will outperform a CPU at a certain matrix size. Another example could be when many complex trigonometric computations (sine/cosine etc) are performed on "few" data elements.
As a rule of thumb: You can assume that reading/writing one data element from the "main" GPU memory has a latency of about 500 instructions....
Therefore, another key point for the performance of GPUs is data locality: If you have to read or write data (and in most cases, you will have to ;-)), then you should make sure that the data is kept as close as possible to the GPU cores. GPUs thus have certain memory areas (referred to as "local memory" or "shared memory") that usually is only a few KB in size, but particularly efficient for data that is about to be involved in a computation.
So to emphasize this again: GPU programming is an art, that is only remotely related to parallel programming on the CPU. Things like Threads in Java, with all the concurrency infrastructure like ThreadPoolExecutors
, ForkJoinPools
etc. might give the impression that you just have to split your work somehow and distribute it among several processors. On the GPU, you may encounter challenges on a much lower level: Occupancy, register pressure, shared memory pressure, memory coalescing ... just to name a few.
However, when you have a data-parallel, compute-bound problem to solve, the GPU is the way to go.
A general remark: Your specifically asked for CUDA. But I'd strongly recommend you to also have a look at OpenCL. It has several advantages. First of all, it's an vendor-independent, open industry standard, and there are implementations of OpenCL by AMD, Apple, Intel and NVIDIA. Additionally, there is a much broader support for OpenCL in the Java world. The only case where I'd rather settle for CUDA is when you want to use the CUDA runtime libraries, like CUFFT for FFT or CUBLAS for BLAS (Matrix/Vector operations). Although there are approaches for providing similar libraries for OpenCL, they can not directly be used from Java side, unless you create your own JNI bindings for these libraries.
You might also find it interesting to hear that in October 2012, the OpenJDK HotSpot group started the project "Sumatra": http://openjdk.java.net/projects/sumatra/ . The goal of this project is to provide GPU support directly in the JVM, with support from the JIT. The current status and first results can be seen in their mailing list at http://mail.openjdk.java.net/mailman/listinfo/sumatra-dev
However, a while ago, I collected some resources related to "Java on the GPU" in general. I'll summarize these again here, in no particular order.
(Disclaimer: I'm the author of http://jcuda.org/ and http://jocl.org/ )
https://github.com/aparapi/aparapi : An open-source library that is created and actively maintained by AMD. In a special "Kernel" class, one can override a specific method which should be executed in parallel. The byte code of this method is loaded at runtime using an own bytecode reader. The code is translated into OpenCL code, which is then compiled using the OpenCL compiler. The result can then be executed on the OpenCL device, which may be a GPU or a CPU. If the compilation into OpenCL is not possible (or no OpenCL is available), the code will still be executed in parallel, using a Thread Pool.
https://github.com/pcpratts/rootbeer1 : An open-source library for converting parts of Java into CUDA programs. It offers dedicated interfaces that may be implemented to indicate that a certain class should be executed on the GPU. In contrast to Aparapi, it tries to automatically serialize the "relevant" data (that is, the complete relevant part of the object graph!) into a representation that is suitable for the GPU.
https://code.google.com/archive/p/java-gpu/ : A library for translating annotated Java code (with some limitations) into CUDA code, which is then compiled into a library that executes the code on the GPU. The Library was developed in the context of a PhD thesis, which contains profound background information about the translation process.
https://github.com/ochafik/ScalaCL : Scala bindings for OpenCL. Allows special Scala collections to be processed in parallel with OpenCL. The functions that are called on the elements of the collections can be usual Scala functions (with some limitations) which are then translated into OpenCL kernels.
http://www.ateji.com/px/index.html : A language extension for Java that allows parallel constructs (e.g. parallel for loops, OpenMP style) which are then executed on the GPU with OpenCL. Unfortunately, this very promising project is no longer maintained.
http://www.habanero.rice.edu/Publications.html (JCUDA) : A library that can translate special Java Code (called JCUDA code) into Java- and CUDA-C code, which can then be compiled and executed on the GPU. However, the library does not seem to be publicly available.
https://www2.informatik.uni-erlangen.de/EN/research/JavaOpenMP/index.html : Java language extension for for OpenMP constructs, with a CUDA backend
https://github.com/ochafik/JavaCL : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings
http://jogamp.org/jocl/www/ : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings
http://www.lwjgl.org/ : Java bindings for OpenCL: Auto-generated low-level bindings and object-oriented convenience classes
http://jocl.org/ : Java bindings for OpenCL: Low-level bindings that are a 1:1 mapping of the original OpenCL API
http://jcuda.org/ : Java bindings for CUDA: Low-level bindings that are a 1:1 mapping of the original CUDA API
http://sourceforge.net/projects/jopencl/ : Java bindings for OpenCL. Seem to be no longer maintained since 2010
http://www.hoopoe-cloud.com/ : Java bindings for CUDA. Seem to be no longer maintained
This can be done by obtaining the HTTP Status code (404 = not found) which is possible with file_get_contents
Docs making use of context options. The following code takes redirects into account and will return the status code of the final destination (Demo):
$url = 'http://example.com/';
$code = FALSE;
$options['http'] = array(
'method' => "HEAD",
'ignore_errors' => 1
);
$body = file_get_contents($url, NULL, stream_context_create($options));
foreach($http_response_header as $header)
sscanf($header, 'HTTP/%*d.%*d %d', $code);
echo "Status code: $code";
If you don't want to follow redirects, you can do it similar (Demo):
$url = 'http://example.com/';
$code = FALSE;
$options['http'] = array(
'method' => "HEAD",
'ignore_errors' => 1,
'max_redirects' => 0
);
$body = file_get_contents($url, NULL, stream_context_create($options));
sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);
echo "Status code: $code";
Some of the functions, options and variables in use are explained with more detail on a blog post I've written: HEAD first with PHP Streams.
Syntax:
CASE value WHEN [compare_value] THEN result
[WHEN [compare_value] THEN result ...]
[ELSE result]
END
Alternative: CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]
mysql> SELECT CASE WHEN 2>3 THEN 'this is true' ELSE 'this is false' END;
+-------------------------------------------------------------+
| CASE WHEN 2>3 THEN 'this is true' ELSE 'this is false' END |
+-------------------------------------------------------------+
| this is false |
+-------------------------------------------------------------+
I am use:
SELECT act.*,
CASE
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NULL) THEN lises.location_id
WHEN (lises.session_date IS NULL AND ses.session_date IS NOT NULL) THEN ses.location_id
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date>ses.session_date) THEN ses.location_id
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date<ses.session_date) THEN lises.location_id
END AS location_id
FROM activity AS act
LEFT JOIN li_sessions AS lises ON lises.activity_id = act.id AND lises.session_date >= now()
LEFT JOIN session AS ses ON ses.activity_id = act.id AND ses.session_date >= now()
WHERE act.id
Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644
or 755
(spelled (100644
and 100755
; the 100
part means "regular file"):
diff --git a/path b/path
new file mode 100644
The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask
setting, which would normally be 022
to remove write permission from "group" and "other", or 002
to remove write permission only from "other". It might also be 077
if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".
1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664
in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.
The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.
Another example using PowerShell for set permissions (File / Directory) :
Get-Acl "C:\file.txt" | fl *
$acl = Get-Acl "C:\file.txt"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("everyone","FullControl","Allow")
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "C:\file.txt"
Hope this helps
I guess your code uses somewhere in the second case a singular matrix (i.e. not invertible), and the solve function needs to invert it. This has nothing to do with the size but with the fact that some of your vectors are (probably) colinear.
Android 10 (Q) onwards wifi can not be enabled/disabled you need to open the setting intent,
// for android Q and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Intent panelIntent = new
Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY);
startActivityForResult(panelIntent, 0);
} else {
// for previous android version
WifiManager wifiManager = (WifiManager)
this.getApplicationContext().getSystemService(WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
In manifest,
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE"
android:required="true" />
A couple of additional points re use of vector
here.
Unlike ArrayList
and Array
in Java, you don't need to do anything special to treat a vector
as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.
Unlike ArrayList
, a vector
can efficiently hold primitive types without encapsulation as a full-fledged object.
When removing items from a vector
, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.
Make sure if you store complex objects in the vector
that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.
Advice about reserve()
ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.
Unless you're looking for something specific, you can already do Regular Expression matching using regular Javascript with strings.
For example, you can do matching using a string by something like this...
var phrase = "This is a phrase";
phrase = phrase.replace(/is/i, "is not");
alert(phrase);
Is there something you're looking for other than just Regular Expression matching in general?
If you use Windows, probably the location is like this:
C:\User\YourUser\.android\debug.keystore
I found that when I got this error it wasn't because I didn't have my default db path set up. It was because I was trying to run mongo.exe before running mongod.exe.
In my case, the page needed to close, but may have been opened by a link and thus window.close
would fail.
The solution I chose is to issue the window.close
, followed by a window.setTimeout
that redirects to a different page.
That way, if window.close
succeeds, execution on that page stops, but if it fails, in a second, it will redirect to a different page.
window.close();
window.setTimeout(function(){location.href = '/some-page.php';},1000);
Based on the syntax, I'm guessing this is Python. The point of a tuple is that it is immutable, so you need to replace each element with a new tuple:
list = [l + (''.join(l),) for l in list]
# output:
[('1', '2', '3', '4', '1234'),
('2', '3', '4', '5', '2345'),
('3', '4', '5', '6', '3456'),
('4', '5', '6', '7', '4567')]
This is only an add-on to the accepted answer:
def get_results(db_cursor):
desc = [d[0] for d in db_cursor.description]
results = [dotdict(dict(zip(desc, res))) for res in db_cursor.fetchall()]
return results
where dotdict
is:
class dotdict(dict):
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
This will allow you to access much easier the values by column names.
Suppose you have a user
table with columns name
and email
:
cursor.execute('select * from users')
results = get_results(cursor)
for res in results:
print(res.name, res.email)
Use the formatting options available to you, use the Decimal format string. It is far more flexible and requires little to no maintenance compared to direct string manipulation.
To get the string representation using at least 4 digits:
int length = 4;
int number = 50;
string asString = number.ToString("D" + length); //"0050"
TL;DR Just Run this command to Kill it
sudo kill -9 $(lsof -i :3000 -t)
Root Cause: Because PID is locked in a file and web server thinks that if that file exists then it means it is already running. Normally when a web server is closed that file is deleted, but in some cases, proper deletion doesn't happen so you have to remove the file manually New Solutions
when you run rails s
=> Booting WEBrick
=> Rails 4.0.4 application starting in development on http://0.0.0.0:3000
=> Run rails server -h
for more startup options
=> Ctrl-C to shutdown server
A server is already running. Check /your_project_path/tmp/pids/server.pid. Exiting
So place your path shown here /your_project_path/tmp/pids/server.pid
and remove this server.pid file:
rm /your_project_path/tmp/pids/server.pid
OR Incase you're server was detached then follow below guidelines:
If you detached you rails server by using command "rails -d" then,
Remove rails detached server by using command
ps -aef | grep rails
OR by this command
sudo lsof -wni tcp:3000
then
kill -9 pID
OR use this command
To find and kill process by port name on which that program is running. For 3000 replace port on which your program is running.
sudo kill -9 $(lsof -i :3000 -t)
Old Solution:
rails s -p 4000 -P tmp/pids/server2.pid
Also you can find this post for more options Rails Update to 3.2.11 breaks running multiple servers
Personally I like the & function for this
Assuming that you are using cells A1 and A2 for John Smith
=left(a1,1) & b1
If you want to add text between, for example a period
=left(a1,1) & "." & b1
I Improved Aacini Answer to make it Echo Full day of week Name
So here's my Code
@echo off
for /F "skip=1 tokens=2-4 delims=(-/)" %%A in ('date ^< NUL') do (
for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
set %%A=%%a
set %%B=%%b
set %%C=%%c
)
)
set /A mm=10%mm% %% 100, dd=10%dd% %% 100
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=4-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10,dow=(c+dd+e+f-1523)%%7 + 1
for /F "tokens=%dow%" %%a in ("Sunday Monday Tuesday Wednesday Thursday Friday Saturday ") do set dow=%%a
echo Today is %dow%>"Today is %dow%.txt"
echo Today is %dow%
Pause>Nul
REM Sun Mon Tue Wed Thu Fri Sat
REM Sunday Monday Tuesday Wednesday Thursday Friday Saturday
The parameter view is the root layout object.
public static Bitmap screenShot(View view) {
Bitmap bitmap = null;
if (view.getWidth() > 0 && view.getHeight() > 0) {
bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
}
return bitmap;
}
Do like this:
HTML
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
CSS
.parent{
width: 400px;
background: red;
}
.child{
float: left;
width:200px;
background:green;
height: 100px;
}
This is working jsfiddle. Change child width
to more then 200px
and they will stack.
If you want to do it using XAML set the property isReadOnly
to true
.
One of Androids powerful feature is the AsyncTask class.
To work with it, you have to first extend it and override doInBackground
(...).
doInBackground
automatically executes on a worker thread, and you can add some
listeners on the UI Thread to get notified about status update, those functions are
called: onPreExecute()
, onPostExecute()
and onProgressUpdate()
You can find a example here.
Refer to below post for other alternatives:
On my end, the problem was an unsuccessful connection to the VPN (while working from home). And yeah, the connectionString was using a context from remote server. Which resulted in the following error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>The network path was not found</ExceptionMessage>
<ExceptionType>System.ComponentModel.Win32Exception</ExceptionType>
<StackTrace/>
</Error>
If you are using callback functions use return
after the err
block. This is one of the scenarios in which this error can happen.
userModel.createUser(data, function(err, data) {
if(err) {
res.status = 422
res.json(err)
return // without this return the error can happen.
}
return res.json(data)
})
Tested on Node version v10.16.0
and express 4.16.4
It may be caused by IE's box model bug. To fix this, you can use the Box Model Hack.
if you want to delete all files that belong to a directory at once. For example: your Directory name is "log" and "log" directory include abc.log.2012-03-14, abc.log.2012-03-15,... etc files. You have to be above the log directory and:
rm -rf /log/*
I think you want NUL
, at least within a command prompt or batch files.
For example:
type c:\autoexec.bat > NUL
doesn't create a file.
(I believe the same is true if you try to create a file programmatically, but I haven't tried it.)
In PowerShell, you want $null
:
echo 1 > $null
You Create Custom ListView Which is non Scrollable
public class NonScrollListView extends ListView {
public NonScrollListView(Context context) {
super(context);
}
public NonScrollListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
In Your Layout Resources File
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<!-- com.Example Changed with your Package name -->
<com.Example.NonScrollListView
android:id="@+id/lv_nonscroll_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</com.Example.NonScrollListView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/lv_nonscroll_list" >
<!-- Your another layout in scroll view -->
</RelativeLayout>
</RelativeLayout>
In Java File
Create a object of your customListview instead of ListView like : NonScrollListView non_scroll_list = (NonScrollListView) findViewById(R.id.lv_nonscroll_list);
Generating all the indices of a sequence is generally a bad idea, as it might take a lot of time, especially if the ratio of the numbers to be chosen to MAX
is low (the complexity becomes dominated by O(MAX)
). This gets worse if the ratio of the numbers to be chosen to MAX
approaches one, as then removing the chosen indices from the sequence of all also becomes expensive (we approach O(MAX^2/2)
). But for small numbers, this generally works well and is not particularly error-prone.
Filtering the generated indices by using a collection is also a bad idea, as some time is spent in inserting the indices into the sequence, and progress is not guaranteed as the same random number can be drawn several times (but for large enough MAX
it is unlikely). This could be close to complexity O(k n log^2(n)/2)
, ignoring the duplicates and assuming the collection uses a tree for efficient lookup (but with a significant constant cost k
of allocating the tree nodes and possibly having to rebalance).
Another option is to generate the random values uniquely from the beginning, guaranteeing progress is being made. That means in the first round, a random index in [0, MAX]
is generated:
items i0 i1 i2 i3 i4 i5 i6 (total 7 items)
idx 0 ^^ (index 2)
In the second round, only [0, MAX - 1]
is generated (as one item was already selected):
items i0 i1 i3 i4 i5 i6 (total 6 items)
idx 1 ^^ (index 2 out of these 6, but 3 out of the original 7)
The values of the indices then need to be adjusted: if the second index falls in the second half of the sequence (after the first index), it needs to be incremented to account for the gap. We can implement this as a loop, allowing us to select arbitrary number of unique items.
For short sequences, this is quite fast O(n^2/2)
algorithm:
void RandomUniqueSequence(std::vector<int> &rand_num,
const size_t n_select_num, const size_t n_item_num)
{
assert(n_select_num <= n_item_num);
rand_num.clear(); // !!
// b1: 3187.000 msec (the fastest)
// b2: 3734.000 msec
for(size_t i = 0; i < n_select_num; ++ i) {
int n = n_Rand(n_item_num - i - 1);
// get a random number
size_t n_where = i;
for(size_t j = 0; j < i; ++ j) {
if(n + j < rand_num[j]) {
n_where = j;
break;
}
}
// see where it should be inserted
rand_num.insert(rand_num.begin() + n_where, 1, n + n_where);
// insert it in the list, maintain a sorted sequence
}
// tier 1 - use comparison with offset instead of increment
}
Where n_select_num
is your 5 and n_number_num
is your MAX
. The n_Rand(x)
returns random integers in [0, x]
(inclusive). This can be made a bit faster if selecting a lot of items (e.g. not 5 but 500) by using binary search to find the insertion point. To do that, we need to make sure that we meet the requirements.
We will do binary search with the comparison n + j < rand_num[j]
which is the same as n < rand_num[j] - j
. We need to show that rand_num[j] - j
is still a sorted sequence for a sorted sequence rand_num[j]
. This is fortunately easily shown, as the lowest distance between two elements of the original rand_num
is one (the generated numbers are unique, so there is always difference of at least 1). At the same time, if we subtract the indices j
from all the elements rand_num[j]
, the differences in index are exactly 1. So in the "worst" case, we get a constant sequence - but never decreasing. The binary search can therefore be used, yielding O(n log(n))
algorithm:
struct TNeedle { // in the comparison operator we need to make clear which argument is the needle and which is already in the list; we do that using the type system.
int n;
TNeedle(int _n)
:n(_n)
{}
};
class CCompareWithOffset { // custom comparison "n < rand_num[j] - j"
protected:
std::vector<int>::iterator m_p_begin_it;
public:
CCompareWithOffset(std::vector<int>::iterator p_begin_it)
:m_p_begin_it(p_begin_it)
{}
bool operator ()(const int &r_value, TNeedle n) const
{
size_t n_index = &r_value - &*m_p_begin_it;
// calculate index in the array
return r_value < n.n + n_index; // or r_value - n_index < n.n
}
bool operator ()(TNeedle n, const int &r_value) const
{
size_t n_index = &r_value - &*m_p_begin_it;
// calculate index in the array
return n.n + n_index < r_value; // or n.n < r_value - n_index
}
};
And finally:
void RandomUniqueSequence(std::vector<int> &rand_num,
const size_t n_select_num, const size_t n_item_num)
{
assert(n_select_num <= n_item_num);
rand_num.clear(); // !!
// b1: 3578.000 msec
// b2: 1703.000 msec (the fastest)
for(size_t i = 0; i < n_select_num; ++ i) {
int n = n_Rand(n_item_num - i - 1);
// get a random number
std::vector<int>::iterator p_where_it = std::upper_bound(rand_num.begin(), rand_num.end(),
TNeedle(n), CCompareWithOffset(rand_num.begin()));
// see where it should be inserted
rand_num.insert(p_where_it, 1, n + p_where_it - rand_num.begin());
// insert it in the list, maintain a sorted sequence
}
// tier 4 - use binary search
}
I have tested this on three benchmarks. First, 3 numbers were chosen out of 7 items, and a histogram of the items chosen was accumulated over 10,000 runs:
4265 4229 4351 4267 4267 4364 4257
This shows that each of the 7 items was chosen approximately the same number of times, and there is no apparent bias caused by the algorithm. All the sequences were also checked for correctness (uniqueness of contents).
The second benchmark involved choosing 7 numbers out of 5000 items. The time of several versions of the algorithm was accumulated over 10,000,000 runs. The results are denoted in comments in the code as b1
. The simple version of the algorithm is slightly faster.
The third benchmark involved choosing 700 numbers out of 5000 items. The time of several versions of the algorithm was again accumulated, this time over 10,000 runs. The results are denoted in comments in the code as b2
. The binary search version of the algorithm is now more than two times faster than the simple one.
The second method starts being faster for choosing more than cca 75 items on my machine (note that the complexity of either algorithm does not depend on the number of items, MAX
).
It is worth mentioning that the above algorithms generate the random numbers in ascending order. But it would be simple to add another array to which the numbers would be saved in the order in which they were generated, and returning that instead (at negligible additional cost O(n)
). It is not necessary to shuffle the output: that would be much slower.
Note that the sources are in C++, I don't have Java on my machine, but the concept should be clear.
EDIT:
For amusement, I have also implemented the approach that generates a list with all the indices 0 .. MAX
, chooses them randomly and removes them from the list to guarantee uniqueness. Since I've chosen quite high MAX
(5000), the performance is catastrophic:
// b1: 519515.000 msec
// b2: 20312.000 msec
std::vector<int> all_numbers(n_item_num);
std::iota(all_numbers.begin(), all_numbers.end(), 0);
// generate all the numbers
for(size_t i = 0; i < n_number_num; ++ i) {
assert(all_numbers.size() == n_item_num - i);
int n = n_Rand(n_item_num - i - 1);
// get a random number
rand_num.push_back(all_numbers[n]); // put it in the output list
all_numbers.erase(all_numbers.begin() + n); // erase it from the input
}
// generate random numbers
I have also implemented the approach with a set
(a C++ collection), which actually comes second on benchmark b2
, being only about 50% slower than the approach with the binary search. That is understandable, as the set
uses a binary tree, where the insertion cost is similar to binary search. The only difference is the chance of getting duplicate items, which slows down the progress.
// b1: 20250.000 msec
// b2: 2296.000 msec
std::set<int> numbers;
while(numbers.size() < n_number_num)
numbers.insert(n_Rand(n_item_num - 1)); // might have duplicates here
// generate unique random numbers
rand_num.resize(numbers.size());
std::copy(numbers.begin(), numbers.end(), rand_num.begin());
// copy the numbers from a set to a vector
Full source code is here.
JLS§14.14.1, The basic for Statement, makes it clear that the ForUpdate expression(s) are evaluated and the value(s) are discarded. The effect is to make the two forms identical in the context of a for
statement.
The above answers are incorrect in that most over-ride the 'is this connection HTTPS' test to allow serving the pages over http irrespective of connection security.
The secure answer using an error-page on an NGINX specific http 4xx error code to redirect the client to retry the same request to https. (as outlined here https://serverfault.com/questions/338700/redirect-http-mydomain-com12345-to-https-mydomain-com12345-in-nginx )
The OP should use:
server {
listen 12345;
server_name php.myadmin.com;
root /var/www/php;
ssl on;
# If they come here using HTTP, bounce them to the correct scheme
error_page 497 https://$server_name:$server_port$request_uri;
[....]
}
This is certainly something that has a lot of traps. I was working with Paolo Bergantino's answer, and realising that even that has some limitations. I found working with string representations of dates a good place to quickly find some of the main problems. Start with an input string like this:
'12-2-2019 5:1:48.670'
and set up Paolo's function like this:
function count(re, str) {
if (typeof re !== "string") {
return 0;
}
re = (re === '.') ? ('\\' + re) : re;
var cre = new RegExp(re, 'g');
return ((str || '').match(cre) || []).length;
}
I wanted the regular expression to be passed in, so that the function is more reusable, secondly, I wanted the parameter to be a string, so that the client doesn't have to make the regex, but simply match on the string, like a standard string utility class method.
Now, here you can see that I'm dealing with issues with the input. With the following:
if (typeof re !== "string") {
return 0;
}
I am ensuring that the input isn't anything like the literal 0
, false
, undefined
, or null
, none of which are strings. Since these literals are not in the input string, there should be no matches, but it should match '0'
, which is a string.
With the following:
re = (re === '.') ? ('\\' + re) : re;
I am dealing with the fact that the RegExp constructor will (I think, wrongly) interpret the string '.'
as the all character matcher \.\
Finally, because I am using the RegExp constructor, I need to give it the global 'g'
flag so that it counts all matches, not just the first one, similar to the suggestions in other posts.
I realise that this is an extremely late answer, but it might be helpful to someone stumbling along here. BTW here's the TypeScript version:
function count(re: string, str: string): number {
if (typeof re !== 'string') {
return 0;
}
re = (re === '.') ? ('\\' + re) : re;
const cre = new RegExp(re, 'g');
return ((str || '').match(cre) || []).length;
}
You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree
option for single commands, or the GIT_WORK_TREE
environment variable. There is also the core.worktree
configuration option but it will not work in a bare repository (check the man page for what it does).
# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status
Well, here's an example for overloaded constructors.
public class Employee
{
private String name;
private int age;
public Employee()
{
System.out.println("We are inside Employee() constructor");
}
public Employee(String name)
{
System.out.println("We are inside Employee(String name) constructor");
this.name = name;
}
public Employee(String name, int age)
{
System.out.println("We are inside Employee(String name, int age) constructor");
this.name = name;
this.age = age;
}
public Employee(int age)
{
System.out.println("We are inside Employee(int age) constructor");
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
In the above example you can see overloaded constructors. Name of the constructors is same but each constructors has different parameters.
Here are some resources which throw more light on constructor overloading in java,
As an alternative way you can use DriverManagerDataSource such as:
public DataSource getDataSource(DBInfo db) {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUsername(db.getUsername());
dataSource.setPassword(db.getPassword());
dataSource.setUrl(db.getUrl());
dataSource.setDriverClassName(db.getDriverClassName());
return dataSource;
}
However be careful about using it, because:
NOTE: This class is not an actual connection pool; it does not actually pool Connections. It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface, but creating new Connections on every call. reference
If you have a command window open and call the commands manually, you can display a timestamp on each prompt, e.g.
prompt $d $t $_$P$G
It gives you something like:
23.03.2009 15:45:50,77
C:\>
If you have a small batch script that executes your commands, have an empty line before each command, e.g.
(empty line)
myCommand.exe
(next empty line)
myCommand2.exe
You can calculate the execution time for each command by the time information in the prompt. The best would probably be to pipe the output to a textfile for further analysis:
MyBatchFile.bat > output.txt
Sort of solution using metatable...
local function preparetable(t)
setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end
local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)
if workingtable[456] then
...
end
I've found that using a simple for loop, iterating over all elements in the string and comparing using charAt
performs faster than indexOf
or Regex
. The code and proof is available at JSPerf.
ETA: indexOf
and charAt
both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com
On your branch - say master, pull and allow unrelated histories
git pull origin master --allow-unrelated-histories
Worked for me.
To my knowledge, only ENV
allows that, as mentioned in "Environment replacement"
Environment variables (declared with the
ENV
statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.
They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build
.
In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.
This day, I use both ARG
(docker 1.10+, and docker build --build-arg var=value
) and ENV
.
Using ARG
alone means your variable is visible at build time, not at runtime.
My Dockerfile usually has:
ARG var
ENV var=${var}
In your case, ARG
is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.
If you are using Python2.6 or newer, it's convenient to use socket.create_connection
sock = socket.create_connection(address, timeout=10)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)
$(document).ready ->
$("a[href^='#']").click ->
$(document.body).animate
scrollTop: $($(this).attr("href")).offset().top, 1000
I would like to expand on Martin's answer there...
His solution is rather nice, but it can be tweaked so any "variable type" can be printed like that.(It's actually Value Type, more on the topic). That said, "tweaked" may be a strong word for this. Regardless, it may be helpful.
Martins Solution:
a.getClass().getName()
However, If you want it to work with anything you can do this:
((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()
In this case, the primitive will simply be wrapped in a Wrapper. You will get the Object of the primitive in that case.
I myself used it like this:
private static String nameOf(Object o) {
return o.getClass().getSimpleName();
}
Using Generics:
public static <T> String nameOf(T o) {
return o.getClass().getSimpleName();
}
@will's method is the best. Just add few lines about the details for the people didn't use ExcelDNA before like me.
Download Excel-DNA IntelliSense from https://github.com/Excel-DNA/IntelliSense/releases
There are two version, one is for 64, check your Excel version. For my case, I'm using 64 version.
Open Excel/Developer/Add-Ins/Browse and select ExcelDna.IntelliSense64.xll.
Insert a new sheet, change name to "IntelliSense", add function description, as https://github.com/Excel-DNA/IntelliSense/wiki/Getting-Started
Then enjoy! :)
gb = df.groupby(['A'])
gb_groups = grouped_df.groups
If you are looking for selective groupby objects then, do: gb_groups.keys(), and input desired key into the following key_list..
gb_groups.keys()
key_list = [key1, key2, key3 and so on...]
for key, values in gb_groups.iteritems():
if key in key_list:
print df.ix[values], "\n"
You don't need to update anything. Just download the SDK for API 25 from Android SDK Manager or by launching Android standalone SDK manager. The error is for missing platform and not for missing tool.
The article linked to by MrMage is no longer working. So, here is what I've learned in my (very) short time coding in Objective-C:
nonatomic vs. atomic - "atomic" is the default. Always use "nonatomic". I don't know why, but the book I read said there is "rarely a reason" to use "atomic". (BTW: The book I read is the BNR "iOS Programming" book.)
readwrite vs. readonly - "readwrite" is the default. When you @synthesize, both a getter and a setter will be created for you. If you use "readonly", no setter will be created. Use it for a value you don't want to ever change after the instantiation of the object.
retain vs. copy vs. assign
Deleting everything under your workspace's .metadata\.plugins\org.eclipse.core.runtime\.settings
will restore to defaults but you will lose every other setting too. You can selectively undo changes made by importing RainbowDrops.epf
Open RanbowDrops.epf
. Mine looks like this
file_export_version=3.0
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION=167,236,33
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION.bold=false
...
/instance/com.adobe.flexide.as.core/asASDocItalic=true
/instance/com.adobe.flexide.as.core/asASDocColor=#626262
...
/instance/com.android.ide.eclipse.ddms/logcat.msg.color.assert=205,22,137
/instance/com.android.ide.eclipse.ddms/logcat.msg.color.debug=123,182,234
...
/instance/com.powerflasher.fdt.ui/AS_CONSTANTS_color=152,118,170
/instance/com.powerflasher.fdt.ui/AS_CORE_color=18,144,195
the lines starting with /instance/ccw.core
will go into file ccw.core.prefs
. Lines instance/com.adobe.flexide.as.core
will go into com.adobe.flexide.as.core.prefs
and so on. You need to delete those files only. There are quite a lot of them though (i had to delete 53), easy way to sift them is to find the first one and sort by modification time they will group together.
BTW there is nice dark theme available by default in eclipse 4.7 (2017). You can try and switch color themes without this kind of hassle by installing Eclipse Color Themes plugin, it also has good selection of dark color themes too.
When I used Apache HTTP Client 4.3, I was using the Pooled or Basic Connection Managers to the HTTP Client. I noticed, from using java SSL debugging, that these classes loaded the cacerts trust store and not the one I had specified programmatically.
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
builder.setConnectionManager( cm );
I wanted to use them but ended up removing them and creating an HTTP Client without them. Note that builder is an HttpClientBuilder.
I confirmed when running my program with the Java SSL debug flags, and stopped in the debugger. I used -Djavax.net.debug=ssl as a VM argument. I stopped my code in the debugger and when either of the above *ClientConnectionManager were constructed, the cacerts file would be loaded.
I can see only 1 things happening here: You did't set properly dependences to thelibrary.lib in your project meaning that thelibrary.lib is built in the wrong order (Or in the same time if you have more then 1 CPU build configuration, which can also explain randomness of the error). ( You can change the project dependences in: Menu->Project->Project Dependencies )
Go to Tools > Options. In the tree on the left, select SQL Server Object Explorer. Set the option "Value for Edit Top Rows command" to 0. It'll now allow you to view and edit the entire table from the context menu.
You might consider installing pipenv
via pipsi
.
curl https://raw.githubusercontent.com/mitsuhiko/pipsi/master/get -pipsi.py | python3
pipsi install pew
pipsi install pipenv
Unfortunately there are some issues with macOS + python3 at the time of writing, see 1, 2. In my case I had to change the bashprompt to #!/Users/einselbst/.local/venvs/pipsi/bin/python
You need to explicitly enable the home action if running on ICS. From the docs:
Note: If you're using the icon to navigate to the home activity, beware that beginning with Android 4.0 (API level 14), you must explicitly enable the icon as an action item by calling setHomeButtonEnabled(true) (in previous versions, the icon was enabled as an action item by default).
You can do that in this way:
ORDER BY `products`.`product_category_id` DESC ,`naam` ASC
Have a look at ORDER BY
Optimization
You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.
There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.
By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.
In addition to the other suggestions - you can also wrap the flag in a control class and make a final instance of it in your parent class:
public class Test {
class Control {
public volatile boolean flag = false;
}
final Control control = new Control();
class T1 implements Runnable {
@Override
public void run() {
while ( !control.flag ) {
}
}
}
class T2 implements Runnable {
@Override
public void run() {
while ( !control.flag ) {
}
}
}
private void test() {
T1 main = new T1();
T2 help = new T2();
new Thread(main).start();
new Thread(help).start();
}
public static void main(String[] args) throws InterruptedException {
try {
Test test = new Test();
test.test();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Classes have an implicit strong reference to their ClassLoader instance, and vice versa. They are garbage collected as with Java objects. Without hitting the tools interface or similar, you can't remove individual classes.
As ever you can get memory leaks. Any strong reference to one of your classes or class loader will leak the whole thing. This occurs with the Sun implementations of ThreadLocal, java.sql.DriverManager and java.beans, for instance.
Every minor version of Python, that is any 3.x and 2.x version, will install side-by-side with other versions on your computer. Only patch versions will upgrade existing installations.
So if you want to keep your installed Python 2.7 around, then just let it and install a new version using the installer. If you want to get rid of Python 2.7, you can uninstall it before or after installing a newer version—there is no difference to this.
Current Python 3 installations come with the py.exe
launcher, which by default is installed into the system directory. This makes it available from the PATH, so you can automatically run it from any shell just by using py
instead of python
as the command. This avoids you having to put the current Python installation into PATH yourself. That way, you can easily have multiple Python installations side-by-side without them interfering with each other. When running, just use py script.py
instead of python script.py
to use the launcher. You can also specify a version using for example py -3
or py -3.6
to launch a specific version, otherwise the launcher will use the current default (which will usually be the latest 3.x).
Using the launcher, you can also run Python 2 scripts (which are often syntax incompatible to Python 3), if you decide to keep your Python 2.7 installation. Just use py -2 script.py
to launch a script.
As for PyPI packages, every Python installation comes with its own folder where modules are installed into. So if you install a new version and you want to use modules you installed for a previous version, you will have to install them first for the new version. Current versions of the installer also offer you to install pip
; it’s enabled by default, so you already have pip
for every installation. Unless you explicitly add a Python installation to the PATH, you cannot just use pip
though. Luckily, you can also simply use the py.exe
launcher for this: py -m pip
runs pip
. So for example to install Beautiful Soup for Python 3.6, you could run py -3.6 -m pip install beautifulsoup4
.
DATETIME2
has a date range of "0001 / 01 / 01" through "9999 / 12 / 31" while the DATETIME
type only supports year 1753-9999.
Also, if you need to, DATETIME2
can be more precise in terms of time; DATETIME is limited to 3 1/3 milliseconds, while DATETIME2
can be accurate down to 100ns.
Both types map to System.DateTime
in .NET - no difference there.
If you have the choice, I would recommend using DATETIME2
whenever possible. I don't see any benefits using DATETIME
(except for backward compatibility) - you'll have less trouble (with dates being out of range and hassle like that).
Plus: if you only need the date (without time part), use DATE - it's just as good as DATETIME2
and saves you space, too! :-) Same goes for time only - use TIME
. That's what these types are there for!
Kotlin supports operators overloading
In Kotlin you can easily compare dates with compare operators. Because Kotlin already support operators overloading. So to compare date objects :
firstDate: Date = // your first date
secondDate: Date = // your second date
if(firstDate < secondDate){
// fist date is before second date
}
and if you're using calendar objects, you can easily compare like this:
if(cal1.time < cal2.time){
// cal1 date is before cal2 date
}
It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.
The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:
You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:
Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:
#toolbar=0&navpanes=0
So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.
string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);
You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.
Just try this one as a full copy paste in the shell and you will grasp it
# create the example file to be working on ..
cat << EOF > tmp.json
[
{ "card_id": "id-00", "card_id_type": "card_id_type-00"},
{"card_id": "id-01", "card_id_type": "card_id_type-01"},
{ "card_id": "id-02", "card_id_type": "card_id_type-02"}
]
EOF
# pipe the content of the file to the jq query, which gets the array of objects
# and select the attribute named "card_id" ONLY if it's neighbour attribute
# named "card_id_type" has the "card_id_type-01" value
# jq -r means give me ONLY the value of the jq query no quotes aka raw
cat tmp.json | jq -r '.[]| select (.card_id_type == "card_id_type-01")|.card_id'
id-01
or with an aws cli command
# list my vpcs or
# list the values of the tags which names are "Name"
aws ec2 describe-vpcs | jq -r '.| .Vpcs[].Tags[]|select (.Key == "Name") | .Value'|sort -nr
Assign your image to a string. Eg image Now set icon to a fixed size label.
image.setIcon(new javax.swing.ImageIcon(image.getScaledInstance(50,50,WIDTH)));
SET NOCOUNT ON; Above code will stop the message generated by sql server engine to fronted result window after the DML/DDL command execution.
Why we do it? As SQL server engine takes some resource to get the status and generate the message, it is considered as overload to the Sql server engine.So we set the noncount message on.
You can do it manually. (I know, that that isn't great solution, but..)
use while
loop till the result
hasn't a value
kickOff().then(function(result) {
while(true){
if (result === undefined) continue;
else {
$("#output").append(result);
return;
}
}
});
In Preferences, select Python Interpreter
Under Python Interpreter, change from "Default" to "Use the following Python interpreter"
The path there should be the default Python executable. Find your Python 2.7 executable and use that.
Since I first saw break
in C a couple of decades back, this problem has vexed me. I was hoping some language enhancement would have an extension to break which would work thus:
break; // our trusty friend, breaks out of current looping construct.
break 2; // breaks out of the current and it's parent looping construct.
break 3; // breaks out of 3 looping constructs.
break all; // totally decimates any looping constructs in force.
I did this with a combination of:
Here's a jsfiddle example to demonstrate.
Haven't tested on all browsers but I imagine it's not great on older IE versions.
$("#clscroll-content").scroll(function() {_x000D_
$("#clscroll-row-headers").scrollTop($("#clscroll-content").scrollTop());_x000D_
$("#clscroll-column-headers").scrollLeft($("#clscroll-content").scrollLeft());_x000D_
});_x000D_
_x000D_
$("#clscroll-column-headers").scroll(function() {_x000D_
$("#clscroll-content").scrollLeft($("#clscroll-column-headers").scrollLeft());_x000D_
});_x000D_
_x000D_
$("#clscroll-row-headers").scroll(function() {_x000D_
$("#clscroll-content").scrollTop($("#clscroll-row-headers").scrollTop());_x000D_
});
_x000D_
.clscroll table {_x000D_
table-layout: fixed;_x000D_
}_x000D_
_x000D_
.clscroll td, .clscroll th { _x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.corner-header {_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.column-headers {_x000D_
float: left;_x000D_
overflow: scroll;_x000D_
}_x000D_
_x000D_
.row-headers {_x000D_
clear: both;_x000D_
float: left; _x000D_
overflow: scroll;_x000D_
}_x000D_
_x000D_
.table-content {_x000D_
table-layout: fixed;_x000D_
float: left;_x000D_
overflow: scroll;_x000D_
}_x000D_
_x000D_
.clscroll td, .clscroll th { _x000D_
width: 200px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
.row-headers, .table-content {_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
.column-headers, .table-content, .table-content table, .column-headers table {_x000D_
width: 400px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="clscroll corner-header">_x000D_
<table>_x000D_
<tr>_x000D_
<th> </th>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
<div class="clscroll column-headers" id="clscroll-column-headers">_x000D_
<table>_x000D_
<tr>_x000D_
<th>Bus</th>_x000D_
<th>Plane</th>_x000D_
<th>Boat</th>_x000D_
<th>Bicycle</th>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
<div class="clscroll row-headers" id="clscroll-row-headers">_x000D_
<table>_x000D_
<tr>_x000D_
<th>Red</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Green</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Blue</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Orange</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Purple</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Yellow</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Pink</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Brown</th>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
<div class="clscroll table-content" id="clscroll-content">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Red Bus</td>_x000D_
<td>Red Plane</td>_x000D_
<td>Red Boat</td>_x000D_
<td>Red Bicycle</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Green Bus</td>_x000D_
<td>Green Plane</td>_x000D_
<td>Green Boat</td>_x000D_
<td>Green Bicycle</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Blue Bus</td>_x000D_
<td>Blue Plane</td>_x000D_
<td>Blue Boat</td>_x000D_
<td>Blue Bicycle</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Orange Bus</td>_x000D_
<td>Orange Plane</td>_x000D_
<td>Orange Boat</td>_x000D_
<td>Orange Bicycle</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Purple Bus</td>_x000D_
<td>Purple Plane</td>_x000D_
<td>Purple Boat</td>_x000D_
<td>Purple Bicycle</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Yellow Bus</td>_x000D_
<td>Yellow Plane</td>_x000D_
<td>Yellow Boat</td>_x000D_
<td>Yellow Bicycle</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Pink Bus</td>_x000D_
<td>Pink Plane</td>_x000D_
<td>Pink Boat</td>_x000D_
<td>Pink Bicycle</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Brown Bus</td>_x000D_
<td>Brown Plane</td>_x000D_
<td>Brown Boat</td>_x000D_
<td>Brown Bicycle</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
I am also a Windows user. And I have installed Python 3.7 and when I try to install any package it throws the same error that you are getting.
Try this out. This worked for me.
python -m pip install numpy
And whenever you install new package just write python -m pip install <package_name>
Hope this is helpful.
This is actual code I once had to support. After struggling to comprehend the logic in AstaSaysGooGoo and AstaSaysGaaGaa (where many more astaTempVars were declared and used ) I was ready to give up. I finally looked up and saw the "@author" comment and the whole thing began to makes sense.
/*
* @author Andrew Asta
*/
public class AstaClass{
private String astaVar1;
private String astaVar2;
private String astaVar3;
private String astaVar4;
private String astaVar5;
private String astaVar6;
private String astaVar7;
private String astaVar8;
private String astaVar9;
private String astaVar10;
public void AstaSaysGetData(){
//JDBC statement to populate astavars 1 through 10
//...
String astaSqlStatment = "Select astaCol1, astaCol2, astaCol3... From AstaTable Where...";
//..
//...
}
//Perform data manipulation on astavars...
public void AstaSaysGaaGaa(){
[removed for sake of brevity]
}
//Perform more data manipulation on astavars...
public void AstaSaysGooGoO(){
[removed for sake of brevity]
}
public void AstaSaysPersist(){
//JDBC statement to save astavars to DB
String astaSqlStatment = "Update AstaTable set astaCol1 = @astaVar1
, set astaCol2 = @astaVar2
, set astaCol3 = astaCol3...
Where...";
}
}
PS I changed the actual authors real name so as to avoid me getting in any disputes etc...
I use JS to show only the div with a specific id in the tags page in a jekyll site. With a set of links in the same page, you show the corresponding element:
function hide_others() {
$('div.item').hide();
selected = location.hash.slice(1);
if (selected) {
$('#' + selected).show();
}
else {
$('div.item').show();
}
}
links use links like:
<a href="javascript:window.location.href='/tags.html#{{ tag[0] }}-ref'; hide_others()">{{ tag[0] }}</a>
To elaborate on Ben's answer:
If you add a reference to Microsoft Scripting Runtime
and correctly type the variable fso you can take advantage of autocompletion (Intellisense) and discover the other great features of FileSystemObject
.
Here is a complete example module:
Option Explicit
' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
' the FileSystemObject which has many useful features for handling files and folders
Public Sub SaveTextToFile()
Dim filePath As String
filePath = "C:\temp\MyTestFile.txt"
' The advantage of correctly typing fso as FileSystemObject is to make autocompletion
' (Intellisense) work, which helps you avoid typos and lets you discover other useful
' methods of the FileSystemObject
Dim fso As FileSystemObject
Set fso = New FileSystemObject
Dim fileStream As TextStream
' Here the actual file is created and opened for write access
Set fileStream = fso.CreateTextFile(filePath)
' Write something to the file
fileStream.WriteLine "something"
' Close it, so it is not locked anymore
fileStream.Close
' Here is another great method of the FileSystemObject that checks if a file exists
If fso.FileExists(filePath) Then
MsgBox "Yay! The file was created! :D"
End If
' Explicitly setting objects to Nothing should not be necessary in most cases, but if
' you're writing macros for Microsoft Access, you may want to uncomment the following
' two lines (see https://stackoverflow.com/a/517202/2822719 for details):
'Set fileStream = Nothing
'Set fso = Nothing
End Sub
Pass a duration to show()
and hide()
:
When a duration is provided,
.show()
becomes an animation method.
E.g. element.delay(1000).show(0)
You can use the Interval
class from Eclipse Collections.
List<Integer> range = Interval.oneTo(10);
range.forEach(System.out::print); // prints 12345678910
The Interval
class is lazy, so doesn't store all of the values.
LazyIterable<Integer> range = Interval.oneTo(10);
System.out.println(range.makeString(",")); // prints 1,2,3,4,5,6,7,8,9,10
Your method would be able to be implemented as follows:
public List<Integer> makeSequence(int begin, int end) {
return Interval.fromTo(begin, end);
}
If you would like to avoid boxing ints as Integers, but would still like a list structure as a result, then you can use IntList
with IntInterval
from Eclipse Collections.
public IntList makeSequence(int begin, int end) {
return IntInterval.fromTo(begin, end);
}
IntList
has the methods sum()
, min()
, minIfEmpty()
, max()
, maxIfEmpty()
, average()
and median()
available on the interface.
Update for clarity: 11/27/2017
An Interval
is a List<Integer>
, but it is lazy and immutable. It is extremely useful for generating test data, especially if you deal a lot with collections. If you want you can easily copy an interval to a List
, Set
or Bag
as follows:
Interval integers = Interval.oneTo(10);
Set<Integer> set = integers.toSet();
List<Integer> list = integers.toList();
Bag<Integer> bag = integers.toBag();
An IntInterval
is an ImmutableIntList
which extends IntList
. It also has converter methods.
IntInterval ints = IntInterval.oneTo(10);
IntSet set = ints.toSet();
IntList list = ints.toList();
IntBag bag = ints.toBag();
An Interval
and an IntInterval
do not have the same equals
contract.
Update for Eclipse Collections 9.0
You can now create primitive collections from primitive streams. There are withAll
and ofAll
methods depending on your preference. If you are curious, I explain why we have both here. These methods exist for mutable and immutable Int/Long/Double Lists, Sets, Bags and Stacks.
Assert.assertEquals(
IntInterval.oneTo(10),
IntLists.mutable.withAll(IntStream.rangeClosed(1, 10)));
Assert.assertEquals(
IntInterval.oneTo(10),
IntLists.immutable.withAll(IntStream.rangeClosed(1, 10)));
Note: I am a committer for Eclipse Collections
If there is a space in the beginning of the tns name define in file tnsnames.ora
, then some of the the connectors like odbc may give this error. Remove space character in the beginning.
In SQL Server 2008, there is a DATE datetype (also a TIME datatype).
CAST(GetDate() as DATE)
or
declare @Dt as DATE = GetDate()
Several of these things did not work for me... however, this did. Might help someone else in the future. Here is the CSS:
.img-area {
display: block;
padding: 0px 0 0 0px;
text-indent: 0;
width: 100%;
background-size: 100% 95%;
background-repeat: no-repeat;
background-image: url("https://yourimage.png");
}
Querying user_tables
and dba_tables
didn't work.
This one did:
select table_name from all_tables
@media (max-width: @iphone-screen) {
background-attachment:inherit;
background-size:cover;
-webkit-background-size:cover;
}
DECLARE @FDate DATETIME='05-05-2019' /*This is first date*/
GETDATE()/*This is Current date*/
SELECT (DATEDIFF(DAY,(@LastDate),GETDATE())) As DifferenceDays/*this query will return no of days between firstdate & Current date*/
There is another way of performing the fit, which is by using the 'lmfit' package. It basically uses the cuve_fit but is much better in fitting and offers complex fitting as well. Detailed step by step instructions are given in the below link. http://cars9.uchicago.edu/software/python/lmfit/model.html#model.best_fit
I am always using:
input.disabled {
pointer-events:none;
color:#AAA;
background:#F5F5F5;
}
and then applying the css class to the input field:
<input class="disabled" type="text" value="90" name="myinput" id="myinput" />
Another possible solution to this error that I found. Might not have answered OP's exact question but may help others who stumble across this error message.
I was creating my Client in code using WebHttpBinding, in order to replicate the following line:
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" proxyCredentialType="Windows" />
</security>
I had to do:
var binding = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Windows;
as well as setting proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
So long as Excel can open the file, the functionality to change the format of the opened file is built in.
To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).
To do it using VBA, the code would look like this:
Sub Open_HTML_Save_XLSX()
Workbooks.Open Filename:="C:\Temp\Example.html"
ActiveWorkbook.SaveAs Filename:= _
"C:\Temp\Example.xlsx", FileFormat:= _
xlOpenXMLWorkbook
End Sub
Have a look at java.io.File.list()
and FilenameFilter
.
Yet another one. Short and keeps special characters:
imaginação é mato => imaginacao-e-mato
function slugify (text) {
const a = 'àáäâãèéëêìíïîòóöôùúüûñçßÿœærsn?????u?z?·/_,:;'
const b = 'aaaaaeeeeiiiioooouuuuncsyoarsnpwgnmuxzh------'
const p = new RegExp(a.split('').join('|'), 'g')
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(p, c =>
b.charAt(a.indexOf(c))) // Replace special chars
.replace(/&/g, '-and-') // Replace & with 'and'
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, '') // Trim - from end of text
}
Change this line:
mMyListView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems));
to:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems)
mMyListView.setAdapter(adapter);
and after updating the value of a list item, call:
adapter.notifyDataSetChanged();
It'll need to be something tailored to the needs, which are dependent on the structure you're presented with. For the example you've provided, this works:
$(document).ready(function(){
var $tmp = $('#listItem').children().remove();
$('#listItem').text('').append($tmp);
});
Demo: http://jquery.nodnod.net/cases/2385/run
But it's fairly dependent on the markup being similar to what you posted.
After a bit of googling, it seems that there never was a separate redistributable for Visual C++ 2003 (7.1). At least that is what a post on the microsoft forum says.
You may however be able to extract the runtime DLLs from the VC 7.1 DST timezone update.
you need to add jar file in your build path..
commons-dbcp-1.1-RC2.jar
or any version of that..!!!!
ADDED : also make sure you have commons-pool-1.1.jar too in your build path.
ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.
HttpWebRequest request =(HttpWebRequest)WebRequest.Create("some url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
request.Accept = "/";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
doc.Save(request.GetRequestStream());
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
Hope it helps
It is and old question but let me add a detail just in case more people like me arrive here.
The excellent answer posted by Brian is not working for me in Jelly Bean. I have to add also:
browser.setInitialScale(30);
The parameter can be any percentage tha accomplishes that the resized content is smaller than the webview width. Then setUseWideViewPort(true) extends the content width to the maximum of the webview width.
As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.
Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.
With the repository pattern, you would only need to change one object and one repository. The impact is very small.
Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:
You have a single place to make changes to your data access
You have a single place responsible for a set of tables (usually)
It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests
There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!
Dan, no need to use fancy tricks. All you need to do is make copy of arr1 by doing this.
var arr2 = new Array(arr1);
_x000D_
Now arr1
and arr2
are two different array variables stored in separate stacks.
Check this out on jsfiddle.
This worked for me:
mv xyz.war ./tmp
cd tmp
jar -xvf xyz.war
rm -rf WEB-INF/lib/zookeeper-3.4.10.jar
rm -rf xyz.war
jar -cvf xyz.war *
mv xyz.war ../
cd ..
For future reference if somebody else runs into this problem. I found a solution that should work in all modern browsers:
select{
scrollbar-width: none; /*For Firefox*/;
-ms-overflow-style: none; /*For Internet Explorer 10+*/;
}
select:-webkit-scrollbar { /*For WebKit Browsers*/
width: 0;
height: 0;
}
Basically this way the scrollbar is set to a width of 0 and is hence not displayed.
You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.
Addition to most voted answer.
I want to add some words about obtainStyledAttributes() usage, when we create custom view using android:xxx prdefined attributes. Especially when we use TextAppearance.
As was mentioned in "2. Creating constructors", custom view gets AttributeSet on its creation. Main usage we can see in TextView source code (API 16).
final Resources.Theme theme = context.getTheme();
// TextAppearance is inspected first, but let observe it later
TypedArray a = theme.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TextView, defStyle, 0);
int n = a.getIndexCount();
for (int i = 0; i < n; i++)
{
int attr = a.getIndex(i);
// huge switch with pattern value=a.getXXX(attr) <=> a.getXXX(a.getIndex(i))
}
a.recycle();
What we can see here?
obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
Attribute set is processed by theme according to documentation. Attribute values are compiled step by step. First attributes are filled from theme, then values are replaced by values from style, and finally exact values from XML for special view instance replace others.
Array of requested attributes - com.android.internal.R.styleable.TextView
It is an ordinary array of constants. If we are requesting standard attributes, we can build this array manually.
What is not mentioned in documentation - order of result TypedArray elements.
When custom view is declared in attrs.xml, special constants for attribute indexes are generated. And we can extract values this way: a.getString(R.styleable.MyCustomView_android_text)
. But for manual int[]
there are no constants. I suppose, that getXXXValue(arrayIndex) will work fine.
And other question is: "How we can replace internal constants, and request standard attributes?" We can use android.R.attr.* values.
So if we want to use standard TextAppearance attribute in custom view and read its values in constructor, we can modify code from TextView this way:
ColorStateList textColorApp = null;
int textSize = 15;
int typefaceIndex = -1;
int styleIndex = -1;
Resources.Theme theme = context.getTheme();
TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.CustomLabel, defStyle, 0);
TypedArray appearance = null;
int apResourceId = a.getResourceId(R.styleable.CustomLabel_android_textAppearance, -1);
a.recycle();
if (apResourceId != -1)
{
appearance =
theme.obtainStyledAttributes(apResourceId, new int[] { android.R.attr.textColor, android.R.attr.textSize,
android.R.attr.typeface, android.R.attr.textStyle });
}
if (appearance != null)
{
textColorApp = appearance.getColorStateList(0);
textSize = appearance.getDimensionPixelSize(1, textSize);
typefaceIndex = appearance.getInt(2, -1);
styleIndex = appearance.getInt(3, -1);
appearance.recycle();
}
Where CustomLabel is defined:
<declare-styleable name="CustomLabel">
<!-- Label text. -->
<attr name="android:text" />
<!-- Label text color. -->
<attr name="android:textColor" />
<!-- Combined text appearance properties. -->
<attr name="android:textAppearance" />
</declare-styleable>
Maybe, I'm mistaken some way, but Android documentation on obtainStyledAttributes() is very poor.
At the same time we can just extend standard UI component, using all its declared attributes. This approach is not so good, because TextView for instance declares a lot of properties. And it will be impossible to implement full functionality in overriden onMeasure() and onDraw().
But we can sacrifice theoretical wide reusage of custom component. Say "I know exactly what features I will use", and don't share code with anybody.
Then we can implement constructor CustomComponent(Context, AttributeSet, defStyle)
.
After calling super(...)
we will have all attributes parsed and available through getter methods.
Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}
then you create a menu strip item to exit the application.
cheers
There are actually three things here: origin master
is two separate things, and origin/master
is one thing. Three things total.
Two branches:
master
is a local branchorigin/master
is a remote branch (which is a local copy of the branch named "master" on the remote named "origin")One remote:
origin
is a remoteSince origin/master
is a branch, you can merge it. Here's a pull in two steps:
Step one, fetch master
from the remote origin
. The master
branch on origin
will be fetched and the local copy will be named origin/master
.
git fetch origin master
Then you merge origin/master
into master
.
git merge origin/master
Then you can push your new changes in master
back to origin
:
git push origin master
You can fetch multiple branches by name...
git fetch origin master stable oldstable
You can merge multiple branches...
git merge origin/master hotfix-2275 hotfix-2276 hotfix-2290
Only if you need to support ancient versions of Internet Explorer.
The modern approach is to do margin: 0 auto
in your CSS.
Example here: http://jsfiddle.net/bKRMY/
HTML:
<p>Hello the following image is centered</p>
<p class="pic"><img src="https://twimg0-a.akamaihd.net/profile_images/440228301/StackoverflowLogo_reasonably_small.png"/></p>
<p>Did it work?</p>
CSS:
p.pic {
width: 48px;
margin: 0 auto;
}
The only issue here is that the width of the paragraph must be the same as the width of the image. If you don't put a width on the paragraph, it will not work, because it will assume 100% and your image will be aligned left, unless of course you use text-align:center
.
Try out the fiddle and experiment with it if you like.
Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:
var peopleInOrder = people.OrderBy(person => person.LastName);
To sort in place, you'd need an IComparer<Person>
or a Comparison<Person>
. For that, you may wish to consider ProjectionComparer
in MiscUtil.
(I know I keep bringing MiscUtil up - it just keeps being relevant...)
And when I debug this the logic does fall into the sentence.replace.
Yes, and then you discard the return value.
Strings in Java are immutable - when you call replace
, it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:
sentence = sentence.replace("and", " ");
This applies to all the methods in String (substring
, toLowerCase
etc). None of them change the contents of the string.
Note that you don't really need to do this in a condition - after all, if the sentence doesn't contain "and"
, it does no harm to perform the replacement:
String sentence = "Define, Measure, Analyze, Design and Verify";
sentence = sentence.replace("and", " ");
You can loop to create the String
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
}
String[] stringArray = list.toArray(new String[list.size()]);
V=`php -v | sed -e '/^PHP/!d' -e 's/.* \([0-9]\+\.[0-9]\+\).*$/\1/'` \
sudo apt-get install php$V-zip
If the WAMP icon is Orange then one of the services has not started.
In your case it looks like MySQL has not started as you are getting the message that indicates there is no server running and therefore listening for requests.
Look at the mysql log and if that tells you nothing look at the Windows event log, in the Windows -> Applications
section. Error messages in there are pretty good at identifying the cause of MySQL failing to start.
Sometimes this is caused by a my.ini file from another install being picked up by WAMPServers MySQL, normally in the \windows or \windows\system32 folders. Do a search for 'my.ini' and 'my.cnf' and if you find one of these anywhere outside of the \wamp.... folder structure then delete it, or at least rename it so it wont be found. Then restart the MySQL service.
Turning Hardware Acceleration OFF seems to be the setting that affects popups & dialogs.
Chrome was continually hiding Dialog Windows when I needed to respond Yes or No to things, also when I needed to Rename folders in my bookmarks panel. After weeks of doing this. I disabled all the Chrome helpers in Settings, Also In windows 10 I switched Window Snapping off. It has done something to put the popups and dialogs back in the Viewport.
When this bug is happening, I was able to shut a tab by first pressing Enter before clicking the tab close X button. The browser had an alert box, hidden which needed a response from the user.
Switching Hardware Accleration Off and back On, Killing the Chrome process and switching all the other Helpers Off and back has fixed it for me... It must be in chrome itself because Ive just gone into a Chrome window in the Mac and it has now stopped the problem, without any intervention. Im guessing flicking the chrome settings on/off/on has caused it to reposition the dialogs. I cant get the browser to repeat the fault now...
This is the real solution:
<td>
<span class="inline-flag">
<i class="flag-bfh-ES"></i>
<span>+34 666 66 66 66</span>
</span>
</td>
css:
.inline-flag {
position: relative;
display: inline;
line-height: 14px; /* play with this */
}
.inline-flag > i {
position: absolute;
display: block;
top: -1px; /* play with this */
}
.inline-flag > span {
margin-left: 18px; /* play with this */
}
Example, images which always before text:
Take a look at RedGate SQL Source Control.
http://www.red-gate.com/products/sql-development/sql-source-control/
This tool is a SQL Server Management Studio snap-in which will allow you to place your database under Source Control with Git.
It's a bit pricey at $495 per user, but there is a 28 day free trial available.
NOTE I am not affiliated with RedGate in any way whatsoever.
You need to implement the equals() method in your MyClass
.
The reason that ==
didn't work is this is checking that they refer to the same instance. Since you did new
for each, each one is a different instance.
The reason that equals()
didn't work is because you didn't implement it yourself yet. I believe it's default behavior is the same thing as ==
.
Note that you should also implement hashcode()
if you're going to implement equals()
because a lot of java.util Collections expect that.
It doesn't look like you can do this with a single command, but here's the closest thing to it that I could find.
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
You can always set the options, based on this page you can set, to get rid of the seconds, something like this
var dateWithouthSecond = new Date();
dateWithouthSecond.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
Supported by Firefox, Chrome, IE9+ and Opera. Try it on your web browser console.
I think this would be a better option as it shows the URL running the server:
var http = require('http'),
fs = require('fs');
const hostname = '<your_machine_IP>';
const port = 3000;
const html=fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
})
});
Building on the installation concept of chocolatey
and the idea suggested by @Tracker, what worked for me was to do the following and all users on windows were then happy working with nodejs
and npm
.
Choose C:\ProgramData\nodejs
as installation directory for nodejs
and install nodejs
with any user that is a member of the administrator group.
This can be done with chocolatey as: choco install nodejs.install -ia "'INSTALLDIR=C:\ProgramData\nodejs'"
Then create a folder called npm-cache
at the root of the installation directory, which after following above would be C:\ProgramData\nodejs\npm-cache
.
Create a folder called etc
at the root of the installation directory, which after following above would be C:\ProgramData\nodejs\etc
.
Set NODE
environment variable as C:\ProgramData\nodejs
.
Set NODE_PATH
environment variable as C:\ProgramData\nodejs\node_modules
.
Ensure %NODE%
environment variable previously created above is added (or its path) is added to %PATH%
environment variable.
Edit %NODE_PATH%\npm\npmrc
with the following content prefix=C:\ProgramData\nodejs
From command prompt, set the global config like so...
npm config --global set prefix "C:\ProgramData\nodejs"
npm config --global set cache "C:\ProgramData\nodejs\npm-cache"
It is important the steps above are carried out preferably in sequence and before updating npm (npm -g install npm@latest
) or attempting to install any npm
module.
Performing the above steps helped us running nodejs
as system wide installation, easily available to all users with proper permissions. Each user can then run node
and npm
as required.
I'm exceptionally new to VBScript, so this may not be considered best practice or there may be a reason it shouldn't be done this that way I'm not yet aware of, but this is the solution I came up with to trim down the amount of error logging code in my main code block.
Dim oConn, connStr
Set oConn = Server.CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX"
ON ERROR RESUME NEXT
oConn.Open connStr
If err.Number <> 0 Then : showError() : End If
Sub ShowError()
'You could write the error details to the console...
errDetail = "<script>" & _
"console.log('Description: " & err.Description & "');" & _
"console.log('Error number: " & err.Number & "');" & _
"console.log('Error source: " & err.Source & "');" & _
"</script>"
Response.Write(errDetail)
'...you could display the error info directly in the page...
Response.Write("Error Description: " & err.Description)
Response.Write("Error Source: " & err.Source)
Response.Write("Error Number: " & err.Number)
'...or you could execute additional code when an error is thrown...
'Insert error handling code here
err.clear
End Sub
Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.
Html
<div id="xx"></div>
Javascript:
if (document.getElementById('xx') !=null)
console.log('it exists!');
if (document.getElementById('xxThisisNotAnElementOnThePage') ==null)
console.log('does not exist!');
use the String.Trim()
function.
string foo = " hello ";
string bar = foo.Trim();
Console.WriteLine(bar); // writes "hello"
Why not add "display: none;" to the divs style attribute? Thats all JQuery's .hide() function does.
Or mayby even more simple with convert
from hablar
:
library(hablar)
dat %>%
convert(fct(fac1, fac2, fac3),
num(dbl1, dbl2, dbl3))
or combines with tidyselect
:
dat %>%
convert(fct(contains("fac")),
num(contains("dbl")))
@ronmurp raises a valid concern - the cast/floor approach returns different values for the same time. Along the lines of the answer by @littlechris and for a more general solution that solves for times that have a minute, seconds, milliseconds component, you could use this function to count the number of milliseconds from the start of the day.
Create Function [dbo].[MsFromStartOfDay] ( @DateTime datetime )
Returns int
As
Begin
Return (
( Datepart( ms , @DateTime ) ) +
( Datepart( ss , @DateTime ) * 1000 ) +
( Datepart( mi , @DateTime ) * 1000 * 60 ) +
( Datepart( hh , @DateTime ) * 1000 * 60 * 60 )
)
End
I've verified that it returns the same int for two different dates with the same time
declare @first datetime
set @first = '1900-01-01 23:59:39.090'
declare @second datetime
set @second = '2000-11-02 23:56:39.090'
Select dbo.MsFromStartOfDay( @first )
Select dbo.MsFromStartOfDay( @second )
This solution doesn't always return the int you would expect. For example, try the below in SQL 2005, it returns an int ending in '557' instead of '556'.
set @first = '1900-01-01 23:59:39.556'
set @second = '2000-11-02 23:56:39.556'
I think this has to do with the nature of DateTime stored as float. You can still compare the two number, though. And when I used this approach on a "real" dataset of DateTime captured in .NET using DateTime.Now() and stored in SQL, I found that the calculations were accurate.
I solved this problem with ModelViewSet and ModelSerializer. Hope this will help community.
I also preffer to have validation and Object->JSON (and vice-versa) login in serializer itself rather than in views.
Lets understand it by example.
Say, I want to create FileUploader API. Where it will be storing fields like id, file_path, file_name, size, owner etc in database. See sample model below:
class FileUploader(models.Model):
file = models.FileField()
name = models.CharField(max_length=100) #name is filename without extension
version = models.IntegerField(default=0)
upload_date = models.DateTimeField(auto_now=True, db_index=True)
owner = models.ForeignKey('auth.User', related_name='uploaded_files')
size = models.IntegerField(default=0)
Now, For APIs this is what I want:
When I fire the GET endpoint, I want all above fields for every uploaded file.
But for user to create/upload file, why she has to worry about passing all these fields. She can just upload the file and then, I suppose, serializer can get rest of the fields from uploaded FILE.
Searilizer: Question: I created below serializer to serve my purpose. But not sure if its the right way to implement it.
class FileUploaderSerializer(serializers.ModelSerializer):
# overwrite = serializers.BooleanField()
class Meta:
model = FileUploader
fields = ('file','name','version','upload_date', 'size')
read_only_fields = ('name','version','owner','upload_date', 'size')
def validate(self, validated_data):
validated_data['owner'] = self.context['request'].user
validated_data['name'] = os.path.splitext(validated_data['file'].name)[0]
validated_data['size'] = validated_data['file'].size
#other validation logic
return validated_data
def create(self, validated_data):
return FileUploader.objects.create(**validated_data)
Viewset for reference:
class FileUploaderViewSet(viewsets.ModelViewSet):
serializer_class = FileUploaderSerializer
parser_classes = (MultiPartParser, FormParser,)
# overriding default query set
queryset = LayerFile.objects.all()
def get_queryset(self, *args, **kwargs):
qs = super(FileUploaderViewSet, self).get_queryset(*args, **kwargs)
qs = qs.filter(owner=self.request.user)
return qs
For Sql server try this
SELECT T.name,
I.rows AS [ROWCOUNT]
FROM sys.tables AS T
INNER JOIN sys.sysindexes AS I
ON T.object_id = I.id AND I.indid < 2
WHERE T.name = 'Your_Table_Name'
ORDER BY I.rows DESC
You can iterate DefaultView
as the following code by Indexer
:
DataTable dt = new DataTable();
// add some rows to your table
// ...
dt.DefaultView.Sort = "OneColumnName ASC"; // For example
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow oRow = dt.DefaultView[i].Row;
// Do your stuff with oRow
// ...
}
In pthread_exit
, ret
is an input parameter. You are simply passing the address of a variable to the function.
In pthread_join
, ret
is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL
.
Long explanation:
In pthread_join
, you get back the address passed to pthread_exit
by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.
Any script tags posted on an ASP.NET web form will cause your site to throw and unhandled exception.
You can use a asp regex validator to confirm input, just ensure you wrap your code behind method with a if(IsValid) clause in case your javascript is bypassed. If your client javascript is bypassed and script tags are posted to your asp.net form, asp.net will throw a unhandled exception.
You can use something like:
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
This code will have exactly the given amount of characters; filled with spaces or truncated on the right side:
private String leftpad(String text, int length) {
return String.format("%" + length + "." + length + "s", text);
}
private String rightpad(String text, int length) {
return String.format("%-" + length + "." + length + "s", text);
}
@neilfws's solution works great for data.frame
s, but not for data.table
s since they lack the row.names
property. This approach works for both:
df.expanded <- df[rep(seq(nrow(df)), df$freq), 1:2]
The code for data.table
is a tad cleaner:
# convert to data.table by reference
setDT(df)
df.expanded <- df[rep(seq(.N), freq), !"freq"]
The problem in my case was that I needed to add environment variables for http_proxy
and https_proxy
.
E.g.,
http_proxy=http://your_proxy:your_port
https_proxy=https://your_proxy:your_port
To set these environment variables in Windows, see the answers to this question.
Yet another solution.
Add ErrorControllers or static page to with 404 error information.
Modify your web.config (in case of controller).
<system.web>
<customErrors mode="On" >
<error statusCode="404" redirect="~/Errors/Error404" />
</customErrors>
</system.web>
Or in case of static page
<system.web>
<customErrors mode="On" >
<error statusCode="404" redirect="~/Static404.html" />
</customErrors>
</system.web>
This will handle both missed routes and missed actions.
There are basically 4 types of main constraints in SQL:
Domain Constraint: if one of the attribute values provided for a new tuple is not of the specified attribute domain
Key Constraint: if the value of a key attribute in a new tuple already exists in another tuple in the relation
Referential Integrity: if a foreign key value in a new tuple references a primary key value that does not exist in the referenced relation
Entity Integrity: if the primary key value is null in a new tuple
In Mvc 4 you can use AcceptVerbsAttribute, I think this is a very clean solution
[AcceptVerbs(WebRequestMethods.Http.Get, WebRequestMethods.Http.Post)]
public IHttpActionResult Login()
{
// Login logic
}
If you want to convert string to double data type then most choose parseDouble() method. See the example code:
String str = "123.67";
double d = parseDouble(str);
You will get the value in double. See the StringToDouble tutorial at tutorialData.
As greg said you can embed HTML content in Markdown, but one of the points of Markdown is to avoid having to have extensive (or any, for that matter) CSS/HTML markup knowledge, right? This is what I do:
In my Markdown file I simply instruct all my wiki editors to embed wrap all images with something that looks like this:
'<div> // Put image here </div>`
(of course.. they don't know what <div>
means, but that shouldn't matter)
So the Markdown file looks like this:
<div>
![optional image description][1]
</div>
[1]: /image/path
And in the CSS content that wraps the whole page I can do whatever I want with the image tag:
img {
float: right;
}
Of course you can do more with the CSS content... (in this particular case, wrapping the img
tag with div prevents other text from wrapping against the image... this is just an example, though), but IMHO the point of Markdown is that you don't want potentially non-technical people getting into the ins and outs of CSS/HTML.. it's up to you as a web developer to make your CSS content that wraps the page as generic and clean as possible, but then again your editors need not know about that.
To convert (ISO) date to Unix timestamp, I ended up with a timestamp 3 characters longer than needed so my year was somewhere around 50k...
I had to devide it by 1000:
new Date('2012-02-26').getTime() / 1000
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div
= document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i <
a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
_x000D_
#myInput {
box-sizing: border-box;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #ddd;
}
.show {
display: block;
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<a href="#about">home</a>
<a href="#base">contact</a>
</div>
</div>
_x000D_
You can also use JSONObject class from json.org to this will convert your HashMap to JSON string which is well formatted
Example:
Map<String,Object> map = new HashMap<>();
map.put("myNumber", 100);
map.put("myString", "String");
JSONObject json= new JSONObject(map);
String result= json.toString();
System.out.print(result);
result:
{'myNumber':100, 'myString':'String'}
Your can also get key from it like
System.out.print(json.get("myNumber"));
result:
100
Very similar to Marc, only difference I would make would be to spool to a parameter like so:
WHENEVER SQLERROR EXIT 1
SET LINES 32000
SET TERMOUT OFF ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF
SET SERVEROUTPUT ON
spool &1
-- Code
spool off
exit
And then to call the SQLPLUS as
sqlplus -s username/password@sid @tmp.sql /tmp/output.txt
Another OpenSource signature field is https://github.com/applicius/jquery.signfield/ , registered jQuery plugin using Sketch.js .
All of the other responses suggest using the standard CSS pointer, however, there are two methods:
Apply the CSS property cursor:pointer;
to the elements. (This is the default style when a cursor hovers over a button.)
Apply the CSS property cursor:url(pointer.png);
using a custom graphic for your pointer. This may be more desirable if you want to ensure that the user experience is identical on all platforms (instead of allowing the browser/OS decide what your pointer cursor should look like). Note that fallback options may be added in case the image is not found, including secondary urls or any of the other options i.e. cursor:url(pointer.png,fallback.png,pointer);
Of course these may be applied to the list items in this manner li{cursor:pointer;}
, as a class .class{cursor:pointer;}
, or as a value for the style attribute of each element style="cursor:pointer;"
.
click on the project that you want to run on the left side in package explorer and then click the Run button.
Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):
byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();
Keep Trying!
I have had this a few times (including today), and each time, without changing anything, it has worked when I tried again.
Sometimes the 2nd time, other times 20 minutes later.
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
"final" guarantees that a variable must be initialized before end of object initializer code. Likewise "static final" guarantees that a variable will be initialized by the end of class initialization code. Omitting the "static" from your initialization code turns it into object initialization code; thus your variable no longer satisfies its guarantees.
One thing I see here to optimize.
While I do agree that the balls hit when the distance is the sum of their radii one should never actually calculate this distance! Rather, calculate it's square and work with it that way. There's no reason for that expensive square root operation.
Also, once you have found a collision you have to continue to evaluate collisions until no more remain. The problem is that the first one might cause others that have to be resolved before you get an accurate picture. Consider what happens if the ball hits a ball at the edge? The second ball hits the edge and immediately rebounds into the first ball. If you bang into a pile of balls in the corner you could have quite a few collisions that have to be resolved before you can iterate the next cycle.
As for the O(n^2), all you can do is minimize the cost of rejecting ones that miss:
1) A ball that is not moving can't hit anything. If there are a reasonable number of balls lying around on the floor this could save a lot of tests. (Note that you must still check if something hit the stationary ball.)
2) Something that might be worth doing: Divide the screen into a number of zones but the lines should be fuzzy--balls at the edge of a zone are listed as being in all the relevant (could be 4) zones. I would use a 4x4 grid, store the zones as bits. If an AND of the zones of two balls zones returns zero, end of test.
3) As I mentioned, don't do the square root.
Finally, Anaconda3-2020.07 is out and its core is Python 3.8!
You can now download Anaconda packed with Python 3.8 goodness at:
Having done some more digging, I think my issue is something to do with the type of library I am building gtest into. When building gtest with CMake, if BUILD_SHARED_LIBS is un-checked, and I link my program against these .lib files I get the errors mentioned above. However, if BUILD_SHARED_LIBS is checked then I produce a set of .lib and .dll files. When now linking against these .lib files the program compiles, but when run complains that it can't find gtest.dll.
That is because you have to add -DGTEST_LINKED_AS_SHARED_LIBRARY=1 to compiler definitions in your project if you want to use gtest as a shared library.
You could also use the static libraries, provided you compiled it with gtest_force_shared_crt option on to eliminate errors you have seen.
I like the library but adding it to the project is a real pain. And you have no chance to do it right unless you dig (and hack) into the gtest cmake files. Shame. In particular I do not like the idea of adding gtest as a source. :)
playSound is a static method meaning it exists when the program is loaded. audioSounds and minTime are SoundManager instance variable, meaning they will exist within an instance of SoundManager. You have not created an instance of SoundManager so audioSounds doesn't exist (or it does but you do not have a reference to a SoundManager object to see that).
To solve your problem you can either make audioSounds static:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
so they will be created and may be referenced in the same way that PlaySound will be. Alternatively you can create an instance of SoundManager from within your method:
SoundManager soundManager = new SoundManager();
foreach (AudioSource sound in soundManager.audioSounds) // Loop through List with foreach
{
if (sourceSound.name != sound.name && sound.time <= soundManager.minTime)
{
playsound = true;
}
}
If you only need to execute only one command all by itself and no wait needed, you should try "cmd /c", this works for me!
cmd /c start iexplore "http://your/url.html"
cmd /c means executing a command and then exit.
You can learn the functions of your switches by typing in your command prompt
anycmd /?
The following will work for a DateTime that has fractional milliseconds, and also preserves the Kind property (Local, Utc or Undefined).
DateTime dateTime = ... anything ...
dateTime = new DateTime(
dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond),
dateTime.Kind
);
or the equivalent and shorter:
dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond));
This could be generalized into an extension method:
public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan)
{
if (timeSpan == TimeSpan.Zero) return dateTime; // Or could throw an ArgumentException
if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) return dateTime; // do not modify "guard" values
return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}
which is used as follows:
dateTime = dateTime.Truncate(TimeSpan.FromMilliseconds(1)); // Truncate to whole ms
dateTime = dateTime.Truncate(TimeSpan.FromSeconds(1)); // Truncate to whole second
dateTime = dateTime.Truncate(TimeSpan.FromMinutes(1)); // Truncate to whole minute
...
You can select dropdown option value by name
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
As explained by this answer, the exact location of the string pool is not specified and can vary from one JVM implementation to another.
It is interesting to note that until Java 7, the pool was in the permgen space of the heap on hotspot JVM but it has been moved to the main part of the heap since Java 7:
Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences. RFE: 6962931
And in Java 8 Hotspot, Permanent Generation has been completely removed.
Write an empty string to the file, flush, and close. Make sure that the file writer is not in append-mode. I think that should do the trick.
You could also turn on autoextend for the whole database using this command:
ALTER DATABASE DATAFILE 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\SYSTEM.DBF'
AUTOEXTEND ON NEXT 1M MAXSIZE 1024M;
Just change the filepath to point to your system.dbf file.
Credit Here
You can directly create your own style in this way:
input[type=button]
{
//Change the style as you like
}
this is output of this program
Scanner s=new Scanner (System.in);
int row, elem, col;
Systm.out.println("Enter Element to insert");
elem = s.nextInt();
System.out.println("Enter row");
row=s.nextInt();
System.out.println("Enter row");
col=s.nextInt();
for (int c=row-1; c < row; c++)
{
for (d = col-1 ; d < col ; d++)
array[c][d] = elem;
}
for(c = 0; c < size; c++)
{
for (d = 0 ; d < size ; d++)
System.out.print( array[c] [d] +" ");
System.out.println();
}
Add the following line in your .profile
file in your home directory (using vi ~/.profile
):
PATH=$PATH:/home/me/play
export PATH
Then, for the change to take effect, simply type in your terminal:
$ . ~/.profile
One approach would be to add the Second for Loop where the printing is being done inside the first for loop. Like this:
static String[] SENTENCE;
public static void main(String []args) throws Exception{
Scanner sentence = new Scanner(new File("assets/blah.txt"));
ArrayList<String> sentenceList = new ArrayList<String>();
while (sentence.hasNextLine())
{
sentenceList.add(sentence.nextLine());
}
sentence.close();
String[] sentenceArray = sentenceList.toArray(new String[sentenceList.size()]);
// System.out.println(sentenceArray.length);
for (int r=0;r<sentenceArray.length;r++)
{
SENTENCE = sentenceArray[r].split("(?<=[.!?])\\s*"); //split sentences and store in array
for (int i=0;i<SENTENCE.length;i++)
{
System.out.println("Sentence " + (i+1) + ": " + SENTENCE[i]);
}
}
}
In case somebody wants to do this, using Play Framework (and using LogBack http://logback.qos.ch/), then you can configure the application-logger.xml with this line:
<logger name="org.apache.cxf" level="DEBUG"/>
For me, it did the trick ;)
you should try the new Java Executor Services. http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
With this you don't need to program the loop the time measuring by yourself.
public class Starter {
public static void main(final String[] args) {
final ExecutorService service = Executors.newSingleThreadExecutor();
try {
final Future<Object> f = service.submit(() -> {
// Do you long running calculation here
Thread.sleep(1337); // Simulate some delay
return "42";
});
System.out.println(f.get(1, TimeUnit.SECONDS));
} catch (final TimeoutException e) {
System.err.println("Calculation took to long");
} catch (final Exception e) {
throw new RuntimeException(e);
} finally {
service.shutdown();
}
}
}
You can do this by adding a parameter &hd=1
to the video URL. That forces the video to start in the highest resolution available for the video. However you cannot specifically set it to 720p, because not every video has that hd ish.
http://code.google.com/apis/youtube/player_parameters.html
UPDATE: as of 2014, hd is deprecated https://developers.google.com/youtube/player_parameters?csw=1#Deprecated_Parameters
Why not using LEFT(string, length) function instead of substring.
LEFT(col,char_length(col)-2)
you can visit here https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_left to know more about Mysql String Functions.
As far as you're concerned once you've "pulled out" the contents with something like .html() it's just a string. You can test that with
<html>
<head>
<title>runthis</title>
<script type="text/javascript" language="javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready( function() {
var x = $("#foo").html();
alert( typeof(x) );
});
</script>
</head>
<body>
<div id="foo"><table><tr><td>x</td></tr></table><span>xyz</span></div>
</body>
</html>
The alert text is string. As long as you don't pass it to a parser there's no magic about it, it's a string like any other string.
There's nothing that hinders you from using .post() to send this string back to the server.
edit: Don't pass a string as the parameter data to .post() but an object, like
var data = {
id: currid,
html: div_html
};
$.post("http://...", data, ...);
jquery will handle the encoding of the parameters.
If you (for whatever reason) want to keep your string you have to encode the values with something like escape().
var data = 'id='+ escape(currid) +'&html='+ escape(div_html);
You can simply use the method change
of JQuery to get the value of the current radio checked with the following code:
$(document).on('change', '[type="radio"]', function() {
var currentlyValue = $(this).val(); // Get the radio checked value
alert('Currently value: '+currentlyValue); // Show a alert with the current value
});
You can change the selector '[type="radio"]'
for a class or id that you want.
Collection is a interface and Collections is class in Java.util package
if your table is like this
rowId col1 col2 col3 col4
1 a e 12 2
2 b f 42 5
3 a e 32 2
4 b f 44 5
var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});
The name
property is marked as protected
. This was added in TypeScript 1.3 and is now firmly established.
The makeSound
method is marked as abstract
, as is the class. You cannot directly instantiate an Animal
now, because it is abstract. This is part of TypeScript 1.6, which is now officially live.
abstract class Animal {
constructor(protected name: string) { }
abstract makeSound(input : string) : string;
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
makeSound(input : string) : string {
return "sssss"+input;
}
move() {
alert("Slithering...");
super.move(5);
}
}
The old way of mimicking an abstract method was to throw an error if anyone used it. You shouldn't need to do this any more once TypeScript 1.6 lands in your project:
class Animal {
constructor(public name) { }
makeSound(input : string) : string {
throw new Error('This method is abstract');
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
constructor(name) { super(name); }
makeSound(input : string) : string {
return "sssss"+input;
}
move() {
alert("Slithering...");
super.move(5);
}
}
document.querySelector('input').addEventListener('change', function(){_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(){_x000D_
var arrayBuffer = this.result,_x000D_
array = new Uint8Array(arrayBuffer),_x000D_
binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
console.log(binaryString);_x000D_
console.log(arrayBuffer);_x000D_
document.querySelector('#result').innerHTML = arrayBuffer + ' '+arrayBuffer.byteLength;_x000D_
}_x000D_
reader.readAsArrayBuffer(this.files[0]);_x000D_
}, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$tag = 'YOUR_TAG_HERE';
$client_id = "YOUR_CLIENT_ID";
$url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
//Now parse through the $results array to display your results...
foreach($results['data'] as $item){
$image_link = $item['images']['low_resolution']['url'];
echo '<img src="'.$image_link.'" />';
}
I guess Simple solution to this will be:
//X.h
#pragma once
class X
{
public:
X(void);
~X(void);
private:
static bool IsInit;
static bool Init();
};
//X.cpp
#include "X.h"
#include <iostream>
X::X(void)
{
}
X::~X(void)
{
}
bool X::IsInit(Init());
bool X::Init()
{
std::cout<< "ddddd";
return true;
}
// main.cpp
#include "X.h"
int main ()
{
return 0;
}
Is this what you're looking for?
You can directly set the content type like below:
res.writeHead(200, {'Content-Type': 'text/plain'});
For reference go through the nodejs Docs link.
Install the appropriate version of OpenJDK
JAVA_VERSION=8
sudo add-apt-repository -y ppa:openjdk-r/ppa
sudo apt-get update
sudo apt-get -qq install -y openjdk-$JAVA_VERSION-jdk
Set Environment Variables in /etc/profile.d/jdk.sh
JAVA_HOME=/usr/lib/jvm/java-$JAVA_VERSION-openjdk-amd64
echo "export JAVA_HOME=$JAVA_HOME" | sudo tee -a /etc/profile.d/jdk.sh
echo "export J2SDKDIR=$JAVA_HOME" | sudo tee -a /etc/profile.d/jdk.sh
echo "export J2REDIR=$JAVA_HOME/jre" | sudo tee -a /etc/profile.d/jdk.sh
echo "export PATH=$PATH:$JAVA_HOME/bin:$J2REDIR/bin" | sudo tee -a /etc/profile.d/jdk.sh
Check your installation
/bin/bash /etc/profile.d/jdk.sh
java -version
echo $JAVA_HOME
echo $J2REDIR
echo $PATH
First go to the Directory : vendor/plugins/open_flash_chart_2 and DELETE
THEN :
git rm --cached vendor/plugins/open_flash_chart_2
git add .
git commit -m "Message"
git push -u origin master
git status
OUTPUT
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean
with assuming below setting in .config file:
<configuration>
<appSettings>
<add key="PFUserName" value="myusername"/>
<add key="PFPassWord" value="mypassword"/>
</appSettings>
</configuration>
try this:
public class myController : Controller
{
NameValueCollection myKeys = ConfigurationManager.AppSettings;
public void MyMethod()
{
var myUsername = myKeys["PFUserName"];
var myPassword = myKeys["PFPassWord"];
}
}
Indexing a list is done using double bracket, i.e. hypo_list[[1]]
(e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table
does not return a table but a dataframe (see value section in ?read.table
). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.
Note: In R, the index for the first entry is a 1
(not 0
like in some other languages).
Dataframes
l <- list(anscombe, iris) # put dfs in list
l[[1]] # returns anscombe dataframe
anscombe[1:2, 2] # access first two rows and second column of dataset
[1] 10 8
l[[1]][1:2, 2] # the same but selecting the dataframe from the list first
[1] 10 8
Table objects
tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2) # put tables in a list
tbl1[1:2] # access first two elements of table 1
Now with the list
l[[1]] # access first table from the list
1 2 3 4 5
9 11 12 9 9
l[[1]][1:2] # access first two elements in first table
1 2
9 11
Salam, this answer works only in Chrome, cause IE and FF support color transition.
There is no need to make your HTML elements opacity:0
, cause some times they contain text, and no need to double your elements!.
The question with link to an example in jsfiddle needed a small change, that is to put an empty image in .title a
like background:url(link to an empty image);
same as you put it in .title a:hover
but make it empty image, and the code will work.
.title a {
display: block;
width: 340px;
height: 338px;
color: black;
background: url(https://upload.wikimedia.org/wikipedia/commons/5/59/Empty.png) repeat;
/* TRANSISITION */
transition: background 1s;
-webkit-transition: background 1s;
-moz-transition: background 1s;
-o-transition: background 1s;
}
.title a:hover{ background: transparent;
background: url(https://lh3.googleusercontent.com/-p1nr1fkWKUo/T0zUp5CLO3I/AAAAAAAAAWg/jDiQ0cUBuKA/s800/red-pattern.png) repeat;
/* TRANSISITION */
transition: background 1s;
-webkit-transition: background 1s;
-moz-transition: background 1s;
-o-transition: background 1s;
}
Check this out https://jsfiddle.net/Tobasi/vv8q9hum/
In my case, this error happened with a new project.
none of the proposed solutions here worked, so I simply reinstalled all the packages and started working correctly.
As far as I know, Apache supports SNI since Version 2.2.12 Sadly the documentation does not yet reflect that change.
Go for http://wiki.apache.org/httpd/NameBasedSSLVHostsWithSNI until that is finished
The built-in function system.time()
will do it.
Use like: system.time(result <- myfunction(with, arguments))
If you are able to copy the actual SQLite database file to your desktop, you can use this tools to browse the data.
maybe there are some unmerged paths in your git repository that you have to resolve before stashing.
Taking DWins example.
What I often do, particularly when I use many, many different plots with the same colours or size information, is I store them in variables I otherwise never use. This helps me keep my code a little cleaner AND I can change it "globally".
E.g.
clab = 1.5
cmain = 2
caxis = 1.2
plot(1, 1 ,xlab="x axis", ylab="y axis", pch=19,
col.lab="red", cex.lab=clab,
col="green", main = "Testing scatterplots", cex.main =cmain, cex.axis=caxis)
You can also write a function, doing something similar. But for a quick shot this is ideal. You can also store that kind of information in an extra script, so you don't have a messy plot script:
which you then call with setwd("") source("plotcolours.r")
in a file say called plotcolours.r you then store all the e.g. colour or size variables
clab = 1.5
cmain = 2
caxis = 1.2
for colours could use
darkred<-rgb(113,28,47,maxColorValue=255)
as your variable 'darkred' now has the colour information stored, you can access it in your actual plotting script.
plot(1,1,col=darkred)