Node * merge_sort(Node *a, Node *b){
Node *result = NULL;
if(a == NULL)
return b;
else if(b == NULL)
return a;
/* For the first node, we would set the result to either a or b */
if(a->data <= b->data){
result = a;
/* Result's next will point to smaller one in lists
starting at a->next and b */
result->next = merge_sort(a->next,b);
}
else {
result = b;
/*Result's next will point to smaller one in lists
starting at a and b->next */
result->next = merge_sort(a,b->next);
}
return result;
}
Please refer to my blog post for http://www.algorithmsandme.com/2013/10/linked-list-merge-two-sorted-linked.html
Here are the simple steps to create a GitHub Tag, when you release build from master.
Open source_tree tab
Right click on Tag sections from Tag which appear on left navigation section
Click on New Tag()
Click on Add Tag from give name to tag (preferred version name of the code)
If you want to push the TAG on remote, while creating the TAG ref: step 5 which gives checkbox push TAG to origin check it and pushed tag appears on remote repository
In case while creating the TAG if you have forgotten to check the box Push to origin, you can do it later by right-clicking on the created TAG, click on Push to origin.
For developers who REALLY want to keep it in parameter, here might be another workaround.
Change the parameter to an array or List to wrap the actual value up. Remember to initialize the list before sending into the method. After returned, be sure to check value existence before consuming it. Code with caution.
Not necessarily better, but since it's nice to have options here's how to do it using Jinja statements:
- debug:
msg: "{% for address in network.addresses.private_man %}\
{% if address.type == 'fixed' %}\
{{ address.addr }}\
{% endif %}\
{% endfor %}"
Or if you prefer to put it all on one line:
- debug:
msg: "{% for address in network.addresses.private_man if address.type == 'fixed' %}{{ address.addr }}{% endfor %}"
Which returns:
ok: [localhost] => {
"msg": "172.16.1.100"
}
As @Sean said, fcntl()
is largely standardized, and therefore available across platforms. The ioctl()
function predates fcntl()
in Unix, but is not standardized at all. That the ioctl()
worked for you across all the platforms of relevance to you is fortunate, but not guaranteed. In particular, the names used for the second argument are arcane and not reliable across platforms. Indeed, they are often unique to the particular device driver that the file descriptor references. (The ioctl()
calls used for a bit-mapped graphics device running on an ICL Perq running PNX (Perq Unix) of twenty years ago never translated to anything else anywhere else, for example.)
This is my opinion for my database as recommended by my mentor
I got the same problem in here, and guess what.... looking at the csproj's xml' structure, I noticed the Content node (inside ItemGroup node) was as "none"... not sure why but that was the reason I was getting the same error, just edited that to "Content" as the others, and it's working.
Hope that helps
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
Every time setColor
gets hit, you are setting count = 1. You would need to define count
outside of the scope of the function. Example:
var count=1;
function setColor(btn, color){
var property = document.getElementById(btn);
if (count == 0){
property.style.backgroundColor = "#FFFFFF"
count=1;
}
else{
property.style.backgroundColor = "#7FFF00"
count=0;
}
}
You cannot start a container from a Dockerfile.
The process goes like this:
Dockerfile =[
docker build
]=> Docker image =[docker run
]=> Docker container
To start (or run) a container you need an image. To create an image you need to build the Dockerfile[1].
[1]: you can also docker import
an image from a tarball or again docker load
.
Try this using list comprehension:
import pandas as pd
df = pd.DataFrame(
[p, p.team, p.passing_att, p.passer_rating()] for p in game.players.passing()
)
Assuming that you have access to Prototype, this could work. I wrote this code for myself just a few minutes ago; I only needed a single key at a time, so this isn't time efficient for big lists of key:value pairs or for spitting out multiple key names.
function key(int) {
var j = -1;
for(var i in this) {
j++;
if(j==int) {
return i;
} else {
continue;
}
}
}
Object.prototype.key = key;
This is numbered to work the same way that arrays do, to save headaches. In the case of your code:
buttons.key(0) // Should result in "button1"
From CLI:
$ su - postgres
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q
PHP (as tested on localhost, it works as expected):
$connString = 'port=5432 dbname=test_database user=tester password=test_password';
$connHandler = pg_connect($connString);
echo 'Connected to '.pg_dbname($connHandler);
Try the below steps:
adb kill-server
(Eclipse should be closed before issuing these commands)adb start-server
It worked for me this way.
Restart your phone as well!
There are various ways to get a class onto the HTML element, identifying which IE version you're contending with: Modernizr, the HTML 5 Boilerplate, etc - or just roll your own. Then you can use that class (eg .lt-ie9) in a normal CSS selector, no hack needed. If you only want to affect IE8 and not previous versions, put the old value back using a .lt-ie8 selector.
For what is worth:
the closest integer to any given input as shown in the following table can be calculated using Math.ceil or Math.floor depending of the distance between the input and the next integer
+-------+--------+
| input | output |
+-------+--------+
| 1 | 0 |
| 2 | 0 |
| 3 | 5 |
| 4 | 5 |
| 5 | 5 |
| 6 | 5 |
| 7 | 5 |
| 8 | 10 |
| 9 | 10 |
+-------+--------+
private int roundClosest(final int i, final int k) {
int deic = (i % k);
if (deic <= (k / 2.0)) {
return (int) (Math.floor(i / (double) k) * k);
} else {
return (int) (Math.ceil(i / (double) k) * k);
}
}
The solutions offered here and in other places didn't work for me, so I'll add to the discussion for future readers. I admittedly don't fully understand the procedure yet, but have finally solved my (similar) problem and want to share.
I had accidentally cached some doc-directories with several hundred files when working with git in IntelliJ IDEA on Windows 10, and after adding them to .gitignore
(and PROBABLY moving them around a bit) I couldn't get them removed from the Default Changelist.
I first commited the actual changes I had made, then went about solving this - took me far too long.
I tried git rm -r --cached .
but would always get path-spec
ERRORS, with different variations of the path-spec
as well as with the -f
and -r
flags.
git status
would still show the filenames, so I tried using some of those verbatim with git rm -cached
, but no luck.
Stashing and unstashing the changes seemed to work, but they got queued again after a time (I'm a bity hazy on the exact timeframe).
I have finally removed these entries for good using
git reset
I assume this is only a GOOD IDEA when you have no changes staged/cached that you actually want to commit.
<input type="text" class="form-control" id="odometer_reading" name="odometer_reading" placeholder="Odometer Reading" onblur="odometer_reading1();" onkeypress='validate(event)' required="" />
<script>
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
</script>
# Pure Python 3.x demo, 256 colors
# Works with bash under Linux and MacOS
fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"
def print_six(row, format, end="\n"):
for col in range(6):
color = row*6 + col - 2
if color>=0:
text = "{:3d}".format(color)
print (format(text,color), end=" ")
else:
print(end=" ") # four spaces
print(end=end)
for row in range(0, 43):
print_six(row, fg, " ")
print_six(row, bg)
# Simple usage: print(fg("text", 160))
<script type="text/javascript">_x000D_
function validateForm() {_x000D_
var a = document.forms["Form"]["answer_a"].value;_x000D_
var b = document.forms["Form"]["answer_b"].value;_x000D_
var c = document.forms["Form"]["answer_c"].value;_x000D_
var d = document.forms["Form"]["answer_d"].value;_x000D_
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {_x000D_
alert("Please Fill All Required Field");_x000D_
return false;_x000D_
}_x000D_
}_x000D_
</script>_x000D_
_x000D_
<form method="post" name="Form" onsubmit="return validateForm()" action="">_x000D_
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>_x000D_
</form>
_x000D_
Is the drive E a mapped drive? Then, it can be created by another account other than the user account. This may be the cause of the error.
You can get value by using id for that element in onclick function
function dosomething(){
var buttonValue = document.getElementById('buttonId').value;
}
The simple way to get a date x days in the future is to increment the date:
function addDays(dateObj, numDays) {
return dateObj.setDate(dateObj.getDate() + numDays);
}
Note that this modifies the supplied date object, e.g.
function addDays(dateObj, numDays) {
dateObj.setDate(dateObj.getDate() + numDays);
return dateObj;
}
var now = new Date();
var tomorrow = addDays(new Date(), 1);
var nextWeek = addDays(new Date(), 7);
alert(
'Today: ' + now +
'\nTomorrow: ' + tomorrow +
'\nNext week: ' + nextWeek
);
self
(not $self) refers to the type of class, where as $this
refers to the current instance of the class. self
is for use in static member functions to allow you to access static member variables. $this
is used in non-static member functions, and is a reference to the instance of the class on which the member function was called.
Because this
is an object, you use it like: $this->member
Because self
is not an object, it's basically a type that automatically refers to the current class, you use it like: self::member
If the two byte arrays you mention is your entire key, the values are in the range 0-51, unique and the order within the a and b arrays is insignificant, my math tells me that there is only just about 26 million possible permutations and that you likely are trying to fill the map with values for all possible keys.
In this case, both filling and retrieving values from your data store would of course be much faster if you use an array instead of a HashMap and index it from 0 to 25989599.
Please look at this document
http://www.socialsecurity.gov/employer/randomization.html
The SSA is instituting a new policy the where all previously unused sequences are will be available for use.
Goes into affect June 25, 2011.
Taken from the new FAQ:
What changes will result from randomization?
The SSA will eliminate the geographical significance of the first three digits of the SSN, currently referred to as the area number, by no longer allocating the area numbers for assignment to individuals in specific states. The significance of the highest group number (the fourth and fifth digits of the SSN) for validation purposes will be eliminated. Randomization will also introduce previously unassigned area numbers for assignment excluding area numbers 000, 666 and 900-999. Top
Will SSN randomization assign group number (the fourth and fifth digits of the SSN) 00 or serial number (the last four digits of the SSN) 0000?
SSN randomization will not assign group number 00 or serial number 0000. SSNs containing group number 00 or serial number 0000 will continue to be invalid.
If you know the element type then: (eg: replace 'element' with 'div')
$("element[id$='txtTitle']")
If you don't know the element type:
$("[id$='txtTitle']")
// the old way, needs exact ID: document.getElementById("hi").value = "kk";_x000D_
$(function() {_x000D_
$("[id$='txtTitle']").val("zz");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="ctl_blabla_txtTitle" type="text" />
_x000D_
You have to look at the bigger problem. How to write the directives that solve one problem. You should try directive use-form-error. Would it help to solve this problem, and many others.
<form name="ExampleForm">
<label>Password</label>
<input ng-model="password" required />
<br>
<label>Confirm password</label>
<input ng-model="confirmPassword" required />
<div use-form-error="isSame" use-error-expression="password && confirmPassword && password!=confirmPassword" ng-show="ExampleForm.$error.isSame">Passwords Do Not Match!</div>
</form>
Live example jsfiddle
Darian Moody has a nice solution to this challenge in his blog post:
a = 1
b = 2
c = True
rules = [a == 1,
b == 2,
c == True]
if all(rules):
print("Success!")
The all() method returns True
when all elements in the given iterable are true. If not, it returns False
.
You can read a little more about it in the python docs here and more information and examples here.
(I also answered the similar question with this info here - How to have multiple conditions for one if statement in python)
With deferred
(another promise/deferred implementation) you can do:
// Setup 'pdrop', promise version of 'drop' method
var deferred = require('deferred');
mongoose.Collection.prototype.pdrop =
deferred.promisify(mongoose.Collection.prototype.drop);
// Drop collections:
deferred.map(['aaa','bbb','ccc'], function(name){
return conn.collection(name).pdrop()(function () {
console.log("dropped");
});
}).end(function () {
console.log("all dropped");
}, null);
The way to do this is to set the EnableHeadersVisualStyles
flag for the data grid view to False
, and set the background colour via the ColumnHeadersDefaultCellStyle.BackColor
property. For example, to set the background colour to blue, use the following (or set in the designer if you prefer):
_dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
_dataGridView.EnableHeadersVisualStyles = false;
If you do not set the EnableHeadersVisualStyles
flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme. The MSDN documentation for this property is here.
git shortlog
by itself does not address the original question of total number of commits (not grouped by author)
That is true, and git rev-list HEAD --count remains the simplest answer.
However, with Git 2.29 (Q4 2020), "git shortlog
"(man) has become more precise.
It has been taught to group commits by the contents of the trailer lines, like "Reviewed-by:
", "Coauthored-by:
", etc.
See commit 63d24fa, commit 56d5dde, commit 87abb96, commit f17b0b9, commit 47beb37, commit f0939a0, commit 92338c4 (27 Sep 2020), and commit 45d93eb (25 Sep 2020) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 2fa8aac, 04 Oct 2020)
shortlog
: allow multiple groups to be specifiedSigned-off-by: Jeff King
Now that
shortlog
supports reading from trailers, it can be useful to combine counts from multiple trailers, or between trailers and authors.
This can be done manually by post-processing the output from multiple runs, but it's non-trivial to make sure that each name/commit pair is counted only once.This patch teaches shortlog to accept multiple
--group
options on the command line, and pull data from all of them.That makes it possible to run:
git shortlog -ns --group=author --group=trailer:co-authored-by
to get a shortlog that counts authors and co-authors equally.
The implementation is mostly straightforward. The "
group
" enum becomes a bitfield, and the trailer key becomes a list.
I didn't bother implementing the multi-group semantics for reading from stdin. It would be possible to do, but the existing matching code makes it awkward, and I doubt anybody cares.The duplicate suppression we used for trailers now covers authors and committers as well (though in non-trailer single-group mode we can skip the hash insertion and lookup, since we only see one value per commit).
There is one subtlety: we now care about the case when no group bit is set (in which case we default to showing the author).
The caller inbuiltin/log.c
needs to be adapted to ask explicitly for authors, rather than relying onshortlog_init()
. It would be possible with some gymnastics to make this keep working as-is, but it's not worth it for a single caller.
git shortlog
now includes in its man page:
--group=<type>
Group commits based on
<type>
. If no--group
option is specified, the default isauthor
.<type>
is one of:
author
, commits are grouped by authorcommitter
, commits are grouped by committer (the same as-c
)This is an alias for
--group=committer
.
git shortlog
now also includes in its man page:
If
--group
is specified multiple times, commits are counted under each value (but again, only once per unique value in that commit). For example,git shortlog --group=author --group=trailer:co-authored-by
counts both authors and co-authors.
Important:
I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.
First remember below two rules:
Primary key of a socket: A socket is identified by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL}
not by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT}
- Protocol is an important part of a socket's definition.
OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.
Example 1: Two clients connecting to same server port means: socket1 {SRC-A, 100, DEST-X,80, TCP}
and socket2{SRC-B, 100, DEST-X,80, TCP}
. This means host A connects to server X's port 80 and another host B also connects to same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single threaded or multiple threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.
To answer the original question of the post:
Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by SRC-PORT
. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.
To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to same port, there could be more than one sockets (may be from same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which client initially tried to connect. If any server allocates different server-ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.
A bit more for completeness:
Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of parameter defining socket then the answer is no. This is so because we can say that in such case, a single client trying to connect to a server-port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However this is WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in same node can listen to same port only if they are using different protocol. For example two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server-processes.
Server Types - single & multiple:
When a server's processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server. Note that irrespective of the server's type a server can/should always uses the same initial socket to respond back (no need to allocate another server-port).
Suggested Books and rest of the two volumes if you can.
A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')
Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by parent child relationship. OS's (especially UNIX) by design allow a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that a process A listening to, can be listened by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to same socket. In addition, also note that this rule of disallowing two independent processes to listen to same socket lies on an OS (or its network libraries) and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restrictions.
I found a working win7 binary here: Unofficial Windows Binaries for Python Extension Packages It's from Christoph Gohlke at UC Irvine. There are binaries for python 2.5, 2.6, 2.7 , 3.1 and 3.2 for both 32bit and 64 bit windows.
There are a whole lot of other compiled packages here, too.
Be sure to uninstall your old PILfirst.
If you used easy_install:
easy_install -mnX pil
And then remove the egg in python/Lib/site-packages
Be sure to remove any other failed attempts. I had moved the _image dll into Python*.*/DLLs and I had to remove it.
If you want to include the column that is the current identity, you can still do that but you have to explicitly list the columns and cast the current identity to an int (assuming it is one now), like so:
select cast (CurrentID as int) as CurrentID, SomeOtherField, identity(int) as TempID
into #temp
from myserver.dbo.mytable
I tried the following three methods, my file size is 1M, and I got results:
I run the program several times it looks that BufferedReader is faster.
@Test
public void testLargeFileIO_Scanner() throws Exception {
long start = new Date().getTime();
String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
InputStream inputStream = new FileInputStream(fileName);
try (Scanner fileScanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
//System.out.println(line);
}
}
long end = new Date().getTime();
long time = end - start;
System.out.println("Scanner Time Consumed => " + time);
}
@Test
public void testLargeFileIO_BufferedReader() throws Exception {
long start = new Date().getTime();
String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
try (BufferedReader fileBufferReader = new BufferedReader(new FileReader(fileName))) {
String fileLineContent;
while ((fileLineContent = fileBufferReader.readLine()) != null) {
//System.out.println(fileLineContent);
}
}
long end = new Date().getTime();
long time = (long) (end - start);
System.out.println("BufferedReader Time Consumed => " + time);
}
@Test
public void testLargeFileIO_Stream() throws Exception {
long start = new Date().getTime();
String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
try (Stream inputStream = Files.lines(Paths.get(fileName), StandardCharsets.UTF_8)) {
//inputStream.forEach(System.out::println);
}
long end = new Date().getTime();
long time = end - start;
System.out.println("Stream Time Consumed => " + time);
}
By using mode
df.name.mode()
Out[712]:
0 alex
1 helen
dtype: object
Set the data as a vector and then place in the function.
You can detect a lot of heap corruption problems by enabling Page Heap for your application . To do this you need to use gflags.exe that comes as a part of Debugging Tools For Windows
Run Gflags.exe and in the Image file options for your executable, check "Enable Page Heap" option.
Now restart your exe and attach to a debugger. With Page Heap enabled, the application will break into debugger whenever any heap corruption occurs.
add <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
in head
reference: http://thehackernews.com/2015/04/disable-mixed-content-warning.html
browser compatibility: http://caniuse.com/#feat=upgradeinsecurerequests
I found a somewhat hacky-feeling but much safer way of doing this that doesn't require typing the values twice or referencing the memory of the enum values, making it very unlikely to break.
Basically, instead of using an enum, make a struct with a single instance, and make all of the enum-values constants. The variables can then be queried using a Mirror
public struct Suit{
// the values
let spades = "?"
let hearts = "?"
let diamonds = "?"
let clubs = "?"
// make a single instance of the Suit struct, Suit.instance
struct SStruct{static var instance: Suit = Suit()}
static var instance : Suit{
get{return SStruct.instance}
set{SStruct.instance = newValue}
}
// an array with all of the raw values
static var allValues: [String]{
var values = [String]()
let mirror = Mirror(reflecting: Suit.instance)
for (_, v) in mirror.children{
guard let suit = v as? String else{continue}
values.append(suit)
}
return values
}
}
If you use this method, to get a single value you'll need to use Suit.instance.clubs
or Suit.instance.spades
But all of that is so boring... Let's do some stuff that makes this more like a real enum!
public struct SuitType{
// store multiple things for each suit
let spades = Suit("?", order: 4)
let hearts = Suit("?", order: 3)
let diamonds = Suit("?", order: 2)
let clubs = Suit("?", order: 1)
struct SStruct{static var instance: SuitType = SuitType()}
static var instance : SuitType{
get{return SStruct.instance}
set{SStruct.instance = newValue}
}
// a dictionary mapping the raw values to the values
static var allValuesDictionary: [String : Suit]{
var values = [String : Suit]()
let mirror = Mirror(reflecting: SuitType.instance)
for (_, v) in mirror.children{
guard let suit = v as? Suit else{continue}
values[suit.rawValue] = suit
}
return values
}
}
public struct Suit: RawRepresentable, Hashable{
public var rawValue: String
public typealias RawValue = String
public var hashValue: Int{
// find some integer that can be used to uniquely identify
// each value. In this case, we could have used the order
// variable because it is a unique value, yet to make this
// apply to more cases, the hash table address of rawValue
// will be returned, which should work in almost all cases
//
// you could also add a hashValue parameter to init() and
// give each suit a different hash value
return rawValue.hash
}
public var order: Int
public init(_ value: String, order: Int){
self.rawValue = value
self.order = order
}
// an array of all of the Suit values
static var allValues: [Suit]{
var values = [Suit]()
let mirror = Mirror(reflecting: SuitType.instance)
for (_, v) in mirror.children{
guard let suit = v as? Suit else{continue}
values.append(suit)
}
return values
}
// allows for using Suit(rawValue: "?"), like a normal enum
public init?(rawValue: String){
// get the Suit from allValuesDictionary in SuitType, or return nil if that raw value doesn't exist
guard let suit = SuitType.allValuesDictionary[rawValue] else{return nil}
// initialize a new Suit with the same properties as that with the same raw value
self.init(suit.rawValue, order: suit.order)
}
}
You can now do stuff like
let allSuits: [Suit] = Suit.allValues
or
for suit in Suit.allValues{
print("The suit \(suit.rawValue) has the order \(suit.order)")
}
However, To get a single you'll still need to use SuitType.instance.spades
or SuitType.instance.hearts
. To make this a little more intuitive, you could add some code to Suit
that allows you to use Suit.type.*
instead of SuitType.instance.*
public struct Suit: RawRepresentable, Hashable{
// ...your code...
static var type = SuitType.instance
// ...more of your code...
}
You can now use Suit.type.diamonds
instead of SuitType.instance.diamonds
, or Suit.type.clubs
instead of SuitType.instance.clubs
Based on your comment, moddify this:
$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV
to:
$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV
More about selectors: https://api.jquery.com/category/selectors/
via command line we in centOs we can do this
httpd -l
The following is based on the answers above (plus a correction for the milliseconds) and emulates datetime.timestamp()
for Python 3 before 3.3 when timezones are used.
def datetime_timestamp(datetime):
'''
Equivalent to datetime.timestamp() for pre-3.3
'''
try:
return datetime.timestamp()
except AttributeError:
utc_datetime = datetime.astimezone(utc)
return timegm(utc_datetime.timetuple()) + utc_datetime.microsecond / 1e6
To strictly answer the question as asked, you'd want:
datetime_timestamp(my_datetime) + 5 * 60
datetime_timestamp
is part of simple-date. But if you were using that package you'd probably type:
SimpleDate(my_datetime).timestamp + 5 * 60
which handles many more formats / types for my_datetime.
// --------Start Scroll Bar Slide--------
final HorizontalScrollView xHorizontalScrollViewHeader = (HorizontalScrollView) findViewById(R.id.HorizontalScrollViewHeader);
final HorizontalScrollView xHorizontalScrollViewData = (HorizontalScrollView) findViewById(R.id.HorizontalScrollViewData);
xHorizontalScrollViewData.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
int scrollX; int scrollY;
scrollX=xHorizontalScrollViewData.getScrollX();
scrollY=xHorizontalScrollViewData.getScrollY();
xHorizontalScrollViewHeader.scrollTo(scrollX, scrollY);
}
});
// ---------End Scroll Bar Slide---------
You can avoid using own Component
s and SwingX library and ImageIO
class:
File f = new File("hello.jpg");
JLabel imgLabel = new JLabel(new ImageIcon(file.getName()));
Try this command
msiexec /x {product-id} /qr
Yes, you can do this solely in interface builder and without writing code - the one caveat is that you are resizing the label instead of distributing whitespace. In this case, align Label 2's X and Y to the superview so it is fixed in the center. Then set label 1's vertical space to the superview and to label 2 to the standard, repeat for label 3. After setting label 2 the easiest way to set label 1 and 3 is to resize them until they snap.
Here is the horizontal display, note that the vertical space between label 1 and 2 is set to standard:
And here is the portrait version:
I realize they are not absolutely 100% equally spaced between the baselines due to the difference between the standard space between labels and the standard space to the superview. If that bothers you, set the size to 0 instead of standard
1. Create class Name RecyclerTouchListener.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener
{
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
2. Call RecyclerTouchListener
recycleView.addOnItemTouchListener(new RecyclerTouchListener(this, recycleView,
new RecyclerTouchListener.ClickListener() {
@Override
public void onClick(View view, int position) {
Toast.makeText(MainActivity.this,Integer.toString(position),Toast.LENGTH_SHORT).show();
}
@Override
public void onLongClick(View view, int position) {
}
}));
Basically it allows Java to store several types of objects in one structure implementation, by generic type declaration (like class MyStructure<T extends TT>
), which is one of Javas main features.
Object-oriented approaches are based in modularity and reusability by separation of concerns - the ability to use a structure with any kind of types of object (as long as it obeys a few rules).
You could just instantiate things as followed:
ArrayList list = new ArrayList();
instead of
ArrayList<String> list = new ArrayList<>();
By declaring and using generic types you are informing a structure of the kind of objects it will manage and the compiler will be able to inform you if you're inserting an illegal type into that structure, for instance. Let's say:
// this works
List list1 = new ArrayList();
list1.add(1);
list1.add("one");
// does not work
List<String> list2 = new ArrayList<>();
list2.add(1); // compiler error here
list2.add("one");
If you want to see some examples check the documentation documentation:
/**
* Generic version of the Box class.
* @param <T> the type of the value being boxed
*/
public class Box<T> {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
Then you could instantiate things like:
class Paper { ... }
class Tissue { ... }
// ...
Box<Paper> boxOfPaper = new Box<>();
boxOfPaper.set(new Paper(...));
Box<Tissue> boxOfTissues = new Box<>();
boxOfTissues.set(new Tissue(...));
The main thing to draw from this is you're specifying which type of object you want to box.
As for using Object l = new ArrayList<>();
, you're not accessing the List
or ArrayList
implementation so you won't be able to do much with the collection.
I've connected to bank with two-way SSL (client and server certificate) with Spring Boot. So describe here all my steps, hope it helps someone (simplest working solution, I've found):
Generate sertificate request:
Generate private key:
openssl genrsa -des3 -passout pass:MY_PASSWORD -out user.key 2048
Generate certificate request:
openssl req -new -key user.key -out user.csr -passin pass:MY_PASSWORD
Keep user.key
(and password) and send certificate request user.csr
to bank for my sertificate
Receive 2 certificate: my client root certificate clientId.crt
and bank root certificate: bank.crt
Create Java keystore (enter key password and set keystore password):
openssl pkcs12 -export -in clientId.crt -inkey user.key -out keystore.p12 -name clientId -CAfile ca.crt -caname root
Don't pay attention on output: unable to write 'random state'
. Java PKCS12 keystore.p12
created.
Add into keystore bank.crt
(for simplicity I've used one keystore):
keytool -import -alias banktestca -file banktestca.crt -keystore keystore.p12 -storepass javaops
Check keystore certificates by:
keytool -list -keystore keystore.p12
Ready for Java code:) I've used Spring Boot RestTemplate
with add org.apache.httpcomponents.httpcore
dependency:
@Bean("sslRestTemplate")
public RestTemplate sslRestTemplate() throws Exception {
char[] storePassword = appProperties.getSslStorePassword().toCharArray();
URL keyStore = new URL(appProperties.getSslStore());
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(keyStore, storePassword)
// use storePassword twice (with key password do not work)!!
.loadKeyMaterial(keyStore, storePassword, storePassword)
.build();
// Solve "Certificate doesn't match any of the subject alternative names"
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
RestTemplate restTemplate = new RestTemplate(factory);
// restTemplate.setMessageConverters(List.of(new Jaxb2RootElementHttpMessageConverter()));
return restTemplate;
}
Look, there's no easy way to do this. I'm working on a project that is inherently multithreaded. Events come in from the operating system and I have to process them concurrently.
The simplest way to deal with testing complex, multithreaded application code is this: If it's too complex to test, you're doing it wrong. If you have a single instance that has multiple threads acting upon it, and you can't test situations where these threads step all over each other, then your design needs to be redone. It's both as simple and as complex as this.
There are many ways to program for multithreading that avoids threads running through instances at the same time. The simplest is to make all your objects immutable. Of course, that's not usually possible. So you have to identify those places in your design where threads interact with the same instance and reduce the number of those places. By doing this, you isolate a few classes where multithreading actually occurs, reducing the overall complexity of testing your system.
But you have to realize that even by doing this, you still can't test every situation where two threads step on each other. To do that, you'd have to run two threads concurrently in the same test, then control exactly what lines they are executing at any given moment. The best you can do is simulate this situation. But this might require you to code specifically for testing, and that's at best a half step towards a true solution.
Probably the best way to test code for threading issues is through static analysis of the code. If your threaded code doesn't follow a finite set of thread safe patterns, then you might have a problem. I believe Code Analysis in VS does contain some knowledge of threading, but probably not much.
Look, as things stand currently (and probably will stand for a good time to come), the best way to test multithreaded apps is to reduce the complexity of threaded code as much as possible. Minimize areas where threads interact, test as best as possible, and use code analysis to identify danger areas.
Since nobody mentioned it: Since Java 1.6 The Java JDK also comes bundled with a JavaScript commandline and REPL.
It is based on Rhino: https://developer.mozilla.org/en/docs/Rhino
In Java 1.6 and 1.7 the command is called jrunscript
(jrunscript.exe
on Windows) and can be found in the bin folder of the JDK.
Starting from Java 1.8 there is bundled a new JavaScript implementation (Nashorn: https://blogs.oracle.com/nashorn/)
So in Java 1.8 the command is called jjs
(jjs.exe
on Windows)
tl;dr ~
flips the bits. As a result the sign changes. ~2
is a negative number (0b..101
). To output a negative number ruby
prints -
, then two's complement of ~2
: -(~~2 + 1) == -(2 + 1) == 3
. Positive numbers are output as is.
There's an internal value, and its string representation. For positive integers, they basically coincide:
irb(main):001:0> '%i' % 2
=> "2"
irb(main):002:0> 2
=> 2
The latter being equivalent to:
irb(main):003:0> 2.to_s
"2"
~
flips the bits of the internal value. 2
is 0b010
. ~2
is 0b..101
. Two dots (..
) represent an infinite number of 1
's. Since the most significant bit (MSB) of the result is 1
, the result is a negative number ((~2).negative? == true
). To output a negative number ruby
prints -
, then two's complement of the internal value. Two's complement is calculated by flipping the bits, then adding 1
. Two's complement of 0b..101
is 3
. As such:
irb(main):005:0> '%b' % 2
=> "10"
irb(main):006:0> '%b' % ~2
=> "..101"
irb(main):007:0> ~2
=> -3
To sum it up, it flips the bits, which changes the sign. To output a negative number it prints -
, then ~~2 + 1
(~~2 == 2
).
The reason why ruby
outputs negative numbers like so, is because it treats the stored value as a two's complement of the absolute value. In other words, what's stored is 0b..101
. It's a negative number, and as such it's a two's complement of some value x
. To find x
, it does two's complement of 0b..101
. Which is two's complement of two's complement of x
. Which is x
(e.g ~(~2 + 1) + 1 == 2
).
In case you apply ~
to a negative number, it just flips the bits (which nevertheless changes the sign):
irb(main):008:0> '%b' % -3
=> "..101"
irb(main):009:0> '%b' % ~-3
=> "10"
irb(main):010:0> ~-3
=> 2
What is more confusing is that ~0xffffff00 != 0xff
(or any other value with MSB equal to 1
). Let's simplify it a bit: ~0xf0 != 0x0f
. That's because it treats 0xf0
as a positive number. Which actually makes sense. So, ~0xf0 == 0x..f0f
. The result is a negative number. Two's complement of 0x..f0f
is 0xf1
. So:
irb(main):011:0> '%x' % ~0xf0
=> "..f0f"
irb(main):012:0> (~0xf0).to_s(16)
=> "-f1"
In case you're not going to apply bitwise operators to the result, you can consider ~
as a -x - 1
operator:
irb(main):018:0> -2 - 1
=> -3
irb(main):019:0> --3 - 1
=> 2
But that is arguably of not much use.
An example Let's say you're given a 8-bit (for simplicity) netmask, and you want to calculate the number of 0
's. You can calculate them by flipping the bits and calling bit_length
(0x0f.bit_length == 4
). But ~0xf0 == 0x..f0f
, so we've got to cut off the unneeded bits:
irb(main):014:0> '%x' % (~0xf0 & 0xff)
=> "f"
irb(main):015:0> (~0xf0 & 0xff).bit_length
=> 4
Or you can use the XOR operator (^
):
irb(main):016:0> i = 0xf0
irb(main):017:0> '%x' % i ^ ((1 << i.bit_length) - 1)
=> "f"
This generally means that the owning Hibernate session has already closed. You can do one of the following to fix it:
HibernateTemplate.initialize(object name)
lazy=false
in your hbm files.Try this... Worked for me and printed 10/22/2013 01:37:56 AM
Ofcourse this is your code only with little modifications.
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // This line converts the given date into UTC time zone
final java.util.Date dateObj = sdf.parse("2013-10-22T01:37:56");
aRevisedDate = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a").format(dateObj);
System.out.println(aRevisedDate);
list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append
Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]
Time complexity, append O(1), insert O(n)
The simple <u>some text</u>
should work for you.
See this example also
<?php
function get_timezones()
{
$o = array();
$t_zones = timezone_identifiers_list();
foreach($t_zones as $a)
{
$t = '';
try
{
//this throws exception for 'US/Pacific-New'
$zone = new DateTimeZone($a);
$seconds = $zone->getOffset( new DateTime("now" , $zone) );
$hours = sprintf( "%+02d" , intval($seconds/3600));
$minutes = sprintf( "%02d" , ($seconds%3600)/60 );
$t = $a ." [ $hours:$minutes ]" ;
$o[$a] = $t;
}
//exceptions must be catched, else a blank page
catch(Exception $e)
{
//die("Exception : " . $e->getMessage() . '<br />');
//what to do in catch ? , nothing just relax
}
}
ksort($o);
return $o;
}
$o = get_timezones();
?>
<html>
<body>
<select name="time_zone">
<?php
foreach($o as $tz => $label)
{
echo "<option value="$tz">$label</option>";
}
?>
</select>
</body>
</html>
@Pascal's comment on the OP's question is right. By simply adding the image, it removes the black borders and the app will use the full height.
You will need to make adjustments to any CGRects by determining that the device is using the bigger display. I.e. If you need something aligned to the bottom of the screen.
I am sure there is a built in method, but I haven't seen anything and a lot is still under NDA so the method we use in our apps is quite simply a global function. Add the following to your .pch file and then its a simple if( is4InchRetina() ) { ... }
call to make adjustments to your CGRects etc.
static BOOL is4InchRetina()
{
if (![UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 548 || [UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 568)
return YES;
return NO;
}
Use Collections.swap
and Arrays.asList
:
Collections.swap(Arrays.asList(arr), i, j);
try to use following query
select *
from xxx
where convert(date,dates) >= '2012-10-26' and convert(date,dates) <= '2012-10-27'
Simple Solution. No Jquery
<img id="output" src="" width="100" height="100">_x000D_
_x000D_
<input name="photo" type="file" accept="image/*" onchange="document.getElementById('output').src = window.URL.createObjectURL(this.files[0])">
_x000D_
We can force the checksum validation in maven with at least two options:
1.Adding the --strict-checksums
to our maven command.
2.Adding the following configuration to our maven settings file:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<!--...-->
<profiles>
<profile>
<!--...-->
<repositories>
<repository>
<id>codehausSnapshots</id>
<name>Codehaus Snapshots</name>
<releases>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</snapshots>
<url>
<!--...-->
</url>
</repository>
</repositories>
<pluginRepositories>
<!--...-->
</pluginRepositories>
<!--...-->
</profile>
</profiles>
<!--...-->
</settings>
More details in this post: https://dzone.com/articles/maven-artifact-checksums-what
VS 2012/13 Win 7 64 bit gacutil.exe is located in
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools
Using a
instead of w
should let you update the file instead of creating a new one/overwriting everything in the existing file.
See this answer for a difference in the modes.
As almost anyone said, adding a runtime service will solve the problem. But if there is no runtime services or there is something like Google App Engine which is not your favorite any how, click New button right down the Targeted Runtimes list and add a new runtime server environment. Then check it and click OK and let the compiler to compile your project again.
Hope it helps ;)
Use json_encode() if your server side scripting lang is PHP,
json_encode()
escapes the newline & other unexpected tokens for you
(if not using PHP look for similar function for your scripting language)
then use $.parseJSON()
in your JavaScript, done!
If everything looks fine. I would advice to check this for PATHEXT .CMD must be added.
Make a bat file with the following in it:
copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt
However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:
C:\temp\test.bat > C:\temp\test.log
(assuming the first bat file was called test.bat and was located in that directory)
I faced similar problem a while ago and decided to write Eclipse plug-in that shows complete build path dependency tree of a Java project (although not in graphic mode - result is written into file). The plug-in's sources are here http://github.com/PetrGlad/dependency-tree
note - Lepl is no longer maintained or supported.
RFC 3696 defines "best practices" for URL validation - http://www.faqs.org/rfcs/rfc3696.html
The latest release of Lepl (a Python parser library) includes an implementation of RFC 3696. You would use it something like:
from lepl.apps.rfc3696 import Email, HttpUrl
# compile the validators (do once at start of program)
valid_email = Email()
valid_http_url = HttpUrl()
# use the validators (as often as you like)
if valid_email(some_email):
# email is ok
else:
# email is bad
if valid_http_url(some_url):
# url is ok
else:
# url is bad
Although the validators are defined in Lepl, which is a recursive descent parser, they are largely compiled internally to regular expressions. That combines the best of both worlds - a (relatively) easy to read definition that can be checked against RFC 3696 and an efficient implementation. There's a post on my blog showing how this simplifies the parser - http://www.acooke.org/cute/LEPLOptimi0.html
Lepl is available at http://www.acooke.org/lepl and the RFC 3696 module is documented at http://www.acooke.org/lepl/rfc3696.html
This is completely new in this release, so may contain bugs. Please contact me if you have any problems and I will fix them ASAP. Thanks.
I ran into this issue as well. My fix was to create a child schema. See below for an example for your models.
---- Person model
const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema = mongoose.Schema;
const productSchema = new Schema({
friends : [SingleFriend.schema]
});
module.exports = mongoose.model('Person', personSchema);
***Important: SingleFriend.schema -> make sure to use lowercase for schema
--- Child schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SingleFriendSchema = new Schema({
Name: String
});
module.exports = mongoose.model('SingleFriend', SingleFriendSchema);
jQuery debounce is a nice one for problems like this. jsFidlle
$(window).scroll($.debounce( 250, true, function(){
$('#scrollMsg').html('SCROLLING!');
}));
$(window).scroll($.debounce( 250, function(){
$('#scrollMsg').html('DONE!');
}));
The second parameter is the "at_begin" flag. Here I've shown how to execute code both at "scroll start" and "scroll finish".
As suggested by Barry P, jsFiddle, underscore or lodash also have a debounce, each with slightly different apis.
$(window).scroll(_.debounce(function(){
$('#scrollMsg').html('SCROLLING!');
}, 150, { 'leading': true, 'trailing': false }));
$(window).scroll(_.debounce(function(){
$('#scrollMsg').html('STOPPED!');
}, 150));
you can find it by running the following command
mysql --help
it will give you the mysql installed directory and all commands for mysql.
>>> s = 'abcd'
>>> len(s)
4
$(document).ready(function() {
$("#form1").validate({
rules: {
field1: "required"
},
messages: {
field1: "Please specify your name"
}
})
});
<form id="form1" name="form1">
Field 1: <input id="field1" type="text" class="required">
<input id="btn" type="submit" value="Validate">
</form>
You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.
Some of the common ways to create a String array are
This will create an array of 5 strings with initial values to be empty string.
<String?>
(5)This will create an array of size 5 with initial values to be null. You can use String data to modify the array.
When you know the contents of array already then you can initialise the array directly.
There is an easy way for creating an multi dimensional array of strings as well.
var matrix = Array(5){Array(6) {""}}
This is how you can create a matrix with 5 rows and 6 columns with initial values of empty string.
While not standard, I found that some of the JSON libraries have options to support multiline Strings. I am saying this with the caveat, that this will hurt your interoperability.
However in the specific scenario I ran into, I needed to make a config file that was only ever used by one system readable and manageable by humans. And opted for this solution in the end.
Here is how this works out on Java with Jackson:
JsonMapper mapper = JsonMapper.builder()
.enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS)
.build()
Tests like unit tests? What for? Tests HAVE to be independant, otherwise.... you can not run a test individually. If they are independent, why even interfere? Plus - what is an "order" if you run them in multiple threads on multiple cores?
I actually came here looking to sort a list by a list where the values matched.
list_a = ['foo', 'bar', 'baz']
list_b = ['baz', 'bar', 'foo']
sorted(list_b, key=lambda x: list_a.index(x))
# ['foo', 'bar', 'baz']
It is to mark the parameter as optional.
Just wanted to add to Abizern answer.
If anyone is using a non-administrator account, you can create a "local" variable instead of a "system" variable which allows access to standard/limited accounts.
When on the "Environmental Variables" window:
1) Select "New..." button within the "User variables for ..." section.
2) Set the "Variable name:" as "path" and "Variable value:" as "[your-git-path]" (usually found at C:\Program Files (x86)\Git\bin
).
3) Then click OK.
I used the construction of $.each (data [i], function (key, value)
But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: autocomplete form with ajax success
A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.
Check the success field for true or false
private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
JsonObject jsonObject = null;
URLConnection connection = null;
InputStream is = null;
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String url = "https://www.google.com/recaptcha/api/siteverify";
try {
String query = String.format("secret=%s&response=%s&remoteip=%s",
URLEncoder.encode(secret, charset),
URLEncoder.encode(response, charset),
URLEncoder.encode(remoteip, charset));
connection = new URL(url + "?" + query).openConnection();
is = connection.getInputStream();
JsonReader rdr = Json.createReader(is);
jsonObject = rdr.readObject();
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return jsonObject;
}
Use
System.getProperty("java.class.path")
see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
You can also split it into it's elements easily
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
You can center any number of child in a FrameLayout
.
<FrameLayout
>
<child1
....
android:layout_gravity="center"
.....
/>
<Child2
....
android:layout_gravity="center"
/>
</FrameLayout>
So the key is
adding
android:layout_gravity="center"
in the child views.
I centered a CustomView and a TextView on a FrameLayout
like this
Code:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<com.airbnb.lottie.LottieAnimationView
android:layout_width="180dp"
android:layout_height="180dp"
android:layout_gravity="center"
app:lottie_fileName="red_scan.json"
app:lottie_autoPlay="true"
app:lottie_loop="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:textSize="10dp"
android:textStyle="bold"
android:padding="10dp"
android:text="Networks Available: 1\n click to see all"
android:gravity="center" />
</FrameLayout>
Result:
You can use:
SELECT CONVERT(datetime, '24.04.2012', 103) AS Date
Reference: CAST and CONVERT (Transact-SQL)
Where clause and args work together to form the WHERE statement of the SQL query. So say you looking to express
WHERE Column1 = 'value1' AND Column2 = 'value2'
Then your whereClause and whereArgs will be as follows
String whereClause = "Column1 =? AND Column2 =?";
String[] whereArgs = new String[]{"value1", "value2"};
If you want to select all table columns, i believe a null string passed to tableColumns will suffice.
I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.
I generally use this to reset the git to the specific commit in source tree.
select commit to reset on sourcetree.
In dropdowns select the active branch , first Parent Only
And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)
and then go to terminal git push -f
You should be all set!
I refined the bash solution a bit, so that the more efficient scan is used instead of keys, and printing out array and hash values is supported. My solution also prints out the key name.
redis_print.sh:
#!/bin/bash
# Default to '*' key pattern, meaning all redis keys in the namespace
REDIS_KEY_PATTERN="${REDIS_KEY_PATTERN:-*}"
for key in $(redis-cli --scan --pattern "$REDIS_KEY_PATTERN")
do
type=$(redis-cli type $key)
if [ $type = "list" ]
then
printf "$key => \n$(redis-cli lrange $key 0 -1 | sed 's/^/ /')\n"
elif [ $type = "hash" ]
then
printf "$key => \n$(redis-cli hgetall $key | sed 's/^/ /')\n"
else
printf "$key => $(redis-cli get $key)\n"
fi
done
Note: you can formulate a one-liner of this script by removing the first line of redis_print.sh and commanding: cat redis_print.sh | tr '\n' ';' | awk '$1=$1'
Right click on the particular element (e.g. div
, table
, td
) and select the copy as html.
<ul>
<li>this is my text</li>
<li>this is my text</li>
<li>this is my text</li>
<li>this is my text</li>
<li>this is my text</li>
</ul>
you can use this simple css style
ul {
list-style-type: '\2713';
}
Solution using Google Guava
String filled = Strings.repeat("*", 10);
This can be easily solved with the the utility make_axes_locatable
. I provide a minimal example that shows how this works and should be readily adaptable:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
m1 = np.random.rand(3, 3)
m2 = np.arange(0, 3*3, 1).reshape((3, 3))
fig = plt.figure(figsize=(16, 12))
ax1 = fig.add_subplot(121)
im1 = ax1.imshow(m1, interpolation='None')
divider = make_axes_locatable(ax1)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im1, cax=cax, orientation='vertical')
ax2 = fig.add_subplot(122)
im2 = ax2.imshow(m2, interpolation='None')
divider = make_axes_locatable(ax2)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im2, cax=cax, orientation='vertical');
I came across this thread in search of an answer to this error.
The odd thing, for me, was that everything worked while running in dev (npm start), but the error would happen when the app was built (npm run build) and then run with serve -s build
.
It turns out that if you have comments in the render block, like the below, it will cause the error:
ReactDOM.render(
<React.StrictMode>
// this will cause an error!
<Provider store={store}>
<AppRouter />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
I'm sharing in case someone else comes across this thread with the same issue.
Eager Loading When you are sure that want to get multiple entities at a time, for example you have to show user, and user details at the same page, then you should go with eager loading. Eager loading makes single hit on database and load the related entities.
Lazy loading When you have to show users only at the page, and by clicking on users you need to show user details then you need to go with lazy loading. Lazy loading make multiple hits, to get load the related entities when you bind/iterate related entities.
I see this isn't answered yet, this is an exact quote from here:
WSHttpBinding will try and perform an internal negotiate at the SSP layer. In order for this to be successful, you will need to allow anonymous in IIS for the VDir. WCF will then by default perfrom an SPNEGO for window credentials. Allowing anonymous at IIS layer is not allowing anyone in, it is deferring to the WCF stack.
I found this via: http://fczaja.blogspot.com/2009/10/http-request-is-unauthorized-with.html
After googling: http://www.google.tt/#hl=en&source=hp&q=+The+HTTP+request+is+unauthorized+with+client+authentication+scheme+%27Anonymous
Usually you hear Task is a higher level concept than thread... and that's what this phrase means:
You can't use Abort/ThreadAbortedException, you should support
cancel event in your "business code" periodically testing token.IsCancellationRequested
flag (also avoid long or timeoutless connections e.g. to db, otherwise you will never get a chance to test this flag). By the similar reason Thread.Sleep(delay)
call should be replaced with Task.Delay(delay, token)
call (passing token inside to have possibility to interrupt delay).
There are no thread's Suspend
and Resume
methods functionality with tasks. Instance of task can't be reused either.
But you get two new tools:
a) continuations
// continuation with ContinueWhenAll - execute the delegate, when ALL
// tasks[] had been finished; other option is ContinueWhenAny
Task.Factory.ContinueWhenAll(
tasks,
() => {
int answer = tasks[0].Result + tasks[1].Result;
Console.WriteLine("The answer is {0}", answer);
}
);
b) nested/child tasks
//StartNew - starts task immediately, parent ends whith child
var parent = Task.Factory.StartNew
(() => {
var child = Task.Factory.StartNew(() =>
{
//...
});
},
TaskCreationOptions.AttachedToParent
);
So system thread is completely hidden from task, but still task's code is executed in the concrete system thread. System threads are resources for tasks and ofcourse there is still thread pool under the hood of task's parallel execution. There can be different strategies how thread get new tasks to execute. Another shared resource TaskScheduler cares about it. Some problems that TaskScheduler solves 1) prefer to execute task and its conitnuation in the same thread minimizing switching cost - aka inline execution) 2) prefer execute tasks in an order they were started - aka PreferFairness 3) more effective distribution of tasks between inactive threads depending on "prior knowledge of tasks activity" - aka Work Stealing. Important: in general "async" is not same as "parallel". Playing with TaskScheduler options you can setup async tasks be executed in one thread synchronously. To express parallel code execution higher abstractions (than Tasks) could be used: Parallel.ForEach
, PLINQ
, Dataflow
.
Tasks are integrated with C# async/await features aka Promise Model, e.g there requestButton.Clicked += async (o, e) => ProcessResponce(await client.RequestAsync(e.ResourceName));
the execution of client.RequestAsync
will not block UI thread. Important: under the hood Clicked
delegate call is absolutely regular (all threading is done by compiler).
That is enough to make a choice. If you need to support Cancel functionality of calling legacy API that tends to hang (e.g. timeoutless connection) and for this case supports Thread.Abort(), or if you are creating multithread background calculations and want to optimize switching between threads using Suspend/Resume, that means to manage parallel execution manually - stay with Thread. Otherwise go to Tasks because of they will give you easy manipulate on groups of them, are integrated into the language and make developers more productive - Task Parallel Library (TPL) .
Open the Command Prompt and type in the following:
FOR /L %i IN (1,1,254) DO ping -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txt
Change 192.168.10 to match you own network.
By using -n 1 you are asking for only 1 packet to be sent to each computer instead of the usual 4 packets.
The above command will ping all IP Addresses on the 192.168.10.0 network and create a text document in the C:\ drive called ipaddresses.txt. This text document should only contain IP Addresses that replied to the ping request.
Although it will take quite a bit longer to complete, you can also resolve the IP Addresses to HOST names by simply adding -a to the ping command.
FOR /L %i IN (1,1,254) DO ping -a -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txt
This is from Here
Hope this helps
For every system that support relative URI resolution, both relative and absolute URIs do serve the same goal: referencing. And they can be used interchangeably. So you could decide in each case differently. Technically, they provide the same referencing.
To be precise, with each relative URI there already is an absolute URI. And that's the base-URI that relative URI is resolved against. So a relative URI is actually a feature on top of absolute URIs.
And that's also why with relative URIs you can do more as with an absolute URI alone - this is especially important for static websites which otherwise couldn't be as flexible to maintain as compared to absolute URIs.
These positive effects of relative URI resolution can be exploited for dynamic web-application development as well. The inflexibility absolute URIs do introduce are also easier to cope up with, in a dynamic environment, so for some developers that are unsure about URI resolution and how to properly implement and manage it (not that it's always easy) do often opt into using absolute URIs in a dynamic part of a website as they can introduce other dynamic features (e.g. configuration variable containing the URI prefix) so to work around the inflexibility.
So what is the benefit then in using absolute URIs? Technically there ain't, but one I'd say: Relative URIs are more complex because they need to be resolved against the so called absolute base-URI. Even the resolution is strictly define since years, you might run over a client that has a mistake in URI resolution. As absolute URIs do not need any resolution, using absolute URIs have no risk to run into faulty client behaviour with relative URI resolution. So how high is that risk actually? Well, it's very rare. I only know about one Internet browser that had an issue with relative URI resolution. And that was not generally but only in a very (obscure) case.
Next to the HTTP client (browser) it's perhaps more complex for an author of hypertext documents or code as well. Here the absolute URI has the benefit that it is easier to test, as you can just enter it as-is into your browsers address bar. However, if it's not just your one-hour job, it's most often of more benefit to you to actually understand absolute and relative URI handling so that you can actually exploit the benefits of relative linking.
You'll need to clear out your cache to have it completely wiped. this help page from git will help you out. (it helped me) http://help.github.com/remove-sensitive-data/
No, it is not okay to put a link
element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):
“This element defines a link. Unlike
A
, it may only appear in theHEAD
section of a document, although it may appear any number of times.”
Live example of Curl command to send OPTIONS requests: https://reqbin.com/req/c-d8nxa0fl
If you like a nice way to do this from the command line use jstat:
http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstat.html
It gives raw information at configurable intervals which is very useful for logging and graphing purposes.
It looks like what you want to do is remove your first merge. You could follow the following procedure:
git checkout master # Let's make sure we are on master branch
git reset --hard master~ # Let's get back to master before the merge
git pull # or git merge remote/master
git merge topic
That would give you what you want.
You need to call the AddAddress
method once for every recipient. Like so:
$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..
Better yet, add them as Carbon Copy recipients.
$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..
To make things easy, you should loop through an array to do this.
$recipients = array(
'[email protected]' => 'Person One',
'[email protected]' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
Using Spring Framework , you can add many attachments :
package com.mkyong.common;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailMail
{
private JavaMailSender mailSender;
private SimpleMailMessage simpleMailMessage;
public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String dear, String content) {
MimeMessage message = mailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(simpleMailMessage.getFrom());
helper.setTo(simpleMailMessage.getTo());
helper.setSubject(simpleMailMessage.getSubject());
helper.setText(String.format(
simpleMailMessage.getText(), dear, content));
FileSystemResource file = new FileSystemResource("/home/abdennour/Documents/cv.pdf");
helper.addAttachment(file.getFilename(), file);
}catch (MessagingException e) {
throw new MailParseException(e);
}
mailSender.send(message);
}
}
To know how to configure your project to deal with this code , complete reading this tutorial .
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
Just access the element and append it to the value.
<input
type="button"
onclick="document.getElementById('myTextArea').value += '•'"
value="Add •">
See a live demo.
For the sake of keeping things simple, I haven't written unobtrusive JS. For a production system you should.
Also it needs to be a UTF8 character.
Browsers generally submit forms using the encoding they received the page in. Serve your page as UTF-8 if you want UTF-8 data submitted back.
SOA is a new badge for some very old ideas:
Divide your code into reusable modules.
Encapsulate in a module any design decision that is likely to change.
Design your modules in such a way that they can be combined in different useful ways (sometimes called a "family" or "product line").
These are all bedrock software-development principles, many of them first articulated by David Parnas.
What's new in SOA is
You're doing it on a network.
Modules are communicating by sending messages to each other over the network, rather than by more tradtional programming-language mechanisms like procedure calls. In particular, in a service-oriented architecture the parts generally don't share mutable state (global variables in a traditional program). Or if they do share state, that state is carefully locked up in a database which is itself an agent and which can easily manage multiple concurrent clients.
Project Files Services Tabls
go files tabs
drag drop file to libs files hover.
return project tabs and what are you see :)
You can add function to:
c:\Users\David\Documents\WindowsPowerShell\profile.ps1
An the function will be available.
MailKit is an Open Source cross-platform .NET mail-client library that is based on MimeKit and optimized for mobile devices. It has more and advance features better than System.Net.Mail Microsoft TNEF support via MimeKit.
Download nuget package from here.
See this example you can send mail
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(senderName, [email protected]));
mailMessage.Sender = new MailboxAddress(senderName, [email protected]);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.TextBody = "Hello There";
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("[email protected]", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
}
}
catch (SmtpCommandException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Here's how I do it in JavaScript:
function isMobile() {
var index = navigator.appVersion.indexOf("Mobile");
return (index > -1);
}
See an example at www.tablemaker.net/test/mobile.html where it triples the font size on mobile phones.
Schema information which is designed to be very close to that of the SQL-92 INFORMATION_SCHEMA may be obtained for the Jet/ACE engine (which is what I assume you mean by 'access') via the OLE DB providers.
See:
You can simply use Arrays.sort()
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));
Working Example :
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
_x000D_
console.log(array);
_x000D_
Just use the function plot
as follows
figure()
...
plot(t, a)
plot(t, b)
plot(t, c)
Today, in Oracle 12c or newer, you probably have the column defined as GENERATED ... AS IDENTITY, and Oracle takes care of the sequence itself.
You can use an ALTER TABLE Statement to modify "START WITH" of the identity.
ALTER TABLE tbl MODIFY ("ID" NUMBER(13,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 3580 NOT NULL ENABLE);
Use This as the solution
This worked for me perfectly..
<div align="center">
<img src="">
</div>
You shouldn´t use client javascript to access databases for several reasons (bad practice, security issues, etc) but if you really want to do this, here is an example:
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
document.write(rs.fields(1));
rs.movenext;
}
rs.close;
connection.close;
A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.
And there are rumors of an ancient legend about the existence of server javascript, but this is another story. ;)
I like the answer from 30thh using Iterators
from Guava. However, from some frameworks I get null instead of an empty array, and Iterators.forArray(array)
does not handle that well. So I came up with this helper method, which you can call with Iterator<String> it = emptyIfNull(array);
public static <F> UnmodifiableIterator<F> emptyIfNull(F[] array) {
if (array != null) {
return Iterators.forArray(array);
}
return new UnmodifiableIterator<F>() {
public boolean hasNext() {
return false;
}
public F next() {
return null;
}
};
}
For me it works that when I create new Name tag for the same range from the Name Manager it gives me the option to change scope ;) workbook comes as default and can be changed to any of the available sheets.
You can override any built-in function by just re-declaring it.
parseFloat = function(a){
alert(a)
};
Now parseFloat(3)
will alert 3.
Looks file you use the .mkdirs()
method on a File
object: http://www.roseindia.net/java/beginners/java-create-directory.shtml
// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
// Directory creation failed
}
I also had the same problem and it tooks me several hours to figured out.
I just changed 'config' to 'cookie'
$cfg['Servers'][$i]['auth_type'] = 'config';
Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.
[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.
Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.
I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement
.
TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).
As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.
BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.
My answer only supports single line text. Check out gfullam's comment below for the multi-line fork, it looks pretty promising.
I rewrote the code from the first answer a few times, and I think this should be the fastest.
It first finds an "Estimated" text length, and then adds or removes a character until the width is correct.
The logic it uses is shown below:
After an "estimated" text length is found, characters are added or removed until the desired width is reached.
I'm sure it needs some tweaking, but here's the code:
(function ($) {
$.fn.ellipsis = function () {
return this.each(function () {
var el = $(this);
if (el.css("overflow") == "hidden") {
var text = el.html().trim();
var t = $(this.cloneNode(true))
.hide()
.css('position', 'absolute')
.css('overflow', 'visible')
.width('auto')
.height(el.height())
;
el.after(t);
function width() { return t.width() > el.width(); };
if (width()) {
var myElipse = "....";
t.html(text);
var suggestedCharLength = (text.length * el.width() / t.width()) - myElipse.length;
t.html(text.substr(0, suggestedCharLength) + myElipse);
var x = 1;
if (width()) {
while (width()) {
t.html(text.substr(0, suggestedCharLength - x) + myElipse);
x++;
}
}
else {
while (!width()) {
t.html(text.substr(0, suggestedCharLength + x) + myElipse);
x++;
}
x--;
t.html(text.substr(0, suggestedCharLength + x) + myElipse);
}
el.html(t.html());
t.remove();
}
}
});
};
})(jQuery);
Added: I found something that should do the trick right away, but the rest of the code below also offers an alternative.
Use the subplots_adjust()
function to move the bottom of the subplot up:
fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot.
Then play with the offset in the legend bbox_to_anchor
part of the legend command, to get the legend box where you want it. Some combination of setting the figsize
and using the subplots_adjust(bottom=...)
should produce a quality plot for you.
Alternative: I simply changed the line:
fig = plt.figure(1)
to:
fig = plt.figure(num=1, figsize=(13, 13), dpi=80, facecolor='w', edgecolor='k')
and changed
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))
to
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,-0.02))
and it shows up fine on my screen (a 24-inch CRT monitor).
Here figsize=(M,N)
sets the figure window to be M inches by N inches. Just play with this until it looks right for you. Convert it to a more scalable image format and use GIMP to edit if necessary, or just crop with the LaTeX viewport
option when including graphics.
This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.
In this case, tester method needs to have access to Class, and you can construct
JavaType type = mapper.getTypeFactory().
constructCollectionType(List.class, Foo.class)
and then
List<Foo> list = mapper.readValue(new File("input.json"), type);
Inspired by NSMutableString
idea from Chris, I make a perfect macro imho.
It supports insert nil elements without any Exceptions.
#import <libextobjc/metamacros.h>
#define STR_CONCAT(...) \
({ \
__auto_type str__ = [NSMutableString string]; \
metamacro_foreach_cxt(never_use_immediately_str_concatify_,, str__, __VA_ARGS__) \
(NSString *)str__.copy; \
})
#define never_use_immediately_str_concatify_(INDEX, CONTEXT, VAR) \
[CONTEXT appendString:VAR ?: @""];
Example:
STR_CONCAT(@"button_bg_", @(count).stringValue, @".png");
// button_bg_2.png
If you like, you can use id
type as parameter by using [VAR description]
instead of NSString
.
Use Java script to change action url dynamically Works for me well
function chgAction( action_name )
{
{% for data in sidebar_menu_data %}
if( action_name== "ABC"){ document.forms.action = "/ABC/";
}
else if( action_name== "XYZ"){ document.forms.action = "/XYZ/";
}
}
<form name="forms" method="post" action="<put default url>" onSubmit="return checkForm(this);">{% csrf_token %}
TRUNCATE TABLE table;
is the SQL command. In PHP, you'd use:
mysql_query('TRUNCATE TABLE table;');
Controller not supposed to be called from view. That's the whole idea of MVC - clear separation of concerns.
If you need to call controller from View - you are doing something wrong. Time for refactoring.
Many screencasts displaying an iPhone application simply use the iPhone Simulator, which is one option.
You can also take screenshots on the phone by quickly pressing the menu and the power/sleep button at the same time. The image is then saved to your "Camera Roll" and easily transferable to the computer
The other way is only possible with a Jailbroken phone - Veency is a VNC server for the iPhone, which you can connect to with a regular VNC client.
If you hafe upload your file in media than:
media
example-input-file.txt
views.py
def download_csv(request):
file_path = os.path.join(settings.MEDIA_ROOT, 'example-input-file.txt')
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
urls.py
path('download_csv/', views.download_csv, name='download_csv'),
download.html
a href="{% url 'download_csv' %}" download=""
I also thought this would work but it's misleading:
myStruct _m1 = {0};
When I tried this:
myStruct _m1 = {0xff};
Only the 1st byte was set to 0xff
, the remaining ones were set to 0
. So I wouldn't get into the habit of using this.
I have prepared a Shell Script to create a Backup of MYSQL database. You can use it so that we have backup of our database(s).
#!/bin/bash
export PATH=/bin:/usr/bin:/usr/local/bin
TODAY=`date +"%d%b%Y_%I:%M:%S%p"`
################################################################
################## Update below values ########################
DB_BACKUP_PATH='/backup/dbbackup'
MYSQL_HOST='localhost'
MYSQL_PORT='3306'
MYSQL_USER='auriga'
MYSQL_PASSWORD='auriga@123'
DATABASE_NAME=( Project_O2 o2)
BACKUP_RETAIN_DAYS=30 ## Number of days to keep local backup copy; Enable script code in end of th script
#################################################################
{ mkdir -p ${DB_BACKUP_PATH}/${TODAY}
echo "
${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
} || {
echo "Can not make Directry"
echo "Possibly Path is wrong"
}
{ if ! mysql -u ${MYSQL_USER} -p${MYSQL_PASSWORD} -e 'exit'; then
echo 'Failed! You may have Incorrect PASSWORD/USER ' >> ${DB_BACKUP_PATH}/Backup-Report.txt
exit 1
fi
for DB in "${DATABASE_NAME[@]}"; do
if ! mysql -u ${MYSQL_USER} -p${MYSQL_PASSWORD} -e "use "${DB}; then
echo "Failed! Database ${DB} Not Found on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
else
# echo "Backup started for database - ${DB}"
# mysqldump -h localhost -P 3306 -u auriga -pauriga@123 Project_O2 # use gzip..
mysqldump -h ${MYSQL_HOST} -P ${MYSQL_PORT} -u ${MYSQL_USER} -p${MYSQL_PASSWORD} \
--databases ${DB} | gzip > ${DB_BACKUP_PATH}/${TODAY}/${DB}-${TODAY}.sql.gz
if [ $? -eq 0 ]; then
touch ${DB_BACKUP_PATH}/Backup-Report.txt
echo "successfully backed-up of ${DB} on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
# echo "Database backup successfully completed"
else
touch ${DB_BACKUP_PATH}/Backup-Report.txt
echo "Failed to backup of ${DB} on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
# echo "Error found during backup"
exit 1
fi
fi
done
} || {
echo "Failed during backup"
echo "Failed to backup on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
# ./myshellsc.sh 2> ${DB_BACKUP_PATH}/Backup-Report.txt
}
##### Remove backups older than {BACKUP_RETAIN_DAYS} days #####
# DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`
# if [ ! -z ${DB_BACKUP_PATH} ]; then
# cd ${DB_BACKUP_PATH}
# if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
# rm -rf ${DBDELDATE}
# fi
# fi
### End of script ####
In the script we just need to give our Username, Password, Name of Database(or Databases if more than one) also Port number if Different.
To Run the script use Command as:
sudo ./script.sc
I also Suggest that if You want to see the Result in a file Like: Failure Occurs or Successful in backing-up, then Use the Command as Below:
sudo ./myshellsc.sh 2>> Backup-Report.log
Thank You.
You could only write one where clause.
SELECT table1.f_id FROM table1
INNER JOIN table2
ON table2.f_id = table1.f_id
where table1.f_com_id = '430' AND
table1.f_status = 'Submitted' AND table2.f_type = 'InProcess'
Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-
We are doing AND operation in this example. There are also other masking operators- OR, XOR.
Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-
1 1 1 0 1 1 0 1 [input] (&) 0 0 1 1 1 1 0 0 [mask] ------------------------------ 0 0 1 0 1 1 0 0 [output]
So, only the middle 4 bits (as these bits are 1
in this mask) remain.
Lets see this with XOR-
1 1 1 0 1 1 0 1 [input] (^) 0 0 1 1 1 1 0 0 [mask] ------------------------------ 1 1 0 1 0 0 0 1 [output]
Now, the middle 4 bits are flipped (1
became 0
, 0
became 1
).
So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-
bool isOdd(int i) {
return i%2;
}
This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-
bool isOdd(int i) {
return i&1;
}
Short Explanation: If the least significant bit of a binary number is 1
then it is odd; for 0
it will be even. So, by doing AND with 1
we are removing all other bits except for the least significant bit i.e.:
55 -> 0 0 1 1 0 1 1 1 [input] (&) 1 -> 0 0 0 0 0 0 0 1 [mask] --------------------------------------- 1 <- 0 0 0 0 0 0 0 1 [output]
'\r'
means 'carriage return' and it is similar to '\n'
which means 'line break' or more commonly 'new line'
in the old days of typewriters, you would have to move the carriage that writes back to the start of the line, and move the line down in order to write onto the next line.
in the modern computer era we still have this functionality for multiple reasons. but mostly we use only '\n'
and automatically assume that we want to start writing from the start of the line, since it would not make much sense otherwise.
however, there are some times when we want to use JUST the '\r'
and that would be if i want to write something to an output, and the instead of going down to a new line and writing something else, i want to write something over what i already wrote, this is how many programs in linux or in windows command line are able to have 'progress' information that changes on the same line.
nowadays most systems use only the '\n'
to denote a newline. but some systems use both together.
you can see examples of this given in some of the other answers, but the most common are:
'\r\n'
'\r'
'\n'
and some other programs also have specific uses for them.
for more information about the history of these characters
If all those kill process commands don't work for you, my suggestion is to check if you were using any other packages to run your node process.
I had the similar issue, and it was due to I was running my node process using PM2(a NPM package). The kill [processID]
command disables the process but keeps the port occupied. Hence I had to go into PM2 and dump all node process to free up the port again.
Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below
intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);
intentClearCookies.setIntent(clearcookies);
intentClearCookies.setTitle(R.string.ClearCookies);
intentClearCookies.setEnabled(true);
launchPrefCat.addPreference(intentClearCookies);
And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.
public class ClearCookies extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
showDialog();
}
/**
* @throws NotFoundException
*/
private void showDialog() throws NotFoundException {
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.ClearCookies))
.setMessage(
getResources().getString(R.string.ClearCookieQuestion))
.setIcon(
getResources().getDrawable(
android.R.drawable.ic_dialog_alert))
.setPositiveButton(
getResources().getString(R.string.PostiveYesButton),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
})
.setNegativeButton(
getResources().getString(R.string.NegativeNoButton),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
}).show();
}}
As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.
Below function would work. You can copy from here and paste there...
-(void)savePhotoToAlbum:(UIImage*)imageToSave {
CGImageRef imageRef = imageToSave.CGImage;
NSDictionary *metadata = [NSDictionary new]; // you can add
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:imageRef metadata:metadata completionBlock:^(NSURL *assetURL,NSError *error){
if(error) {
NSLog(@"Image save eror");
}
}];
}
This steps are used in spring boot with self signed ssl certificate implementation
if SSL turns off then HTTPS call will be worked as expected.
https://localhost:8443/test/hello
These are the steps we have to follow,
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650
after key generation has done then copy that file in to the resource foder in your project
server.port: 8443
server.ssl.key-store:classpath:keystore.p12
server.ssl.key-store-password: test123
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
now verify the url: https://localhost:8443/test/hello
No, you don't need to add them as a remote. That would be clumbersome and a pain to do each time.
git fetch [email protected]:theirusername/reponame.git theirbranch:ournameforbranch
This creates a local branch named ournameforbranch
which is exactly the same as what theirbranch
was for them. For the question example, the last argument would be foo:foo
.
Note :ournameforbranch
part can be further left off if thinking up a name that doesn't conflict with one of your own branches is bothersome. In that case, a reference called FETCH_HEAD
is available. You can git log FETCH_HEAD
to see their commits then do things like cherry-picked
to cherry pick their commits.
Oftentimes, you want to fix something of theirs and push it right back. That's possible too:
git fetch [email protected]:theirusername/reponame.git theirbranch
git checkout FETCH_HEAD
# fix fix fix
git push [email protected]:theirusername/reponame.git HEAD:theirbranch
If working in detached state worries you, by all means create a branch using :ournameforbranch
and replace FETCH_HEAD
and HEAD
above with ournameforbranch
.
Here's how you can mock your FileConnection
Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
.Throws(new IOException());
Then instantiate your Transfer class and use the mock in your method call
Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);
Update:
First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.
Since you are setting those properties using another dependency, I would write it like this:
public class Transfer
{
public Transfer(IInternalConfig internalConfig)
{
source = internalConfig.GetFileConnection("source");
destination = internalConfig.GetFileConnection("destination");
}
//you should consider making these private or protected fields
public virtual IFileConnection source { get; set; }
public virtual IFileConnection destination { get; set; }
public virtual void GetFile(IFileConnection connection,
string remoteFilename, string localFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void PutFile(IFileConnection connection,
string localFilename, string remoteFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void TransferFiles(string sourceName, string destName)
{
var tempName = Path.GetTempFileName();
GetFile(source, sourceName, tempName);
PutFile(destination, tempName, destName);
}
}
This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.
Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:
ViewModel
, and include the Model as member in the ViewModel
, then you effectively sent your model to the View => this is BADSo how can you create a better coupling?
I would use a tool like AutoMapper
or ValueInjecter to map between ViewModel
and Model.
AutoMapper
does seem to have the better syntax and feel to it, but the current version lacks a
very severe topic: It is not able to perform the mapping from ViewModel
to Model (under certain circumstances like flattening, etc., but this is off topic)
So at present I prefer to use ValueInjecter
.
So you create a ViewModel
with the fields you need in the view.
You add the SelectList items you need as lookups.
And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist:
You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList
from the view to the controller.
// StaffTypes is an IEnumerable<StaffType> from dbContext
// viewModel is the viewModel initialized to copy content of Model Employee
// viewModel.StaffTypes is of type SelectList
viewModel.StaffTypes =
new SelectList(
StaffTypes.OrderBy( item => item.Name )
"StaffTypeID",
"Type",
viewModel.StaffTypeID
);
In the view you just have to call
@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )
Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel
. You then check for validation.
If the validation fails, you have to remember to re-populate the viewModel.StaffTypes
SelectList, because this item will be null on entering the post function.
So I tend to have those population things separated into a function.
You just call back return new View(viewModel)
if anything is wrong.
Validation errors found by MVC3 will automatically be shown in the view.
If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState
to get info on that.
If the viewModel
is valid you have to perform the next step:
If it is a create of a new item, you have to populate a model from the viewModel
(best suited is ValueInjecter
). Then you can add it to the EF collection of that type and commit changes.
If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel
back to the model (again using ValueInjecter
gets you do that very quick).
After that you can SaveChanges
and are done.
Feel free to ask if anything is unclear.
Programmatically display text over rect using basic Javascript
var svg = document.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0];_x000D_
_x000D_
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
text.setAttribute('x', 20);_x000D_
text.setAttribute('y', 50);_x000D_
text.setAttribute('width', 500);_x000D_
text.style.fill = 'red';_x000D_
text.style.fontFamily = 'Verdana';_x000D_
text.style.fontSize = '35';_x000D_
text.innerHTML = "Some text line";_x000D_
_x000D_
svg.appendChild(text);_x000D_
_x000D_
var text2 = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
text2.setAttribute('x', 20);_x000D_
text2.setAttribute('y', 100);_x000D_
text2.setAttribute('width', 500);_x000D_
text2.style.fill = 'green';_x000D_
text2.style.fontFamily = 'Calibri';_x000D_
text2.style.fontSize = '35';_x000D_
text2.style.fontStyle = 'italic';_x000D_
text2.innerHTML = "Some italic line";_x000D_
_x000D_
_x000D_
svg.appendChild(text2);_x000D_
_x000D_
var text3 = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
text3.setAttribute('x', 20);_x000D_
text3.setAttribute('y', 150);_x000D_
text3.setAttribute('width', 500);_x000D_
text3.style.fill = 'green';_x000D_
text3.style.fontFamily = 'Calibri';_x000D_
text3.style.fontSize = '35';_x000D_
text3.style.fontWeight = 700;_x000D_
text3.innerHTML = "Some bold line";_x000D_
_x000D_
_x000D_
svg.appendChild(text3);
_x000D_
<svg width="510" height="250" xmlns="http://www.w3.org/2000/svg">_x000D_
<rect x="0" y="0" width="510" height="250" fill="aquamarine" />_x000D_
</svg>
_x000D_
Try giving the full path to apache2ctl.
First, upvote (at the least) alsami's answer. That got me on the right path.
But for those of you doing IoC, here is a little bit of a deeper dive.
My error (same as others)
One or more errors occurred. (A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.)
My code setup. "Just the basics"...
public class MyCoolDbContext: DbContext{
public DbSet <MySpecialObject> MySpecialObjects { get; set; }
}
and
public interface IMySpecialObjectDomainData{}
and (note MyCoolDbContext is being injected)
public class MySpecialObjectEntityFrameworkDomainDataLayer: IMySpecialObjectDomainData{
public MySpecialObjectEntityFrameworkDomainDataLayer(MyCoolDbContext context) {
/* HERE IS WHERE TO SET THE BREAK POINT, HOW MANY TIMES IS THIS RUNNING??? */
this.entityDbContext = context ?? throw new ArgumentNullException("MyCoolDbContext is null", (Exception)null);
}
}
and
public interface IMySpecialObjectManager{}
and
public class MySpecialObjectManager: IMySpecialObjectManager
{
public const string ErrorMessageIMySpecialObjectDomainDataIsNull = "IMySpecialObjectDomainData is null";
private readonly IMySpecialObjectDomainData mySpecialObjectDomainData;
public MySpecialObjectManager(IMySpecialObjectDomainData mySpecialObjectDomainData) {
this.mySpecialObjectDomainData = mySpecialObjectDomainData ?? throw new ArgumentNullException(ErrorMessageIMySpecialObjectDomainDataIsNull, (Exception)null);
}
}
And finally , my multi threaded class, being called from a Console App(Command Line Interface app)
public interface IMySpecialObjectThatSpawnsThreads{}
and
public class MySpecialObjectThatSpawnsThreads: IMySpecialObjectThatSpawnsThreads
{
public const string ErrorMessageIMySpecialObjectManagerIsNull = "IMySpecialObjectManager is null";
private readonly IMySpecialObjectManager mySpecialObjectManager;
public MySpecialObjectThatSpawnsThreads(IMySpecialObjectManager mySpecialObjectManager) {
this.mySpecialObjectManager = mySpecialObjectManager ?? throw new ArgumentNullException(ErrorMessageIMySpecialObjectManagerIsNull, (Exception)null);
}
}
and the DI buildup. (Again, this is for a console application (command line interface)...which exhibits slight different behavior than web-apps)
private static IServiceProvider BuildDi(IConfiguration configuration) {
/* this is being called early inside my command line application ("console application") */
string defaultConnectionStringValue = string.Empty; /* get this value from configuration */
////setup our DI
IServiceCollection servColl = new ServiceCollection()
////.AddLogging(loggingBuilder => loggingBuilder.AddConsole())
/* THE BELOW TWO ARE THE ONES THAT TRIPPED ME UP. */
.AddTransient<IMySpecialObjectDomainData, MySpecialObjectEntityFrameworkDomainDataLayer>()
.AddTransient<IMySpecialObjectManager, MySpecialObjectManager>()
/* so the "ServiceLifetime.Transient" below................is what you will find most commonly on the internet search results */
# if (MY_ORACLE)
.AddDbContext<ProvisioningDbContext>(options => options.UseOracle(defaultConnectionStringValue), ServiceLifetime.Transient);
# endif
# if (MY_SQL_SERVER)
.AddDbContext<ProvisioningDbContext>(options => options.UseSqlServer(defaultConnectionStringValue), ServiceLifetime.Transient);
# endif
servColl.AddSingleton <IMySpecialObjectThatSpawnsThreads, MySpecialObjectThatSpawnsThreads>();
ServiceProvider servProv = servColl.BuildServiceProvider();
return servProv;
}
The ones that surprised me were the (change to) transient for
.AddTransient<IMySpecialObjectDomainData, MySpecialObjectEntityFrameworkDomainDataLayer>()
.AddTransient<IMySpecialObjectManager, MySpecialObjectManager>()
Note, I think because IMySpecialObjectManager was being injected into "MySpecialObjectThatSpawnsThreads", those injected objects needed to be Transient to complete the chain.
The point being.......it wasn't just the (My)DbContext that needed .Transient...but a bigger chunk of the DI Graph.
Debugging Tip:
This line:
this.entityDbContext = context ?? throw new ArgumentNullException("MyCoolDbContext is null", (Exception)null);
Put your debugger break point there. If your MySpecialObjectThatSpawnsThreads is making N number of threads (say 10 threads for example)......and that line is only being hit once...that's your issue. Your DbContext is crossing threads.
BONUS:
I would suggest reading this below url/article (oldie but goodie) about the differences web-apps and console-apps
https://mehdi.me/ambient-dbcontext-in-ef6/
Here is the header of the article in case the link changes.
MANAGING DBCONTEXT THE RIGHT WAY WITH ENTITY FRAMEWORK 6: AN IN-DEPTH GUIDE Mehdi El Gueddari
I hit this issue with WorkFlowCore https://github.com/danielgerlag/workflow-core
<ItemGroup>
<PackageReference Include="WorkflowCore" Version="3.1.5" />
</ItemGroup>
sample code below.. to help future internet searchers
namespace MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.MySpecialObjectInterview.Workflows
{
using System;
using MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.MySpecialObjectInterview.Constants;
using MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.MySpecialObjectInterview.Glue;
using MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.WorkflowSteps;
using WorkflowCore.Interface;
using WorkflowCore.Models;
public class MySpecialObjectInterviewDefaultWorkflow : IWorkflow<MySpecialObjectInterviewPassThroughData>
{
public const string WorkFlowId = "MySpecialObjectInterviewWorkflowId";
public const int WorkFlowVersion = 1;
public string Id => WorkFlowId;
public int Version => WorkFlowVersion;
public void Build(IWorkflowBuilder<MySpecialObjectInterviewPassThroughData> builder)
{
builder
.StartWith(context =>
{
Console.WriteLine("Starting workflow...");
return ExecutionResult.Next();
})
/* bunch of other Steps here that were using IMySpecialObjectManager.. here is where my DbContext was getting cross-threaded */
.Then(lastContext =>
{
Console.WriteLine();
bool wroteConcreteMsg = false;
if (null != lastContext && null != lastContext.Workflow && null != lastContext.Workflow.Data)
{
MySpecialObjectInterviewPassThroughData castItem = lastContext.Workflow.Data as MySpecialObjectInterviewPassThroughData;
if (null != castItem)
{
Console.WriteLine("MySpecialObjectInterviewDefaultWorkflow complete :) {0} -> {1}", castItem.PropertyOne, castItem.PropertyTwo);
wroteConcreteMsg = true;
}
}
if (!wroteConcreteMsg)
{
Console.WriteLine("MySpecialObjectInterviewDefaultWorkflow complete (.Data did not cast)");
}
return ExecutionResult.Next();
}))
.OnError(WorkflowCore.Models.WorkflowErrorHandling.Retry, TimeSpan.FromSeconds(60));
}
}
}
and
ICollection<string> workFlowGeneratedIds = new List<string>();
for (int i = 0; i < 10; i++)
{
MySpecialObjectInterviewPassThroughData currentMySpecialObjectInterviewPassThroughData = new MySpecialObjectInterviewPassThroughData();
currentMySpecialObjectInterviewPassThroughData.MySpecialObjectInterviewPassThroughDataSurrogateKey = i;
//// private readonly IWorkflowHost workflowHost;
string wfid = await this.workflowHost.StartWorkflow(MySpecialObjectInterviewDefaultWorkflow.WorkFlowId, MySpecialObjectInterviewDefaultWorkflow.WorkFlowVersion, currentMySpecialObjectInterviewPassThroughData);
workFlowGeneratedIds.Add(wfid);
}
we can be submit multiple updates together in JDBC to submit batch updates.
we can use Statement, PreparedStatement, and CallableStatement objects for bacth update with disable autocommit
addBatch() and executeBatch() functions are available with all statement objects to have BatchUpdate
here addBatch() method adds a set of statements or parameters to the current batch.
use sc.nextLine(); two time so that we can read the last line of string
sc.nextLine() sc.nextLine()
Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from __future__
you can do simplify things a bit.
Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.
from __future__ import division
def Pythag(league):
def win_percentages():
for team, (runs_scored, runs_allowed) in league.iteritems():
win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
yield win_percentage
for win_percentage in win_percentages():
print win_percentage
I'm not sure what your reasons are, and even if you could pull it off somehow with Reflection Emit (I' not sure that you can), it doesn't sound like a good idea. What is probably a better idea is to have some kind of Dictionary and you can wrap access to the dictionary through methods in your class. That way you can store the data from the database in this dictionary, and then retrieve them using those methods.
This a variant of brettdj's & pstraton post.
This will return a true Value and not give you the #NUM!
error. And \D
is shorthand for anything but digits. The rest is much like the others only with this minor fix.
Function StripChar(Txt As String) As Variant
With CreateObject("VBScript.RegExp")
.Global = True
.Pattern = "\D"
StripChar = Val(.Replace(Txt, " "))
End With
End Function
This solves the problem:
df['newcolumn'] = df.A * df.B
You could also do:
def fab(row):
return row['A'] * row['B']
df['newcolumn'] = df.apply(fab, axis=1)
Depending on what browsers/devices you are looking to support, or what you are prepared to put up with for non-compliant browsers you may want to check out the <summary>
and <detail>
tags. They are for exactly this purpose. No css is required at all as the collapsing and showing are part of the tags definition/formatting.
I've made an example here:
<details>
<summary>This is what you want to show before expanding</summary>
<p>This is where you put the details that are shown once expanded</p>
</details>
Browser support varies. Try in webkit for best results. Other browsers may default to showing all the solutions. You can perhaps fallback to the hide/show method described above.
This has always worked well for me:
yAxes: [{
ticks: {
display: false;
},
Only this one worked for me:
<script type="text/javascript">
var frames = document.getElementsByTagName("iframe");
for (var i = 0; i < frames.length; i++) {
src = frames[i].src;
if (src.indexOf('embed') != -1) {
if (src.indexOf('?') != -1) {
frames[i].src += "&wmode=transparent";
} else {
frames[i].src += "?wmode=transparent";
}
}
}
</script>
I load it in the footer.php Wordpress file. Code found in comment here (thanks Gerson)
Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.
<?php
function getSSLPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>
When you set the SSL Version with curl to v3 then it works.
Edit:
Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.
http://curl.haxx.se/docs/caextract.html
here you can download the root certificates.
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
Then you can use the CURLOPT_SSL_VERIFYPEER
option with true
otherwise you get an error.
Basically, fs.readFileSync
throws an error when a file is not found. This error is from the Error
prototype and thrown using throw
, hence the only way to catch is with a try / catch
block:
var fileContents;
try {
fileContents = fs.readFileSync('foo.bar');
} catch (err) {
// Here you get the error when the file was not found,
// but you also get any other error
}
Unfortunately you can not detect which error has been thrown just by looking at its prototype chain:
if (err instanceof Error)
is the best you can do, and this will be true for most (if not all) errors. Hence I'd suggest you go with the code
property and check its value:
if (err.code === 'ENOENT') {
console.log('File not found!');
} else {
throw err;
}
This way, you deal only with this specific error and re-throw all other errors.
Alternatively, you can also access the error's message
property to verify the detailed error message, which in this case is:
ENOENT, no such file or directory 'foo.bar'
Hope this helps.
The comprehensive place for Acrobat JavaScript documentation is the Acrobat SDK, which can be downloaded from the Adobe website. In the Documentation section, you will find all the material needed to work with Acrobat JavaScript.
To complete the documentation you may in addition get the specification of the JavaScript Core. My book of choice for that is "JavaScript, the Definitive Guide" by David Flanagan, published by O'Reilly.
You could use the maven enforcer plugin with the banned dependency rule. This would allow you to ban all the aliases that you don't want and allow only the one you do want. These rules will fail the maven build of your project when violated. Furthermore, if this rule applies to all projects in an enterprise you could put the plugin configuration in a corporate parent pom.
see:
If you are using Jersey (which I was, my server component needs to make outbound HTTP requests) it contains the following public method:
var multiValueMap = UriComponent.decodeQuery(uri, true);
It is part of org.glassfish.jersey.uri.UriComponent
, and the javadoc is here. Whilst you may not want all of Jersey, it is part of the Jersey common package which isn't too bad on dependencies...
I've had a similar requirement: I needed to inject a Spring-managed repository bean into my Person
entity class ("entity" as in "something with an identity", for example an JPA entity). A Person
instance has friends, and for this Person
instance to return its friends, it shall delegate to its repository and query for friends there.
@Entity
public class Person {
private static PersonRepository personRepository;
@Id
@GeneratedValue
private long id;
public static void setPersonRepository(PersonRepository personRepository){
this.personRepository = personRepository;
}
public Set<Person> getFriends(){
return personRepository.getFriends(id);
}
...
}
.
@Repository
public class PersonRepository {
public Person get Person(long id) {
// do database-related stuff
}
public Set<Person> getFriends(long id) {
// do database-related stuff
}
...
}
So how did I inject that PersonRepository
singleton into the static field of the Person
class?
I created a @Configuration
, which gets picked up at Spring ApplicationContext construction time. This @Configuration
gets injected with all those beans that I need to inject as static fields into other classes. Then with a @PostConstruct
annotation, I catch a hook to do all static field injection logic.
@Configuration
public class StaticFieldInjectionConfiguration {
@Inject
private PersonRepository personRepository;
@PostConstruct
private void init() {
Person.setPersonRepository(personRepository);
}
}
use below code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String[] permissions = {Manifest.permission.READ_PHONE_STATE};
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, READ_PHONE_STATE);
}
} else {
try {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
String imei = telephonyManager.getDeviceId();
} catch (Exception e) {
e.printStackTrace();
}
}
And call onRequestPermissionsResult method following code:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case READ_PHONE_STATE:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
try {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
String imei = telephonyManager.getDeviceId();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Add following permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
I was able to convert string to DWORD and back with this code:
char strAddr[] = "127.0.0.1"
DWORD ip = inet_addr(strAddr); // ip contains 16777343 [0x0100007f in hex]
struct in_addr paddr;
paddr.S_un.S_addr = ip;
char *strAdd2 = inet_ntoa(paddr); // strAdd2 contains the same string as strAdd
I am working in a maintenance project of old MFC code, so converting deprecated functions calls is not applicable.
Looking at your requirement, there is alternate solution as well. It seems you know the dimensions in dp at compile time, so you can add a dimen entry in the resources. Then you can query the dimen entry and it will be automatically converted to pixels in this call:
final float inPixels= mActivity.getResources().getDimension(R.dimen.dimen_entry_in_dp);
And your dimens.xml will have:
<dimen name="dimen_entry_in_dp">72dp</dimen>
Extending this idea, you can simply store the value of 1dp or 1sp as a dimen entry and query the value and use it as a multiplier. Using this approach you will insulate the code from the math stuff and rely on the library to perform the calculations.
Example code:
a = pd.Series([1,2,3,4], index=[7,2,8,9])
b = pd.Series([5,6,7,8], index=[7,2,8,9])
data = pd.DataFrame({'a': a,'b':b, 'idx_col':a.index})
Pandas allows you to create a DataFrame
from a dict
with Series
as the values and the column names as the keys. When it finds a Series
as a value, it uses the Series
index as part of the DataFrame
index. This data alignment is one of the main perks of Pandas. Consequently, unless you have other needs, the freshly created DataFrame
has duplicated value. In the above example, data['idx_col']
has the same data as data.index
.
The general rule is that the const
keyword applies to what precedes it immediately. Exception, a starting const
applies to what follows.
const int*
is the same as int const*
and means "pointer to constant int".const int* const
is the same as int const* const
and means "constant pointer to constant int".Edit: For the Dos and Don'ts, if this answer isn't enough, could you be more precise about what you want?
Use GETDATE()
Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.
UPDATE table SET date = GETDATE()
If you have your hex value, and your just wondering what the value for the alpha would be, this snippet may help:
const alphaToHex = (alpha => {_x000D_
if (alpha > 1 || alpha < 0 || isNaN(alpha)) {_x000D_
throw new Error('The argument must be a number between 0 and 1');_x000D_
}_x000D_
return Math.ceil(255 * alpha).toString(16).toUpperCase();_x000D_
})_x000D_
_x000D_
console.log(alphaToHex(0.45));
_x000D_
This is less for @easwee and more for others that might have the same question:
If you do not require support for IE < 10, you can use Flexbox. It's an exciting CSS3 property that unfortunately was implemented in several different versions,; add in vendor prefixes, and getting good cross-browser support suddenly requires quite a few more properties than it should.
With the current, final standard, you would be done with
.container {
display: flex;
}
.container div {
flex: 1;
}
.column_center {
order: 2;
}
That's it. If you want to support older implementations like iOS 6, Safari < 6, Firefox 19 or IE10, this blossoms into
.container {
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Chrome */
display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
.container div {
-webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-flex: 1; /* OLD - Firefox 19- */
-webkit-flex: 1; /* Chrome */
-ms-flex: 1; /* IE 10 */
flex: 1; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
.column_center {
-webkit-box-ordinal-group: 2; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-ordinal-group: 2; /* OLD - Firefox 19- */
-ms-flex-order: 2; /* TWEENER - IE 10 */
-webkit-order: 2; /* NEW - Chrome */
order: 2; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
Here is an excellent article about Flexbox cross-browser support: Using Flexbox: Mixing Old And New
It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:
Viewport Changes
Viewport meta tags using
"width=device-width"
cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding"shrink-to-fit=no"
to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.
Here's a worked visual example which shows the difference upon loading the page in the two configurations.
The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw
). Note how in the first example the page is zoomed to fit when shrink-to-fit=no
is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.
The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.
You should mention the content type as well to omit the file accessing issue.
import os
image='fly.png'
s3_filestore_path = 'images/fly.png'
filename, file_extension = os.path.splitext(image)
content_type_dict={".png":"image/png",".html":"text/html",
".css":"text/css",".js":"application/javascript",
".jpg":"image/png",".gif":"image/gif",
".jpeg":"image/jpeg"}
content_type=content_type_dict[file_extension]
s3 = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'),
region_name='ap-south-1',
aws_access_key_id=S3_KEY,
aws_secret_access_key=S3_SECRET)
s3.put_object(Body=image, Bucket=S3_BUCKET, Key=s3_filestore_path, ContentType=content_type)
The accepted answer on this question doesn't seem to work for me. I achieved the same thing with a slightly different method:
IF (select object_id from sys.foreign_keys where [name] = 'FK_TableName_TableName2') IS NOT NULL
BEGIN
ALTER TABLE dbo.TableName DROP CONSTRAINT FK_TableName_TableName2
END
I fixed it by passing this as command-line parameter to msbuild.exe:
Your mileage will vary depending on the SDK version you have on your system
/p:TargetFrameworkSDKToolsDirectory="C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools
you can do:
A = randi(10, [3 4]); %# a random matrix
any( A(:)==5 ) %# does A contain 5?
To do the above in a vectorized way, use:
any( bsxfun(@eq, A(:), [5 7 11] )
or as @woodchips suggests:
ismember([5 7 11], A)
As a newbie to combinators, I found Mike Vanier's article (thanks Nicholas Mancuso) to be really helpful. I would like to write a summary, besides documenting my understanding, if it could be of help to some others I would be very glad.
Using factorial as an example, we use the following almost-factorial
function to calculate factorial of number x
:
def almost-factorial f x = if iszero x
then 1
else * x (f (- x 1))
In the pseudo-code above, almost-factorial
takes in function f
and number x
(almost-factorial
is curried, so it can be seen as taking in function f
and returning a 1-arity function).
When almost-factorial
calculates factorial for x
, it delegates the calculation of factorial for x - 1
to function f
and accumulates that result with x
(in this case, it multiplies the result of (x - 1) with x).
It can be seen as almost-factorial
takes in a crappy version of factorial function (which can only calculate till number x - 1
) and returns a less-crappy version of factorial (which calculates till number x
). As in this form:
almost-factorial crappy-f = less-crappy-f
If we repeatedly pass the less-crappy version of factorial to almost-factorial
, we will eventually get our desired factorial function f
. Where it can be considered as:
almost-factorial f = f
The fact that almost-factorial f = f
means f
is the fix-point of function almost-factorial
.
This was a really interesting way of seeing the relationships of the functions above and it was an aha moment for me. (please read Mike's post on fix-point if you haven't)
To generalize, we have a non-recursive function fn
(like our almost-factorial), we have its fix-point function fr
(like our f), then what Y
does is when you give Y
fn
, Y
returns the fix-point function of fn
.
So in summary (simplified by assuming fr
takes only one parameter; x
degenerates to x - 1
, x - 2
... in recursion):
fn
: def fn fr x = ...accumulate x with result from (fr (- x 1))
, this is the almost-useful function - although we cannot use fn
directly on x
, it will be useful very soon. This non-recursive fn
uses a function fr
to calculate its resultfn fr = fr
, fr
is the fix-point of fn
, fr
is the useful funciton, we can use fr
on x
to get our resultY fn = fr
, Y
returns the fix-point of a function, Y
turns our almost-useful function fn
into useful fr
Y
(not included)I will skip the derivation of Y
and go to understanding Y
. Mike Vainer's post has a lot of details.
Y
Y
is defined as (in lambda calculus format):
Y f = ?s.(f (s s)) ?s.(f (s s))
If we replace the variable s
in the left of the functions, we get
Y f = ?s.(f (s s)) ?s.(f (s s))
=> f (?s.(f (s s)) ?s.(f (s s)))
=> f (Y f)
So indeed, the result of (Y f)
is the fix-point of f
.
(Y f)
work?Depending the signature of f
, (Y f)
can be a function of any arity, to simplify, let's assume (Y f)
only takes one parameter, like our factorial function.
def fn fr x = accumulate x (fr (- x 1))
since fn fr = fr
, we continue
=> accumulate x (fn fr (- x 1))
=> accumulate x (accumulate (- x 1) (fr (- x 2)))
=> accumulate x (accumulate (- x 1) (accumulate (- x 2) ... (fn fr 1)))
the recursive calculation terminates when the inner-most (fn fr 1)
is the base case and fn
doesn't use fr
in the calculation.
Looking at Y
again:
fr = Y fn = ?s.(fn (s s)) ?s.(fn (s s))
=> fn (?s.(fn (s s)) ?s.(fn (s s)))
So
fr x = Y fn x = fn (?s.(fn (s s)) ?s.(fn (s s))) x
To me, the magical parts of this setup are:
fn
and fr
interdepend on each other: fr
'wraps' fn
inside, every time fr
is used to calculate x
, it 'spawns' ('lifts'?) an fn
and delegates the calculation to that fn
(passing in itself fr
and x
); on the other hand, fn
depends on fr
and uses fr
to calculate result of a smaller problem x-1
.fr
is used to define fn
(when fn
uses fr
in its operations), the real fr
is not yet defined.fn
which defines the real business logic. Based on fn
, Y
creates fr
- a helper function in a specific form - to facilitate the calculation for fn
in a recursive manner.It helped me understanding Y
this way at the moment, hope it helps.
BTW, I also found the book An Introduction to Functional Programming Through Lambda Calculus very good, I'm only part through it and the fact that I couldn't get my head around Y
in the book led me to this post.
df_concat = df_1.union(df_2)
The dataframes may need to have identical columns, in which case you can use withColumn()
to create normal_1
and normal_2
If it needs to run on the onload
event of the page, meaning that the document and all its assets have loaded, this needs to be in a content script embedded in each page for which you wish to track onload
.
None of the above was suitable, without calling session_start() in all php files that depend on $Session variables they will not be included. The Notice is so annoying and quickly fill up the Error_log. The only solution that I can find that works is this....
error_reporting(E_ALL ^ E_NOTICE);
session_start();
A Bad fix , but it works.
You can use the microtime
function for this. From the documentation:
microtime
— Return current Unix timestamp with microseconds
If
get_as_float
is set toTRUE
, thenmicrotime()
returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.
Example usage:
$start = microtime(true);
while (...) {
}
$time_elapsed_secs = microtime(true) - $start;
I don't think it can. When a service is "stopped", it gets totally unloaded.
Well, OK, there's always a way I suppose. For instance, you could create a detached process to stop the service, then restart it, then exit.
$("#message > span").text("your text");
or
$("#message").find("span").text("your text");
or
$("span","#message").text("your text");
or
$("#message > a.close-notify").siblings('span').text("your text");
driver.findElement(locator).clear()
- This command will work in all cases
Here is a good tutorial with code. Let me know if it works for you! This is also a good tutorial.
EDIT
In This example, all you need to do is add this line:
gallery.setSelection(1);
after setting the adapter to gallery object, that is this line:
gallery.setAdapter(new ImageAdapter(this));
UPDATE1
Alright, I got your problem. This open source library is your solution. I also have used it for one of my projects. Hope this will solve your problem finally.
UPDATE2:
I would suggest you to go through this tutorial. You might get idea. I think I got your problem, you want the horizontal scrollview with snap. Try to search with that keyword on google or out here, you might get your solution.
If i
is the int
, then
char c = i;
makes it a char
. You might want to add a check that the value is <128
if it comes from an untrusted source. This is best done with isascii
from <ctype.h>
, if available on your system (see @Steve Jessop's comment to this answer).
If it helps anyone, I combined the top two answers into an older-browser-tolerant version, which uses the fast version if reduce
is available and falls back to esmiralha's solution if it's not.
/**
* @see http://stackoverflow.com/q/7616461/940217
* @return {number}
*/
String.prototype.hashCode = function(){
if (Array.prototype.reduce){
return this.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);
}
var hash = 0;
if (this.length === 0) return hash;
for (var i = 0; i < this.length; i++) {
var character = this.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
Usage is like:
var hash = "some string to be hashed".hashCode();
You can put it in a different class and then call a function. This works when ajax refresh
$(document).on("change", ".inputQty", function(e) {
//Call a function(input,input);
});
Your Nesting DIV structure was missing, you must add another ".row" div when creating nested divs in bootstrap :
Here is the Code:
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-4"> <a href="">About</a>
</div>
<div class="col-md-4">
<img src="https://www.google.ca/images/srpr/logo11w.png" width="100px" />
</div>
<div class="col-md-4"> <a href="#myModal1" data-toggle="modal">SHARE</a>
</div>
</div>
</div>
</div>
</div>
To nest your content with the default grid, add a new .row and set of .col-sm-* columns within an existing .col-sm-* column. Nested rows should include a set of columns that add up to 12 or less (it is not required that you use all 12 available columns).
I'm astonished by the second number you mention (and confirm by your requested rounding) -- at first I thought my instinct for mental arithmetic was starting to fail me (I am getting older, after all, so that might be going the same way as my once-sharp memory!-)... but then I confirmed it hasn't, yet, by using, as I imagine you are, Python 3.1, and copying and pasting..:
>>> def input_meal():
... mealPrice = input('Enter the meal subtotal: $')
... mealPrice = float (mealPrice)
... return mealPrice
...
>>> def calc_tax(mealPrice):
... tax = mealPrice*.06
... return tax
...
>>> m = input_meal()
Enter the meal subtotal: $34.45
>>> print(calc_tax(m))
2.067
>>>
...as expected -- yet, you say it instead "returns a display of $ 2.607"... which might be a typo, just swapping two digits, except that you then ask "How can I set that to $2.61 instead?" so it really seems you truly mean 2.607
(which might be rounded to 2.61 in various ways) and definitely not the arithmetically correct result, 2.067
(which at best might be rounded to 2.07... definitely not to 2.61 as you request).
I imagine you first had the typo occur in transcription, and then mentally computed the desired rounding from the falsified-by-typo 2.607
rather than the actual original result -- is that what happened? It sure managed to confuse me for a while!-)
Anyway, to round a float to two decimal digits, simplest approach is the built-in function round with a second argument of 2
:
>>> round(2.067, 2)
2.07
>>> round(2.607, 2)
2.61
For numbers exactly equidistant between two possibilities, it rounds-to-even:
>>> round(2.605, 2)
2.6
>>> round(2.615, 2)
2.62
or, as the docs put it (exemplifying with the single-argument form of round
, which rounds to the closest integer):
if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).
However, for computations on money, I second the recommendation, already given in other answers, to stick with what the decimal module offers, instead of float
numbers.
# . /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh
# sqlplus /nolog
SQL> connect sys/password as sysdba
SQL> EXEC DBMS_XDB.SETLISTENERLOCALACCESS(FALSE);
SQL> CONNECT sys/password@hostname:1521 as sysdba