SQL Server default port is 1434.
To allow remote access I had to release those ports on my firewall:
Protocol | Port
---------------------
UDP | 1050
TCP | 1050
TCP | 1433
UDP | 1434
if you don't know the value of XML Element, you can use
$value = (string) $xml->code[0]->lat;
if (ctype_digit($value)) {
// the value is probably an integer because consists only of digits
}
It works when you need to determine if value is a number, because (string)
will always return string and is_int($value)
returns false
In my case, there were two main sources of memory hogging: the IDE and Gradle:
The IDE's JVM is configured to have a max heap size. You can see this in the lower-right corner of the main interface:
You can reduce this by editing the memory-related settings in the .vmoptions
file. For example, I changed my max heap size to 512MB:
-Xmx512m
Unfortunately, I found that lowering this value increases the frequency of Android Studio temporarily freezing, perhaps to do its garbage collection.
Gradle can also use a lot of RAM after developing for a while. Windows just shows it as Java(TM) Platform SE Binary
:
You can fix this by changing the Gradle JVM options. You can do this on a per-user basis by editing gradle.properties
:
gradle.properties
file, creating it if it doesn't exist:
%USERPROFILE%\.gradle\gradle.properties
~/.gradle/gradle.properties
Update the org.gradle.jvmargs
property, creating it if necessary. I set mine to this:
org.gradle.jvmargs=-Xmx256m -XX:MaxPermSize=256m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
I haven't noticed any difference in build performance for my small project with the max heap size set to 256MB (-Xmx256m
).
Note that you might need to restart Android Studio so the old Gradle process is killed; otherwise you might end up with both running at the same time.
Regarding the emulator taking up a lot of your RAM, your screenshot shows it taking about 800MB. You can choose how much RAM to allocate to the emulator:
This works fine
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$con->query("SET GLOBAL time_zone = 'Asia/Calcutta'");
$con->query("SET time_zone = '+05:30'");
$con->query("SET @@session.time_zone = '+05:30'");
?>
Another way to do this is:
// inflate the layout
View myLayout = LayoutInflater.from(this).inflate(R.layout.MY_LAYOUT,null);
// load the text view
TextView myView = (TextView) myLayout.findViewById(R.id.MY_VIEW);
Using the power of datetime:
from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime('8/18/2008', date_format)
b = datetime.strptime('9/26/2008', date_format)
delta = b - a
print delta.days # that's it
See Python Web Frameworks wiki.
You probably do not need the full stack frameworks, but the remaining list is still quite long.
I wrote an extension method of DataRow which gets me the object via the column name.
public static object Column(this DataRow source, string columnName)
{
var c = source.Table.Columns[columnName];
if (c != null)
{
return source.ItemArray[c.Ordinal];
}
throw new ObjectNotFoundException(string.Format("The column '{0}' was not found in this table", columnName));
}
And its called like this:
DataTable data = LoadDataTable();
foreach (DataRow row in data.Rows)
{
var obj = row.Column("YourColumnName");
Console.WriteLine(obj);
}
Use an array, not a string, as given as guidance in BashFAQ #50.
Using a string is extremely bad security practice: Consider the case where password
(or a where clause in the query, or any other component) is user-provided; you don't want to eval
a password containing $(rm -rf .)
!
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
"${cmd[@]}"
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf 'Proposing to run: '
printf '%q ' "${cmd[@]}"
printf '\n'
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf -v cmd_str '%q ' "${cmd[@]}"
ssh other_host 'bash -s' <<<"$cmd_str"
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf -v cmd_str '%q ' "${cmd[@]}"
ssh other_host "bash -c $cmd_str"
i guess you mean System Programs and Application programs
System Programs makes the hardware run , Applications are for specific tasks
an Example for System Programs are Device Drivers
as for the Applications you can say web browsers , word porcessros etc
Technically speaking the answer is correct, but there is a potential problem remaining.
string test = rb.SelectedValue
is an object and while this implicit cast works. It may not work correction if you were sending it to another method (and granted this may depend on the version of framework, I am unsure) it may not recognize the value.
string test = rb.SelectedValue; //May work fine
SomeMethod(rb.SelectedValue);
where SomeMethod
is expecting a string may not.
Sadly the rb.SelectedValue.ToString();
can save a few unexpected issues.
It wants the full time in DD-MM-YYYY_HH-MM-SS.TT
where TT is the ticks. The exception says it all.
I had the same issue, but I wanted a solution that didn't use locks.
Problem: I have at most one thread consuming from a queue. Multiple producer threads are constantly inserting into the queue and need to notify the consumer if it's waiting. The queue is lock-free so using locks for notification causes unnecessary blocking in producer threads. Each producer thread needs to acquire the lock before it can notify the waiting consumer. I believe I came up with a lock-free solution using LockSupport
and AtomicReferenceFieldUpdater
. If a lock-free barrier exists within the JDK, I couldn't find it. Both CyclicBarrier
and CoundDownLatch
use locks internally from what I could find.
This is my slightly abbreviated code. Just to be clear, this code will only allow one thread to wait at a time. It could be modified to allow for multiple awaiters/consumers by using some type of atomic collection to store multiple owner (a ConcurrentMap
may work).
I have used this code and it seems to work. I have not tested it extensively. I suggest you read the documentation for LockSupport
before use.
/* I release this code into the public domain.
* http://unlicense.org/UNLICENSE
*/
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.LockSupport;
/**
* A simple barrier for awaiting a signal.
* Only one thread at a time may await the signal.
*/
public class SignalBarrier {
/**
* The Thread that is currently awaiting the signal.
* !!! Don't call this directly !!!
*/
@SuppressWarnings("unused")
private volatile Thread _owner;
/** Used to update the owner atomically */
private static final AtomicReferenceFieldUpdater<SignalBarrier, Thread> ownerAccess =
AtomicReferenceFieldUpdater.newUpdater(SignalBarrier.class, Thread.class, "_owner");
/** Create a new SignalBarrier without an owner. */
public SignalBarrier() {
_owner = null;
}
/**
* Signal the owner that the barrier is ready.
* This has no effect if the SignalBarrer is unowned.
*/
public void signal() {
// Remove the current owner of this barrier.
Thread t = ownerAccess.getAndSet(this, null);
// If the owner wasn't null, unpark it.
if (t != null) {
LockSupport.unpark(t);
}
}
/**
* Claim the SignalBarrier and block until signaled.
*
* @throws IllegalStateException If the SignalBarrier already has an owner.
* @throws InterruptedException If the thread is interrupted while waiting.
*/
public void await() throws InterruptedException {
// Get the thread that would like to await the signal.
Thread t = Thread.currentThread();
// If a thread is attempting to await, the current owner should be null.
if (!ownerAccess.compareAndSet(this, null, t)) {
throw new IllegalStateException("A second thread tried to acquire a signal barrier that is already owned.");
}
// The current thread has taken ownership of this barrier.
// Park the current thread until the signal. Record this
// signal barrier as the 'blocker'.
LockSupport.park(this);
// If a thread has called #signal() the owner should already be null.
// However the documentation for LockSupport.unpark makes it clear that
// threads can wake up for absolutely no reason. Do a compare and set
// to make sure we don't wipe out a new owner, keeping in mind that only
// thread should be awaiting at any given moment!
ownerAccess.compareAndSet(this, t, null);
// Check to see if we've been unparked because of a thread interrupt.
if (t.isInterrupted())
throw new InterruptedException();
}
/**
* Claim the SignalBarrier and block until signaled or the timeout expires.
*
* @throws IllegalStateException If the SignalBarrier already has an owner.
* @throws InterruptedException If the thread is interrupted while waiting.
*
* @param timeout The timeout duration in nanoseconds.
* @return The timeout minus the number of nanoseconds that passed while waiting.
*/
public long awaitNanos(long timeout) throws InterruptedException {
if (timeout <= 0)
return 0;
// Get the thread that would like to await the signal.
Thread t = Thread.currentThread();
// If a thread is attempting to await, the current owner should be null.
if (!ownerAccess.compareAndSet(this, null, t)) {
throw new IllegalStateException("A second thread tried to acquire a signal barrier is already owned.");
}
// The current thread owns this barrier.
// Park the current thread until the signal. Record this
// signal barrier as the 'blocker'.
// Time the park.
long start = System.nanoTime();
LockSupport.parkNanos(this, timeout);
ownerAccess.compareAndSet(this, t, null);
long stop = System.nanoTime();
// Check to see if we've been unparked because of a thread interrupt.
if (t.isInterrupted())
throw new InterruptedException();
// Return the number of nanoseconds left in the timeout after what we
// just waited.
return Math.max(timeout - stop + start, 0L);
}
}
To give a vague example of usage, I'll adopt james large's example:
SignalBarrier barrier = new SignalBarrier();
Consumer thread (singular, not plural!):
try {
while(!conditionIsTrue()) {
barrier.await();
}
doSomethingThatRequiresConditionToBeTrue();
} catch (InterruptedException e) {
handleInterruption();
}
Producer thread(s):
doSomethingThatMakesConditionTrue();
barrier.signal();
You can use as below,
Select X.a, X.b, Y.c from (
Select X.a as a, sum (b) as sum_b from name_table X
group by X.a)X
left join from name_table Y on Y.a = X.a
Example;
CREATE TABLE #products (
product_name VARCHAR(MAX),
code varchar(3),
list_price [numeric](8, 2) NOT NULL
);
INSERT INTO #products VALUES ('paku', 'ACE', 2000)
INSERT INTO #products VALUES ('paku', 'ACE', 2000)
INSERT INTO #products VALUES ('Dinding', 'ADE', 2000)
INSERT INTO #products VALUES ('Kaca', 'AKB', 2000)
INSERT INTO #products VALUES ('paku', 'ACE', 2000)
--SELECT * FROM #products
SELECT distinct x.code, x.SUM_PRICE, product_name FROM (SELECT code, SUM(list_price) as SUM_PRICE From #products
group by code)x
left join #products y on y.code=x.code
DROP TABLE #products
As per @Nitsew's answer, Create your personal access token and use your token as your username and enter with blank password.
Later you won't need any credentials to access all your private repo(s).
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
json_encode works only with UTF-8 data. You'll have to ensure that your data is in UTF-8. alternatively, you can use iconv() to convert your results to UTF-8 before feeding them to json_encode()
These are the directories that gcc looks in by default for the specified header files ( given that the header files are included in chevrons <>); 1. /usr/local/include/ --used for 3rd party header files. 2. /usr/include/ -- used for system header files.
If in case you decide to put your custom header file in a place other than the above mentioned directories, you can include them as follows: 1. using quotes ("./custom_header_files/foo.h") with files path, instead of chevrons in the include statement. 2. using the -I switch when compiling the code. gcc -I /home/user/custom_headers/ -c foo.c -p foo.o Basically the -I switch tells the compiler to first look in the directory specified with the -I switch ( before it checks the standard directories).When using the -I switch the header files may be included using chevrons.
Setting the body margins to 0, the width of the outer container to 100%, and using an inner container with 50px left/right margins seems to work.
<style>
body {
margin: 0;
padding: 0;
}
.full-width
{
width: 100%;
}
.innerContainer
{
margin: 0px 50px 0px 50px;
}
</style>
<body>
<div class="full-width" style="background-color: #ff0000;">
<div class="innerContainer" style="background-color: #00ff00;">
content here
</div>
</div>
</body>
If you get this error in PowerShell, it's most likely because you're using Resolve-Path
to resolve a remote path, e.g.
Resolve-Path \\server\share\path
In this case, Resolve-Path
returns an object that, when converted to a string, doesn't return a valid path. It returns PowerShell's internal path:
> [string](Resolve-Path \\server\share\path)
Microsoft.PowerShell.Core\FileSystem::\\server\share\path
The solution is to use the ProviderPath
property on the object returned by Resolve-Path
:
> Resolve-Path \\server\share\path | Select-Object -ExpandProperty PRoviderPath
\\server\share\path
> (Resolve-Path \\server\share\path).ProviderPath
\\server\share\path
In your flask code, you should ideally specify the MIME type as often as possible, as well:
return html_page_str, 200, {'ContentType':'text/html'}
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
...etc
Call this in the project:
svn diff -r REVNO:HEAD --summarize
REVNO
is the start revision number and HEAD
is the end revision number. If HEAD is equal to the last revision number, it can skip it.
The command returns a list with all files that are changed/added/deleted in this revision period.
The command can be called with the URL revision parameter to check changes like this:
svn diff -r REVNO:HEAD --summarize SVN_URL
Update: 22.01.2019, 13.41 I optimized the solution by jhay, which also supports closing and opening same or different dialogs when for example stepping from one detail data to another forwards or backwards.
(function ($, window) {
'use strict';
var MultiModal = function (element) {
this.$element = $(element);
this.modalIndex = 0;
};
MultiModal.BASE_ZINDEX = 1040;
/* Max index number. When reached just collate the zIndexes */
MultiModal.MAX_INDEX = 5;
MultiModal.prototype.show = function (target) {
var that = this;
var $target = $(target);
// Bootstrap triggers the show event at the beginning of the show function and before
// the modal backdrop element has been created. The timeout here allows the modal
// show function to complete, after which the modal backdrop will have been created
// and appended to the DOM.
// we only want one backdrop; hide any extras
setTimeout(function () {
/* Count the number of triggered modal dialogs */
that.modalIndex++;
if (that.modalIndex >= MultiModal.MAX_INDEX) {
/* Collate the zIndexes of every open modal dialog according to its order */
that.collateZIndex();
}
/* Modify the zIndex */
$target.css('z-index', MultiModal.BASE_ZINDEX + (that.modalIndex * 20) + 10);
/* we only want one backdrop; hide any extras */
if (that.modalIndex > 1)
$('.modal-backdrop').not(':first').addClass('hidden');
that.adjustBackdrop();
});
};
MultiModal.prototype.hidden = function (target) {
this.modalIndex--;
this.adjustBackdrop();
if ($('.modal.in').length === 1) {
/* Reset the index to 1 when only one modal dialog is open */
this.modalIndex = 1;
$('.modal.in').css('z-index', MultiModal.BASE_ZINDEX + 10);
var $modalBackdrop = $('.modal-backdrop:first');
$modalBackdrop.removeClass('hidden');
$modalBackdrop.css('z-index', MultiModal.BASE_ZINDEX);
}
};
MultiModal.prototype.adjustBackdrop = function () {
$('.modal-backdrop:first').css('z-index', MultiModal.BASE_ZINDEX + (this.modalIndex * 20));
};
MultiModal.prototype.collateZIndex = function () {
var index = 1;
var $modals = $('.modal.in').toArray();
$modals.sort(function(x, y)
{
return (Number(x.style.zIndex) - Number(y.style.zIndex));
});
for (i = 0; i < $modals.length; i++)
{
$($modals[i]).css('z-index', MultiModal.BASE_ZINDEX + (index * 20) + 10);
index++;
};
this.modalIndex = index;
this.adjustBackdrop();
};
function Plugin(method, target) {
return this.each(function () {
var $this = $(this);
var data = $this.data('multi-modal-plugin');
if (!data)
$this.data('multi-modal-plugin', (data = new MultiModal(this)));
if (method)
data[method](target);
});
}
$.fn.multiModal = Plugin;
$.fn.multiModal.Constructor = MultiModal;
$(document).on('show.bs.modal', function (e) {
$(document).multiModal('show', e.target);
});
$(document).on('hidden.bs.modal', function (e) {
$(document).multiModal('hidden', e.target);
});}(jQuery, window));
The following code will help you
mvv_count_df.select('mvv').rdd.map(lambda row : row[0]).collect()
Most modern regex implementations allow for recursive regexpressions, which can verify a complete JSON serialized structure. The json.org specification makes it quite straightforward.
$pcre_regex = '
/
(?(DEFINE)
(?<number> -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
(?<boolean> true | false | null )
(?<string> " ([^"\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
(?<array> \[ (?: (?&json) (?: , (?&json) )* )? \s* \] )
(?<pair> \s* (?&string) \s* : (?&json) )
(?<object> \{ (?: (?&pair) (?: , (?&pair) )* )? \s* \} )
(?<json> \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
)
\A (?&json) \Z
/six
';
It works quite well in PHP with the PCRE functions . Should work unmodified in Perl; and can certainly be adapted for other languages. Also it succeeds with the JSON test cases.
A simpler approach is the minimal consistency check as specified in RFC4627, section 6. It's however just intended as security test and basic non-validity precaution:
var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
eval('(' + text + ')');
Are you hosting the site on iis? if so make sure the account your website runs under has access to local file system?
Straight from msdn .....
The Network Service account has Read and Execute permissions on the IIS server root folder by default. The IIS server root folder is named Wwwroot. This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.
To provide access to an ASP.NET application running as Network Service, you must grant access to the Network Service account.
To grant read, write, and modify permissions to a specific file
Click here for more
You can add elements of a list
to a set
like this:
>>> foo = set(range(0, 4))
>>> foo
set([0, 1, 2, 3])
>>> foo.update(range(2, 6))
>>> foo
set([0, 1, 2, 3, 4, 5])
To be honest I have to add my 2 cents.
You can do it with msbuild.exe. There are many version of the msbuild.exe.
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\msbuild.exe C:\Windows\Microsoft.NET\Framework64\v3.5\msbuild.exe C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
C:\Windows\Microsoft.NET\Framework\v2.0.50727\msbuild.exe C:\Windows\Microsoft.NET\Framework\v3.5\msbuild.exe C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
Use version you need. Basically you have to use the last one.
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
So how to do it.
Run the COMMAND window
Input the path to msbuild.exe
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
"C:\Users\Clark.Kent\Documents\visual studio 2012\Projects\WpfApplication1\WpfApplication1.sln"
Add any flags you need after the solution path.
Press ENTER
Note you can get help about all possible flags like
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe /help
This webpage have an explanation and a solution.
The solution is:
To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:
vm.overcommit_memory = 2
vm.overcommit_ratio = 80
In my case, I config zoo.cfg like this:
server.1=host-1:2888:3888
server.2=host-2:2888:3888
server.3=host-3:2888:3888
But, in host-1, I config host-1 resolve to 127.0.0.1 in /etc/hosts:
127.0.0.1 localhost host-1
which may results other hosts can't communicate with it. Resolve host-1 to its real ip solved this problem.
Hope this can help.
I think
SELECT CALL.* FROM CALL LEFT JOIN Phone_book ON
CALL.id = Phone_book.id WHERE Phone_book.name IS NULL
Options 1 to 3 have issues with multiple whitespace (but are simple).
That is the reason to develop options 4 and 5, which process multiple white spaces with no problem.
Of course, if options 4 or 5 are used with n=0
both will preserve any leading whitespace as n=0
means no splitting.
A simple cut solution (works with single delimiters):
$ echo '1 2 3 4 5 6 7 8' | cut -d' ' -f4-
4 5 6 7 8
Forcing an awk re-calc sometimes solve the problem (works with some versions of awk) of added leading spaces:
$ echo '1 2 3 4 5 6 7 8' | awk '{ $1=$2=$3="";$0=$0;} NF=NF'
4 5 6 7 8
Printing each field formated with printf
will give more control:
$ echo ' 1 2 3 4 5 6 7 8 ' |
awk -v n=3 '{ for (i=n+1; i<=NF; i++){printf("%s%s",$i,i==NF?RS:OFS);} }'
4 5 6 7 8
However, all previous answers change all FS between fields to OFS. Let's build a couple of solutions to that.
A loop with sub to remove fields and delimiters is more portable, and doesn't trigger a change of FS to OFS:
$ echo ' 1 2 3 4 5 6 7 8 ' |
awk -v n=3 '{ for(i=1;i<=n;i++) { sub("^["FS"]*[^"FS"]+["FS"]+","",$0);} } 1 '
4 5 6 7 8
NOTE: The "^["FS"]*" is to accept an input with leading spaces.
It is quite possible to build a solution that does not add extra leading or trailing whitespace, and preserve existing whitespace using the function gensub
from GNU awk, as this:
$ echo ' 1 2 3 4 5 6 7 8 ' |
awk -v n=3 '{ print gensub("["FS"]*([^"FS"]+["FS"]+){"n"}","",1); }'
4 5 6 7 8
It also may be used to swap a field list given a count n
:
$ echo ' 1 2 3 4 5 6 7 8 ' |
awk -v n=3 '{ a=gensub("["FS"]*([^"FS"]+["FS"]+){"n"}","",1);
b=gensub("^(.*)("a")","\\1",1);
print "|"a"|","!"b"!";
}'
|4 5 6 7 8 | ! 1 2 3 !
Of course, in such case, the OFS is used to separate both parts of the line, and the trailing white space of the fields is still printed.
Note1: ["FS"]*
is used to allow leading spaces in the input line.
You can use a single group for seconds/minutes. The following expression may suit your needs:
([0-9]+)\s*(seconds|minutes)
Edited on 2014/8/25: Here was where I forked it.
Thanks @anvarik.
Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @
<div ng-controller="MyCtrl">
<h2>Parent Scope</h2>
<input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>
<br><br>
<!-- attribute-foo binds to a DOM attribute which is always
a string. That is why we are wrapping it in curly braces so
that it can be interpolated. -->
<my-component attribute-foo="{{foo}}" binding-foo="foo"
isolated-expression-foo="updateFoo(newFoo)" >
<h2>Attribute</h2>
<div>
<strong>get:</strong> {{isolatedAttributeFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedAttributeFoo">
<i>// This does not update the parent scope.</i>
</div>
<h2>Binding</h2>
<div>
<strong>get:</strong> {{isolatedBindingFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedBindingFoo">
<i>// This does update the parent scope.</i>
</div>
<h2>Expression</h2>
<div>
<input ng-model="isolatedFoo">
<button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
<i>// And this calls a function on the parent scope.</i>
</div>
</my-component>
</div>
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
isolatedAttributeFoo:'@attributeFoo',
isolatedBindingFoo:'=bindingFoo',
isolatedExpressionFoo:'&'
}
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.foo = 'Hello!';
$scope.updateFoo = function (newFoo) {
$scope.foo = newFoo;
}
}]);
<Spinner
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="16dp"
android:paddingLeft="10dp"
android:spinnerMode="dropdown" />
break
is used when you want to exit from the loop, while return
is used to go back to the step where it was called or to stop further execution.
On Linux you can run $(dirname $(dirname $(readlink -f $(which javac))))
On Mac you can run $(dirname $(readlink $(which javac)))/java_home
I'm not sure about windows but I imagine where javac
would get you pretty close
As others have said you definitely want to call Dispose
if the class implements IDisposable
. I take a fairly rigid position on this. Some might claim that calling Dispose
on DataSet
, for example, is pointless because they disassembled it and saw that it did not do anything meaningful. But, I think there are fallacies abound in that argument.
Read this for an interesting debate by respected individuals on the subject. Then read my reasoning here why I think Jeffery Richter is in the wrong camp.
Now, on to whether or not you should set a reference to null
. The answer is no. Let me illustrate my point with the following code.
public static void Main()
{
Object a = new Object();
Console.WriteLine("object created");
DoSomething(a);
Console.WriteLine("object used");
a = null;
Console.WriteLine("reference set to null");
}
So when do you think the object referenced by a
is eligible for collection? If you said after the call to a = null
then you are wrong. If you said after the Main
method completes then you are also wrong. The correct answer is that it is eligible for collection sometime during the call to DoSomething
. That is right. It is eligible before the reference is set to null
and perhaps even before the call to DoSomething
completes. That is because the JIT compiler can recognize when object references are no longer dereferenced even if they are still rooted.
Something like this:
class Class {
// visibility will default to private unless you specify it
struct Struct {
//specify members here;
};
};
It comes down to whether the feature is used by one person or if others are working off of it.
You can force the push after the rebase if it's just you:
git push origin feature -f
However, if others are working on it, you should merge and not rebase off of master.
git merge master
git push origin feature
This will ensure that you have a common history with the people you are collaborating with.
On a different level, you should not be doing back-merges. What you are doing is polluting your feature branch's history with other commits that don't belong to the feature, making subsequent work with that branch more difficult - rebasing or not.
This is my article on the subject called branch per feature.
Hope this helps.
If you use moment.js, they have an add function. Here's the link - https://momentjs.com/docs/#/manipulating/add/
moment().add(7, 'months');
I also wrote a recursive function based on paxdiablo's answer to add a variable number of months. By default this function would add a month to the current date.
function addMonths(after = 1, now = new Date()) {
var current;
if (now.getMonth() == 11) {
current = new Date(now.getFullYear() + 1, 0, 1);
} else {
current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}
return (after == 1) ? current : addMonths(after - 1, new Date(now.getFullYear(), now.getMonth() + 1, 1))
}
Example
console.log('Add 3 months to November', addMonths(3, new Date(2017, 10, 27)))
Output -
Add 3 months to November Thu Feb 01 2018 00:00:00 GMT-0800 (Pacific Standard Time)
I only found one way that worked...
$quote = $pdomodel->executeQuery("SELECT * FROM MyTable");
//if (!is_array($quote)) { didn't work
//if (!isset($quote)) { didn't work
if (count($quote) == 0) { //yep the count worked.
echo 'Record does not exist.';
die;
}
Working with thicker strokes gets a bit messy, if you have the pleasure of sass try this mixin, not perfect and depending on stroke weight it generates a fair amount of css.
@mixin stroke($width, $colour: #000000) {
$shadow: 0 0 0 $colour; // doesn't do anything but I couldn't work out how to create a blank string and maintain commas
@for $i from 0 through $width {
$shadow: $shadow,
-$i + px -$width + px 0 $colour,
$i + px -$width + px 0 $colour,
-$i + px $width + px 0 $colour,
$i + px $width + px 0 $colour,
-$width + px -$i + px 0 $colour,
$width + px -$i + px 0 $colour,
-$width + px $i + px 0 $colour,
$width + px $i + px 0 $colour,
}
text-shadow: $shadow;
}
To list all unpushed commit in all branches easily you can use this command:
git log --branches @{u}..
In my case i had to move the html code of the element i wanted at the front at the end of the html file, because if one element has z-index and the other doesn't have z index it doesn't work.
Your resource probably use a self-signed SSL certificate over HTTPS protocol. Chromium, so Google Chrome block by default this kind of resource considered unsecure.
You can bypass this this way :
https://www.domain.com
, open a new tab in chrome and go to https://www.domain.com
.The problem as you can guess, is that each visitor of your website has to do this task to access your frame.
You can notice that chrome will block your URL for each navigation session, while chrome can memorise for ever that you trust this domain.
If your frame can be accessed by HTTP rather than HTTPS, I suggest you to use it, so this problem will be solved.
The best way to handle this (with ease and no additional software) is with Excel - but using Powerpivot (which has MSFT Power Query embedded). Simply create a new Power Pivot data model that attaches to your large csv or text file. You will then be able to import multi-million rows into memory using the embedded X-Velocity (in-memory compression) engine. The Excel sheet limit is not applicable - as the X-Velocity engine puts everything up in RAM in compressed form. I have loaded 15 million rows and filtered at will using this technique. Hope this helps someone... - Jaycee
Wonderful answer! I needed to fill in the empty cells in a column where there were titles in cells that applied to the empty cells below until the next title cell.
I used your code above to develop the code that is below my example sheet here. I applied this code as a macro ctl/shft/D to rapidly run down the column copying the titles.
--- Example Spreadsheet ------------ Title1 is copied to rows 2 and 3; Title2 is copied to cells below it in rows 5 and 6. After the second run of the Macro the active cell is the Title3 cell.
' **row** **Column1** **Column2**
' 1 Title1 Data 1 for title 1
' 2 Data 2 for title 1
' 3 Data 3 for title 1
' 4 Title2 Data 1 for title 2
' 5 Data 2 for title 2
' 6 Data 3 for title 2
' 7 Title 3 Data 1 for title 3
----- CopyDown code ----------
Sub CopyDown()
Dim Lastrow As String, FirstRow As String, strtCell As Range
'
' CopyDown Macro
' Copies the current cell to any empty cells below it.
'
' Keyboard Shortcut: Ctrl+Shift+D
'
Set strtCell = ActiveCell
FirstRow = strtCell.Address
' Lastrow is address of the *list* of empty cells
Lastrow = Range(Selection, Selection.End(xlDown).Offset(-1, 0)).Address
' MsgBox Lastrow
Range(Lastrow).Formula = strtCell.Formula
Range(Lastrow).End(xlDown).Select
End Sub
I did this plunker to explore one way to do what you want.
Here I get mystyle
from the parent component but you can get it from a service.
import {Component, View} from 'angular2/angular2'
@Component({
selector: '[my-person]',
inputs: [
'name',
'mystyle: customstyle'
],
host: {
'[style.backgroundColor]': 'mystyle.backgroundColor'
}
})
@View({
template: `My Person Component: {{ name }}`
})
export class Person {}
hash.store(key, value) - Stores a key-value pair in hash.
Example:
hash #=> {"a"=>9, "b"=>200, "c"=>4}
hash.store("d", 42) #=> 42
hash #=> {"a"=>9, "b"=>200, "c"=>4, "d"=>42}
unchecked the "Automatically detect settings" in the Local Area Network Settings (found in "Internet Options" > Connections > LAN Settings.
You shouldn't use CascadeType.ALL
on @ManyToOne
since entity state transitions should propagate from parent entities to child ones, not the other way around.
The @ManyToOne
side is always the Child association since it maps the underlying Foreign Key column.
Therefore, you should move the CascadeType.ALL
from the @ManyToOne
association to the @OneToMany
side, which should also use the mappedBy
attribute since it's the most efficient one-to-many table relationship mapping.
pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.
If you need a lot of decimal numbers, in this example 17, I share with you MySql code:
This is the calculate:
=(9/1147)*100
SELECT TRUNCATE(((CAST(9 AS DECIMAL(30,20))/1147)*100),17);
I ended up keeping Link and adding the reload to the Link's onClick event with a timeout like this:
function refreshPage() {
setTimeout(()=>{
window.location.reload(false);
}, 500);
console.log('page to reload')
}
<Link to={{pathname:"/"}} onClick={refreshPage}>Home</Link>
without the timeout, the refresh function would run first
it turns out that I got this error because my requested module is not bundled in the minification prosses
due to path misspelling
so make sure that your module exists in minified js file (do search for a word within it to be sure)
You can use postman.
Where select Post as method. and In Request Body send JSON Object.
The verbose
configuration option might allow you to see what you want. There is an example in the documentation.
NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.
When use CMS GC in jdk1.8 will appeare this error, i change the G1 Gc solve this problem.
-Xss512k -Xms6g -Xmx6g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=70 -XX:NewRatio=1 -XX:SurvivorRatio=6 -XX:G1ReservePercent=10 -XX:G1HeapRegionSize=32m -XX:ConcGCThreads=6 -Xloggc:gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps
import csv
inf = csv.reader(open('yourfile.csv','r'))
for row in inf:
print row[1]
I am using: Apache Commons Lang: StringUtils.ordinalIndexOf()
StringUtils.ordinalIndexOf("Java Language", "a", 2)
If you are creating a new app instead of converting an existing one, the easiest way to create WAR based spring boot application is through Spring Initializr.
It auto-generates the application for you. By default it creates Jar, but in the advanced options, you can select to create WAR. This war can be also executed directly.
Even easier is to create the project from IntelliJ IDEA directly:
File ? New Project ? Spring Initializr
None of the answers posted here worked for me.
In my case the problem was, by the one hand, that the .conf file (/etc/apache2/sites-available/default-ssl.conf or /etc/apache2/sites-available/000-default.conf) did not contain the directive AllowOverride All
for the site directory, which caused the .htaccess to not been processed. To solve this, add:
<Directory /var/www/html/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
On the other hand, the problem was that the .htaccess was created by the root user, and therefore the apache user could not read it. So, changing the file owner solved definitely the problem:
chown www-data:www-data .htaccess
Option 1- From Studio
In Android Studio, go to File > Project Structure. Then select the "project" tab on the left.
Your Gradle version will be displayed here.
Option 2- gradle-wrapper.properties
If you are using the Gradle wrapper, then your project will have a gradle/wrapper/gradle-wrapper.properties
folder.
This file should contain a line like this:
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
This determines which version of Gradle you are using. In this case, gradle-2.2.1-all.zip
means I am using Gradle 2.2.1.
Option 3- Local Gradle distribution
If you are using a version of Gradle installed on your system instead of the wrapper, you can run gradle --version
to check.
We can also use the json
module in the case when dictionaries or some other data can be easily mapped to JSON format.
import json
# Serialize data into file:
json.dump( data, open( "file_name.json", 'w' ) )
# Read data from file:
data = json.load( open( "file_name.json" ) )
This solution brings many benefits, eg works for Python 2.x and Python 3.x in an unchanged form and in addition, data saved in JSON format can be easily transferred between many different platforms or programs. This data are also human-readable.
You need to group on the grade field. This query should give you what your looking for in pretty much any database.
Select Grade, CountofGrade / sum(CountofGrade) *100
from
(
Select Grade, Count(*) as CountofGrade
From Grades
Group By Grade) as sub
Group by Grade
You should specify the system you're using.
Your list:
List<MyCustomObject> myCustomObjectList;
Your JSONArray:
// Don't need to loop through it. JSONArray constructor do it for you.
new JSONArray(myCustomObjectList)
Your response:
return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList));
Your post/put http body request would be like this:
{
"yourCustomKey: [
{
"myCustomObjectProperty": 1
},
{
"myCustomObjectProperty": 2
}
]
}
create .env using command!
composer run post-root-package-install or sudo composer run post-root-package-install
Assuming that your enum is already defined, you can create an array of pairs:
std::pair<QTask::TASK, QString> pairs [] = {
std::pair<OS_type, string>(Linux, "Linux"),
std::pair<OS_type, string>(Windows, "Windows"),
std::pair<OS_type, string>(Apple, "Apple"),
};
Now, you can create a map:
std::map<OS_type, std::string> stdmap(pairs, pairs + sizeof(pairs) / sizeof(pairs[0]));
Now, you can use the map. If your enum is changed, you have to add/remove pair from array pairs[]. I thinkk that it is the most elegant way to obtain a string from enum in C++.
Try this
Check this How do i get the gmt time in php
date_default_timezone_set("UTC");
echo date("Y-m-d H:i:s", time());
In your example the $ has no special significance other than being a character of the name.
However, in ECMAScript 6 (ES6) the $ may represent a Template Literal
var user = 'Bob'
console.log(`We love ${user}.`); //Note backticks
// We love Bob.
Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td>
that have $
inside. Example:
using nth-child in tables tr td
html
<tr>
<td> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
table tr td[data-content='$'] {_x000D_
background-color: #333;_x000D_
color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>B</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>C</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Just to point out that cordova brings in it's own npm with the graceful-fs dependency, so if you use Cordova make sure that it is the latest so you get the latest graceful-fs from that as well.
I tried the below stuff and it really works well HTML
input.hai {_x000D_
width: 450px;_x000D_
padding-left: 25px;_x000D_
margin: 15px;_x000D_
height: 25px;_x000D_
background-image: url('https://cdn4.iconfinder.com/data/icons/casual-events-and-opinions/256/User-512.png') ;_x000D_
background-size: 20px 20px;_x000D_
background-repeat: no-repeat;_x000D_
background-position: left;_x000D_
background-color: grey;_x000D_
}
_x000D_
<div >_x000D_
_x000D_
<input class="hai" placeholder="Search term">_x000D_
_x000D_
</div>
_x000D_
There is also configuration option: query_cache_size=0
To disable the query cache at server startup, set the query_cache_size system variable to 0. By disabling the query cache code, there is no noticeable overhead. If you build MySQL from source, query cache capabilities can be excluded from the server entirely by invoking configure with the --without-query-cache option.
That line should be sufficient:
BooleanUtils.and(boolean... array)
but to calm the link-only purists:
Performs an and on a set of booleans.
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
#An example for counting matched groups
import re
pattern = re.compile(r'(\w+).(\d+).(\w+).(\w+)', re.IGNORECASE)
search_str = "My 11 Char String"
res = re.match(pattern, search_str)
print(len(res.groups())) # len = 4
print (res.group(1) ) #My
print (res.group(2) ) #11
print (res.group(3) ) #Char
print (res.group(4) ) #String
This is a way:
values = [1, 2, 3]
Foo.__table__.insert().execute([{'bar': x} for x in values])
This will insert like this:
INSERT INTO `foo` (`bar`) VALUES (1), (2), (3)
Reference: The SQLAlchemy FAQ includes benchmarks for various commit methods.
There is an old plugin called HEX Editor here.
According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.
I would suggest the following simple approach for conversion:
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:
date += timedelta(days=10)
date -= timedelta(days=5)
And convert back using:
s = date.strftime("%Y%m%d")
To convert the integer to a string safely, use:
s = "{0:-08d}".format(i)
This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).
Further reference: datetime objects, timedelta objects
I sometimes use an approach that resembles to the answers using property injection, but keeps the code cleaner. Instead of having a base class/interface with a set of properties, it only contains a (virtual) Initialize()-method that acts as a "poor man's constructor". Then you can let each class handle it's own initialization just as a constructor would, which also adds a convinient way of handling inheritance chains.
If often find myself in situations where I want each class in the chain to initialize its unique properties, and then call its parent's Initialize()-method which in turn initializes the parent's unique properties and so forth. This is especially useful when having different classes, but with a similar hierarchy, for example business objects that are mapped to/from DTO:s.
Example that uses a common Dictionary for initialization:
void Main()
{
var values = new Dictionary<string, int> { { "BaseValue", 1 }, { "DerivedValue", 2 } };
Console.WriteLine(CreateObject<Base>(values).ToString());
Console.WriteLine(CreateObject<Derived>(values).ToString());
}
public T CreateObject<T>(IDictionary<string, int> values)
where T : Base, new()
{
var obj = new T();
obj.Initialize(values);
return obj;
}
public class Base
{
public int BaseValue { get; set; }
public virtual void Initialize(IDictionary<string, int> values)
{
BaseValue = values["BaseValue"];
}
public override string ToString()
{
return "BaseValue = " + BaseValue;
}
}
public class Derived : Base
{
public int DerivedValue { get; set; }
public override void Initialize(IDictionary<string, int> values)
{
base.Initialize(values);
DerivedValue = values["DerivedValue"];
}
public override string ToString()
{
return base.ToString() + ", DerivedValue = " + DerivedValue;
}
}
You should compare dates in sql just like you compare number values,
SELECT * FROM Product_sales
WHERE From_date >= '2013-01-01' AND To_date <= '2013-01-20'
simply multiplying by -1 works in both ways ...
>>> -10 * -1
10
>>> 10 * -1
-10
Yes you can convert it back. You can try:
date("Y-m-d H:i:s", 1388516401);
The logic behind this conversion from date to an integer is explained in strtotime in PHP:
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
For example, strtotime("1970-01-01 00:00:00")
gives you 0 and strtotime("1970-01-01 00:00:01")
gives you 1.
This means that if you are printing strtotime("2014-01-01 00:00:01")
which will give you output 1388516401
, so the date 2014-01-01 00:00:01
is 1,388,516,401 seconds after January 1 1970 00:00:00 UTC.
I found a good Blog post about the behaviour of Hibernate in this kind of object mappings: http://blog.eyallupu.com/2010/06/hibernate-exception-simultaneously.html
list(set(df[['Col1', 'Col2']].as_matrix().reshape((1,-1)).tolist()[0]))
The output will be ['Mary', 'Joe', 'Steve', 'Bob', 'Bill']
From the manual:
If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).
The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.
$qry = '
INSERT INTO non-existant-table (id, score)
SELECT id, 40
FROM another-non-existant-table
WHERE description LIKE "%:search_string%"
AND available = "yes"
ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());
Simplest solution:
Just add quotes, I really don't know why it's not auto-implemented by Spring boot when response type defined as application/json, but it works great.
@PostMapping("/create")
public String foo()
{
String result = "something"
return "\"" + result + "\"";
}
Here is an easy way to get only unique raw values from array. If you convert the array to Set and after this, do the conversion from Set to array. This conversion works only for raw values, for objects in the array it is not valid. Try it by yourself.
let myObj1 = {
name: "Dany",
age: 35,
address: "str. My street N5"
}
let myObj2 = {
name: "Dany",
age: 35,
address: "str. My street N5"
}
var myArray = [55, 44, 65, myObj1, 44, myObj2, 15, 25, 65, 30];
console.log(myArray);
var mySet = new Set(myArray);
console.log(mySet);
console.log(mySet.size === myArray.length);// !! The size differs because Set has only unique items
let uniqueArray = [...mySet];
console.log(uniqueArray);
// Here you will see your new array have only unique elements with raw
// values. The objects are not filtered as unique values by Set.
// Try it by yourself.
Go to Project Properties and under Build Make sure that the "Optimize Code" checkbox is unchecked.
Also, set the "Debug Info" dropdown to "Full" in the Advanced Options (Under Build tab).
since others have answered how to do it, I'll answer how it happens line by line.
with FileOpenerCM('file.txt') as fp: # is equal to "with open('file.txt') as fp:"
fp.write('dummy text')
this is a so-called context manager
, anything that comes with a with
block is a context manager. so let's see how this happens under the hood.
class FileOpenerCM:
def __init__(self, file, mode='w'):
self.file = open(file, mode)
def __enter__(self):
return self.file
def __exit__(self, exc_type, exc_value, exc_traceback):
self.file.close()
the first method __init__
is (as you all know) the initialization method of an object. whenever an object is created obj.__init__
is definitely called. and that's the place where you put your all the init kinda code.
the second method __enter__
is a bit interesting. some of you might not have seen it because it is a specific method for context managers. what it returns is the value to be assigned to the variable after the as
keyword. in our case, fp
.
the last method is the method to run after an error is captured or if the code exits the with block. exc_type
, exc_value
, exc_traceback
variables are the variables that hold the values of the errors that occurred inside with block. for example,
exc_type: TypeError
exc_value: unsupported operand type(s) for +: 'int' and 'str
exc_traceback: <traceback object at 0x6af8ee10bc4d>
from the first two variables, you can get info enough info about the error. honestly, I don't know the use of the third variable, but for me, the first two are enough. if you want to do more research on context managers surely you can do it and note that writing classes are not the only way to write context managers. with contextlib you can write context managers through functions(actually generators) as well. it's totally up to you to have a look at it. you can surely try generator functions with contextlib but as I see classes are much cleaner.
I've got this problem too. My solution is use Expanded
widget to expand remain space.
new Column(
children: <Widget>[
new Expanded(
child: horizontalList,
)
],
);
To create a proper, mysql, varchar 32 GUID
SecureRandom.uuid.gsub('-','').upcase
This one just worked for me....
The error message displayed is:
“# 1146 – Table ‘phpmyadmin.pma_table_uiprefs’ doesn’t exist“
on your programme files,locate the configuration file config.inc.php
phpmyadmin
Then trace the file $Cfg ['Servers'] [$ i] ['table_uiprefs'] = ‘pma_table_uiprefs’;
and replace it to the code : $cfg ['Servers'] [$ i] ['pma__table_uiprefs'] = ‘pma__table_uiprefs’;
restart your XAMMP and start localhost
solved.
You can run ruby commands in one line with the -e
flag:
ruby -e "puts 'hi'"
Check the man page for more information.
To load your data in WebView. Call loadData() method of WebView
webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");
You can check this example
http://developer.android.com/reference/android/webkit/WebView.html
You seem to be unnecessarily setting properties on your ComboBox
. You can remove the DisplayMemberPath
and SelectedValuePath
properties which have different uses. It might be an idea for you to take a look at the Difference between SelectedItem, SelectedValue and SelectedValuePath post here for an explanation of these properties. Try this:
<ComboBox Name="cbxSalesPeriods"
ItemsSource="{Binding SalesPeriods}"
SelectedItem="{Binding SelectedSalesPeriod}"
IsSynchronizedWithCurrentItem="True"/>
Furthermore, it is pointless using your displayPeriod
property, as the WPF Framework would call the ToString
method automatically for objects that it needs to display that don't have a DataTemplate
set up for them explicitly.
UPDATE >>>
As I can't see all of your code, I cannot tell you what you are doing wrong. Instead, all I can do is to provide you with a complete working example of how to achieve what you want. I've removed the pointless displayPeriod
property and also your SalesPeriodVO
property from your class as I know nothing about it... maybe that is the cause of your problem??. Try this:
public class SalesPeriodV
{
private int month, year;
public int Year
{
get { return year; }
set
{
if (year != value)
{
year = value;
NotifyPropertyChanged("Year");
}
}
}
public int Month
{
get { return month; }
set
{
if (month != value)
{
month = value;
NotifyPropertyChanged("Month");
}
}
}
public override string ToString()
{
return String.Format("{0:D2}.{1}", Month, Year);
}
public virtual event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(params string[] propertyNames)
{
if (PropertyChanged != null)
{
foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
PropertyChanged(this, new PropertyChangedEventArgs("HasError"));
}
}
}
Then I added two properties into the view model:
private ObservableCollection<SalesPeriodV> salesPeriods = new ObservableCollection<SalesPeriodV>();
public ObservableCollection<SalesPeriodV> SalesPeriods
{
get { return salesPeriods; }
set { salesPeriods = value; NotifyPropertyChanged("SalesPeriods"); }
}
private SalesPeriodV selectedItem = new SalesPeriodV();
public SalesPeriodV SelectedItem
{
get { return selectedItem; }
set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}
Then initialised the collection with your values:
SalesPeriods.Add(new SalesPeriodV() { Month = 3, Year = 2013 } );
SalesPeriods.Add(new SalesPeriodV() { Month = 4, Year = 2013 } );
And then data bound only these two properties to a ComboBox
:
<ComboBox ItemsSource="{Binding SalesPeriods}" SelectedItem="{Binding SelectedItem}" />
That's it... that's all you need for a perfectly working example. You should see that the display of the items comes from the ToString
method without your displayPeriod
property. Hopefully, you can work out your mistakes from this code example.
You can take advantage of the "deleted" pseudo table in this example. Something like:
begin transaction;
declare @deletedIds table ( id int );
delete from t1
output deleted.id into @deletedIds
from table1 as t1
inner join table2 as t2
on t2.id = t1.id
inner join table3 as t3
on t3.id = t2.id;
delete from t2
from table2 as t2
inner join @deletedIds as d
on d.id = t2.id;
delete from t3
from table3 as t3 ...
commit transaction;
Obviously you can do an 'output deleted.' on the second delete as well, if you needed something to join on for the third table.
As a side note, you can also do inserted.* on an insert statement, and both inserted.* and deleted.* on an update statement.
EDIT: Also, have you considered adding a trigger on table1 to delete from table2 + 3? You'll be inside of an implicit transaction, and will also have the "inserted." and "deleted." pseudo-tables available.
You could create a user form:
You can wrap and unwrap exceptions this way.
class A {
void foo() throws Exception {
throw new Exception();
}
};
interface Task {
void run() throws Exception;
}
static class TaskException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TaskException(Exception e) {
super(e);
}
}
void bar() throws Exception {
Stream<A> as = Stream.generate(()->new A());
try {
as.forEach(a -> wrapException(() -> a.foo())); // or a::foo instead of () -> a.foo()
} catch (TaskException e) {
throw (Exception)e.getCause();
}
}
static void wrapException(Task task) {
try {
task.run();
} catch (Exception e) {
throw new TaskException(e);
}
}
"simple solution is here"
1 .Create a folder named libs under the app directory for that matter any directory within the project..
2 .Copy Paste your Library to libs folder
3.You simply copy the JAR to your libs/ directory and then from inside Android Studio, right click the Jar that shows up under libs/ > Add As Library..
Peace!
A single inlined code would be enough for this task. This worked for me effortlessly.
For #android devlopers out there.
String strValue=Objects.requireNonNull(getIntent().getExtras()).getString("string_Key");
Check out startOfDay([offset]). That gets what you are looking for without the pesky time constraints and its built in as of 4.3.x. It also has variants like endOfDay, startOfWeek, startOfMonth, etc.
In my case, the 'page.dt' event did not do the trick.
I used 'draw.dt' event instead, and it works!, some code:
$(document).on('draw.dt', function () {
//Do something
});
'Draw.dt' event is fired everytime the datatable page change by searching, ordering or page changing.
/***** Aditional Info *****/
There are some diferences in the way we can declare the event listener. You can asign it to the 'document' or to a 'html object'. The 'document' listeners will always exist in the page and the 'html object' listener will exist only if the object exist in the DOM in the moment of the declaration. Some code:
//Document event listener
$(document).on('draw.dt', function () {
//This will also work with objects loaded by ajax calls
});
//HTML object event listener
$("#some-id").on('draw.dt', function () {
//This will work with existing objects only
});
For a hyperlink just use www.facebook.com/++page ID++/like
Eg: www.facebook.com/MYPAGEISAWESOME/like
To make it work with m.facebook.com
here's what you do:
Open the Facebook page you're looking for then change the URL to the mobile URL ( which is www.m.facebook.com/MYPAGEISAWESOME
).
Now you should see a big version of the mobile Facebook page. Copy the target URL of the like button.
Pop that URL into the QR generator to make a "scan to like" barcode. This will open the m.Facebook
page in the browser of most mobiles directly from the QR reader. If they are not logged into Facebook then they will be prompted to log in and then click 'like'. If logged in, it will auto like.
Hope this helps!
Also, definitely include something with a "click here/scan here to like us on Facebook"
You can get more info about the error with the method $mail->ErrorInfo
. For example:
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
This is an alternative to the exception model that you need to active with new PHPMailer(true)
. But if can use exception model, use it as @Phil Rykoff answer.
This comes from the main page of PHPMailer on github https://github.com/PHPMailer/PHPMailer.
It's related about revert origin : to set origin when the object is drag : just use $(this).data("draggable").originalPosition = {top:0, left:0};
For example : i use like this
drag: function() {
var t = $(this);
left = parseInt(t.css("left")) * -1;
if(left > 0 ){
left = 0;
t.draggable( "option", "revert", true );
$(this).data("draggable").originalPosition = {top:0, left:0};
}
else t.draggable( "option", "revert", false );
$(".slider-work").css("left", left);
}
To Make it work in Eclipse Juno - I had to do some additional steps.
In General -> Editors -> File Association
This actually works for me:
Per the README.SSO that comes with the jtdsd distribution:
In order for Single Sign On to work, jTDS must be able to load the native SPPI library ntlmauth.dll
. Place this DLL anywhere in the system path (defined by the PATH
system variable) and you're all set.
I placed it in my jre/bin folder
I configured a port dedicated the sql server instance (2302) to alleviate the need for an instance name - just something I do. lportal is my database name.
jdbc.default.url=jdbc:jtds:sqlserver://192.168.0.147:2302/lportal;useNTLMv2=true;domain=mydomain.local
One simple approach is to check if unicode
is a builtin function. If so, you're in Python 2 and your string will be a string. To ensure everything is in unicode
one can do:
import builtins
i = 'cats'
if 'unicode' in dir(builtins): # True in python 2, False in 3
i = unicode(i)
I'd be cautious as dismissing something as a bad idea because it is slow. If it is a part of the code that does not take much time to execute then the slowness is irrelevant. I just used the following code:
for (ic in 1:(dim(centroid)[2]))
{
cluster[[ic]]=matrix(,nrow=2,ncol=0)
}
# code to identify cluster=pindex[ip] to which to add the point
if(pdist[ip]>-1)
{
cluster[[pindex[ip]]]=cbind(cluster[[pindex[ip]]],points[,ip])
}
for a problem that ran in less than 1 second.
AssertJ 3.9.1 supports direct predicate usage in anyMatch
method.
assertThat(collection).anyMatch(element -> element.someProperty.satisfiesSomeCondition())
This is generally suitable use case for arbitrarily complex condition.
For simple conditions I prefer using extracting
method (see above) because resulting iterable-under-test might support value verification with better readability.
Example: it can provide specialized API such as contains
method in Frank Neblung's answer. Or you can call anyMatch
on it later anyway and use method reference such as "searchedvalue"::equals
. Also multiple extractors can be put into extracting
method, result subsequently verified using tuple()
.
For myself, it turns out that wlan0 was down, which resulted in me being unable to connect out. So, ensuring that wlan0 was up, allowed pip / pip3 to work without issue.
You could just add a new Variable under the properties of your project Each time you want to get that variable you just have to use
My.Settings.(Name of variable)
That'll work for the entire Project in all forms
bind tells the running process to claim a port. i.e, it should bind itself to port 80 and listen for incomming requests. with bind, your process becomes a server. when you use connect, you tell your process to connect to a port that is ALREADY in use. your process becomes a client. the difference is important: bind wants a port that is not in use (so that it can claim it and become a server), and connect wants a port that is already in use (so it can connect to it and talk to the server)
You need to store the psftp script (lines from open
to bye
) into a separate file and pass that to psftp
using -b
switch:
cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b
EDIT: For username+password: As you cannot use psftp
commands in a batch file, for the same reason, you cannot specify the username and the password as psftp
commands. These are inputs to the open
command. While you can specify the username with the open
command (open <user>@<IP>
), you cannot specify the password this way. This can be done on a psftp
command line only. Then it's probably cleaner to do all on the command-line:
cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>
And remove the open
, <user>
and <PW>
lines from your script.txt
.
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw
What you are doing atm is that you run psftp
without any parameter or commands. Once you exit it (like by typing bye
), your batch file continues trying to run open
command (and others), what Windows shell obviously does not understand.
If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:
(
echo cd ...
echo lcd ...
echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>
It will be something like that:
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN "The quantity is greater than 30"
WHEN Quantity = 30 THEN "The quantity is 30"
ELSE "The quantity is under 30"
END AS QuantityText
FROM OrderDetails;
Add these lines after newWin.document.write(divToPrint.innerHTML)
newWin.document.close();
newWin.focus();
newWin.print();
newWin.close();
Then print function will work in all browser...
Pretty simple but another said you dont pass session variables through the url bar
1.You dont need to because a session is passed throughout the whole website from header when you put in header file
2.security risks
Here is first page code
$url = "http://localhost/main.php?email=" . urlencode($email_address) . "&eventid=" . urlencode($event_id);
2nd page when getting the variables from the url bar is:
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['eventid']) && !empty($_GET['eventid'])){
////do whatever here
}
Now if you want to do it the proper way of using the session you created then ignore my above code and call the session variables on the second page for instance create a session on the first page lets say for example:
$_SESSION['WEB_SES'] = $email_address . "^" . $event_id;
obvious that you would have already assigned values to the session variables in the code above, you can call the session name whatever you want to i just used the example web_ses , the second page all you need to do is start a session and see if the session is there and check the variables and do whatever with them, example:
session_start();
if (isset($_SESSION['WEB_SES'])){
$Array = explode("^", $_SESSION['WEB_SES']);
$email = $Array[0];
$event_id = $Array[1]
echo "$email";
echo "$event_id";
}
Like I said before the good thing about sessions are they can be carried throughout the entire website if this type of code in put in the header file that gets called upon on all pages that load, you can simple use the variable wherever and whenever. Hope this helps :)
#Think about how index works with string in Python,
>>> a = "123456"
>>> a[::-1]
'654321'
Below code worked for me:
string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);
Here is another version if you have to reference a specific docker file:
version: "3"
services:
nginx:
container_name: nginx
build:
context: ../..
dockerfile: ./docker/nginx/Dockerfile
image: my_nginx:latest
Then you just run
docker-compose build
Since it sounds like you've tried many different potentional solutions, you'll probably have to do this the long methodical way now.
Create a new blank workbook. Then piece by piece copy your old workbook into it. Add a reference, write a little bit of code to test it. Ensure it compiles, ensure it runs. Add a sub or function, again, write a little test sub to run it, also ensure it compiles. Repeat this process slowly adding and testing everything.
You can speed this up a bit by first trying larger chunks, then when you find one that triggers the problem, remove it and break it into smaller peices for testing.
Either you will find the offender, or you'll have a new workbook that magically does not have the problem. The latter would be due to some sort of hidden corruption in the workbook file, probably in the binary vbproject part.
Welcome to the world of debugging without debuggers or other helpful tools to do the heavy lifting for you!
If your sed
allows in place editing via the -i
parameter:
sed -e 's/$/string after each line/' -i filename
If not, you have to make a temporary file:
typeset TMP_FILE=$( mktemp )
touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename
json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";
return new MemoryStream(Encoding.UTF8.GetBytes(json));
#Creating dictionary
animals = {"Cat" : "Pat", "Dog" : "Pat", "Tiger" : "Wild"}
#Convert dictionary to list (array)
keys = list(animals)
#Printing 1st dictionary key by index
print(keys[0])
#Done :)
CREATE PROC SP_EMPLOYEE --By Using TYPE parameter and CASE in Stored procedure
(@TYPE INT)
AS
BEGIN
IF @TYPE=1
BEGIN
SELECT DESIGID,DESIGNAME FROM GP_DESIGNATION
END
IF @TYPE=2
BEGIN
SELECT ID,NAME,DESIGNAME,
case D.ISACTIVE when 'Y' then 'ISACTIVE' when 'N' then 'INACTIVE' else 'not' end as ACTIVE
FROM GP_EMPLOYEEDETAILS ED
JOIN GP_DESIGNATION D ON ED.DESIGNATION=D.DESIGID
END
END
Since this issue is kind of old a lot of things have changed.
You can now get this behavior by adding this to the footer div
data-position="fixed"
More info here: http://jquerymobile.com/test/docs/toolbars/bars-fixed.html
Also beware, if you use the previously mentioned CSS together with the new JQM solution you will NOT get the appropriate behavior!
A tensor in pytorch is a view of an underlying contiguous block of numbers in memory (known as a storage
). pytorch can achieve fast operations by modifying the shape parameters of a view of a storage without changing the underlying memory allocations themselves. Hence multiple different tensors may reference the same underlying storage
object.
view
is a way of specifying a change of shape on an existing tensor.
super() can be used only in the new-style classes, which means the root class needs to inherit from the 'object' class.
For example, the top class need to be like this:
class SomeClass(object):
def __init__(self):
....
not
class SomeClass():
def __init__(self):
....
So, the solution is that call the parent's init method directly, like this way:
class TextParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.all_data = []
Try with a CASE in this way :
SUM(CASE
WHEN PaymentType = "credit card"
THEN TotalAmount
ELSE 0
END) AS CreditCardTotal,
Should give what you are looking for ...
If you want to learn, REALLY want to learn, then time is not of consequence. Just move forward everyday. Let your passion for this stuff drive you forward. And one day you'll see that you are good at C#/.NET.
This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.
here's the gist of the demo
.container{
display: flex;
height: 100%;
justify-content: center;
align-items: center;
}
html
<div class="container">
<div class='content'> //you can size this anyway you want
put anything you want here,
</div>
</div>
Here is an Angular4+ directive that you can re-use in any component. Based on code given in the answer by Niel T in this question.
import { NgZone, Renderer, Directive, Input } from '@angular/core';
@Directive({
selector: '[focusDirective]'
})
export class FocusDirective {
@Input() cssSelector: string
constructor(
private ngZone: NgZone,
private renderer: Renderer
) { }
ngOnInit() {
console.log(this.cssSelector);
this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
this.renderer.selectRootElement(this.cssSelector).focus();
}, 0);
});
}
}
You can use it in a component template like this:
<input id="new-email" focusDirective cssSelector="#new-email"
formControlName="email" placeholder="Email" type="email" email>
Give the input an id and pass the id to the cssSelector
property of the directive. Or you can pass any cssSelector you like.
Comments from Niel T:
Since the only thing I'm doing is setting the focus on an element, I don't need to concern myself with change detection, so I can actually run the call to renderer.selectRootElement outside of Angular. Because I need to give the new sections time to render, the element section is wrapped in a timeout to allow the rendering threads time to catch up before the element selection is attempted. Once all that is setup, I can simply call the element using basic CSS selectors.
Floating point numbers are encoded using an exponential form, that is something like m * b ^ e
, i.e. not like integers at all. The question you ask would be meaningful in the context of fixed point numbers. There are numerous fixed point arithmetic libraries available.
Regarding floating point arithmetic: The number of decimal digits depends on the presentation and the number system. For example there are periodic numbers (0.33333
) which do not have a finite presentation in decimal but do have one in binary and vice versa.
Also it is worth mentioning that floating point numbers up to a certain point do have a difference larger than one, i.e. value + 1
yields value
, since value + 1
can not be encoded using m * b ^ e
, where m
, b
and e
are fixed in length. The same happens for values smaller than 1, i.e. all the possible code points do not have the same distance.
Because of this there is no precision of exactly n
digits like with fixed point numbers, since not every number with n
decimal digits does have a IEEE encoding.
There is a nearly obligatory document which you should read then which explains floating point numbers: What every computer scientist should know about floating point arithmetic.
If you want an recent copy of npgsql, then go here
This can be installed via package manager console as
PM> Install-Package Npgsql
If one want to attach a process, this process must have the same owner. The root is able to attach to any process.
web.py is probably the simplest web framework out there. "Bare" CGI is simpler, but you're completely on your own when it comes to making a service that actually does something.
"Hello, World!" according to web.py isn't much longer than an bare CGI version, but it adds URL mapping, HTTP command distinction, and query parameter parsing for free:
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
For me it was the difference between
var response = Request.CreateResponse(HttpStatusCode.OK, new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");
and
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");
The first one was returning the JSON representation of StringContent: {"Headers":[{"Key":"Content-Type","Value":["application/octet-stream; charset=utf-8"]}]}
While the second one was returning the file proper.
It seems that Request.CreateResponse has an overload that takes a string as the second parameter and this seems to have been what was causing the StringContent object itself to be rendered as a string, instead of the actual content.
You can simple put like this
public sealed class Employee
{
public int Id { get; set; } = 101;
}
Take a look at launch4j
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
This was a fresh linux Mint xfce machine
I have been battling this for a about a week. I'm trying to learn Java on Netbeans IDE and so naturally I get the combo file straight from Oracle. Which is a package of the JDK and the Netbeans IDE together in a tar file located here.
located http://www.oracle.com/technetwork/java/javase/downloads/index.html file name JDK 8u25 with NetBeans 8.0.1
after installing them (or so I thought) I would make/compile a simple program like "hello world" and that would spit out a jar file that you would be able to run in a terminal. Keep in mind that the program ran in the Netbeans IDE.
I would end up with this error: java.lang.UnsupportedClassVersionError:
Even though I ran the file from oracle website I still had the old version of the Java runtime which was not compatible to run my jar file which was compiled with the new java runtime.
After messing with stuff that was mostly over my head from setting Paths to editing .bashrc with no remedy.
I came across a solution that was easy enough for even me. I have come across something that auto installs java and configures it on your system and it works with the latest 1.8.*
One of the steps is adding a PPA wasn't sure about this at first but seems ok as it has worked for me
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
domenic@domenic-AO532h ~ $ java -version java version "1.8.0_25" Java(TM) SE Runtime Environment (build 1.8.0_25-b17) Java HotSpot(TM) Server VM (build 25.25-b02, mixed mode)
I think it also configures the browser java as well.
I hope this helps others.
If I understand your requirement correctly, the simple answer is: you can't.
That's because the client of the WCF service may be generated by any third party that uses your service.
IF you have control of the clients of your service, you can create a base client class that add the desired header and inherit the behavior on the worker classes.
I encountered this problem too and what solved it has nothing to do with Facebook but the prior script I included that was in bad form
<script type="text/javascript" src="js/my_script.js" />
I changed it to
<script type="text/javascript" src="js/my_script.js"></script>
And it works...
Weew... hopefully my experience can help others stuck in this that has done almost about everything but still can't get it to work...
Oh Boy... ^^
Your question is difficult to understand, but if you want to select the numbers from 1
to 100
, then this should do the trick:
Select Rownum r
From dual
Connect By Rownum <= 100
__FILE__
is the filename with extension of the file containing the code being executed.
In foo.rb
, __FILE__
would be "foo.rb".
If foo.rb
were in the dir /home/josh
then File.dirname(__FILE__)
would return /home/josh
.
This is the total number of connections to the server till now. To find current conection status you can use
mysqladmin -u -p extended-status | grep -wi 'threads_connected\|threads_running' | awk '{ print $2,$4}'
This will show you:
Threads_connected 12
Threads_running 1
Threads_connected: Number of connections
Threads_running: connections currently running some sql
Be aware that a value of 1 equals 100% in Excel's interpretation. If you enter 5.66 and you want to show 5.66%, then AxGryndr's hack with the formatting will work, but it is a display format only and does not represent the true numeric value. If you want to use that percentage in further calculations, these calculations will return the wrong result unless you divide by 100 at calculation time.
The consistent and less error-prone way is to enter 0.0566 and format the number with the built-in percentage format. That way, you can easily calculate 5.6% of A1 by just multiplying A1 with the value.
The good news is that you don't need to go through the rigmarole of entering 0.0566 and then formatting as percent. You can simply type
5.66%
into the cell, including the percentage symbol, and Excel will take care of the rest and store the number correctly as 0.0566 if formatted as General.
Using this,
String s = "03/24/2013 21:54";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("date : "+simpleDateFormat.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
It seems that for 32-bit servers there is a JVM limitation that cannot be overcome (unless you find a special 32-bit JVM that does not impose a 2GB limit or less).
This thread on The Server Side has more details including several people who tested out various JVMs on 32-bit architectures. IBM's JVM seems to allow 100 more MB but that's not really going to get you what you want.
http://www.theserverside.com/discussions/thread.tss?thread_id=26347
The "real" solution is to use a 64-bit server with a 64-bit JVM to get heaps larger than 2GB per process. However, it's important to also consider the impact of increasing your address size (not just the addressable space) by using a 64-bit JVM. There will likely be performance and memory impacts for processing using less than 4GB of memory.
Food for thought: do each of these jobs really require 2GB of memory? Is there any way for the jobs to be modified to run within 1.8GB so this limit is not a problem?
I've tried to improve this solution in several ways. Now resulting image has right proportions.
Set sheet = ActiveSheet
output = "D:\SavedRange4.png"
zoom_coef = 100 / sheet.Parent.Windows(1).Zoom
Set area = sheet.Range(sheet.PageSetup.PrintArea)
area.CopyPicture xlPrinter
Set chartobj = sheet.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
chartobj.Chart.Paste
chartobj.Chart.Export output, "png"
chartobj.Delete
For iOS 7 - 10:
Objective-C:
[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft) forKey:@"orientation"];
[UINavigationController attemptRotationToDeviceOrientation];
Swift 3:
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()
Just call it in - viewDidAppear:
of the presented view controller.
To have the same flexibility in CONCAT_WS as in CONCAT (if you don't want the same separator between every member for instance) use the following:
SELECT CONCAT_WS("",affiliate_name,':',model,'-',ip,... etc)
in the form load event add this line
this.WindowState = FormWindowState.Maximized;
In the "Turn Windows features on or off" window, un-check Hyper-V and also ensure that Windows Hypervisor Platform is unchecked. Windows Hypervisor Platform being enabled can also block the installation of the Intel HaxM
You can get the bin path by AppDomain.CurrentDomain.RelativeSearchPath
Depending on what program you use for ssh, the way to get the proper key could vary. Putty (popular with Windows) uses their own format for ssh keys. With most variants of Linux and BSD that I've seen, you just have to look in ~/.ssh/known_hosts
. I usually ssh from a Linux machine and then copy this file to a Windows machine. Then I use something similar to
jsch.setKnownHosts("C:\\Users\\cabbott\\known_hosts");
Assuming I have placed the file in C:\Users\cabbott
on my Windows machine. If you don't have access to a Linux machine, try http://www.cygwin.com/
Maybe someone else can suggest another Windows alternative. I find putty's way of handling SSH keys by storing them in the registry in a non-standard format bothersome to extract.
AFAIK you can't do that.
What I did at my place of work, is transfer the files to your home
(~
) folder (or really any folder that you have full permissions in, i.e chmod 777
or variants) via WinSCP, and then SSH to to your linux machine and sudo
from there to your destination folder.
Another solution would be to change permissions of the directories you are planning on uploading the files to, so your user (which is without sudo
privileges) could write to those dirs.
I would also read about WinSCP Remote Commands for further detail.
if (yourString.Length > 1)
withoutLast = yourString.Substring(0, yourString.Length - 1);
or
if (yourString.Length > 1)
withoutLast = yourString.TrimEnd().Substring(0, yourString.Length - 1);
...in case you want to remove a non-whitespace character from the end.
Edit: See Sebastien Lorber's answer which fixes a bug in my implementation.
Use the onInput event, and optionally onBlur as a fallback. You might want to save the previous contents to prevent sending extra events.
I'd personally have this as my render function.
var handleChange = function(event){
this.setState({html: event.target.value});
}.bind(this);
return (<ContentEditable html={this.state.html} onChange={handleChange} />);
Which uses this simple wrapper around contentEditable.
var ContentEditable = React.createClass({
render: function(){
return <div
onInput={this.emitChange}
onBlur={this.emitChange}
contentEditable
dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
},
shouldComponentUpdate: function(nextProps){
return nextProps.html !== this.getDOMNode().innerHTML;
},
emitChange: function(){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
this.props.onChange({
target: {
value: html
}
});
}
this.lastHtml = html;
}
});
The Mobile Device Browser File is a great way to detect mobile (and other) broswers for ASP.NET projects: http://mdbf.codeplex.com/
An alternate solution using the JsonProperty
attribute:
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
// or
[JsonProperty("property_name", NullValueHandling=NullValueHandling.Ignore)]
// or for all properties in a class
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
As seen in this online doc.
Though this was asked almost 6 years, ago still hot topic in UX design, here is demo snippet if any newbie wanted to use
$(function() {_x000D_
_x000D_
/* this is only for demonstration purpose */_x000D_
var t = $('.posts').html(),_x000D_
c = 1,_x000D_
scroll_enabled = true;_x000D_
_x000D_
function load_ajax() {_x000D_
_x000D_
/* call ajax here... on success enable scroll */_x000D_
$('.posts').append('<h4>' + (++c) + ' </h4>' + t);_x000D_
_x000D_
/*again enable loading on scroll... */_x000D_
scroll_enabled = true;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
$(window).bind('scroll', function() {_x000D_
if (scroll_enabled) {_x000D_
_x000D_
/* if 90% scrolled */_x000D_
if($(window).scrollTop() >= ($('.posts').offset().top + $('.posts').outerHeight()-window.innerHeight)*0.9) {_x000D_
_x000D_
/* load ajax content */_x000D_
scroll_enabled = false; _x000D_
load_ajax();_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
});_x000D_
_x000D_
});
_x000D_
h4 {_x000D_
color: red;_x000D_
font-size: 36px;_x000D_
background-color: yellow;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<div class="posts">_x000D_
Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit_x000D_
sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut_x000D_
libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet_x000D_
lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque_x000D_
</div>
_x000D_
Programmatically you can do it by adding the following constraints.
NSLayoutConstraint *constraintHorizontal = [NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.superview
attribute:attribute
multiplier:1.0f
constant:0.0f];
NSLayoutConstraint *constraintVertical = [NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.superview
attribute:attribute
multiplier:1.0f
constant:0.0f];
In my case the binding name in under protocol mapping did not match the binding name on the endpoint. They match in the example below.
<endpoint address="" binding="basicHttpsBinding" contract="serviceName" />
and
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
Here is a simple solution. This is a late answer but may be simple one-
const data = {
city: 'foo',
year: 2020,
person: {
name: {
firstName: 'john',
lastName: 'doe'
},
age: 20,
type: {
a: 2,
b: 3,
c: {
d: 4,
e: 5
}
}
},
}
function getKey(obj, res = [], parent = '') {
const keys = Object.keys(obj);
/** Loop throw the object keys and check if there is any object there */
keys.forEach(key => {
if (typeof obj[key] !== 'object') {
// Generate the heirarchy
parent ? res.push(`${parent}.${key}`) : res.push(key);
} else {
// If object found then recursively call the function with updpated parent
let newParent = parent ? `${parent}.${key}` : key;
getKey(obj[key], res, newParent);
}
});
}
const result = [];
getKey(data, result, '');
console.log(result);
_x000D_
.as-console-wrapper{min-height: 100%!important; top: 0}
_x000D_
You can run it through Number()
var myInt = Number(new Date(dates_as_int[0]));
If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC.
As @RE350 suggested passing the JSON data in the body in the post would be ideal. However, you could still send the json object as a parameter in a GET request, decode the json string in the server-side logic and use it as an object.
For example, if you are on php you could do this (use the appropriate json decode in other languages):
Server request:
http://<php script>?param1={"nameservice":[{"id":89},{"id":3}]}
In the server:
$obj = json_decode($_GET['param1'], true);
$obj["nameservice"][0]["id"]
out put:
89
Auth::user()->products->sum('price');
The documentation is a little light for some of the Collection
methods but all the query builder aggregates are seemingly available besides avg()
that can be found at http://laravel.com/docs/queries#aggregates.
In SSMS 2012, you'll have to use:
To enable single-user mode, in SQL instance properties, DO NOT go to "Advance" tag, there is already a "Startup Parameters" tag.
It's not necessarily bad (based on what you're doing), but in the case of arrays, if something has been added to Array.prototype
, then you're going to get strange results. Where you'd expect this loop to run three times:
var arr = ['a','b','c'];
for (var key in arr) { ... }
If a function called helpfulUtilityMethod
has been added to Array
's prototype
, then your loop would end up running four times: key
would be 0
, 1
, 2
, and helpfulUtilityMethod
. If you were only expecting integers, oops.
This is an old thread, but the purposed solutions all have issues (depending on device / Android version / Keyboard).
DIFFERENT APPROACH
So eventually I went with a different approach, instead of using the InputFilter
problematic implementation, I am using TextWatcher
and the TextChangedListener
of the EditText
.
FULL CODE (EXAMPLE)
editText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable editable) {
super.afterTextChanged(editable);
String originalText = editable.toString();
int originalTextLength = originalText.length();
int currentSelection = editText.getSelectionStart();
// Create the filtered text
StringBuilder sb = new StringBuilder();
boolean hasChanged = false;
for (int i = 0; i < originalTextLength; i++) {
char currentChar = originalText.charAt(i);
if (isAllowed(currentChar)) {
sb.append(currentChar);
} else {
hasChanged = true;
if (currentSelection >= i) {
currentSelection--;
}
}
}
// If we filtered something, update the text and the cursor location
if (hasChanged) {
String newText = sb.toString();
editText.setText(newText);
editText.setSelection(currentSelection);
}
}
private boolean isAllowed(char c) {
// TODO: Add the filter logic here
return Character.isLetter(c) || Character.isSpaceChar(c);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Do Nothing
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Do Nothing
}
});
The reason InputFilter
is not a good solution in Android is since it depends on the keyboard implementation. The Keyboard input is being filtered before the input is passed to the EditText
. But, because some keyboards have different implementations for the InputFilter.filter()
invocation, this is problematic.
On the other hand TextWatcher
does not care about the keyboard implementation, it allows us to create a simple solution and be sure it will work on all devices.
I think you are missing your certificates.
You can try generating them by using InstallCerts app. Here you can see how to use it: https://github.com/escline/InstallCert
Once you get your certificate, you need to put it under your security directory within your jdk home, for example:
C:\Program Files\Java\jdk1.6.0_45\jre\lib\security
Let me know if it works.
I actually found that calling fullScroll twice does the trick:
myScrollView.fullScroll(View.FOCUS_DOWN);
myScrollView.post(new Runnable() {
@Override
public void run() {
myScrollView.fullScroll(View.FOCUS_DOWN);
}
});
It may have something to do with the activation of the post() method right after performing the first (unsuccessful) scroll. I think this behavior occurs after any previous method call on myScrollView, so you can try replacing the first fullScroll() method by anything else that may be relevant to you.
I have been able to ping from VMs and the host by setting the VM's network settings to "Bridged" mode. This, in short, places them all on the same physical network. This coupled with your static IP addresses should do the trick.
You have to understand how Unix interprets your input.
The standard Unix shell interpolates environment variables, and what are called globs before it passes the parameters to your program. This is a bit different from Windows which makes the program interpret the expansion.
Try this:
$ echo *
This will echo all the files and directories in your current directory. Before the echo
command acts, the shell interpolates the *
and expands it, then passes that expanded parameter back to your command. You can see it in action by doing this:
$ set -xv
$ echo *
$ set +xv
The set -xv
turns on xtrace and verbose. Verbose echoes the command as entered, and xtrace echos the command that will be executed (that is, after the shell expansion).
Now try this:
$ echo "*"
Note that putting something inside quotes hides the glob expression from the shell, and the shell cannot expand it. Try this:
$ foo="this is the value of foo"
$ echo $foo
$ echo "$foo"
$ echo '$foo'
Note that the shell can still expand environment variables inside double quotes, but not in single quotes.
Now let's look at your statement:
file="home/edward/bank1/fiche/Test*"
The double quotes prevent the shell from expanding the glob expression, so file
is equal to the literal home/edward/bank1/finche/Test*
. Therefore, you need to do this:
file=/home/edward/bank1/fiche/Test*
The lack of quotes (and the introductory slash which is important!) will now make file equal to all files that match that expression. (There might be more than one!). If there are no files, depending upon the shell, and its settings, the shell may simply set file to that literal string anyway.
You certainly have the right idea:
file=/home/edward/bank1/fiche/Test*
if test -s $file
then
echo "found one"
else
echo "found none"
fi
However, you still might get found none returned if there is more than one file. Instead, you might get an error in your test
command because there are too many parameters.
One way to get around this might be:
if ls /home/edward/bank1/finche/Test* > /dev/null 2>&1
then
echo "There is at least one match (maybe more)!"
else
echo "No files found"
fi
In this case, I'm taking advantage of the exit code of the ls
command. If ls
finds one file it can access, it returns a zero exit code. If it can't find one matching file, it returns a non-zero exit code. The if
command merely executes a command, and then if the command returns a zero, it assumes the if
statement as true and executes the if
clause. If the command returns a non-zero value, the if
statement is assumed to be false, and the else
clause (if one is available) is executed.
The test
command works in a similar fashion. If the test
is true, the test
command returns a zero. Otherwise, the test
command returns a non-zero value. This works great with the if
command. In fact, there's an alias to the test
command. Try this:
$ ls -li /bin/test /bin/[
The i
prints out the inode. The inode is the real ID of the file. Files with the same ID are the same file. You can see that /bin/test
and /bin/[
are the same command. This makes the following two commands the same:
if test -s $file
then
echo "The file exists"
fi
if [ -s $file ]
then
echo "The file exists"
fi
The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.
>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
string1.equals(string2)
is the way.
It returns true
if string1
is equals to string2
in value. Else, it will return false
.
Placing a $
in front of the row value to keep constant worked well for me. e.g.
=b2+a$1
This works:
var event = jQuery.Event('keypress');
event.which = 13;
event.keyCode = 13; //keycode to trigger this for simulating enter
jQuery(this).trigger(event);
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
Access the property within the object id like that user._id.$oid
.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class readFile {
/**
* feel free to make any modification I have have been here so I feel you
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
File dir = new File(".");// read file from same directory as source //
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
// if you wanna read file name with txt files
if (file.getName().contains("txt")) {
System.out.println(file.getName());
}
// if you want to open text file and read each line then
if (file.getName().contains("txt")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(
file.getAbsolutePath());
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(
fileReader);
String line;
// get file details and get info you need.
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// here you can say...
// System.out.println(line.substring(0, 10)); this
// prints from 0 to 10 indext
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '"
+ file.getName() + "'");
} catch (IOException ex) {
System.out.println("Error reading file '"
+ file.getName() + "'");
// Or we could just do this:
ex.printStackTrace();
}
}
}
}
}`enter code here`
}
But from what I understand xs:choice still only allows single element selection. Hence setting the MaxOccurs to unbounded like this should only mean that "any one" of the child elements can appear multiple times. Is this accurate?
No. The choice happens individually for every "repetition" of xs:choice
that occurs due to maxOccurs="unbounded"
. Therefore, the code that you have posted is correct, and will actually do what you want as written.
Yes you can. I've used it with Word and PowerPoint. You will need Office 2010 client apps and SharePoint 2010 foundation at least. You must also allow editing without checking out on the document library.
It's quite cool, you can mark regions as 'locked' so no-one can change them and you can see what other people have changed every time you save your changes to the server. You also get to see who's working on the document from the Office app. The merging happens on SharePoint 2010.
Save to EPS and then convert to PDF:
saveas(gcf, 'nombre.eps', 'eps2c')
system('epstopdf nombre.eps') %Needs TeX Live (maybe it works with MiKTeX).
You will need some software that converts EPS to PDF.
Are you trying to submit a form?
Listen to the submit
event instead.
This will handle click
and enter
.
If you must use enter key...
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
you can do
hash.inject({}){|option, (k,v) | option["id"] = v if k == "_id"; option}
This should work for your case!
Better to support all the browsers:
img.lessOpacity {
opacity: 0.4;
filter: alpha(opacity=40);
zoom: 1; /* needed to trigger "hasLayout" in IE if no width or height is set */
}
for those who want to show collapsible json can use renderjson
Here is the example by embedding the render js javascript in html
<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
// Copyright © 2013-2014 David Caldwell <[email protected]>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
// Usage
// -----
// The module exports one entry point, the `renderjson()` function. It takes in
// the JSON you want to render as a single argument and returns an HTML
// element.
//
// Options
// -------
// renderjson.set_icons("+", "-")
// This Allows you to override the disclosure icons.
//
// renderjson.set_show_to_level(level)
// Pass the number of levels to expand when rendering. The default is 0, which
// starts with everything collapsed. As a special case, if level is the string
// "all" then it will start with everything expanded.
//
// renderjson.set_max_string_length(length)
// Strings will be truncated and made expandable if they are longer than
// `length`. As a special case, if `length` is the string "none" then
// there will be no truncation. The default is "none".
//
// renderjson.set_sort_objects(sort_bool)
// Sort objects by key (default: false)
//
// Theming
// -------
// The HTML output uses a number of classes so that you can theme it the way
// you'd like:
// .disclosure ("?", "?")
// .syntax (",", ":", "{", "}", "[", "]")
// .string (includes quotes)
// .number
// .boolean
// .key (object key)
// .keyword ("null", "undefined")
// .object.syntax ("{", "}")
// .array.syntax ("[", "]")
var module;
(module || {}).exports = renderjson = (function () {
var themetext = function (/* [class, text]+ */) {
var spans = [];
while (arguments.length)
spans.push(append(span(Array.prototype.shift.call(arguments)),
text(Array.prototype.shift.call(arguments))));
return spans;
};
var append = function (/* el, ... */) {
var el = Array.prototype.shift.call(arguments);
for (var a = 0; a < arguments.length; a++)
if (arguments[a].constructor == Array)
append.apply(this, [el].concat(arguments[a]));
else
el.appendChild(arguments[a]);
return el;
};
var prepend = function (el, child) {
el.insertBefore(child, el.firstChild);
return el;
}
var isempty = function (obj) {
for (var k in obj) if (obj.hasOwnProperty(k)) return false;
return true;
}
var text = function (txt) { return document.createTextNode(txt) };
var div = function () { return document.createElement("div") };
var span = function (classname) {
var s = document.createElement("span");
if (classname) s.className = classname;
return s;
};
var A = function A(txt, classname, callback) {
var a = document.createElement("a");
if (classname) a.className = classname;
a.appendChild(text(txt));
a.href = '#';
a.onclick = function () { callback(); return false; };
return a;
};
function _renderjson(json, indent, dont_indent, show_level, max_string, sort_objects) {
var my_indent = dont_indent ? "" : indent;
var disclosure = function (open, placeholder, close, type, builder) {
var content;
var empty = span(type);
var show = function () {
if (!content) append(empty.parentNode,
content = prepend(builder(),
A(renderjson.hide, "disclosure",
function () {
content.style.display = "none";
empty.style.display = "inline";
})));
content.style.display = "inline";
empty.style.display = "none";
};
append(empty,
A(renderjson.show, "disclosure", show),
themetext(type + " syntax", open),
A(placeholder, null, show),
themetext(type + " syntax", close));
var el = append(span(), text(my_indent.slice(0, -1)), empty);
if (show_level > 0)
show();
return el;
};
if (json === null) return themetext(null, my_indent, "keyword", "null");
if (json === void 0) return themetext(null, my_indent, "keyword", "undefined");
if (typeof (json) == "string" && json.length > max_string)
return disclosure('"', json.substr(0, max_string) + " ...", '"', "string", function () {
return append(span("string"), themetext(null, my_indent, "string", JSON.stringify(json)));
});
if (typeof (json) != "object") // Strings, numbers and bools
return themetext(null, my_indent, typeof (json), JSON.stringify(json));
if (json.constructor == Array) {
if (json.length == 0) return themetext(null, my_indent, "array syntax", "[]");
return disclosure("[", " ... ", "]", "array", function () {
var as = append(span("array"), themetext("array syntax", "[", null, "\n"));
for (var i = 0; i < json.length; i++)
append(as,
_renderjson(json[i], indent + " ", false, show_level - 1, max_string, sort_objects),
i != json.length - 1 ? themetext("syntax", ",") : [],
text("\n"));
append(as, themetext(null, indent, "array syntax", "]"));
return as;
});
}
// object
if (isempty(json))
return themetext(null, my_indent, "object syntax", "{}");
return disclosure("{", "...", "}", "object", function () {
var os = append(span("object"), themetext("object syntax", "{", null, "\n"));
for (var k in json) var last = k;
var keys = Object.keys(json);
if (sort_objects)
keys = keys.sort();
for (var i in keys) {
var k = keys[i];
append(os, themetext(null, indent + " ", "key", '"' + k + '"', "object syntax", ': '),
_renderjson(json[k], indent + " ", true, show_level - 1, max_string, sort_objects),
k != last ? themetext("syntax", ",") : [],
text("\n"));
}
append(os, themetext(null, indent, "object syntax", "}"));
return os;
});
}
var renderjson = function renderjson(json) {
var pre = append(document.createElement("pre"), _renderjson(json, "", false, renderjson.show_to_level, renderjson.max_string_length, renderjson.sort_objects));
pre.className = "renderjson";
return pre;
}
renderjson.set_icons = function (show, hide) {
renderjson.show = show;
renderjson.hide = hide;
return renderjson;
};
renderjson.set_show_to_level = function (level) {
renderjson.show_to_level = typeof level == "string" &&
level.toLowerCase() === "all" ? Number.MAX_VALUE
: level;
return renderjson;
};
renderjson.set_max_string_length = function (length) {
renderjson.max_string_length = typeof length == "string" &&
length.toLowerCase() === "none" ? Number.MAX_VALUE
: length;
return renderjson;
};
renderjson.set_sort_objects = function (sort_bool) {
renderjson.sort_objects = sort_bool;
return renderjson;
};
// Backwards compatiblity. Use set_show_to_level() for new code.
renderjson.set_show_by_default = function (show) {
renderjson.show_to_level = show ? Number.MAX_VALUE : 0;
return renderjson;
};
renderjson.set_icons('?', '?');
renderjson.set_show_by_default(false);
renderjson.set_sort_objects(false);
renderjson.set_max_string_length("none");
return renderjson;
})();
</script>
</head>
<body>
<div id="dest"></div>
</body>
<script type="application/javascript">
document.getElementById("dest").appendChild(
renderjson.set_show_by_default(true)
//.set_show_to_level(2)
//.set_sort_objects(true)
//.set_icons('+', '-')
.set_max_string_length(100)
([
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
},
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{ "value": "New", "onclick": "CreateNewDoc()" },
{ "value": "Open", "onclick": "OpenDoc()" },
{ "value": "Close", "onclick": "CloseDoc()" }
]
}
}
},
{
"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
},
{
"web-app": {
"servlet": [
{
"servlet-name": "cofaxCDS",
"servlet-class": "org.cofax.cds.CDSServlet",
"init-param": {
"configGlossary:installationAt": "Philadelphia, PA",
"configGlossary:adminEmail": "[email protected]",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
"templateProcessorClass": "org.cofax.WysiwygTemplate",
"templateLoaderClass": "org.cofax.FilesTemplateLoader",
"templatePath": "templates",
"templateOverridePath": "",
"defaultListTemplate": "listTemplate.htm",
"defaultFileTemplate": "articleTemplate.htm",
"useJSP": false,
"jspListTemplate": "listTemplate.jsp",
"jspFileTemplate": "articleTemplate.jsp",
"cachePackageTagsTrack": 200,
"cachePackageTagsStore": 200,
"cachePackageTagsRefresh": 60,
"cacheTemplatesTrack": 100,
"cacheTemplatesStore": 50,
"cacheTemplatesRefresh": 15,
"cachePagesTrack": 200,
"cachePagesStore": 100,
"cachePagesRefresh": 10,
"cachePagesDirtyRead": 10,
"searchEngineListTemplate": "forSearchEnginesList.htm",
"searchEngineFileTemplate": "forSearchEngines.htm",
"searchEngineRobotsDb": "WEB-INF/robots.db",
"useDataStore": true,
"dataStoreClass": "org.cofax.SqlDataStore",
"redirectionClass": "org.cofax.SqlRedirection",
"dataStoreName": "cofax",
"dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
"dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
"dataStoreUser": "sa",
"dataStorePassword": "dataStoreTestQuery",
"dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
"dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
"dataStoreInitConns": 10,
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "debug",
"maxUrlLength": 500
}
},
{
"servlet-name": "cofaxEmail",
"servlet-class": "org.cofax.cds.EmailServlet",
"init-param": {
"mailHost": "mail1",
"mailHostOverride": "mail2"
}
},
{
"servlet-name": "cofaxAdmin",
"servlet-class": "org.cofax.cds.AdminServlet"
},
{
"servlet-name": "fileServlet",
"servlet-class": "org.cofax.cds.FileServlet"
},
{
"servlet-name": "cofaxTools",
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"init-param": {
"templatePath": "toolstemplates/",
"log": 1,
"logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
"logMaxSize": "",
"dataLog": 1,
"dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
"dataLogMaxSize": "",
"removePageCache": "/content/admin/remove?cache=pages&id=",
"removeTemplateCache": "/content/admin/remove?cache=templates&id=",
"fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
"lookInContext": 1,
"adminGroupID": 4,
"betaServer": true
}
}],
"servlet-mapping": {
"cofaxCDS": "/",
"cofaxEmail": "/cofaxutil/aemail/*",
"cofaxAdmin": "/admin/*",
"fileServlet": "/static/*",
"cofaxTools": "/tools/*"
},
"taglib": {
"taglib-uri": "cofax.tld",
"taglib-location": "/WEB-INF/tlds/cofax.tld"
}
}
},
{
"menu": {
"header": "SVG Viewer",
"items": [
{ "id": "Open" },
{ "id": "OpenNew", "label": "Open New" },
null,
{ "id": "ZoomIn", "label": "Zoom In" },
{ "id": "ZoomOut", "label": "Zoom Out" },
{ "id": "OriginalView", "label": "Original View" },
null,
{ "id": "Quality" },
{ "id": "Pause" },
{ "id": "Mute" },
null,
{ "id": "Find", "label": "Find..." },
{ "id": "FindAgain", "label": "Find Again" },
{ "id": "Copy" },
{ "id": "CopyAgain", "label": "Copy Again" },
{ "id": "CopySVG", "label": "Copy SVG" },
{ "id": "ViewSVG", "label": "View SVG" },
{ "id": "ViewSource", "label": "View Source" },
{ "id": "SaveAs", "label": "Save As" },
null,
{ "id": "Help" },
{ "id": "About", "label": "About Adobe CVG Viewer..." }
]
}
},
{
"empty": {
"object": {},
"array": []
}
},
{
"really_long": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla posuere, orci quis laoreet luctus, nunc neque condimentum arcu, sed tristique sem erat non libero. Morbi et velit non justo rutrum pulvinar. Nam pellentesque laoreet lacus eget sollicitudin. Quisque maximus mattis nisl, eget tempor nisi pulvinar et. Nullam accumsan sapien sapien, non gravida turpis consectetur non. Etiam in vestibulum neque. Donec porta dui sit amet turpis efficitur laoreet. Duis eu convallis ex, vel volutpat lacus. Donec sit amet nunc a orci fermentum luctus."
}
]));
</script>
</html>
The function combn is in the standard utils package (i.e. already installed)
choose is also already available in the Special {base}
remove the http
or https
from wget https:github.com/facebook/facebook-php-sdk/archive/master.zip
. this worked fine for me.
max_connections
You can change max_connections
while MySQL is running via SET
:
mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 5000 |
+-----------------+-------+
1 row in set (0.00 sec)
timeout
relatedI had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.
I suggest that you increase this value to 100k or disable connection pooling Pooling=false
he has two questions.
Q1 - what happens if I disable pooling
Slow down making DB connection. connection pooling
is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool
Q2 - Can the value of pooling be increased or the maximum is 100?
you can increase but I'm sure what is MAX value, maybe max_connections
in my.cnf
My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.
If you have Stress Test tool like JMeter
you can test youself.
Simple coding in your activity
like below:
private ProgressDialog dialog = new ProgressDialog(YourActivity.this);
dialog.setMessage("please wait...");
dialog.show();
dialog.dismiss();