You can get deadlocks on more than just row locks, e.g. see this. The scripts may be competing for other resources, such as index blocks.
I've gotten around this in the past by engineering the parallelism in such a way that different instances are working on portions of the workload that are less likely to affect blocks that are close to each other; for example, for an update of a large table, instead of setting up the parallel slaves using something like MOD(n,10)
, I'd use TRUNC(n/10)
which mean that each slave worked on a contiguous set of data.
There are, of course, much better ways of splitting up a job for parallelism, e.g. DBMS_PARALLEL_EXECUTE.
Not sure why you're getting "PL/SQL successfully completed", perhaps your scripts are handling the exception?
The --force
option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.
If you tell rpm
to install all RPMs from some directory, then it does exactly this. rpm
will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.
You can remove the old RPM and rpm
will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.
If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm
to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i
(zypper in
can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.
I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles
. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify
command. It will complain for the new package if the old one has overwritten some files.
Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?
There are several options:
ps -fp <pid>
cat /proc/<pid>/cmdline | sed -e "s/\x00/ /g"; echo
There is more info in /proc/<pid>
on Linux, just have a look.
On other Unixes things might be different. The ps
command will work everywhere, the /proc
stuff is OS specific. For example on AIX there is no cmdline
in /proc
.
Two steps works fine:
create table bu_x as (select a,b,c,d from x ) WITH no data;
insert into bu_x (a,b,c,d) select select a,b,c,d from x ;
Use the df command:
df -h
Explanation: Use unix command find
with -ctime
(creation time) flag
The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the 'primaries' and 'operands') in terms of each file in the tree.
Solution: According to documenation
-ctime n[smhdw]
If no units are specified, this primary evaluates to true if the difference
between the time of last change of file status information and the time find
was started, rounded up to the next full 24-hour period, is n 24-hour peri-
ods.
If units are specified, this primary evaluates to true if the difference
between the time of last change of file status information and the time find
was started is exactly n units. Please refer to the -atime primary descrip-
tion for information on supported time units.
Formula: find <path> -ctime +[number][timeMeasurement] -ctime -[number][timeMeasurment]
Examples:
1.Find everything that were created after 1 week ago ago and before 2 weeks ago
find / -ctime +1w -ctime -2w
2.Find all javascript files (.js
) in current directory that were created between 1 day ago to 3 days ago
find . -name "*\.js" -type f -ctime +1d -ctime -3d
Or if you want to check for existence first:
if [[ ! -e /path/to/newdir ]]; then
mkdir /path/to/newdir
fi
-e is the exist test for KornShell.
You can also try googling a KornShell manual.
Thanks for all help at this issue. I'll post here my solution:
Package Header
CREATE OR REPLACE PACKAGE X IS
TYPE exch_row IS RECORD(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);
TYPE exch_tbl IS TABLE OF X.exch_row;
FUNCTION GetExchangeRate RETURN X.exch_tbl PIPELINED;
END X;
Package Body
CREATE OR REPLACE PACKAGE BODY X IS
FUNCTION GetExchangeRate RETURN X.exch_tbl
PIPELINED AS
exch_rt_usd NUMBER := 1.0; --todo
rw exch_row;
BEGIN
FOR rw IN (SELECT c.currency_cd AS currency_cd, e.exch_rt AS exch_rt_eur, (e.exch_rt / exch_rt_usd) AS exch_rt_usd
FROM exch e, currency c
WHERE c.currency_key = e.currency_key
) LOOP
PIPE ROW(rw);
END LOOP;
END;
PROCEDURE DoIt IS
BEGIN
DECLARE
CURSOR c0 IS
SELECT i.DOC,
i.doc_currency,
i.net_value,
i.net_value / rt.exch_rt_usd AS net_value_in_usd,
i.net_value / rt.exch_rt_eur AS net_value_in_euro,
FROM item i, (SELECT * FROM TABLE(X.GetExchangeRate())) rt
WHERE i.doc_currency = rt.currency_cd;
TYPE c0_type IS TABLE OF c0%ROWTYPE;
items c0_type;
BEGIN
OPEN c0;
LOOP
FETCH c0 BULK COLLECT
INTO items LIMIT batchsize;
EXIT WHEN items.COUNT = 0;
FORALL i IN items.FIRST .. items.LAST SAVE EXCEPTIONS
INSERT INTO detail_items VALUES items (i);
END LOOP;
CLOSE c0;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
RAISE;
END;
END;
END X;
Please review.
You should be using iostream
without the .h
.
Early implementations used the .h
variants but the standard mandates the more modern style.
Here's a cross browser function I have in my standard library:
function getCursorPos(input) {
if ("selectionStart" in input && document.activeElement == input) {
return {
start: input.selectionStart,
end: input.selectionEnd
};
}
else if (input.createTextRange) {
var sel = document.selection.createRange();
if (sel.parentElement() === input) {
var rng = input.createTextRange();
rng.moveToBookmark(sel.getBookmark());
for (var len = 0;
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
len++;
}
rng.setEndPoint("StartToStart", input.createTextRange());
for (var pos = { start: 0, end: len };
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
pos.start++;
pos.end++;
}
return pos;
}
}
return -1;
}
Use it in your code like this:
var cursorPosition = getCursorPos($('#myTextarea')[0])
Here's its complementary function:
function setCursorPos(input, start, end) {
if (arguments.length < 3) end = start;
if ("selectionStart" in input) {
setTimeout(function() {
input.selectionStart = start;
input.selectionEnd = end;
}, 1);
}
else if (input.createTextRange) {
var rng = input.createTextRange();
rng.moveStart("character", start);
rng.collapse();
rng.moveEnd("character", end - start);
rng.select();
}
}
The first thing that comes to my mind is a one-liner regex:
var pageNum = $("#specificLink").attr("href").match(/page=([0-9]+)/)[1];
Thought of writing this answer as nothing worked from above & you don't want to specify proxy location.
If you're using httpClient
then consider this.
HttpClientHandler handler = new HttpClientHandler();
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
handler.Proxy = proxy;
var client = new HttpClient(handler);
// your next steps...
And if you're using HttpWebRequest
:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + _endpoint);
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = proxy;
Kind referencce: https://medium.com/@siriphonnot/the-remote-server-returned-an-error-407-proxy-authentication-required-86ae489e401b
UPDATE : see Mike Todd's solution for a complete answer.
$("#div1").animate({ scrollTop: $('#div1').height()}, 1000);
if you want it to be animated (over 1000 milliseconds).
$('#div1').scrollTop($('#div1').height())
if you want it instantaneous.
$(elem).find('option[value="' + value + '"]').attr("selected", "selected");
I also lost a half of day trying to fix this.
It appeared that root was my project pom.xml file with dependency:
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
Other members of the team had no problems. At the end it appeared, that I got newer tomcat which has different version of jsp-api provided (in tomcat 7.0.60 and above it will be jsp-api 2.2).
So in this case, options would be:
a) installing different (older/newer) tomcat like (Exactly what I did, because team is on older version)
b) changing dependency scope to 'compile'
c) update whole project dependencies to the actual version of Tomcat/lib provided APIs
d) put matching version of the jsp-api.jar in {tomcat folder}/lib
Jon Skeet is correct. Here is the Nul Device Driver page in the Windows Embedded documentation (I have no idea why it's not somewhere else...).
Here is another:
I found git here
C:\Users\<User>\AppData\Local\GitHubDesktop\app-0.5.8\resources\app\git\cmd\git.exe
You have to write file name (git.exe) in the end of path otherwise it will give an error=5
Or you can check here also.
C:\Program Files\Git\bin\git.exe
You can look into UglifyJS
: http://jstarrdewar.com/blog/2013/02/28/use-uglify-to-automatically-strip-debug-messages-from-your-javascript/, https://github.com/mishoo/UglifyJS
I haven't tried it yet.
Quoting,
if (typeof DEBUG === 'undefined') DEBUG = true; // will be removed
function doSomethingCool() {
DEBUG && console.log("something cool just happened"); // will be removed }
...The log message line will be removed by Uglify's dead-code remover (since it will erase any conditional that will always evaluate to false). So will that first conditional. But when you are testing as uncompressed code, DEBUG will start out undefined, the first conditional will set it to true, and all your console.log() messages will work.
Just set usesCleartextTraffic
flag in the application tag of AndroidManifest.xml
file.
No need to create config file for Android.
<application
android:usesCleartextTraffic="true"
.
.
.>
Can be very simplified like that :
input[type="checkbox"]{
outline:2px solid red;
outline-offset: -2px;
}
Works without any plugin :)
USE THIS ONLY IF YOU HAVE LIMITED NUMBER OF ITEMS IN YOUR RECYCLER VIEW.
I tried using boolean value in model and keep the checkbox status, but it did not help in my case.
What worked for me is this.setIsRecyclable(false);
public class ComponentViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView) {
super(itemView);
....
this.setIsRecyclable(false);
}
More explanation on this can be found here https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#isRecyclable()
NOTE: This is a workaround. To use it properly you can refer the document which states "Calls to setIsRecyclable() should always be paired (one call to setIsRecyclabe(false) should always be matched with a later call to setIsRecyclable(true)). Pairs of calls may be nested, as the state is internally reference-counted." I don't know how to do this in code, if someone can provide more code on this.
/* Microsoft Edge Browser 12-18 (All versions before Chromium) */
This one should work:
@supports (-ms-ime-align:auto) {
.selector {
property: value;
}
}
For more see: Browser Strangeness
platform.architecture()
is problematic (and expensive).
Conveniently test for sys.maxsize > 2**32
since Py2.6 .
This is a reliable test for the actual (default) pointer size and compatible at least since Py2.3: struct.calcsize('P') == 8
. Also: ctypes.sizeof(ctypes.c_void_p) == 8
.
Notes: There can be builds with gcc option -mx32
or so, which are 64bit architecture applications, but use 32bit pointers as default (saving memory and speed). 'sys.maxsize = ssize_t' may not strictly represent the C pointer size (its usually 2**31 - 1
anyway). And there were/are systems which have different pointer sizes for code and data and it needs to be clarified what exactly is the purpose of discerning "32bit or 64bit mode?"
If you want to write this compactly all you need is:
var i = 0;
for (;yourElement.parentNode[i]!==yourElement;i++){}
indexOfYourElement = i;
We just cycle through the elements in the parent node, stopping when we find your element.
You can also easily do:
for (;yourElement.parentNode.getElementsByTagName("li")[i]!==yourElement;i++){}
if that's all you want to look through.
I had this exact same problem in VS 2015
. It looks like as of VS 2010
and later you need to include #include "stdafx.h"
in all your projects.
#include "stdafx.h"
#include <iostream>
using namespace std;
The above worked for me. The below did not:
#include <iostream>
using namespace std;
This also failed:
#include <iostream>
using namespace std;
#include "stdafx.h"
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
All you need is to make an ajax request to your pythoncode. You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
The basic difference is the syntax. While SASS has a loose syntax with white space and no semicolons, the SCSS resembles more to CSS.
Remember, Objective-C is a superset of C, so typecasting works as it does in C:
myEditController = [[SelectionListViewController alloc] init];
((SelectionListViewController *)myEditController).list = listOfItems;
The proposed solutions are interesting and offer a good reference, however they are only partially satisfying. It is ok to manually add the separator when you have a single specific case or you know the format of the input string, but there can be cases where you want to do it programmatically on generic inputs.
With a bit of experimenting, I believe the criteria is that the path delimiter is not added if the first segment is a drive letter, meaning a single letter followed by a colon, no matter if it corresponds to a real unit.
For example:
import os
testval = ['c:','c:\\','d:','j:','jr:','data:']
for t in testval:
print ('test value: ',t,', join to "folder"',os.path.join(t,'folder'))
test value: c: , join to "folder" c:folder test value: c:\ , join to "folder" c:\folder test value: d: , join to "folder" d:folder test value: j: , join to "folder" j:folder test value: jr: , join to "folder" jr:\folder test value: data: , join to "folder" data:\folder
A convenient way to test for the criteria and apply a path correction can be to use os.path.splitdrive
comparing the first returned element to the test value, like t+os.path.sep if os.path.splitdrive(t)[0]==t else t
.
Test:
for t in testval:
corrected = t+os.path.sep if os.path.splitdrive(t)[0]==t else t
print ('original: %s\tcorrected: %s'%(t,corrected),' join corrected->',os.path.join(corrected,'folder'))
original: c: corrected: c:\ join corrected-> c:\folder original: c:\ corrected: c:\ join corrected-> c:\folder original: d: corrected: d:\ join corrected-> d:\folder original: j: corrected: j:\ join corrected-> j:\folder original: jr: corrected: jr: join corrected-> jr:\folder original: data: corrected: data: join corrected-> data:\folder
it can be probably be improved to be more robust for trailing spaces, and I have tested it only on windows, but I hope it gives an idea. See also Os.path : can you explain this behavior? for interesting details on systems other then windows.
A possible solutions is to declare a second bean which reads from the same properties file:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/app.properties" />
</bean>
<util:properties id="appProperties" location="classpath:/WEB-INF/app.properties"/>
The bean named 'appProperties' is of type java.util.Properties and can be dependency injected using the @Resource attruibute shown above.
Olof's answer is good, but it needs one more thing before it's perfect. In the comments below his answer, dacwe (correctly) points out that his implementation violates the Compare/Equals contract for Sets. If you try to call contains or remove on an entry that's clearly in the set, the set won't recognize it because of the code that allows entries with equal values to be placed in the set. So, in order to fix this, we need to test for equality between the keys:
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
if (e1.getKey().equals(e2.getKey())) {
return res; // Code will now handle equality properly
} else {
return res != 0 ? res : 1; // While still adding all entries
}
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
"Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface... the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal." (http://docs.oracle.com/javase/6/docs/api/java/util/SortedSet.html)
Since we originally overlooked equality in order to force the set to add equal valued entries, now we have to test for equality in the keys in order for the set to actually return the entry you're looking for. This is kinda messy and definitely not how sets were intended to be used - but it works.
Actually is quite easy with this option at the end:
c:\start BATCH.bat -WindowStyle Hidden
There are 4 dimensions of the tensor you want to convert.
[:, ::-1, :, :]
:
means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.
::-1
means that for the second axes it reverses the the axes
I suggest to use utf8mb4_unicode_ci
, which is based on the Unicode standard for sorting and comparison, which sorts accurately in a very wide range of languages.
Regan's answer is great, but it's a bit out of date, since the correct way to do this is avoid the lxc execution context as Docker has dropped LXC as the default execution context as of docker 0.9.
Instead it's better to tell docker about the nvidia devices via the --device flag, and just use the native execution context rather than lxc.
These instructions were tested on the following environment:
See CUDA 6.5 on AWS GPU Instance Running Ubuntu 14.04 to get your host machine setup.
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9
$ sudo sh -c "echo deb https://get.docker.com/ubuntu docker main > /etc/apt/sources.list.d/docker.list"
$ sudo apt-get update && sudo apt-get install lxc-docker
ls -la /dev | grep nvidia
crw-rw-rw- 1 root root 195, 0 Oct 25 19:37 nvidia0
crw-rw-rw- 1 root root 195, 255 Oct 25 19:37 nvidiactl
crw-rw-rw- 1 root root 251, 0 Oct 25 19:37 nvidia-uvm
I've created a docker image that has the cuda drivers pre-installed. The dockerfile is available on dockerhub if you want to know how this image was built.
You'll want to customize this command to match your nvidia devices. Here's what worked for me:
$ sudo docker run -ti --device /dev/nvidia0:/dev/nvidia0 --device /dev/nvidiactl:/dev/nvidiactl --device /dev/nvidia-uvm:/dev/nvidia-uvm tleyden5iwx/ubuntu-cuda /bin/bash
This should be run from inside the docker container you just launched.
Install CUDA samples:
$ cd /opt/nvidia_installers
$ ./cuda-samples-linux-6.5.14-18745345.run -noprompt -cudaprefix=/usr/local/cuda-6.5/
Build deviceQuery sample:
$ cd /usr/local/cuda/samples/1_Utilities/deviceQuery
$ make
$ ./deviceQuery
If everything worked, you should see the following output:
deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 6.5, CUDA Runtime Version = 6.5, NumDevs = 1, Device0 = GRID K520
Result = PASS
With current projects you may want to use the NS_ENUM()
or NS_OPTIONS()
macros.
typedef NS_ENUM(NSUInteger, PlayerState) {
PLAYER_OFF,
PLAYER_PLAYING,
PLAYER_PAUSED
};
Here is an example implementation, which would make this process seamless (Borrowed from AngularJs)
var CookieReader = (function(){
var lastCookies = {};
var lastCookieString = '';
function safeGetCookie() {
try {
return document.cookie || '';
} catch (e) {
return '';
}
}
function safeDecodeURIComponent(str) {
try {
return decodeURIComponent(str);
} catch (e) {
return str;
}
}
function isUndefined(value) {
return typeof value === 'undefined';
}
return function () {
var cookieArray, cookie, i, index, name;
var currentCookieString = safeGetCookie();
if (currentCookieString !== lastCookieString) {
lastCookieString = currentCookieString;
cookieArray = lastCookieString.split('; ');
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
name = safeDecodeURIComponent(cookie.substring(0, index));
if (isUndefined(lastCookies[name])) {
lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
};
})();
Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.
Step 1. Use the following namespaces
using System.Windows;
using System.Threading;
using System.Windows.Threading;
Step 2. Put the following line where you need to update UI
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
//Update UI here
}));
Syntax
[BrowsableAttribute(false)] public object Invoke( DispatcherPriority priority, Delegate method )
Parameters
priority
Type:
System.Windows.Threading.DispatcherPriority
The priority, relative to the other pending operations in the Dispatcher event queue, the specified method is invoked.
method
Type:
System.Delegate
A delegate to a method that takes no arguments, which is pushed onto the Dispatcher event queue.
Return Value
Type:
System.Object
The return value from the delegate being invoked or null if the delegate has no return value.
Version Information
Available since .NET Framework 3.0
$.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: associated_buildsorprojects_form,
success:function(data){
// do console.log(data);
console.log(data);
// you'll find that what exactly inside data
// I do not prefer alter(data); now because, it does not
// completes requirement all the time
// After that you can easily put if condition that you do not want like
// if(data != '')
// if(data == null)
// or whatever you want
},
error: function(errorThrown){
alert(errorThrown);
alert("There is an error with AJAX!");
}
});
Do you want to order it?
Select * From temp where mydate > '2009-06-29 04:00:44' ORDER BY mydate;
I got this after i copied the svc file and renamed it. Although the file name and the svc.cs file were correctly renamed, the markup still referenced the original file.
To fix this, right click on the copied svc file and choose View Markup and change the service reference.
More accurately, your mod1
and lib
directories are not modules, they are packages. The file mod11.py
is a module.
Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.
>>> import lib
>>> dir(lib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> import lib.pkg1
>>> import lib.pkg1.mod11
>>> lib.pkg1.mod11.mod12()
mod12
An alternative is to use the from
syntax to "pull" a module from a package into you scripts namespace.
>>> from lib.pkg1 import mod11
Then reference the function as simply mod11.mod12()
.
As provided in chosen explanation, git reset is good. But nowadays we often use sub-modules: repositories inside repositories. For example, you if you use ZF3 and jQuery in your project you most probably want them to be cloned from their original repositories. In such case git reset is not enough. We need to update submodules to that exact version that are defined in our repository:
git checkout master
git fetch origin master
git reset --hard origin/master
git pull
git submodule foreach git submodule update
git status
it is the same as you will come (cd) recursively to the working directory of each sub-module and will run:
git submodule update
And it's very different from
git checkout master
git pull
because sub-modules point not to branch but to the commit.
In that cases when you manually checkout some branch for 1 or more submodules you can run
git submodule foreach git pull
[Xcode 11.2.1]
For me it was different app target version in Podfile
(platform :ios, '11.0'
) and in Xcode project file .
It causing Archiving job fail in CI pipeline.
Matching both value fixed an issue! Hope this help anyone.
This little bash script will brute force reassign, you may lose data.
NODE="YOUR NODE NAME"
IFS=$'\n'
for line in $(curl -s 'localhost:9200/_cat/shards' | fgrep UNASSIGNED); do
INDEX=$(echo $line | (awk '{print $1}'))
SHARD=$(echo $line | (awk '{print $2}'))
curl -XPOST 'localhost:9200/_cluster/reroute' -d '{
"commands": [
{
"allocate": {
"index": "'$INDEX'",
"shard": '$SHARD',
"node": "'$NODE'",
"allow_primary": true
}
}
]
}'
done
This creates a "See Also" heading containing the link, i.e.:
/**
* @see <a href="http://google.com">http://google.com</a>
*/
will render as:
See Also:
http://google.com
whereas this:
/**
* See <a href="http://google.com">http://google.com</a>
*/
will create an in-line link:
In general, once a module has been installed, it's much more convenient to use npm ci
instead of npm install
. Please check out this SO answer for the advantages of the former with respect to the later in a production environment.
So please just run
npm ci
All dependencies will be updated, and the problem will disappear. Or it will error in the case there's some grave de-synchronization between one and the other.
http://www.geeksforgeeks.org/archives/9102 discusses in details.
Mutex
is locking mechanism used to synchronize access to a resource.
Semaphore
is signaling mechanism.
Its up to to programmer if he/she wants to use binary semaphore in place of mutex.
I have met a similar problem when checking emptiness in a component. In this case, the controller must define a method that actually performs the test and the view uses it:
function FormNumericFieldController(/*$scope, $element, $attrs*/ ) {
var ctrl = this;
ctrl.isEmptyObject = function(object) {
return angular.equals(object, {});
}
}
<!-- any validation error will trigger an error highlight -->
<span ng-class="{'has-error': !$ctrl.isEmptyObject($ctrl.formFieldErrorRef) }">
<!-- validated control here -->
</span>
Set the display
property to inline
for the list you want this to apply to. There's a good explanation of displaying lists on A List Apart.
Why make it so complicated? This worked.
SELECT m_id,v_id,MAX(TIMESTAMP) AS TIME
FROM table_name
GROUP BY m_id
For simple cases (where sentences are terminated normally), this should work:
import re
text = ''.join(open('somefile.txt').readlines())
sentences = re.split(r' *[\.\?!][\'"\)\]]* *', text)
The regex is *\. +
, which matches a period surrounded by 0 or more spaces to the left and 1 or more to the right (to prevent something like the period in re.split being counted as a change in sentence).
Obviously, not the most robust solution, but it'll do fine in most cases. The only case this won't cover is abbreviations (perhaps run through the list of sentences and check that each string in sentences
starts with a capital letter?)
For SQL Server, if using a newer version, you can use
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'
There are different ways to get the schema. Using ADO.NET, you can use the schema methods. Use the DbConnection
's GetSchema
method or the DataReader
'sGetSchemaTable
method.
Provided that you have a reader for the for the query, you can do something like this:
using(DbCommand cmd = ...)
using(var reader = cmd.ExecuteReader())
{
var schema = reader.GetSchemaTable();
foreach(DataRow row in schema.Rows)
{
Debug.WriteLine(row["ColumnName"] + " - " + row["DataTypeName"])
}
}
See this article for further details.
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
To disable inputting password:
sudo visudo
Then add a new line like below and save then:
# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer
Then you run installer without password:
sudo installer -pkg ...
Use the location header flag:
curl -L <URL>
returning true or false indicates that whether execution should continue or stop right there. So just an example
<input type="button" onclick="return func();" />
Now if func() is defined like this
function func()
{
// do something
return false;
}
the click event will never get executed. On the contrary if return true is written then the click event will always be executed.
If you're coding in an ASP.NET MVC Controller, use
using Microsoft.AspNet.Identity;
...
User.Identity.GetUserId();
Worth mentioning that User.Identity.IsAuthenticated
and User.Identity.Name
will work without adding the above mentioned using
statement. But GetUserId()
won't be present without it.
If you're in a class other than a Controller, use
HttpContext.Current.User.Identity.GetUserId();
In the default template of MVC 5, user ID is a GUID stored as a string.
No best practice yet, but found some valuable info on extending the user profile:
Identity
: https://devblogs.microsoft.com/aspnet/introducing-asp-net-identity-a-membership-system-for-asp-net-applications/EDIT: added a new example for ggplot2 at the end
See ?plotmath for the different mathematical operations in R
You should be able to use expression without paste. If you use the tilda (~) symbol within the expression function it will assume there is a space between the characters, or you could use the * symbol and it won't put a space between the arguments
Sometimes you will need to change the margins in you're putting superscripts on the y-axis.
par(mar=c(5, 4.3, 4, 2) + 0.1)
plot(1:10, xlab = expression(xLab ~ x^2 ~ m^-2),
ylab = expression(yLab ~ y^2 ~ m^-2),
main="Plot 1")
plot(1:10, xlab = expression(xLab * x^2 * m^-2),
ylab = expression(yLab * y^2 * m^-2),
main="Plot 2")
plot(1:10, xlab = expression(xLab ~ x^2 * m^-2),
ylab = expression(yLab ~ y^2 * m^-2),
main="Plot 3")
Hopefully you can see the differences between plots 1, 2 and 3 with the different uses of the ~ and * symbols. An extra note, you can use other symbols such as plotting the degree symbol for temperatures for or mu, phi. If you want to add a subscript use the square brackets.
plot(1:10, xlab = expression('Your x label' ~ mu[3] * phi),
ylab = expression("Temperature (" * degree * C *")"))
Here is a ggplot example using expression with a nonsense example
require(ggplot2)
Or if you have the pacman library installed you can use p_load to automatically download and load and attach add-on packages
# require(pacman)
# p_load(ggplot2)
data = data.frame(x = 1:10, y = 1:10)
ggplot(data, aes(x,y)) + geom_point() +
xlab(expression(bar(yourUnits) ~ g ~ m^-2 ~ OR ~ integral(f(x)*dx, a,b))) +
ylab(expression("Biomass (g per" ~ m^3 *")")) + theme_bw()
You need read.csv("C:/somedirectory/some/file.csv")
and in general it doesn't hurt to actually look at the help page including its example section at the bottom.
The explanation from Scott Meyers in Effective C++ might help understand when to use them:
Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.
In SQL Server Management Studio, go to Object Explorer > (your server) > Security > Logins
and right-click New Login
:
Then in the dialog box that pops up, pick the types of objects you want to see (Groups
is disabled by default - check it!) and pick the location where you want to look for your objects (e.g. use Entire Directory
) and then find your AD group.
You now have a regular SQL Server Login - just like when you create one for a single AD user. Give that new login the permissions on the databases it needs, and off you go!
Any member of that AD group can now login to SQL Server and use your database.
Position Relative:
If you specify position:relative, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document.
Position Absolute:
When you specify position:absolute, the element is removed from the document and placed exactly where you tell it to go.
Here is a good tutorial http://www.barelyfitz.com/screencast/html-training/css/positioning/ with the sample usage of both position with respective to absolute and relative positioning.
A previous answer on this page describes how to use .htaccess to force all files of a certain type to download. However, the solution does not work with all file types across all browsers. This is a more reliable way:
<FilesMatch "\.(?i:csv)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
You might need to flush your browser cache to see this working correctly.
In C# it doesn't matter. The two code samples you give are utterly equivalent. In the first example the C# compiler (or is it the CLR?) will construct an empty constructor and initialise the variables as if they were in the constructor (there's a slight nuance to this that Jon Skeet explains in the comments below). If there is already a constructor then any initialisation "above" will be moved into the top of it.
In terms of best practice the former is less error prone than the latter as someone could easily add another constructor and forget to chain it.
Be careful when checking for existence with a like statement!
If in a series of unfortunate events your variable ends up being empty, and you end up executing this:
SHOW DATABASES like '' -- dangerous!
It will return ALL databases, thus telling the calling script that it exists since some rows were returned.
It's much safer and better practice to use an "=" equal sign to test for existence.
The correct and safe way to test for existence should be:
SHOW DATABASES WHERE `database` = 'xxxxx' -- safe way to test for existence
Note that you have to wrap the column name database with backticks, it can't use relaxed syntax in this case.
This way, if the code creating the variable 'xxxxx' returned blank, then SHOW DATABASES will not return ALL databases, but will return an empty set.
Notice that if the file's parent folder doesn't exist you'll get the same error:
IOError: [Errno 2] No such file or directory:
Below is another solution which handles this case:
(*) I used sys.stdout
and print
instead of f.write
just to show another use case
# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
print_to_log_file(folder_path, "Some File" ,"Some Content")
Where the internal print_to_log_file
just take care of the file level:
# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):
#1) Save a reference to the original standard output
original_stdout = sys.stdout
#2) Choose the mode
write_append_mode = 'a' #Append mode
file_path = folder_path + file_name
if (if not os.path.exists(file_path) ):
write_append_mode = 'w' # Write mode
#3) Perform action on file
with open(file_path, write_append_mode) as f:
sys.stdout = f # Change the standard output to the file we created.
print(file_path, content_to_write)
sys.stdout = original_stdout # Reset the standard output to its original value
Consider the following states:
'w' --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a' --> Append to file
'a+' --> Append to file, Create it if doesn't exist
In your case I would use a different approach and just use 'a'
and 'a+'
.
If you run a script directly e.g., ./xx.py
and your script has no shebang such as #!/usr/bin/env python
at the very top then your shell may execute it as a shell script. POSIX says:
If the execl() function fails due to an error equivalent to the [ENOEXEC] error defined in the System Interfaces volume of POSIX.1-2008, the shell shall execute a command equivalent to having a shell invoked with the pathname resulting from the search as its first operand, with any remaining arguments passed to the new shell, except that the value of "$0" in the new shell may be set to the command name. If the executable file is not a text file, the shell may bypass this command execution. In this case, it shall write an error message, and shall return an exit status of 126.
Note: you may get ENOEXEC
if your text file has no shebang.
Without the shebang, you shell tries to run your Python script as a shell script that leads to the error: import: command not found
.
Also, if you run your script as python xx.py
then you do not need the shebang. You don't even need it to be executable (+x
). Your script is interpreted by python
in this case.
On Windows, shebang is not used unless pylauncher is installed. It is included in Python 3.3+.
The only difference is that you're creating an unnecessary promise when you do return Promise.resolve("bbb")
. Returning a promise from an onFulfilled()
handler kicks off promise resolution. That's how promise chaining works.
I have faced the same problem when I tape the URL
https://www.nameDomain.com/phpmyadmin
the forbidden message shows up, because of the rules on /use/share/phpMyAdmin directory
I fix it by adding in this file /etc/httpd/conf.d/phpMyAdmin.conf
in this section
<Directory /usr/share/phpMyAdmin/>
....
</Directory>
these line of rules
<Directory /usr/share/phpMyAdmin/>
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
Allow from All
...
</Directory>
you save the file, then you restart the apache service whatever method you choose service httpd graceful
or service httpd restart
it depends on your policy
for security reasons you can specify one connection by setting one IP address if your IP does not change, else if your IP changes every time you have to change it also.
<Directory /usr/share/phpMyAdmin/>
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
Allow from 105.105.105.254 ## set here your IP address
...
</Directory>
I found solution. It works fine when I throw away next line from form:
enctype="multipart/form-data"
And now it pass all parameters at request ok:
<form action="/registration" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>
I like @Alex Howansky have used 'cmp --silent' for this. But I need both positive and negative response so I use:
cmp --silent file1 file2 && echo '### SUCCESS: Files Are Identical! ###' || echo '### WARNING: Files Are Different! ###'
I can then run this in the terminal or with a ssh to check files against a constant file.
You can use this OrderedDict recipe
written by Raymond Hettinger and modify it to add a rename
method, but this is going to be a O(N) in complexity:
def rename(self,key,new_key):
ind = self._keys.index(key) #get the index of old key, O(N) operation
self._keys[ind] = new_key #replace old key with new key in self._keys
self[new_key] = self[key] #add the new key, this is added at the end of self._keys
self._keys.pop(-1) #pop the last item in self._keys
Example:
dic = OrderedDict((("a",1),("b",2),("c",3)))
print dic
dic.rename("a","foo")
dic.rename("b","bar")
dic["d"] = 5
dic.rename("d","spam")
for k,v in dic.items():
print k,v
output:
OrderedDict({'a': 1, 'b': 2, 'c': 3})
foo 1
bar 2
c 3
spam 5
The following code outputs the number of words whose first and last letters are equal. Tested and verified using a python online compiler:
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
count = 0
for i in words:
if i[0]==i[-1]:
count = count + 1
print(count)
Output:
$python main.py
3
Just to add to the others, you can pass a function name:
function someFunc($a)
{
echo $a;
}
function callFunc($name)
{
$name('funky!');
}
callFunc('someFunc');
This will work in PHP4.
Put the line
$this->db->order_by("course_name","desc");
at top of your query. Like
$this->db->order_by("course_name","desc");$this->db->select('*');
$this->db->where('tennant_id',$tennant_id);
$this->db->from('courses');
$query=$this->db->get();
return $query->result();
Map
is an interface, i.e. an abstract "thing" that defines how something can be used. HashMap
is an implementation of that interface.
I had similar problem on windows, however sometimes eslint worked (in vscode) sometimes not. Later I realized that it works fine after a while. It was related to this issue: eslint server takes ~3-5 minutes until available
Setting enviroment variable NO_UPDATE_NOTIFIER=1
solved the problem
One way to handle it it to remove something from a copy of a Collection
(not Collection itself), if applicable. Clone
the original collection it to make a copy via a Constructor
.
This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.
For your specific case, first off, i don't think final
is a way to go considering you intend to modify the list past declaration
private static final List<Integer> integerList;
Also consider modifying a copy instead of the original list.
List<Integer> copy = new ArrayList<Integer>(integerList);
for(Integer integer : integerList) {
if(integer.equals(remove)) {
copy.remove(integer);
}
}
Union has not good performance : this article describe about compare them with together
var dict = list2.ToDictionary(p => p.Number);
foreach (var person in list1)
{
dict[person.Number] = person;
}
var merged = dict.Values.ToList();
Lists and LINQ merge: 4820ms
Dictionary merge: 16ms
HashSet and IEqualityComparer: 20ms
LINQ Union and IEqualityComparer: 24ms
Find the element (must be an input element with type="file" attribute) and send the path to the file.
WebElement fileInput = driver.findElement(By.id("uploadFile"));
fileInput.sendKeys("/path/to/file.jpg");
NOTE: If you're using a RemoteWebDriver, you will also have to set a file detector. The default is UselessFileDetector
WebElement fileInput = driver.findElement(By.id("uploadFile"));
driver.setFileDetector(new LocalFileDetector());
fileInput.sendKeys("/path/to/file.jpg");
Use the Chart Wizard.
On Step 2 of 4, there is a tab labeled "Series". There are 3 fields and a list box on this tab. The list box shows the different series you are already including on the chart. Each series has both a "Name" field and a "Values" field that is specific to that series. The final field is the "Category (X) axis labels" field, which is common to all series.
Click on the "Add" button below the list box. This will add a blank series to your list box. Notice that the values for "Name" and for "Values" change when you highlight a series in the list box.
Select your new series.
There is an icon in each field on the right side. This icon allows you to select cells in the workbook to pull the data from. When you click it, the Wizard temporarily hides itself (except for the field you are working in) allowing you to interact with the workbook.
Select the appropriate sheet in the workbook and then select the fields with the data you want to show in the chart. The button on the right of the field can be clicked to unhide the wizard.
Hope that helps.
EDIT: The above applies to 2003 and before. For 2007, when the chart is selected, you should be able to do a similar action using the "Select Data" option on the "Design" tab of the ribbon. This opens up a dialog box listing the Series for the chart. You can select the series just as you could in Excel 2003, but you must use the "Add" and "Edit" buttons to define custom series.
I found information about .bashrc and .bash_profile here to sum it up:
.bash_profile is executed when you login. Stuff you put in there might be your PATH and other important environment variables.
.bashrc is used for non login shells. I'm not sure what that means. I know that RedHat executes it everytime you start another shell (su to this user or simply calling bash again) You might want to put aliases in there but again I am not sure what that means. I simply ignore it myself.
.profile is the equivalent of .bash_profile for the root. I think the name is changed to let other shells (csh, sh, tcsh) use it as well. (you don't need one as a user)
There is also .bash_logout wich executes at, yeah good guess...logout. You might want to stop deamons or even make a little housekeeping . You can also add "clear" there if you want to clear the screen when you log out.
Also there is a complete follow up on each of the configurations files here
These are probably even distro.-dependant, not all distros choose to have each configuraton with them and some have even more. But when they have the same name, they usualy include the same content.
LATEST UPDATE
Now you can use the latest API from whatsapp https://wa.me/
without worrying about the user agent, the API will do the user agent handling.
Share pre-filled text with contact selection option in respective whatsapp client (Android / iOS / Webapp):
https://wa.me/?text=urlencodedtext
Open Chat Dialog for a particular whatsapp user in respective whatsapp client (Android / iOS / Webapp):
https://wa.me/whatsappphonenumber
Share pre-filled text with a particular user (Combine above two):
https://wa.me/whatsappphonenumber/?text=urlencodedtext
Note : whatsappphonenumber
should be full phone number in international format. Omit any zeroes, brackets or dashes when adding the phone number in international format.
For official documentation visit https://faq.whatsapp.com/en/general/26000030
Use dumpbin
command-line.
dumpbin /IMPORTS <path-to-file>
should provide the function imported into that DLL. dumpbin /EXPORTS <path-to-file>
should provide the functions it exports.OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.
The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.
For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream
to be changed, and as long as the API (interface) to FileInputStream
remains consistent, code built against previous versions will still work.
Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.
In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).
For example, the fields of a class can be made private
by default, and only if external access to these was required, would a get()
and/or set()
(or Property
) be exposed from the class. (In modern day OO languages, fields can be marked as readonly
/ final
/ immutable
which further restricts change, even within the class).
Example where NO information hiding has been applied (Bad Practice):
class Foo {
// BAD - NOT Encapsulated - code external to the class can change this field directly
// Class Foo has no control over the range of values which could be set.
public int notEncapsulated;
}
Example where field encapsulation has been applied:
class Bar {
// Improvement - access restricted only to this class
private int encapsulatedPercentageField;
// The state of Bar (and its fields) can now be changed in a controlled manner
public void setEncapsulatedField(int percentageValue) {
if (percentageValue >= 0 && percentageValue <= 100) {
encapsulatedPercentageField = percentageValue;
}
// else throw ... out of range
}
}
Example of immutable / constructor-only initialization of a field:
class Baz {
private final int immutableField;
public void Baz(int onlyValue) {
// ... As above, can also check that onlyValue is valid
immutableField = onlyValue;
}
// Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class
}
Re : Abstraction vs Abstract Class
Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new()
- abstract classes must be subclassed, and only concrete
(non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction
and an abstract class
was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.
Re : Encapsulation vs Information Hiding
The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation
can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.
Quoting Wikipedia:
In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.
For example, in the statement
I've encapsulated the data access code into its own class
.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.
[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed
Though the earlier answers are correct, there's a small complication it would help to remark on.
In case your main module imports another module in which global variables or class member variables are defined and initialized to (or using) some new objects, you may have to condition that import in the same way:
if __name__ == '__main__':
import my_module
One issue that I've come across is that to have a scrollbar a n element needs a height to be specified (and not as a %).
The trick is to nest another set of divs within each column, and set the column parent's display to flex with flex-direction: column.
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
body {
overflow-y: hidden;
overflow-x: hidden;
color: white;
}
.base-container {
display: flex;
flex: 1;
flex-direction: column;
width: 100%;
height: 100%;
overflow-y: hidden;
align-items: stretch;
}
.title {
flex: 0 0 50px;
color: black;
}
.container {
flex: 1 1 auto;
display: flex;
flex-direction: column;
}
.container .header {
flex: 0 0 50px;
background-color: red;
}
.container .body {
flex: 1 1 auto;
display: flex;
flex-direction: row;
}
.container .body .left {
display: flex;
flex-direction: column;
flex: 0 0 80px;
background-color: blue;
}
.container .body .left .content,
.container .body .main .content,
.container .body .right .content {
flex: 1 1 auto;
overflow-y: auto;
height: 100px;
}
.container .body .main .content.noscrollbar {
overflow-y: hidden;
}
.container .body .main {
display: flex;
flex-direction: column;
flex: 1 1 auto;
background-color: green;
}
.container .body .right {
display: flex;
flex-direction: column;
flex: 0 0 300px;
background-color: yellow;
color: black;
}
.test {
margin: 5px 5px;
border: 1px solid white;
height: calc(100% - 10px);
}
</style>
And here's the html:
<div class="base-container">
<div class="title">
Title
</div>
<div class="container">
<div class="header">
Header
</div>
<div class="body">
<div class="left">
<div class="content">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>12</li>
<li>13</li>
<li>14</li>
<li>15</li>
<li>16</li>
<li>17</li>
<li>18</li>
<li>19</li>
<li>20</li>
<li>21</li>
<li>22</li>
<li>23</li>
<li>24</li>
</ul>
</div>
</div>
<div class="main">
<div class="content noscrollbar">
<div class="test">Test</div>
</div>
</div>
<div class="right">
<div class="content">
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>End</div>
</div>
</div>
</div>
</div>
</div>
Percent calculation that worked for me:
(new_num - old_num) / old_num * 100.0
It depends on the business and system.
If your userId is unique and will be unique all the time, you can use userId as your primary key. But if you ever want to expand your system, it will make things difficult. I advise you to add a foreign key in table user to make a relationship with table profile instead of adding a foreign key in table profile.
echo '1.2+3*[4]|5' | sed -r 's#([().+$*\[\]|])#\\&#g;s#\|#\\|#g'
Yes, here you can use LIMIT
.
You can try it by the below query:
SELECT * FROM employee_list SORT BY salary DESC LIMIT 2
The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.
However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).
The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).
For example:
[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
protected override void OnCreate(Bundle bindle)
{
base.OnCreate(bindle);
}
}
This should work with this :
var cnt = $("#div1 p").length;
switch (true) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
break;
default:
alert('>41');
}
I can't add a comment to futtta's reply above, but for a smoother scroll use:
onClick="document.getElementById('more').scrollIntoView({block: 'start', behavior: 'smooth'});"
Settings > Language & input > Current keyboard > Hardware Switch ON.
This option worked.
const obj = { id: 1, name: 'Neel' };_x000D_
let str = '';_x000D_
str = Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');_x000D_
console.log(str);
_x000D_
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
This snippet can convert your string, image and even video file to Base64 string data.
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />_x000D_
<div id="imgTest"></div>_x000D_
<script type='text/javascript'>_x000D_
function encodeImageFileAsURL() {_x000D_
_x000D_
var filesSelected = document.getElementById("inputFileToLoad").files;_x000D_
if (filesSelected.length > 0) {_x000D_
var fileToLoad = filesSelected[0];_x000D_
_x000D_
var fileReader = new FileReader();_x000D_
_x000D_
fileReader.onload = function(fileLoadedEvent) {_x000D_
var srcData = fileLoadedEvent.target.result; // <--- data: base64_x000D_
_x000D_
var newImage = document.createElement('img');_x000D_
newImage.src = srcData;_x000D_
_x000D_
document.getElementById("imgTest").innerHTML = newImage.outerHTML;_x000D_
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);_x000D_
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);_x000D_
}_x000D_
fileReader.readAsDataURL(fileToLoad);_x000D_
}_x000D_
}_x000D_
</script>
_x000D_
Fill the include
property in the first level of the JSON-object in the tsconfig.editor.json
like here:
"include": [
"src/**/*.ts"
]
It works for me well.
Also you can add another Typescript file extensions if it's needed, like here:
"include": [
"src/**/*.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
As the commenters have stated the best option is to fix the errors, but with limited time or knowledge, that's not always possible. In your php.ini change
error_reporting = E_ALL
to
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT
If you don't have access to the php.ini, you can potentially put this in your .htaccess file:
php_value error_reporting 30711
This is the E_ALL value (32767) and the removing the E_STRICT (2048) and E_NOTICE (8) values.
If you don't have access to the .htaccess file or it's not enabled, you'll probably need to put this at the top of the PHP section of any script that gets loaded from a browser call:
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
One of those should help you be able to use the software. The notices and strict stuff are indicators of problems or potential problems though and you may find some of the code is not working correctly in PHP 5.4.
`e` in ['a', 'b', 'c'] # evaluates as False
`b` in ['a', 'b', 'c'] # evaluates as True
EDIT: With the clarification, new answer:
Note that PHP arrays are vastly different from Python's, combining arrays and dicts into one confused structure. Python arrays always have indices from 0
to len(arr) - 1
, so you can check whether your index is in that range. try/catch
is a good way to do it pythonically, though.
If you're asking about the hash functionality of PHP "arrays" (Python's dict
), then my previous answer still kind of stands:
`baz` in {'foo': 17, 'bar': 19} # evaluates as False
`foo` in {'foo': 17, 'bar': 19} # evaluates as True
You need to use the URL for the link, such as this:
NSURL *path = [[NSBundle mainBundle] URLForResource:@"imagename" withExtension:@"jpg"];
It will give you a proper URL ref.
The code date.to_time.to_i
should work fine. The Rails console session below shows an example:
>> Date.new(2009,11,26).to_time
=> Thu Nov 26 00:00:00 -0800 2009
>> Date.new(2009,11,26).to_time.to_i
=> 1259222400
>> Time.at(1259222400)
=> Thu Nov 26 00:00:00 -0800 2009
Note that the intermediate DateTime object is in local time, so the timestamp might be a several hours off from what you expect. If you want to work in UTC time, you can use the DateTime's method "to_utc".
Wrote a small article about inserting and deleting elements at arbitrary positions in Javascript Arrays.
Here's the small snippet to remove an element from any position. This extends the Array class in Javascript and adds the remove(index) method.
// Remove element at the given index
Array.prototype.remove = function(index) {
this.splice(index, 1);
}
So to remove the first item in your example, call arr.remove():
var arr = [1,2,3,5,6];
arr.remove(0);
To remove the second item,
arr.remove(1);
Here's a tiny article with insert and delete methods for Array class.
Essentially this is no different than the other answers using splice, but the name splice
is non-intuitive, and if you have that call all across your application, it just makes the code harder to read.
I think the following code piece may be helpful:
window.fnPureLog = function(sStatement, anyVariable) {
if (arguments.length < 1) {
throw new Error('Arguments sStatement and anyVariable are expected');
}
if (typeof sStatement !== 'string') {
throw new Error('The type of sStatement is not match, please use string');
}
var oCallStackTrack = new Error();
console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\n' + sStatement + ':', anyVariable);
}
Execute the code:
window.fnPureLog = function(sStatement, anyVariable) {
if (arguments.length < 1) {
throw new Error('Arguments sStatement and anyVariable are expected');
}
if (typeof sStatement !== 'string') {
throw new Error('The type of sStatement is not match, please use string');
}
var oCallStackTrack = new Error();
console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\n' + sStatement + ':', anyVariable);
}
function fnBsnCallStack1() {
fnPureLog('Stock Count', 100)
}
function fnBsnCallStack2() {
fnBsnCallStack1()
}
fnBsnCallStack2();
The log looks like this:
Call Stack:
at window.fnPureLog (<anonymous>:8:27)
at fnBsnCallStack1 (<anonymous>:13:5)
at fnBsnCallStack2 (<anonymous>:17:5)
at <anonymous>:20:1
Stock Count: 100
(IN @brugernavn varchar(64)**)**,IN @password varchar(64))
The problem is the )
Simple :::
scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy
scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy
In addition to Richard Cresswells and dpbradleys answer: If you neither want to create a TNS name nor the '//123.45.67.89:1521/Test' input works (some configurations wont), you can put
(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 123.45.67.89)(PORT = 1521)) (CONNECT_DATA = (SID = TEST)(SERVER = DEDICATED)))
(as one line) into the 'database' section of the login dialog.
I managed to get the desired result, but with a slightly different approach. In the Dropdownlist i used the Model and then referenced it. Not sure if this was what you were looking for.
@Html.DropDownList("Example", new SelectList(Model.FeeStructures, "Id", "NameOfFeeStructure", Model.Matters.FeeStructures))
Model.Matters.FeeStructures in above is my id, which could be your value of the item that should be selected.
You can try L&F which i am developing - WebLaF
It combines three parts required for successful UI development:
Binaries: https://github.com/mgarin/weblaf/releases
Source: https://github.com/mgarin/weblaf
Licenses: GPLv3 and Commercial
A few examples showing how some of WebLaF components look like:
Main reason why i have started with a totally new L&F is that most of existing L&F lack flexibility - you cannot re-style them in most cases (you can only change a few colors and turn on/off some UI elements in best case) and/or there are only inconvenient ways to do that. Its even worse when it comes to custom/3rd party components styling - they doesn't look similar to other components styled by some specific L&F or even totally different - that makes your application look unprofessional and unpleasant.
My goal is to provide a fully customizable L&F with a pack of additional widely-known and useful components (for example: date chooser, tree table, dockable and document panes and lots of other) and additional helpful managers and utilities, which will reduce the amount of code required to quickly integrate WebLaF into your application and help creating awesome UIs using Swing.
Lets assume that you want an UIAlertAction with main title, two actions (save and discard) and cancel button:
let actionSheetController = UIAlertController (title: "My Action Title", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
//Add Cancel-Action
actionSheetController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
//Add Save-Action
actionSheetController.addAction(UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
print("handle Save action...")
}))
//Add Discard-Action
actionSheetController.addAction(UIAlertAction(title: "Discard", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
print("handle Discard action ...")
}))
//present actionSheetController
presentViewController(actionSheetController, animated: true, completion: nil)
This works for swift 2 (Xcode Version 7.0 beta 3)
This code below works for me. I always use only single quotes, and it works fine. I suggest you should use only single quotes or only double quotes, but not mixed up.
$.ajax({
url: 'YourRestEndPoint',
headers: {
'Authorization':'Basic xxxxxxxxxxxxx',
'X-CSRF-TOKEN':'xxxxxxxxxxxxxxxxxxxx',
'Content-Type':'application/json'
},
method: 'POST',
dataType: 'json',
data: YourData,
success: function(data){
console.log('succes: '+data);
}
});
EDIT - as pointed out in the comments, this is not the way to go.
There is such a class - the URI Class. "Provides an object representation of a uniform resource identifier (URI) and easy access to the parts of the URI." (Microsoft docs).
The following example creates an instance of the Uri class and uses it to create a WebRequest instance.
C# example
Uri siteUri = new Uri("http://www.contoso.com/");
WebRequest wr = WebRequest.Create(siteUri);
Check it out, there are lots of methods on this class.
your answer is:
round((strtotime($day2) - strtotime($day1))/(60*60))
Copying an audio file to the sd card of the emulator and selecting it via media player as the default ringtone does indeed solve the problem.
make sure the content inside your div ended with clear:both style
I was using CMake to compile my project and I've found the same problem.
The solution described here works like a charm, simply add ${CMAKE_DL_LIBS} to the target_link_libraries() call
The sed way,
sed -e ':a; N; $!ba; s/\n/,/g'
# :a # label called 'a'
# N # append next line into Pattern Space (see info sed)
# $!ba # if it's the last line ($) do not (!) jump to (b) label :a (a) - break loop
# s/\n/,/g # any substitution you want
Note:
This is linear in complexity, substituting only once after all lines are appended into sed's Pattern Space.
@AnandRajaseka's answer, and some other similar answers, such as here, are O(n²), because sed has to do substitute every time a new line is appended into the Pattern Space.
To compare,
seq 1 100000 | sed ':a; N; $!ba; s/\n/,/g' | head -c 80
# linear, in less than 0.1s
seq 1 100000 | sed ':a; /$/N; s/\n/,/; ta' | head -c 80
# quadratic, hung
After several hours frustrated on this, I decided to use this way. It works for both iPhone and iPad (on Xcode 6.1)
- File >> New File >> User Interface >> Launch Screen
- Create new key/value: "Launch screen interface file base name"/"Your Launch Screen Name" in YourApp-Info.plist
1 picture worths more than thousand words. Please look at below:
If you commit one file and push your revision, it will not transfer the whole repository, it will push changes.
Installation:
for 10.10:
sudo add-apt-repository "deb http://archive.canonical.com/ maverick partner"
for 11.04
sudo add-apt-repository "deb http://archive.canonical.com/ natty partner"
Continue with:
sudo apt-get update
sudo apt-get install sun-java6-jre sun-java6-plugin
Use as default:
sudo update-alternatives --config java
Installing JDK:
sudo apt-get install sun-java6-jdk
Source code (to be used in development):
sudo apt-get install sun-java6-source
Source of these instructions: https://help.ubuntu.com/community/Java
Complete talk fully explaining the problem, which proposes a great paradigm shifting way to avoid these serialization problems: https://github.com/samthebest/dump/blob/master/sams-scala-tutorial/serialization-exceptions-and-memory-leaks-no-ws.md
The top voted answer is basically suggesting throwing away an entire language feature - that is no longer using methods and only using functions. Indeed in functional programming methods in classes should be avoided, but turning them into functions isn't solving the design issue here (see above link).
As a quick fix in this particular situation you could just use the @transient
annotation to tell it not to try to serialise the offending value (here, Spark.ctx
is a custom class not Spark's one following OP's naming):
@transient
val rddList = Spark.ctx.parallelize(list)
You can also restructure code so that rddList lives somewhere else, but that is also nasty.
In future Scala will include these things called "spores" that should allow us to fine grain control what does and does not exactly get pulled in by a closure. Furthermore this should turn all mistakes of accidentally pulling in non-serializable types (or any unwanted values) into compile errors rather than now which is horrible runtime exceptions / memory leaks.
http://docs.scala-lang.org/sips/pending/spores.html
When using kyro, make it so that registration is necessary, this will mean you get errors instead of memory leaks:
"Finally, I know that kryo has kryo.setRegistrationOptional(true) but I am having a very difficult time trying to figure out how to use it. When this option is turned on, kryo still seems to throw exceptions if I haven't registered classes."
Strategy for registering classes with kryo
Of course this only gives you type-level control not value-level control.
... more ideas to come.
I spend a lot of time to convert this code to Kotlin hope it save someone's time
Create a gesture detector:
val gestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
override fun onDoubleTap(e: MotionEvent): Boolean {
Toast.makeText(this@DemoActivity,"Double Tap",Toast.LENGTH_LONG).show()
//Show or hide Ip address on double tap
toggleIPaddressVisibility()
return true;
}
override fun onLongPress(e: MotionEvent) {
super.onLongPress(e);
//rotate frame on long press
toggleFrameRotation()
Toast.makeText(this@DemoActivity,"LongClick",Toast.LENGTH_LONG).show()
}
override fun onDoubleTapEvent(e: MotionEvent): Boolean {
return true
}
override fun onDown(e: MotionEvent): Boolean {
return true
}
})
Assign to any of your view:
IPAddress.setOnTouchListener { v, event ->
return@setOnTouchListener gestureDetector.onTouchEvent(event)
}
I found the answer here: http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/
You just concatenate the string and insert a CHAR(13)
where you want your line break.
Example:
DECLARE @text NVARCHAR(100)
SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.'
SELECT @text
This prints out the following:
This is line 1.
This is line 2.
One thing to note in addition to the approaches suggested is that, in OS X 10.5 (Leopard) at least, the variables set in launchd.conf
will be merged with the settings made in .profile
. I suppose this is likely to be valid for the settings in ~/.MacOSX/environment.plist
too, but I haven't verified.
Even though this question was long time ago, thanks all for the inputs that helping me out a similar problem. I also made a bit modification based on the others' answers here and making multiple inputs/valuables into a Single Object (json); and hope this helps someone.
js:
//example: params={id:'123',name:'foo'};
mapInput.name = "data";
mapInput.value = JSON.stringify(params);
php:
$data=json_decode($_POST['data']);
echo $data->id;
echo $data->name;
Try this
MsgBox("Are you sure want to Exit", MsgBoxStyle.YesNo, "")
If True Then
End
End If
You can also use below properties.
display: flex;
align-content: center;
justify-content : center;
Consider using Windmill , although Windmill probably cant do that many threads.
You could do it with a hand rolled Python script on 5 machines, each one connecting outbound using ports 40000-60000, opening 100,000 port connections.
Also, it might help to do a sample test with a nicely threaded QA app such as OpenSTA in order to get an idea of how much each server can handle.
Also, try looking into just using simple Perl with the LWP::ConnCache class. You'll probably get more performance (more connections) that way.
Try the following
double hours = (b-a).TotalHours;
If you just want the hour difference excluding the difference in days you can use the following
int hours = (b-a).Hours;
The difference between these two properties is mainly seen when the time difference is more than 1 day. The Hours property will only report the actual hour difference between the two dates. So if two dates differed by 100 years but occurred at the same time in the day, hours would return 0. But TotalHours will return the difference between in the total amount of hours that occurred between the two dates (876,000 hours in this case).
The other difference is that TotalHours will return fractional hours. This may or may not be what you want. If not, Math.Round can adjust it to your liking.
Although there isn't a standard on the URL part, there is one standard for JavaScript. If you pass objects containing arrays to URLSearchParams
, and call toString()
on it, it will transform it into a comma separated list of items:
let data = {
str: 'abc',
arr: ['abc', 123]
}
new URLSearchParams(data).toString();
// ?str=abc&arr=abc,123 (with escaped characters)
Note, disable wordwrap, otherwise it will not work properly if your lines are longer than sublime's width.
You can do this by using JQuery.
For example ,
<a href="your URL" id="navigate"> click here </a>
Your JQuery
will be,
$(document).ready(function(){
$('a').on('mousedown', stopNavigate);
$('a').on('mouseleave', function () {
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
});
});
function stopNavigate(){
$(window).off('beforeunload');
}
And to get the Leave message alert will be,
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
$(window).on('unload', function(){
logout();
});
This solution works in all browsers and I have tested it.
I had the same problem with Eclipse v3.7 (Indigo) and m2eclipse as my Maven plugin. The error was easily solved by explicitly stating the execution phase within the plugin definition. So my pom looks like this:
<project>
...
<build>
...
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>buildnumber-maven-plugin</artifactId>
<version>1.0</version>
<configuration>
<timestampFormat>yyyy-MM-dd_HH-mm-ss</timestampFormat>
</configuration>
<executions>
<execution>
*<phase>post-clean</phase>*
<goals>
<goal>create-timestamp</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
...
From my experience, the way I do it is create a snapshot of your current image, then once its done you'll see it as an option when launching new instances. Simply launch it as a large instance at that point.
This is my approach if I do not want any downtime(i.e. production server) because this solution only takes a server offline only after the new one is up and running(I also use it to add new machines to my clusters by using this approach to only add new machines). If Downtime is acceptable then see Marcel Castilho's answer.
this how you reset the enitityManager in Symfony3. It should reopen the em if it has been closed:
In a Controller:
$em = $this->getDoctrine()->resetEntityManager();
In a service:
if (!$this->em->isOpen()) {
$this->managerRegistry->resetManager('managername');
$this->em = $this->managerRegistry->getManager('default');
}
$this->em->persist(...);
Don't forget to inject the '@doctrine' as a service argument in service.yml!
I'm wondering, if this problem happens if different methodes concurrently tries to access the same entity at the same time?
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParameters,
HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(httpParameters, true);
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 35 * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 30 * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
UICollectionView is same as UITableView but it gives us the additional functionality of simply creating a grid view, which is a bit problematic in UITableView. It will be a very long post I mention a link from where you will get everything in simple steps.
I have updated your same code please compare code with your's original code :
public class Help {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int array[] = new int[10];
System.out.println("Enter the numbers now.");
for (int i = 0; i < array.length; i++) {
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999) {
break;
}
array[i] = next;
}
System.out.println("These are the numbers you have entered.");
printArray(array);
// get biggest number
System.out.println("Maximum: "+getMaxValue(array));
// get smallest number
System.out.println("Minimum: "+getMinValue(array));
}
// getting the maximum value
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
// getting the miniumum value
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()
where a is your x data b is your y data c is your y error if any
note that c is the error in each direction already
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
Python 2.*
int
s take either 4 or 8 bytes (32 or 64 bits), depending on your Python build. sys.maxint
(2**31-1
for 32-bit ints, 2**63-1
for 64-bit ints) will tell you which of the two possibilities obtains.
In Python 3, int
s (like long
s in Python 2) can take arbitrary sizes up to the amount of available memory; sys.getsizeof
gives you a good indication for any given value, although it does also count some fixed overhead:
>>> import sys
>>> sys.getsizeof(0)
12
>>> sys.getsizeof(2**99)
28
If, as other answers suggests, you're thinking about some string representation of the integer value, then just take the len
of that representation, be it in base 10 or otherwise!
You've used integers in the expression 7/10, and integer 7 divided by integer 10 is zero.
What you're expecting is floating point division. Any of the following would evaluate the way you expected:
7.0 / 10
7 / 10.0
7.0 / 10.0
7 / (double) 10
This might help
temp = ([[1,2,3,4,5,6,.....,7]])
This will return default size of text on button in pixels.
val size = Button(this).textSize
float size = new Button(this).getTextSize();
@Stephen Paul continuation...
ngOnDestroy
(ed) when the modal is exited.Why?
In some cases you might not want to modal to retain its status after having been closed, but rather restored to the initial state.
Original modal issue
Passing the content straightforward into the view actually generates initializes it even before the modal gets it. The modal doesn't have a way to kill such content even if using a *ngIf
wrapper.
Solution
ng-template
. ng-template
doesn't render until ordered to do so.
my-component.module.ts
...
imports: [
...
ModalModule
]
my-component.ts
<button (click)="reuseModal.open()">Open</button>
<app-modal #reuseModal>
<ng-template #header></ng-template>
<ng-template #body>
<app-my-body-component>
<!-- This component will be created only when modal is visible and will be destroyed when it's not. -->
</app-my-body-content>
<ng-template #footer></ng-template>
</app-modal>
modal.component.ts
export class ModalComponent ... {
@ContentChild('header') header: TemplateRef<any>;
@ContentChild('body') body: TemplateRef<any>;
@ContentChild('footer') footer: TemplateRef<any>;
...
}
modal.component.html
<div ... *ngIf="visible">
...
<div class="modal-body">
ng-container *ngTemplateOutlet="body"></ng-container>
</div>
References
I have to say that it wouldn't have been possible without the excellent official and community documentation around the net. It might help some of you too to understand better how ng-template
, *ngTemplateOutlet
and @ContentChild
work.
https://angular.io/api/common/NgTemplateOutlet
https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/
https://medium.com/claritydesignsystem/ng-content-the-hidden-docs-96a29d70d11b
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
modal.component.html
<div
(click)="onContainerClicked($event)"
class="modal fade"
tabindex="-1"
[ngClass]="{'in': visibleAnimate}"
[ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}"
*ngIf="visible">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<ng-container *ngTemplateOutlet="header"></ng-container>
<button class="close" data-dismiss="modal" type="button" aria-label="Close" (click)="close()">×</button>
</div>
<div class="modal-body">
<ng-container *ngTemplateOutlet="body"></ng-container>
</div>
<div class="modal-footer">
<ng-container *ngTemplateOutlet="footer"></ng-container>
</div>
</div>
</div>
</div>
modal.component.ts
/**
* @Stephen Paul https://stackoverflow.com/a/40144809/2013580
* @zurfyx https://stackoverflow.com/a/46949848/2013580
*/
import { Component, OnDestroy, ContentChild, TemplateRef } from '@angular/core';
@Component({
selector: 'app-modal',
templateUrl: 'modal.component.html',
styleUrls: ['modal.component.scss'],
})
export class ModalComponent implements OnDestroy {
@ContentChild('header') header: TemplateRef<any>;
@ContentChild('body') body: TemplateRef<any>;
@ContentChild('footer') footer: TemplateRef<any>;
public visible = false;
public visibleAnimate = false;
ngOnDestroy() {
// Prevent modal from not executing its closing actions if the user navigated away (for example,
// through a link).
this.close();
}
open(): void {
document.body.style.overflow = 'hidden';
this.visible = true;
setTimeout(() => this.visibleAnimate = true, 200);
}
close(): void {
document.body.style.overflow = 'auto';
this.visibleAnimate = false;
setTimeout(() => this.visible = false, 100);
}
onContainerClicked(event: MouseEvent): void {
if ((<HTMLElement>event.target).classList.contains('modal')) {
this.close();
}
}
}
modal.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ModalComponent } from './modal.component';
@NgModule({
imports: [
CommonModule,
],
exports: [ModalComponent],
declarations: [ModalComponent],
providers: [],
})
export class ModalModule { }
Try /^(?:-?[1-9]\d*$)|(?:^0)$/
.
It matches positive, negative numbers as well as zeros.
It doesn't match input like 00
, -0
, +0
, -00
, +00
, 01
.
Online testing available at http://rubular.com/r/FlnXVL6SOq
Lately I've come across yet another way of putting JS code inside PHP code. It involves Heredoc PHP syntax. I hope it'll be helpful for someone.
<?php
$script = <<< JS
$(function() {
// js code goes here
});
JS;
?>
After closing the heredoc construction the $script variable contains your JS code that can be used like this:
<script><?= $script ?></script>
The profit of using this way is that modern IDEs recognize JS code inside Heredoc and highlight it correctly unlike using strings. And you're still able to use PHP variables inside of JS code.
Yeah, no checkbox for you in iOS (-:
Here, this is what I did to create a checkbox:
UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:
[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];
Now in the target method do the following:
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = !checkBoxSelected; /* Toggle */
[checkbox setSelected:checkBoxSelected];
}
That's it!
CSS only
line-height: 1.5;
white-space: normal;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
Dominc has the right idea, but put the calculation on the other side of the expression.
SELECT * FROM my_table WHERE endTime < DATE_SUB(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'), INTERVAL 30 MINUTE)
This has the advantage that you're doing the 30 minute calculation once instead of on every row. That also means MySQL can use the index on that column. Both of thse give you a speedup.
The property IsOneWay=true
may be true in the Operational contract of the interface.
Remove that property to get rid of this error.
What i did was i commented out the
props.put("mail.smtp.starttls.enable","true");
Because apparently for G-mail you did not need it. Then if you haven't already done this you need to create an app password in G-mail for your program. I did that and it worked perfectly. Here this link will show you how: https://support.google.com/accounts/answer/185833.
Type in console as root:
apt-get update && apt-get install php5-curl
or with sudo:
sudo apt-get update && sudo apt-get install php5-curl
Sorry I missread.
1st, check your DNS config and if you can ping any host at all,
ping google.com
ping zm.archive.ubuntu.com
If it does not work, check /etc/resolv.conf
or /etc/network/resolv.conf
, if not, change your apt-source to a different one.
/etc/apt/sources.list
Mirrors: http://www.debian.org/mirror/list
You should not use Ubuntu sources on Debian and vice versa.
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
Special thanks to the answer here for more-or-less the same question.
For me, all I needed was setlocale(LC_ALL, "en_US.UTF-8");
Then, I could use even raw wchar_t
characters.
Since your coordinates belong together as pairs, why not write a struct for them?
struct CoordinatePair
{
int x;
int y;
};
Then you can write an overloaded extraction operator for istreams:
std::istream& operator>>(std::istream& is, CoordinatePair& coordinates)
{
is >> coordinates.x >> coordinates.y;
return is;
}
And then you can read a file of coordinates straight into a vector like this:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
char filename[] = "coordinates.txt";
std::vector<CoordinatePair> v;
std::ifstream ifs(filename);
if (ifs) {
std::copy(std::istream_iterator<CoordinatePair>(ifs),
std::istream_iterator<CoordinatePair>(),
std::back_inserter(v));
}
else {
std::cerr << "Couldn't open " << filename << " for reading\n";
}
// Now you can work with the contents of v
}
You need to make sure your usercontrol hasn't set it's width in the usercontrol's xaml file. Just delete the Width="..." from it and you're good to go!
EDIT: This is the code I tested it with:
SOUserAnswerTest.xaml:
<UserControl x:Class="WpfApplication1.SOAnswerTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Name="LeftSideMenu" Width="100"/>
<ColumnDefinition Name="Middle" Width="*"/>
<ColumnDefinition Name="RightSideMenu" Width="90"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0">a</TextBlock>
<TextBlock Grid.Column="1">b</TextBlock>
<TextBlock Grid.Column="2">c</TextBlock>
</Grid>
</UserControl>
Window1.xaml:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="415">
<Grid>
<local:SOAnswerTest Grid.Column="0" Grid.Row="5" Grid.ColumnSpan="2"/>
</Grid>
</Window>
XAMPP uses a file called mysql_start.bat to start MySQL and if you open that file with a text editor you can see what config file is trying to use, in the current version it is:
mysql\bin\mysqld --defaults-file=mysql\bin\my.ini --standalone --console
If you installed XAMPP on the default path it means it is on c:/xampp/mysql/bin/my.ini
If somehow the file doesn't exist you should open a console terminal (start-> type "cmd", press enter) and then write "mysql --help" and it prints a text mentioning the default locations, in the current version of XAMPP is:
C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf C:\xampp\mysql\my.ini C:\xampp\mysql\my.cnf
Check whether your device supports the version you specified in minSdkVersion in AndroidManifest.xml . If not specify the lower version and try again
use jquery
$("#item").change(function({
var x=$(this).val();
});
Your value will be in x
variable, use this variable value in your jsp, like this {x}
this statement will give the value
I think you might need to use the full path:
export EDITOR=/usr/bin/vim
You can use angular.bootstrap()
directly... the problem is you lose the benefits of directives.
First you need to get a reference to the HTML element in order to bootstrap it, which means your code is now coupled to your HTML.
Secondly the association between the two is not as apparent. With ngApp
you can clearly see what HTML is associated with what module and you know where to look for that information. But angular.bootstrap()
could be invoked from anywhere in your code.
If you are going to do it at all the best way would be by using a directive. Which is what I did. It's called ngModule
. Here is what your code would look like using it:
<!DOCTYPE html>
<html>
<head>
<script src="angular.js"></script>
<script src="angular.ng-modules.js"></script>
<script>
var moduleA = angular.module("MyModuleA", []);
moduleA.controller("MyControllerA", function($scope) {
$scope.name = "Bob A";
});
var moduleB = angular.module("MyModuleB", []);
moduleB.controller("MyControllerB", function($scope) {
$scope.name = "Steve B";
});
</script>
</head>
<body>
<div ng-modules="MyModuleA, MyModuleB">
<h1>Module A, B</h1>
<div ng-controller="MyControllerA">
{{name}}
</div>
<div ng-controller="MyControllerB">
{{name}}
</div>
</div>
<div ng-module="MyModuleB">
<h1>Just Module B</h1>
<div ng-controller="MyControllerB">
{{name}}
</div>
</div>
</body>
</html>
You can get the source code for it at:
http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/
It's implemented in the same way as ngApp
. It simply calls angular.bootstrap()
behind the scenes.
The .success
syntax was correct up to Angular v1.4.3.
For versions up to Angular v.1.6, you have to use then
method. The then()
method takes two arguments: a success
and an error
callback which will be called with a response object.
Using the then()
method, attach a callback
function to the returned promise
.
Something like this:
app.controller('MainCtrl', function ($scope, $http){
$http({
method: 'GET',
url: 'api/url-api'
}).then(function (response){
},function (error){
});
}
See reference here.
Shortcut
methods are also available.
$http.get('api/url-api').then(successCallback, errorCallback);
function successCallback(response){
//success code
}
function errorCallback(error){
//error code
}
The data you get from the response is expected to be in JSON
format.
JSON is a great way of transporting data, and it is easy to use within AngularJS
The major difference between the 2 is that .then()
call returns a promise
(resolved with a value returned from a callback
) while .success()
is more traditional way of registering callbacks
and doesn't return a promise
.
You can also create a new document from MongoDB compass or using command and set the specific _id
value that you want.
"A program doesn't run any faster when it is read from a ".pyc" or ".pyo" file than when it is read from a ".py" file; the only thing that's faster about ".pyc" or ".pyo" files is the speed with which they are loaded. "
I use GUIDs as random keys for database type operations.
The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=', etc..
Instead of hexadecimal, I use a url-safe base64 string. The following does not conform to any UUID/GUID spec though (other than having the required amount of randomness).
import base64
import uuid
# get a UUID - URL safe, Base64
def get_a_uuid():
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.replace('=', '')
Please note that you will most likely need an index on that column too.
class AddUserReferenceToTester < ActiveRecord::Migration
def change
add_column :testers, :user_id, :integer
add_index :testers, :user_id
end
end
Since Qt 5.5 you can use QTextStream::readLineInto
. It behaves similar to std::getline
and is maybe faster as QTextStream::readLine
, because it reuses the string:
QIODevice* device;
QTextStream in(&device);
QString line;
while (in.readLineInto(&line)) {
// ...
}
If you want to run a script to a database:
mysql -u user -p data_base_name_here < db.sql
As suggested by @rqLizard, you can use openssl_encrypt
/openssl_decrypt
PHP functions instead which provides a much
better alternative to implement AES (The Advanced Encryption Standard) also known as Rijndael encryption.
As per the following Scott's comment at php.net:
If you're writing code to encrypt/encrypt data in 2015, you should use
openssl_encrypt()
andopenssl_decrypt()
. The underlying library (libmcrypt
) has been abandoned since 2007, and performs far worse than OpenSSL (which leveragesAES-NI
on modern processors and is cache-timing safe).Also,
MCRYPT_RIJNDAEL_256
is notAES-256
, it's a different variant of the Rijndael block cipher. If you wantAES-256
inmcrypt
, you have to useMCRYPT_RIJNDAEL_128
with a 32-byte key. OpenSSL makes it more obvious which mode you are using (i.e.aes-128-cbc
vsaes-256-ctr
).OpenSSL also uses PKCS7 padding with CBC mode rather than mcrypt's NULL byte padding. Thus, mcrypt is more likely to make your code vulnerable to padding oracle attacks than OpenSSL.
Finally, if you are not authenticating your ciphertexts (Encrypt Then MAC), you're doing it wrong.
Further reading:
AES Authenticated Encryption in GCM mode example for PHP 7.1+
<?php
//$key should have been previously generated in a cryptographically safe way, like openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$cipher = "aes-128-gcm";
if (in_array($cipher, openssl_get_cipher_methods()))
{
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv, $tag);
//store $cipher, $iv, and $tag for decryption later
$original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag);
echo $original_plaintext."\n";
}
?>
AES Authenticated Encryption example for PHP 5.6+
<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
//decrypt later....
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (hash_equals($hmac, $calcmac))//PHP 5.6+ timing attack safe comparison
{
echo $original_plaintext."\n";
}
?>
Based on above examples, I've changed the following code which aims at encrypting user's session id:
class Session {
/**
* Encrypts the session ID and returns it as a base 64 encoded string.
*
* @param $session_id
* @return string
*/
public function encrypt($session_id) {
// Get the MD5 hash salt as a key.
$key = $this->_getSalt();
// For an easy iv, MD5 the salt again.
$iv = $this->_getIv();
// Encrypt the session ID.
$encrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $session_id, MCRYPT_MODE_CBC, $iv);
// Base 64 encode the encrypted session ID.
$encryptedSessionId = base64_encode($encrypt);
// Return it.
return $encryptedSessionId;
}
/**
* Decrypts a base 64 encoded encrypted session ID back to its original form.
*
* @param $encryptedSessionId
* @return string
*/
public function decrypt($encryptedSessionId) {
// Get the MD5 hash salt as a key.
$key = $this->_getSalt();
// For an easy iv, MD5 the salt again.
$iv = $this->_getIv();
// Decode the encrypted session ID from base 64.
$decoded = base64_decode($encryptedSessionId);
// Decrypt the string.
$decryptedSessionId = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $decoded, MCRYPT_MODE_CBC, $iv);
// Trim the whitespace from the end.
$session_id = rtrim($decryptedSessionId, "\0");
// Return it.
return $session_id;
}
public function _getIv() {
return md5($this->_getSalt());
}
public function _getSalt() {
return md5($this->drupal->drupalGetHashSalt());
}
}
into:
class Session {
const SESS_CIPHER = 'aes-128-cbc';
/**
* Encrypts the session ID and returns it as a base 64 encoded string.
*
* @param $session_id
* @return string
*/
public function encrypt($session_id) {
// Get the MD5 hash salt as a key.
$key = $this->_getSalt();
// For an easy iv, MD5 the salt again.
$iv = $this->_getIv();
// Encrypt the session ID.
$ciphertext = openssl_encrypt($session_id, self::SESS_CIPHER, $key, $options=OPENSSL_RAW_DATA, $iv);
// Base 64 encode the encrypted session ID.
$encryptedSessionId = base64_encode($ciphertext);
// Return it.
return $encryptedSessionId;
}
/**
* Decrypts a base 64 encoded encrypted session ID back to its original form.
*
* @param $encryptedSessionId
* @return string
*/
public function decrypt($encryptedSessionId) {
// Get the Drupal hash salt as a key.
$key = $this->_getSalt();
// Get the iv.
$iv = $this->_getIv();
// Decode the encrypted session ID from base 64.
$decoded = base64_decode($encryptedSessionId, TRUE);
// Decrypt the string.
$decryptedSessionId = openssl_decrypt($decoded, self::SESS_CIPHER, $key, $options=OPENSSL_RAW_DATA, $iv);
// Trim the whitespace from the end.
$session_id = rtrim($decryptedSessionId, '\0');
// Return it.
return $session_id;
}
public function _getIv() {
$ivlen = openssl_cipher_iv_length(self::SESS_CIPHER);
return substr(md5($this->_getSalt()), 0, $ivlen);
}
public function _getSalt() {
return $this->drupal->drupalGetHashSalt();
}
}
To clarify, above change is not a true conversion since the two encryption uses a different block size and a different encrypted data. Additionally, the default padding is different, MCRYPT_RIJNDAEL
only supports non-standard null padding. @zaph
Additional notes (from the @zaph's comments):
MCRYPT_RIJNDAEL_128
) is equivalent to AES, however Rijndael 256 (MCRYPT_RIJNDAEL_256
) is not AES-256 as the 256 specifies a block size of 256-bits, whereas AES has only one block size: 128-bits. So basically Rijndael with a block size of 256-bits (MCRYPT_RIJNDAEL_256
) has been mistakenly named due to the choices by the mcrypt developers. @zaphEncryption with different block sizes for Rijndael produces different encrypted data.
For example, MCRYPT_RIJNDAEL_256
(not equivalent to AES-256
) defines a different variant of the Rijndael block cipher with size of 256-bits and a key size based on the passed in key, where aes-256-cbc
is Rijndael with a block size of 128-bits with a key size of 256-bits. Therefore they're using different block sizes which produces entirely different encrypted data as mcrypt uses the number to specify the block size, where OpenSSL used the number to specify the key size (AES only has one block size of 128-bits). So basically AES is Rijndael with a block size of 128-bits and key sizes of 128, 192 and 256 bits. Therefore it's better to use AES, which is called Rijndael 128 in OpenSSL.
The date_add()
function should do what you want. In addition, check out the docs (unofficial, but the official ones are a bit sparse) for the DateTime
object, it's much nicer to work with than the procedural functions in PHP.
Add list-style-position: inside
to the ul
element. (example)
The default value for the list-style-position
property is outside
.
ul {_x000D_
text-align: center;_x000D_
list-style-position: inside;_x000D_
}
_x000D_
<ul>_x000D_
<li>one</li>_x000D_
<li>two</li>_x000D_
<li>three</li>_x000D_
</ul>
_x000D_
Another option (which yields slightly different results) would be to center the entire ul
element:
.parent {_x000D_
text-align: center;_x000D_
}_x000D_
.parent > ul {_x000D_
display: inline-block;_x000D_
}
_x000D_
<div class="parent">_x000D_
<ul>_x000D_
<li>one</li>_x000D_
<li>two</li>_x000D_
<li>three</li>_x000D_
</ul>_x000D_
</div>
_x000D_
I faced this issue when I integrated spring boot with spring mvc. I solved it by just adding these dependencies.
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
In java8
map.entrySet().stream().filter(entry -> entry.getValue().equals(value))
.forEach(entry -> System.out.println(entry.getKey()));
I wasn't happy with any of the suggested time pickers, so I created my own with inspiration from Perifer's and the HTML5 spec:
http://github.com/gregersrygg/jquery.timeInput
You can either use the new html5 attributes for time input (step, min, max), or use an options object:
<input type="time" name="myTime" class="time-mm-hh" min="9:00" max="18:00" step="1800" />
<input type="time" name="myTime2" class="time-mm-hh" />
<script type="text/javascript">
$("input[name='myTime']").timeInput(); // use default or html5 attributes
$("input[name='myTime2']").timeInput({min: "6:00", max: "15:00", step: 900}); // 15 min intervals from 6:00 am to 3:00 pm
</script>
Validates input like this:
The HTML5 spec doesn't allow am/pm or localized time syntax, so it only allowes the format hh:mm. Seconds is allowed according to spec, but I have not implemented it yet.
It's very "alpha", so there might be some bugs. Feel free to send me patches/pull requests. Have manually tested in IE 6&8, FF, Chrome and Opera (Latest stable on Linux for the latter ones).
try this
json = $.grep(newcurrPayment.paymentTypeInsert, function (el, idx) { return el.FirstName == "Test1" }, true)
echo $(($(date +%s) / 60 / 60 / 24))
Here's a list of API links to get your stats:
Facebook: https://api.facebook.com/method/links.getStats?urls=%%URL%%&format=json
Reddit:http://buttons.reddit.com/button_info.json?url=%%URL%%
LinkedIn: http://www.linkedin.com/countserv/count/share?url=%%URL%%&format=json
Digg: http://widgets.digg.com/buttons/count?url=%%URL%%
Delicious: http://feeds.delicious.com/v2/json/urlinfo/data?url=%%URL%%
StumbleUpon: http://www.stumbleupon.com/services/1.01/badge.getinfo?url=%%URL%%
Pinterest: http://widgets.pinterest.com/v1/urls/count.json?source=6&url=%%URL%%
Edit: Removed the Twitter endpoint, since that one has been deprecated.
Edit: Facebook REST API is deprecated
You actually don't need to use the attach at all. I had the same problem and it was resolved by removing the attach statement.
Without using max-width
, or percentage column widths, or table-layout: fixed
etc.
https://jsfiddle.net/tturadqq/
How it works:
Step 1: Just let the table auto-layout do its thing.
When there's one or more columns with a lot of text, it will shrink the other columns as much as possible, then wrap the text of the long columns:
Step 2: Wrap cell contents in a div, then set that div to max-height: 1.1em
(the extra 0.1em is for characters which render a bit below the text base, like the tail of 'g' and 'y')
Step 3: Set title
on the divs
This is good for accessibility, and is necessary for the little trick we'll use in a moment.
Step 4: Add a CSS ::after
on the div
This is the tricky bit. We set a CSS ::after
, with content: attr(title)
, then position that on top of the div and set text-overflow: ellipsis
. I've coloured it red here to make it clear.
(Note how the long column now has a tailing ellipsis)
Step 5: Set the colour of the div text to transparent
And we're done!
Have you tried this?
<appSettings>
<add key="myurl" value="http://www.myurl.com?&cid=&sid="/>
<appSettings>
The difference between both has been explained here. But what has not been explained is the fact that <<include>>
and <<extend>>
should simply not be used at all.
If you read Bittner/Spence you know that use cases are about synthesis, not analysis. A re-use of use cases is nonsense. It clearly shows that you have cut your domain wrongly. Added value must be unique per se. The only re-use of added value I know is franchise. So if you are in burger business, nice. But everywhere else your task as BA is to try to find an USP. And that must be presented in good use cases.
Whenever I see people using one of those relations it is when they try to do functional decomposition. And that's plain wrong.
To put it simple: if you can answer your boss without hesitation "I have done ..." then the "..." is your use case since you got money for doing it. (That will also make clear that "login" is not a use case at all.)
In that respect, finding self standing use cases that are included or extend other use cases is very unlikely. Eventually you can use <<extend>>
to show optionality of your system, i.e. some licensing schema which allows to include use cases for some licenses or to omit them. But else - just avoid them.
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
$id = implode(',',$_POST['id']);
echo $id
you cannot echo an array because it will just print out Array. If you wanna print out an array use print_r
.
print_r($_POST['id']);
Edit: 2015-10-26: thanks for the upvotes - but take a look at tchrist's answer, especially if you develop for the web or something more "international".
Oren Trutners answer isn't quite right (see sample input of "RightHerE" which must be matched but isn't)
Here is the correct solution:
(?!^.*[A-Z]{2,}.*$)^[A-Za-z]*$
edit:
(?!^.*[A-Z]{2,}.*$) // don't match the whole expression if there are two or more consecutive uppercase letters
^[A-Za-z]*$ // match uppercase and lowercase letters
/edit
the key for the solution is a negative lookahead see: http://www.regular-expressions.info/lookaround.html
One more efficient implementation
int i, j;
/* new length of modified array */
int NewLength = 1;
for(i=1; i< Length; i++){
for(j=0; j< NewLength ; j++)
{
if(array[i] == array[j])
break;
}
/* if none of the values in index[0..j] of array is not same as array[i],
then copy the current value to corresponding new position in array */
if (j==NewLength )
array[NewLength++] = array[i];
}
In this implementation there is no need for sorting the array. Also if a duplicate element is found, there is no need for shifting all elements after this by one position.
The output of this code is array[] with size NewLength
Here we are starting from the 2nd elemt in array and comparing it with all the elements in array up to this array. We are holding an extra index variable 'NewLength' for modifying the input array. NewLength variabel is initialized to 0.
Element in array[1] will be compared with array[0]. If they are different, then value in array[NewLength] will be modified with array[1] and increment NewLength. If they are same, NewLength will not be modified.
So if we have an array [1 2 1 3 1], then
In First pass of 'j' loop, array[1] (2) will be compared with array0, then 2 will be written to array[NewLength] = array[1] so array will be [1 2] since NewLength = 2
In second pass of 'j' loop, array[2] (1) will be compared with array0 and array1. Here since array[2] (1) and array0 are same loop will break here. so array will be [1 2] since NewLength = 2
and so on
Posting here because it's taken me over 2 weeks to get to the bottom of this, and I still haven't fully resolved it.
There is a chance, that you're also just running into this bug which has been around since 2017 and hasn't been addressed.
I honestly have no clue how to get around this bug. I'm posting here for my sanity and hopefully to shave a couple weeks of your googling. I'd love any input anyone may have, but my particular "answer" to this problem was not listed in any of the above answers.
There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.
Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.
Copy the PEM file to your Mac and set it to be read-only by your user:
chmod 400 <private-key-filename>.pem
Then you should be able to use ssh to connect to your remote server
ssh -i <private-key-filename>.pem username@hostname
You probably do not have a keyframe at the 3 second mark. Because non-keyframes encode differences from other frames, they require all of the data starting with the previous keyframe.
With the mp4 container it is possible to cut at a non-keyframe without re-encoding using an edit list. In other words, if the closest keyframe before 3s is at 0s then it will copy the video starting at 0s and use an edit list to tell the player to start playing 3 seconds in.
If you are using the latest ffmpeg from git master it will do this using an edit list when invoked using the command that you provided. If this is not working for you then you are probably either using an older version of ffmpeg, or your player does not support edit lists. Some players will ignore the edit list and always play all of the media in the file from beginning to end.
If you want to cut precisely starting at a non-keyframe and want it to play starting at the desired point on a player that does not support edit lists, or want to ensure that the cut portion is not actually in the output file (for example if it contains confidential information), then you can do that by re-encoding so that there will be a keyframe precisely at the desired start time. Re-encoding is the default if you do not specify copy
. For example:
ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4
When re-encoding you may also wish to include additional quality-related options or a particular AAC encoder. For details, see ffmpeg's x264 Encoding Guide for video and AAC Encoding Guide for audio.
Also, the -t
option specifies a duration, not an end time. The above command will encode 8s of video starting at 3s. To start at 3s and end at 8s use -t 5
. If you are using a current version of ffmpeg you can also replace -t
with -to
in the above command to end at the specified time.
If you use WAMP, make sure it is online. What I did was, first turned my firewall off, then it worked, so after that I allowed connection for all local ports, specially port 80. Than I got rid of this problem. For me it was the Firewall who was blocking the connection.
EDIT: I would appreciate it if you do not downvote this answer further. This answer is wrong, but I would rather retain it as a historical note. While it is arguable whether the pytz interface is error-prone, it can do things that dateutil.tz cannot do, especially regarding daylight-saving in the past or in the future. I have honestly recorded my experience in an article "Time zones in Python".
If you are on a Unix-like platform, I would suggest you avoid pytz and look just at /usr/share/zoneinfo. dateutil.tz can utilize the information there.
The following piece of code shows the problem pytz can give. I was shocked when I first found it out. (Interestingly enough, the pytz installed by yum on CentOS 7 does not exhibit this problem.)
import pytz
import dateutil.tz
from datetime import datetime
print((datetime(2017,2,13,14,29,29, tzinfo=pytz.timezone('Asia/Shanghai'))
- datetime(2017,2,13,14,29,29, tzinfo=pytz.timezone('UTC')))
.total_seconds())
print((datetime(2017,2,13,14,29,29, tzinfo=dateutil.tz.gettz('Asia/Shanghai'))
- datetime(2017,2,13,14,29,29, tzinfo=dateutil.tz.tzutc()))
.total_seconds())
-29160.0
-28800.0
I.e. the timezone created by pytz is for the true local time, instead of the standard local time people observe. Shanghai conforms to +0800, not +0806 as suggested by pytz:
pytz.timezone('Asia/Shanghai')
<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>
EDIT: Thanks to Mark Ransom's comment and downvote, now I know I am using pytz the wrong way. In summary, you are not supposed to pass the result of pytz.timezone(…)
to datetime
, but should pass the datetime
to its localize
method.
Despite his argument (and my bad for not reading the pytz documentation more carefully), I am going to keep this answer. I was answering the question in one way (how to enumerate the supported timezones, though not with pytz), because I believed pytz did not provide a correct solution. Though my belief was wrong, this answer is still providing some information, IMHO, which is potentially useful to people interested in this question. Pytz's correct way of doing things is counter-intuitive. Heck, if the tzinfo created by pytz should not be directly used by datetime
, it should be a different type. The pytz interface is simply badly designed. The link provided by Mark shows that many people, not just me, have been misled by the pytz interface.
Based on robertc's answer:
To get proper conversion from colored image to grayscale image instead of using matrix like this:
0.3333 0.3333 0.3333 0 0
0.3333 0.3333 0.3333 0 0
0.3333 0.3333 0.3333 0 0
0 0 0 1 0
You should use conversion matrix like this:
0.299 0.299 0.299 0
0.587 0.587 0.587 0
0.112 0.112 0.112 0
0 0 0 1
This should work fine for all the types of images based on RGBA (red-green-blue-alpha) model.
For more information why you should use matrix I posted more likely that the robertc's one check following links:
In python, extracting substring form string can be done using findall
method in regular expression (re
) module.
>>> import re
>>> s = 'gfgfdAAA1234ZZZuijjk'
>>> ss = re.findall('AAA(.+)ZZZ', s)
>>> print ss
['1234']
You can get the input element and then set its readOnly
property to true
as follows:
document.getElementById('InputFieldID').readOnly = true;
Specifically, this is what you want:
<script type="text/javascript">
function onLoadBody() {
document.getElementById('control_EMAIL').readOnly = true;
}
</script>
Call this onLoadBody()
function on body tag like:
<body onload="onLoadBody">
View Demo: jsfiddle.
CTRL+A, Select the TextFX menu -> TextFX Edit -> Delete Blank Lines as suggested above works.
But if lines contains some space, then move the cursor to that line and do a CTRL + H. The "Find what:" sec will show the blank space and in the "Replace with" section, leave it blank. Now all the spaces are removed and now try CTRL+A, Select the TextFX menu -> TextFX Edit -> Delete Blank Lines
You need to put it in the join
clause, not the where
:
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON
user_category_subscriptions.category_id = categories.category_id
and user_category_subscriptions.user_id =1
See, with an inner join
, putting a clause in the join
or the where
is equivalent. However, with an outer join
, they are vastly different.
As a join
condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1
first, and takes the subset of user_category_subscriptions
with a user_id
of 1
to join to all of the rows in categories
. This will give you all of the rows in categories
, while only the categories
that this particular user has subscribed to will have any information in the user_category_subscriptions
columns. Of course, all other categories
will be populated with null
in the user_category_subscriptions
columns.
Conversely, a where
clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id
doesn't equal 1
. You're left with an inefficient way to get an inner join
.
Hopefully this helps!
Rather than change the type of tag, you should be changing the style of the tag (or rather, the tag with a specific id.) Its not a good practice to be changing the elements of your document to apply stylistic changes. Try this:
$('a.change').click(function() {
$('p#changed').css("font-weight", "bold");
});
<p id="changed">Hello!</p>
<a id="change">change</a>
Open Terminal and execute commands given below.
cd /etc
subl bashrc
subl denotes Sublime editor. You can replace subl with vi to open bashrc file in default editor. This will workout only if you have bashrc file, created earlier.
As some have mentioned a possible way is using git interactive staging. This is great when you have files with different extensions
$ git add -i
staged unstaged path
1: unchanged +0/-1 TODO
2: unchanged +1/-1 index.html
3: unchanged +5/-1 lib/simplegit.rb
*** Commands ***
1: status 2: update 3: revert 4: add untracked
5: patch 6: diff 7: quit 8: help
What now>
If you press 2
then enter
you will get a list of available files to be added:
What now> 2
staged unstaged path
1: unchanged +0/-1 TODO
2: unchanged +1/-1 index.html
3: unchanged +5/-1 lib/simplegit.rb
Update>>
Now you just have to insert the number of the files you want to add, so if we wanted to add TODO
and index.html
we would type 1,2
Update>> 1,2
staged unstaged path
* 1: unchanged +0/-1 TODO
* 2: unchanged +1/-1 index.html
3: unchanged +5/-1 lib/simplegit.rb
Update>>
You see the *
before the number? that means that the file was added.
Now imagine that you have 7 files and you want to add them all except the 7th? Sure we could type 1,2,3,4,5,6
but imagine instead of 7 we have 16, that would be quite cumbersome, the good thing we don't need to type them all because we can use ranges,by typing 1-6
Update>> 1-6
staged unstaged path
* 1: unchanged +0/-1 TODO
* 2: unchanged +1/-1 index.html
* 3: unchanged +5/-1 lib/simplegit.rb
* 4: unchanged +5/-1 file4.html
* 5: unchanged +5/-1 file5.html
* 6: unchanged +5/-1 file6.html
7: unchanged +5/-1 file7.html
Update>>
We can even use multiple ranges, so if we want from 1 to 3 and from 5 to 7 we type 1-3, 5-7
:
Update>> 1-3, 5-7
staged unstaged path
* 1: unchanged +0/-1 TODO
* 2: unchanged +1/-1 index.html
* 3: unchanged +5/-1 lib/simplegit.rb
4: unchanged +5/-1 file4.html
* 5: unchanged +5/-1 file5.html
* 6: unchanged +5/-1 file6.html
* 7: unchanged +5/-1 file7.html
Update>>
We can also use this to unstage files, if we type -number
, so if we wanted to unstage file number 1 we would type -1
:
Update>> -1
staged unstaged path
1: unchanged +0/-1 TODO
* 2: unchanged +1/-1 index.html
* 3: unchanged +5/-1 lib/simplegit.rb
4: unchanged +5/-1 file4.html
* 5: unchanged +5/-1 file5.html
* 6: unchanged +5/-1 file6.html
* 7: unchanged +5/-1 file7.html
Update>>
And as you can imagine we can also unstage a range of files, so if we type -range
all the files on that range would be unstaged. If we wanted to unstage all the files from 5 to 7 we would type -5-7
:
Update>> -5-7
staged unstaged path
1: unchanged +0/-1 TODO
* 2: unchanged +1/-1 index.html
* 3: unchanged +5/-1 lib/simplegit.rb
4: unchanged +5/-1 file4.html
5: unchanged +5/-1 file5.html
6: unchanged +5/-1 file6.html
7: unchanged +5/-1 file7.html
Update>>
I ran into this same issue. Apparently, you shouldn't call a class in the BLL the same name as one of the .aspx/.aspx.cs files. I thought they would not be in the same scope, etc. but it messed with Visual Studio's internal workings too much. I'm a bit surprised there isn't something to keep you from doing this if it is going to produce that type of error. Anyway, just delete the .aspx/.aspx.cs files and rebuild your project. Then bring them back in under another name. You can copy/paste your code into another editor if you don't want to retype it all back in.
my_function.func_name
There are also other fun properties of functions. Type dir(func_name)
to list them. func_name.func_code.co_code
is the compiled function, stored as a string.
import dis
dis.dis(my_function)
will display the code in almost human readable format. :)
Think of (char *) as string.begin(). The essential difference is that (char *) is an iterator and std::string is a container. If you stick to basic strings a (char *) will give you what std::string::iterator does. You could use (char *) when you want the benefit of an iterator and also compatibility with C, but that's the exception and not the rule. As always, be careful of iterator invalidation. When people say (char *) isn't safe this is what they mean. It's as safe as any other C++ iterator.