There's IMHO a more convenient way. You can indeed interactively prompt the user for the machine(s) he wants to apply the playbook to thanks to vars_prompt
:
---
- hosts: "{{ setupHosts }}"
vars_prompt:
- name: "setupHosts"
prompt: "Which hosts would you like to setup?"
private: no
tasks:
[…]
To support language like Hindi which can contain /p{Mark} as well in between language characters.
My solution is ^[\p{L}\p{M}]+([\p{L}\p{Pd}\p{Zs}'.]*[\p{L}\p{M}])+$|^[\p{L}\p{M}]+$
You can find all the test cases for this here https://regex101.com/r/3XPOea/1/tests
jspcal's answer as a string extension.
Program.cs
class Program
{
static void Main(string[] args)
{
var myText = "MYTEXT";
Console.WriteLine(myText.ToTitleCase()); //Mytext
}
}
StringExtensions.cs
using System;
public static class StringExtensions
{
public static string ToTitleCase(this string str)
{
if (str == null)
return null;
return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
}
This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?
In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.
See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html
This one is same on facebook:
<script>_x000D_
var valX = $(window).scrollTop();_x000D_
function syncScroll(target){_x000D_
var valY = $(window).scrollTop();_x000D_
var difYX = valY - valX;_x000D_
var targetX = $(target).scrollTop();_x000D_
if(valY > valX){_x000D_
$(target).scrollTop(difYX);_x000D_
}_x000D_
if(difYX <= 0){_x000D_
$(target).scrollTop(-20);_x000D_
}_x000D_
}_x000D_
_x000D_
$(window).scroll(function(){_x000D_
syncScroll('#demo');_x000D_
})_x000D_
</script>
_x000D_
body{_x000D_
margin:0;_x000D_
padding:0;_x000D_
height:100%;_x000D_
}_x000D_
#demo{_x000D_
position:fixed;_x000D_
height:100vh;_x000D_
overflow:hidden;_x000D_
width:40%;_x000D_
}_x000D_
#content{_x000D_
position:relative;_x000D_
float:right;_x000D_
width:60%;_x000D_
color:red; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
<div id="demo">_x000D_
<ul>_x000D_
<li>_x000D_
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
</li>_x000D_
<li>_x000D_
<p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
</p>_x000D_
</li> _x000D_
<li>_x000D_
<p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
</p>_x000D_
</li>_x000D_
<ul>_x000D_
</div>_x000D_
<div id="content">_x000D_
<ul>_x000D_
<li>_x000D_
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
</li>_x000D_
<li>_x000D_
<p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
</p>_x000D_
</li> _x000D_
<li>_x000D_
<p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
</p>_x000D_
</li>_x000D_
<li>_x000D_
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
</li>_x000D_
<li>_x000D_
<p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
</p>_x000D_
</li> _x000D_
<li>_x000D_
<p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
</p>_x000D_
</li>_x000D_
<li>_x000D_
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
</li>_x000D_
<li>_x000D_
<p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
</p>_x000D_
</li> _x000D_
<li>_x000D_
<p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
</p>_x000D_
</li>_x000D_
<li>_x000D_
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
</li>_x000D_
<li>_x000D_
<p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
</p>_x000D_
</li> _x000D_
<li>_x000D_
<p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
</p>_x000D_
</li>_x000D_
<ul>_x000D_
</div> _x000D_
</body
_x000D_
As stated in prior answers - it depends on the answer to "cpu or i/o bound?",
but also to the answer to "threaded or multi-processing?":
Examples run on Raspberry Pi 3B 1.2GHz 4-core with Python3.7.3
--( With other processes running including htop )
Typical Result:
. Starting 4000 cycles of io-bound threading
. Sequential run time: 39.15 seconds
. 4 threads Parallel run time: 18.19 seconds
. 2 threads Parallel - twice run time: 20.61 seconds
Typical Result:
. Starting 1000000 cycles of cpu-only threading
. Sequential run time: 9.39 seconds
. 4 threads Parallel run time: 10.19 seconds
. 2 threads Parallel twice - run time: 9.58 seconds
Typical Result:
. Starting 4000 cycles of io-bound processing
. Sequential - run time: 39.74 seconds
. 4 procs Parallel - run time: 17.68 seconds
. 2 procs Parallel twice - run time: 20.68 seconds
Typical Result:
. Starting 1000000 cycles of cpu-only processing
. Sequential run time: 9.24 seconds
. 4 procs Parallel - run time: 2.59 seconds
. 2 procs Parallel twice - run time: 4.76 seconds
compare_io_multiproc.py:
#!/usr/bin/env python3
# Compare single proc vs multiple procs execution for io bound operation
"""
Typical Result:
Starting 4000 cycles of io-bound processing
Sequential - run time: 39.74 seconds
4 procs Parallel - run time: 17.68 seconds
2 procs Parallel twice - run time: 20.68 seconds
"""
import time
import multiprocessing as mp
# one thousand
cycles = 1 * 1000
def t():
with open('/dev/urandom', 'rb') as f:
for x in range(cycles):
f.read(4 * 65535)
if __name__ == '__main__':
print(" Starting {} cycles of io-bound processing".format(cycles*4))
start_time = time.time()
t()
t()
t()
t()
print(" Sequential - run time: %.2f seconds" % (time.time() - start_time))
# four procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()
print(" 4 procs Parallel - run time: %.2f seconds" % (time.time() - start_time))
# two procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p1.start()
p2.start()
p1.join()
p2.join()
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p3.start()
p4.start()
p3.join()
p4.join()
print(" 2 procs Parallel twice - run time: %.2f seconds" % (time.time() - start_time))
compare_cpu_multiproc.py
#!/usr/bin/env python3
# Compare single proc vs multiple procs execution for cpu bound operation
"""
Typical Result:
Starting 1000000 cycles of cpu-only processing
Sequential run time: 9.24 seconds
4 procs Parallel - run time: 2.59 seconds
2 procs Parallel twice - run time: 4.76 seconds
"""
import time
import multiprocessing as mp
# one million
cycles = 1000 * 1000
def t():
for x in range(cycles):
fdivision = cycles / 2.0
fcomparison = (x > fdivision)
faddition = fdivision + 1.0
fsubtract = fdivision - 2.0
fmultiply = fdivision * 2.0
if __name__ == '__main__':
print(" Starting {} cycles of cpu-only processing".format(cycles))
start_time = time.time()
t()
t()
t()
t()
print(" Sequential run time: %.2f seconds" % (time.time() - start_time))
# four procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()
print(" 4 procs Parallel - run time: %.2f seconds" % (time.time() - start_time))
# two procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p1.start()
p2.start()
p1.join()
p2.join()
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p3.start()
p4.start()
p3.join()
p4.join()
print(" 2 procs Parallel twice - run time: %.2f seconds" % (time.time() - start_time))
In Eclipse Ganymede (3.4.0):
The following works for me. If there are duplicates, it will use dictA's value.
public static IDictionary<TKey, TValue> Merge<TKey, TValue>(this IDictionary<TKey, TValue> dictA, IDictionary<TKey, TValue> dictB)
where TValue : class
{
return dictA.Keys.Union(dictB.Keys).ToDictionary(k => k, k => dictA.ContainsKey(k) ? dictA[k] : dictB[k]);
}
<form name="input" action="some.php" method="post">
<input type="text" name="user" id="mytext">
<input type="submit" value="Submit">
</form>
<script>
var w = someValue;
document.getElementById("mytext").value = w;
</script>
//php on some.php page
echo $_POST['user'];
Also make sure you using the ssh github url and not the https
The problem is not with extract
, which can certainly handle 'military time'. It looks like you have a default timestamp format which has HH
instead of HH24
; or at least that's the only way I can see to recreate this:
SQL> select value from nls_session_parameters
2 where parameter = 'NLS_TIMESTAMP_FORMAT';
VALUE
--------------------------------------------------------------------------------
DD-MON-RR HH24.MI.SSXFF
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
15
alter session set nls_timestamp_format = 'DD-MON-YYYY HH:MI:SS';
Session altered.
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS') as timestamp)) from dual
*
ERROR at line 1:
ORA-01849: hour must be between 1 and 12
So the simple 'fix' is to set the format to something that does recognise 24-hours:
SQL> alter session set nls_timestamp_format = 'DD-MON-YYYY HH24:MI:SS';
Session altered.
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
15
Although you don't need the to_char
at all:
SQL> select extract(hour from cast(sysdate as timestamp)) from dual;
EXTRACT(HOURFROMCAST(SYSDATEASTIMESTAMP))
-----------------------------------------
15
First of all, you should never use the money datatype. If you do any calculations you will get truncated results. Run the following to see what I mean
DECLARE
@mon1 MONEY,
@mon2 MONEY,
@mon3 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)
SELECT
@mon1 = 100, @mon2 = 339, @mon3 = 10000,
@num1 = 100, @num2 = 339, @num3 = 10000
SET @mon4 = @mon1/@mon2*@mon3
SET @num4 = @num1/@num2*@num3
SELECT @mon4 AS moneyresult,
@num4 AS numericresult
Output: 2949.0000 2949.8525
Now to answer your question (it was a little vague), the money datatype always has two places after the decimal point. Use the integer datatype if you don't want the fractional part or convert to int.
Perhaps you want to use the decimal or numeric datatype?
Not pre-processor directive, but this was what I was looking for when i came to this question;
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:@"iPhone Simulator"]) {
//device is simulator
}
>>> x = 'Pear.good'
>>> y = x.replace('.good','')
>>> y
'Pear'
>>> x
'Pear.good'
.replace
doesn't change the string, it returns a copy of the string with the replacement. You can't change the string directly because strings are immutable.
You need to take the return values from x.replace
and put them in a new set.
You can also use ddms for logcat logs where just giving search of the app name you will all info but you have to select Info instead of verbose or other options. check this below image.
Yes. The entire text of an HTTPS session is secured by SSL. That includes the query and the headers. In that respect, a POST and a GET would be exactly the same.
As to the security of your method, there's no real way to say without proper inspection.
Though it's an old post, the question keep coming up and the answers don't always seem clear to me, so, here's my thoughts:
%w
and %W
are examples of General Delimited Input types, that relate to Arrays. There are other types that include %q
, %Q
, %r
, %x
and %i
.
The difference between the upper and lower case version is that it gives us access to the features of single and double quotes. With single quotes and (lowercase) %w
, we have no code interpolation (#{someCode}
) and a limited range of escape characters that work (\\
, \n
). With double quotes and (uppercase) %W
we do have access to these features.
The delimiter used can be any character, not just the open parenthesis. Play with the examples above to see that in effect.
For a full write up with examples of %w
and the full list, escape characters and delimiters, have a look at "Ruby - %w vs %W – secrets revealed!"
This is a mix of HTML and code but it's pretty basic, easy to understand and should be fairly simple to decouple to suit your needs I think.
try {
// Find out how many items are in the table
$total = $dbh->query('
SELECT
COUNT(*)
FROM
table
')->fetchColumn();
// How many items to list per page
$limit = 20;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '<a href="?page=1" title="First page">«</a> <a href="?page=' . ($page - 1) . '" title="Previous page">‹</a>' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">›</a> <a href="?page=' . $pages . '" title="Last page">»</a>' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Display the paging information
echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';
// Prepare the paged query
$stmt = $dbh->prepare('
SELECT
*
FROM
table
ORDER BY
name
LIMIT
:limit
OFFSET
:offset
');
// Bind the query params
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
// Do we have any results?
if ($stmt->rowCount() > 0) {
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);
// Display the results
foreach ($iterator as $row) {
echo '<p>', $row['name'], '</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
In Python
# O(n log n)
def count_inversion(lst):
return merge_count_inversion(lst)[1]
def merge_count_inversion(lst):
if len(lst) <= 1:
return lst, 0
middle = int( len(lst) / 2 )
left, a = merge_count_inversion(lst[:middle])
right, b = merge_count_inversion(lst[middle:])
result, c = merge_count_split_inversion(left, right)
return result, (a + b + c)
def merge_count_split_inversion(left, right):
result = []
count = 0
i, j = 0, 0
left_len = len(left)
while i < left_len and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
count += left_len - i
j += 1
result += left[i:]
result += right[j:]
return result, count
#test code
input_array_1 = [] #0
input_array_2 = [1] #0
input_array_3 = [1, 5] #0
input_array_4 = [4, 1] #1
input_array_5 = [4, 1, 2, 3, 9] #3
input_array_6 = [4, 1, 3, 2, 9, 5] #5
input_array_7 = [4, 1, 3, 2, 9, 1] #8
print count_inversion(input_array_1)
print count_inversion(input_array_2)
print count_inversion(input_array_3)
print count_inversion(input_array_4)
print count_inversion(input_array_5)
print count_inversion(input_array_6)
print count_inversion(input_array_7)
There is better way. I'm using it in pages where I'm using kendo angularJS directives and grids has'nt IDs...
change: function (e) {
var selectedDataItem = e != null ? e.sender.dataItem(e.sender.select()) : null;
}
If you're running your script in a virtual environment, say venv
, then executing which python
while working on venv
will display the path to the Python interpreter:
~/Envs/venv/bin/python
Note that the name of the virtual environment is embedded in the path to the Python interpreter. Therefore, hardcoding this path in your script will cause two problems:
Therefore, to add to Jonathan's answer, the ideal shebang is #!/usr/bin/env python
, not just for portability across OSes but for portability across virtual environments as well!
Above methods will remove your output file data whenever you run above nohup command.
To Append output in user defined file you can use >>
in nohup command.
nohup your_command >> filename.out &
This command will append all output in your file without removing old data.
UNICODE
definitionsA Windows UNICODE build is built with TCHAR
etc. being defined as wchar_t
etc. When not building with UNICODE
defined as build with TCHAR
defined as char
etc. These UNICODE
and _UNICODE
defines affect all the "T
" string types; LPTSTR
, LPCTSTR
and their elk.
Building one library with UNICODE
defined and attempting to link it in a project where UNICODE
is not defined will result in linker errors since there will be a mismatch in the definition of TCHAR
; char
vs. wchar_t
.
The error usually includes a function a value with a char
or wchar_t
derived type, these could include std::basic_string<>
etc. as well. When browsing through the affected function in the code, there will often be a reference to TCHAR
or std::basic_string<TCHAR>
etc. This is a tell-tale sign that the code was originally intended for both a UNICODE and a Multi-Byte Character (or "narrow") build.
To correct this, build all the required libraries and projects with a consistent definition of UNICODE
(and _UNICODE
).
This can be done with either;
#define UNICODE
#define _UNICODE
Or in the project settings;
Project Properties > General > Project Defaults > Character Set
Or on the command line;
/DUNICODE /D_UNICODE
The alternative is applicable as well, if UNICODE is not intended to be used, make sure the defines are not set, and/or the multi-character setting is used in the projects and consistently applied.
Do not forget to be consistent between the "Release" and "Debug" builds as well.
The former answer is now superseded by .iloc
:
>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
date
17 10
18 18
19 26
20 34
21 42
22 50
23 58
>>> df["date"].iloc[0]
10
>>> df["date"].iloc[-1]
58
The shortest way I can think of uses .iget()
:
>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
date
17 10
18 18
19 26
20 34
21 42
22 50
23 58
>>> df['date'].iget(0)
10
>>> df['date'].iget(-1)
58
Alternatively:
>>> df['date'][df.index[0]]
10
>>> df['date'][df.index[-1]]
58
There's also .first_valid_index()
and .last_valid_index()
, but depending on whether or not you want to rule out NaN
s they might not be what you want.
Remember that df.ix[0]
doesn't give you the first, but the one indexed by 0. For example, in the above case, df.ix[0]
would produce
>>> df.ix[0]
Traceback (most recent call last):
File "<ipython-input-489-494245247e87>", line 1, in <module>
df.ix[0]
[...]
KeyError: 0
Here are scikit-learn options. With both methods, StandardScaler was used because PCA is effected by scale
Method 1: Have scikit-learn choose the minimum number of principal components such that at least x% (90% in example below) of the variance is retained.
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
iris = load_iris()
# mean-centers and auto-scales the data
standardizedData = StandardScaler().fit_transform(iris.data)
pca = PCA(.90)
principalComponents = pca.fit_transform(X = standardizedData)
# To get how many principal components was chosen
print(pca.n_components_)
Method 2: Choose the number of principal components (in this case, 2 was chosen)
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
iris = load_iris()
standardizedData = StandardScaler().fit_transform(iris.data)
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(X = standardizedData)
# to get how much variance was retained
print(pca.explained_variance_ratio_.sum())
Source: https://towardsdatascience.com/pca-using-python-scikit-learn-e653f8989e60
in devices which has Android 4.3 and above you should follow these steps:
How to enable Developer Options:
Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.
In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.
My Method:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String path = request.getRealPath("/WEB-INF/conf.properties");
Properties p = new Properties();
p.load(new FileInputStream(path));
String StringConexion=p.getProperty("StringConexion");
String User=p.getProperty("User");
String Password=p.getProperty("Password");
}
catch(Exception e){
String msg = "Excepcion " + e;
}
}
I've used this successfully inside R script:
library("reshape2",lib.loc="/path/to/R-packages/")
useful if for whatever reason libraries are in more than one place.
Why don't you just save/serve the CSS file as UTF-8?
nav a:hover:after {
content: "?";
}
If that's not good enough, and you want to keep it all-ASCII:
nav a:hover:after {
content: "\2193";
}
The general format for a Unicode character inside a string is \000000
to \FFFFFF
– a backslash followed by six hexadecimal digits. You can leave out leading 0
digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.
Relevant part of the CSS2 spec:
Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:
- with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
- by providing exactly 6 hexadecimal digits: "\000026B" ("&B")
In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.
If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).
- Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
The identifier "te\st" is exactly the same identifier as "test".
Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).
You can use joblib
library to do parallel computation and multiprocessing.
from joblib import Parallel, delayed
You can simply create a function foo
which you want to be run in parallel and based on the following piece of code implement parallel processing:
output = Parallel(n_jobs=num_cores)(delayed(foo)(i) for i in input)
Where num_cores
can be obtained from multiprocessing
library as followed:
import multiprocessing
num_cores = multiprocessing.cpu_count()
If you have a function with more than one input argument, and you just want to iterate over one of the arguments by a list, you can use the the partial
function from functools
library as follow:
from joblib import Parallel, delayed
import multiprocessing
from functools import partial
def foo(arg1, arg2, arg3, arg4):
'''
body of the function
'''
return output
input = [11,32,44,55,23,0,100,...] # arbitrary list
num_cores = multiprocessing.cpu_count()
foo_ = partial(foo, arg2=arg2, arg3=arg3, arg4=arg4)
# arg1 is being fetched from input list
output = Parallel(n_jobs=num_cores)(delayed(foo_)(i) for i in input)
You can find a complete explanation of the python and R multiprocessing with couple of examples here.
You should look into normalizing your database to avoid creating columns at runtime.
Make 3 tables:
Put questions and assessments in their respective tables and link them together through assessment_question using foreign keys.
pandas.Series.astype
You can do something like this :
weather["Temp"] = weather.Temp.astype(float)
You can also use pd.to_numeric
that will convert the column from object to float
Example :
s = pd.Series(['apple', '1.0', '2', -3])
print(pd.to_numeric(s, errors='ignore'))
print("=========================")
print(pd.to_numeric(s, errors='coerce'))
Output:
0 apple
1 1.0
2 2
3 -3
=========================
dtype: object
0 NaN
1 1.0
2 2.0
3 -3.0
dtype: float64
In your case you can do something like this:
weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
convert_objects
Example is as follows
>> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
You can use this as follows:
weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
NaN
... so be careful while using it.Since Node v11.0.0 fs promises are available natively without promisify
:
const fs = require('fs').promises;
async function loadMonoCounter() {
const data = await fs.readFile("monolitic.txt", "binary");
return new Buffer(data);
}
A good explanation from http://www.sqlines.com/postgresql/datatypes/text:
The only difference between TEXT and VARCHAR(n) is that you can limit the maximum length of a VARCHAR column, for example, VARCHAR(255) does not allow inserting a string more than 255 characters long.
Both TEXT and VARCHAR have the upper limit at 1 Gb, and there is no performance difference among them (according to the PostgreSQL documentation).
Do you want the server name? Or the host name?
Request.Url.Host ala Stephen
Dns.GetHostName - Server name
Request.Url will have access to most everything you'll need to know about the page being requested.
You can embed case insensitity into the regular expression like so:
\.(?i:)(?:jpg|gif|doc|pdf)$
To me it happened in DogController
that autowired DogService
that autowired DogRepository
. Dog
class used to have field name
but I changed it to coolName
, but didn't change methods in DogRepository
: Dog findDogByName(String name)
. I change that method to Dog findDogByCoolName(String name)
and now it works.
If you're looking to use powerful, higher level tools rather than building everything yourself, going through the projects and readings for this course is a pretty good option. It's a languages course by the author of the Java parser engine ANTLR. You can get the book for the course as a PDF from the Pragmatic Programmers.
The course goes over the standard compiler compiler stuff that you'd see elsewhere: parsing, types and type checking, polymorphism, symbol tables, and code generation. Pretty much the only thing that isn't covered is optimizations. The final project is a program that compiles a subset of C. Because you use tools like ANTLR and LLVM, it's feasible to write the entire compiler in a single day (I have an existence proof of this, though I do mean ~24 hours). It's heavy on practical engineering using modern tools, a bit lighter on theory.
LLVM, by the way, is simply fantastic. Many situations where you might normally compile down to assembly, you'd be much better off compiling to LLVM's Intermediate Representation instead. It's higher level, cross platform, and LLVM is quite good at generating optimized assembly from it.
Pyparsing can be used to parse mathematical expressions. In particular, fourFn.py shows how to parse basic arithmetic expressions. Below, I've rewrapped fourFn into a numeric parser class for easier reuse.
from __future__ import division
from pyparsing import (Literal, CaselessLiteral, Word, Combine, Group, Optional,
ZeroOrMore, Forward, nums, alphas, oneOf)
import math
import operator
__author__ = 'Paul McGuire'
__version__ = '$Revision: 0.0 $'
__date__ = '$Date: 2009-03-20 $'
__source__ = '''http://pyparsing.wikispaces.com/file/view/fourFn.py
http://pyparsing.wikispaces.com/message/view/home/15549426
'''
__note__ = '''
All I've done is rewrap Paul McGuire's fourFn.py as a class, so I can use it
more easily in other places.
'''
class NumericStringParser(object):
'''
Most of this code comes from the fourFn.py pyparsing example
'''
def pushFirst(self, strg, loc, toks):
self.exprStack.append(toks[0])
def pushUMinus(self, strg, loc, toks):
if toks and toks[0] == '-':
self.exprStack.append('unary -')
def __init__(self):
"""
expop :: '^'
multop :: '*' | '/'
addop :: '+' | '-'
integer :: ['+' | '-'] '0'..'9'+
atom :: PI | E | real | fn '(' expr ')' | '(' expr ')'
factor :: atom [ expop factor ]*
term :: factor [ multop factor ]*
expr :: term [ addop term ]*
"""
point = Literal(".")
e = CaselessLiteral("E")
fnumber = Combine(Word("+-" + nums, nums) +
Optional(point + Optional(Word(nums))) +
Optional(e + Word("+-" + nums, nums)))
ident = Word(alphas, alphas + nums + "_$")
plus = Literal("+")
minus = Literal("-")
mult = Literal("*")
div = Literal("/")
lpar = Literal("(").suppress()
rpar = Literal(")").suppress()
addop = plus | minus
multop = mult | div
expop = Literal("^")
pi = CaselessLiteral("PI")
expr = Forward()
atom = ((Optional(oneOf("- +")) +
(ident + lpar + expr + rpar | pi | e | fnumber).setParseAction(self.pushFirst))
| Optional(oneOf("- +")) + Group(lpar + expr + rpar)
).setParseAction(self.pushUMinus)
# by defining exponentiation as "atom [ ^ factor ]..." instead of
# "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-right
# that is, 2^3^2 = 2^(3^2), not (2^3)^2.
factor = Forward()
factor << atom + \
ZeroOrMore((expop + factor).setParseAction(self.pushFirst))
term = factor + \
ZeroOrMore((multop + factor).setParseAction(self.pushFirst))
expr << term + \
ZeroOrMore((addop + term).setParseAction(self.pushFirst))
# addop_term = ( addop + term ).setParseAction( self.pushFirst )
# general_term = term + ZeroOrMore( addop_term ) | OneOrMore( addop_term)
# expr << general_term
self.bnf = expr
# map operator symbols to corresponding arithmetic operations
epsilon = 1e-12
self.opn = {"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
"^": operator.pow}
self.fn = {"sin": math.sin,
"cos": math.cos,
"tan": math.tan,
"exp": math.exp,
"abs": abs,
"trunc": lambda a: int(a),
"round": round,
"sgn": lambda a: abs(a) > epsilon and cmp(a, 0) or 0}
def evaluateStack(self, s):
op = s.pop()
if op == 'unary -':
return -self.evaluateStack(s)
if op in "+-*/^":
op2 = self.evaluateStack(s)
op1 = self.evaluateStack(s)
return self.opn[op](op1, op2)
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in self.fn:
return self.fn[op](self.evaluateStack(s))
elif op[0].isalpha():
return 0
else:
return float(op)
def eval(self, num_string, parseAll=True):
self.exprStack = []
results = self.bnf.parseString(num_string, parseAll)
val = self.evaluateStack(self.exprStack[:])
return val
You can use it like this
nsp = NumericStringParser()
result = nsp.eval('2^4')
print(result)
# 16.0
result = nsp.eval('exp(2^4)')
print(result)
# 8886110.520507872
I almost always use the standard formating ShortDateString, because I want the user to be in control of the actual output of the date.
Dim d As DateTime = Now
Debug.WriteLine(d.ToLongDateString)
Debug.WriteLine(d.ToShortDateString)
Debug.WriteLine(d.ToString("d"))
Debug.WriteLine(d.ToString("yyyy-MM-dd"))
Wednesday, December 10, 2008
12/10/2008
12/10/2008
2008-12-10
Note that these results will vary depending on the culture settings on your computer.
We can define maximum pool size in following way:
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>200</max-pool-size>
<prefill>true</prefill>
<use-strict-min>true</use-strict-min>
<flush-strategy>IdleConnections</flush-strategy>
</pool>
I was facing this issue in Grafana and all I had to do was go to the config file and change allow_embedding to true and restart the server :)
With zsh you can do this:
% cat infile
tar
more than one word
gz
java
gz
java
tar
class
class
zsh-5.0.0[t]% print -l "${(fu)$(<infile)}"
tar
more than one word
gz
java
class
Or you can use AWK:
% awk '!_[$0]++' infile
tar
more than one word
gz
java
class
I have deal with this problem, I have been solved it by MVC design pattern, I created Card class:
@interface Card : NSObject
@property (strong,nonatomic) UIImage* img;
@property (strong,nonatomic) NSString* url;
@end
//then in the UIViewController
in the DidLoad
Method to Do :
// init Cards
Card* card10= [[Card alloc]init];
card10.url=@"image.jpg";
card10.img = [UIImage imageNamed:[card10 url]];
// for Example
UIImageView * myImageView = [[UIImageView alloc]initWithImage:card10.img];
[self.view addSubview:myImageView];
//may you want to check the image name , so you can do this:
//for example
NSString * str = @"image.jpg";
if([str isEqualToString: [card10 url]]){
// your code here
}
I developed a library for knowing the real viewport size for desktops and mobiles browsers, because viewport sizes are inconsistents across devices and cannot rely on all the answers of that post (according to all the research I made about this) : https://github.com/pyrsmk/W
Short answer:
int
uses up 4 bytes of memory (and it CANNOT contain a decimal), double
uses 8 bytes of memory. Just different tools for different purposes.
I have used this one on MySQL, MS Access and SQL Server. The id fields are the fields on wich the tables coincide, not necesarily the primary index.
UPDATE DestTable INNER JOIN SourceTable ON DestTable.idField = SourceTable.idField SET DestTable.Field1 = SourceTable.Field1, DestTable.Field2 = SourceTable.Field2...
Your __init__.py
should have a docstring.
Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email
package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.
For any other content, see the excellent answers by firecrow and Alex Martelli.
After use codevar json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));
You need use JSON.parse(JSON.stringify(json))
;
os.path.getsize(path)
Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.
% start=$(date +%s)
% echo "Diff: $(date -d @$(($(date +%s)-$start)) +"%M minutes %S seconds")"
Diff: 00 minutes 11 seconds
Per pierce.jason's answer above, I had luck with:
Just create a new DWORD(32) under the Fusion key. Name the DWORD to LogFailures, and set it to value 1. Then restart IIS, refresh the page giving errors, and the assembly bind logs will show in the error message.
CSS properties should be set by cssText
property or setAttribute
method.
// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black";
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");
Styles should not be set by assigning a string directly to the style
property (as in elt.style = "color: blue;"
), since it is considered read-only, as the style
attribute returns a CSSStyleDeclaration
object which is also read-only.
Since 5.0, you can now find those values in a dedicated Enum
: org.hibernate.boot.SchemaAutoTooling
(enhanced with value NONE
since 5.2).
Or even better, since 5.1, you can also use the org.hibernate.tool.schema.Action
Enum
which combines JPA 2 and "legacy" Hibernate DDL actions.
But, you cannot yet configure a DataSource
programmatically with this. It would be nicer to use this combined with org.hibernate.cfg.AvailableSettings#HBM2DDL_AUTO
but the current code expect a String
value (excerpt taken from SessionFactoryBuilderImpl
):
this.schemaAutoTooling = SchemaAutoTooling.interpret( (String) configurationSettings.get( AvailableSettings.HBM2DDL_AUTO ) );
… and internal enum
values of both org.hibernate.boot.SchemaAutoTooling
and org.hibernate.tool.schema.Action
aren't exposed publicly.
Hereunder, a sample programmatic DataSource
configuration (used in ones of my Spring Boot applications) which use a gambit thanks to .name().toLowerCase()
but it only works with values without dash (not create-drop
for instance):
@Bean(name = ENTITY_MANAGER_NAME)
public LocalContainerEntityManagerFactoryBean internalEntityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier(DATA_SOURCE_NAME) DataSource internalDataSource) {
Map<String, Object> properties = new HashMap<>();
properties.put(AvailableSettings.HBM2DDL_AUTO, SchemaAutoTooling.CREATE.name().toLowerCase());
properties.put(AvailableSettings.DIALECT, H2Dialect.class.getName());
return builder
.dataSource(internalDataSource)
.packages(JpaModelsScanEntry.class, Jsr310JpaConverters.class)
.persistenceUnit(PERSISTENCE_UNIT_NAME)
.properties(properties)
.build();
}
This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
Might be worth checking online for the errata section for your book.
There's an example of handling this exception here http://www.dba-oracle.com/sf_ora_01403_no_data_found.htm
I saw this question while I was looking for a way to count multiple files lines, so if you want to count multiple file lines of a .txt file you can do this,
cat *.txt | wc -l
it will also run on one .txt file ;)
After own diligent searches I found several solutions, where each has advantages and disadvantages. Use the most suitable for your task.
All examples tested with the CPython 3.5 on the operation system GNU/Linux Debian 8.
Using a recursion
Code
def get_digits_from_left_to_right(number, lst=None):
"""Return digits of an integer excluding the sign."""
if lst is None:
lst = list()
number = abs(number)
if number < 10:
lst.append(number)
return tuple(lst)
get_digits_from_left_to_right(number // 10, lst)
lst.append(number % 10)
return tuple(lst)
Demo
In [121]: get_digits_from_left_to_right(-64517643246567536423)
Out[121]: (6, 4, 5, 1, 7, 6, 4, 3, 2, 4, 6, 5, 6, 7, 5, 3, 6, 4, 2, 3)
In [122]: get_digits_from_left_to_right(0)
Out[122]: (0,)
In [123]: get_digits_from_left_to_right(123012312312321312312312)
Out[123]: (1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 1, 3, 1, 2, 3, 1, 2, 3, 1, 2)
Using the function divmod
Code
def get_digits_from_right_to_left(number):
"""Return digits of an integer excluding the sign."""
number = abs(number)
if number < 10:
return (number, )
lst = list()
while number:
number, digit = divmod(number, 10)
lst.insert(0, digit)
return tuple(lst)
Demo
In [125]: get_digits_from_right_to_left(-3245214012321021213)
Out[125]: (3, 2, 4, 5, 2, 1, 4, 0, 1, 2, 3, 2, 1, 0, 2, 1, 2, 1, 3)
In [126]: get_digits_from_right_to_left(0)
Out[126]: (0,)
In [127]: get_digits_from_right_to_left(9999999999999999)
Out[127]: (9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)
Using a construction tuple(map(int, str(abs(number)))
In [109]: tuple(map(int, str(abs(-123123123))))
Out[109]: (1, 2, 3, 1, 2, 3, 1, 2, 3)
In [110]: tuple(map(int, str(abs(1412421321312))))
Out[110]: (1, 4, 1, 2, 4, 2, 1, 3, 2, 1, 3, 1, 2)
In [111]: tuple(map(int, str(abs(0))))
Out[111]: (0,)
Using the function re.findall
In [112]: tuple(map(int, re.findall(r'\d', str(1321321312))))
Out[112]: (1, 3, 2, 1, 3, 2, 1, 3, 1, 2)
In [113]: tuple(map(int, re.findall(r'\d', str(-1321321312))))
Out[113]: (1, 3, 2, 1, 3, 2, 1, 3, 1, 2)
In [114]: tuple(map(int, re.findall(r'\d', str(0))))
Out[114]: (0,)
Using the module decimal
In [117]: decimal.Decimal(0).as_tuple().digits
Out[117]: (0,)
In [118]: decimal.Decimal(3441120391321).as_tuple().digits
Out[118]: (3, 4, 4, 1, 1, 2, 0, 3, 9, 1, 3, 2, 1)
In [119]: decimal.Decimal(-3441120391321).as_tuple().digits
Out[119]: (3, 4, 4, 1, 1, 2, 0, 3, 9, 1, 3, 2, 1)
Loop through the file.
f = open("masters.txt")
lines = f.readlines()
for line in lines:
print line
Ems is a typography term, it controls text size, etc. Check here
You can bind with a variable in the controller:
<input type="text" ng-model="inputText" placeholder="{{somePlaceholder}}" />
In the controller:
$scope.somePlaceholder = 'abc';
Give your img tag an id, then you can
document.getElementById("imageid").src="../template/save.png";
Changing only what's after hash - old browsers
document.location.hash = 'lookAtMeNow';
Changing full URL. Chrome, Firefox, IE10+
history.pushState('data to be passed', 'Title of the page', '/test');
The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use
history.replaceState('data to be passed', 'Title of the page', '/test');
Try running these in the console now!
As I know, there is no direct support, but you can use plain-ol' javascript for that:
// Cookies
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
There are several causes for this error.
wait_timeout
- Time in seconds that the server waits for a connection to become active before closing it.interactive_timeout
- Time in seconds that the server waits for an interactive connection.max_allowed_packet
- Maximum size in bytes of a packet or a generated/intermediate string. Set as large as the largest BLOB, in multiples of 1024.Example of my.cnf:
[mysqld]
# 8 hours
wait_timeout = 28800
# 8 hours
interactive_timeout = 28800
max_allowed_packet = 256M
free -h
CONN_MAX_AGE
(see docs)SHOW VARIABLES LIKE '%time%';
mysqladmin variables
log_warnings = 4
log_error_verbosity = 3
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
You can try adding a question mark as below. This worked for me.
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps?.blog?.title,
body: nextProps?.blog?.content
})
}
A full instruction relating to James Fletcher's answer can be found here
Particularly for Anaconda distribution I had to modify it this way:
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D PYTHON3_PACKAGES_PATH=/anaconda/lib/python3.4/site-packages/ \
-D PYTHON3_LIBRARY=/anaconda/lib/libpython3.4m.dylib \
-D PYTHON3_INCLUDE_DIR=/anaconda/include/python3.4m \
-D INSTALL_C_EXAMPLES=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D BUILD_EXAMPLES=ON \
-D BUILD_opencv_python3=ON \
-D OPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules ..
Last line can be ommited (see link above)
If no file available for download, I needed to disable the asp:linkButton, change it to grey and eliminate the underline on the hover. This worked:
.disabled {
color: grey;
text-decoration: none !important;
}
LinkButton button = item.FindControl("lnkFileDownload") as LinkButton;
button.Enabled = false;
button.CssClass = "disabled";
We can take a look at three different ways you can identify the port used by an instance of SQL Server.
Using Windows Application Event Viewer
USE master
GO
xp_readerrorlog 0, 1, N'Server is listening on', 'any', NULL, NULL, N'asc'
GO
Identify Port used by SQL Server Database Engine Using SQL Server Configuration Manager
Click Start -> Programs -> Microsoft SQL Server 2008 -> Configuration Tools -> SQL Server Configuration Manager
In SQL Server Configuration Manager, expand SQL Server Network Configuration and then select Protocols for on the left panel. To identify the TCP/IP Port used by the SQL Server Instance, right click onTCP/IP and select Properties from the drop down as shown below.
For More Help
http://sqlnetcode.blogspot.com/2011/11/sql-server-identify-tcp-ip-port-being.html
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
Just simply use this Style
of DataGridRow
:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
</Style>
</DataGrid.RowStyle>
I generally try to avoid the Convert
class (meaning: I don't use it) because I find it very confusing: the code gives too few hints on what exactly happens here since Convert
allows a lot of semantically very different conversions to occur with the same code. This makes it hard to control for the programmer what exactly is happening.
My advice, therefore, is never to use this class. It's not really necessary either (except for binary formatting of a number, because the normal ToString
method of number classes doesn't offer an appropriate method to do this).
I suggest you step through the code in your debugger as debugging programs is what it is for.
What I would expect you would see is that every time the code loops int x = 0;
is set.
The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.
Like this:
ggplot() +
geom_line(data=Data1, aes(x=A, y=B), color='green') +
geom_line(data=Data2, aes(x=C, y=D), color='red')
instead of
ggplot(data=Data1, aes(x=A, y=B), color='green') +
geom_line() +
geom_line(data=Data2, aes(x=C, y=D), color='red')
I used the answer given by Carcione and modified it to use JSON.
function getUrlJsonSync(url){
var jqxhr = $.ajax({
type: "GET",
url: url,
dataType: 'json',
cache: false,
async: false
});
// 'async' has to be 'false' for this to work
var response = {valid: jqxhr.statusText, data: jqxhr.responseJSON};
return response;
}
function testGetUrlJsonSync()
{
var reply = getUrlJsonSync("myurl");
if (reply.valid == 'OK')
{
console.dir(reply.data);
}
else
{
alert('not valid');
}
}
I added the dataType of 'JSON' and changed the .responseText to responseJSON.
I also retrieved the status using the statusText property of the returned object. Note, that this is the status of the Ajax response, not whether the JSON is valid.
The back-end has to return the response in correct (well-formed) JSON, otherwise the returned object will be undefined.
There are two aspects to consider when answering the original question. One is telling Ajax to perform synchronously (by setting async: false) and the other is returning the response via the calling function's return statement, rather than into a callback function.
I also tried it with POST and it worked.
I changed the GET to POST and added data: postdata
function postUrlJsonSync(url, postdata){
var jqxhr = $.ajax({
type: "POST",
url: url,
data: postdata,
dataType: 'json',
cache: false,
async: false
});
// 'async' has to be 'false' for this to work
var response = {valid: jqxhr.statusText, data: jqxhr.responseJSON};
return response;
}
Note that the above code only works in the case where async is false. If you were to set async: true the returned object jqxhr would not be valid at the time the AJAX call returns, only later when the asynchronous call has finished, but that is much too late to set the response variable.
We can change the default parallelism using the following property:
-Djava.util.concurrent.ForkJoinPool.common.parallelism=16
which can set up to use more parallelism.
could it be that you forgot to load it in the document ready function?
$(document).ready(function () {
//your jQuery function
});
Convert from String to byte[]:
String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);
Convert from byte[] to String:
byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, StandardCharsets.US_ASCII);
You should, of course, use the correct encoding name. My examples used US-ASCII and UTF-8, the two most common encodings.
All values are permitted (unrecognized ones are ignored). The list of recognized ones is compiler specific.
In The Java Tutorials unchecked
and deprecation
are listed as the two warnings required by The Java Language Specification, therefore, they should be valid with all compilers:
Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked.
The specific sections inside The Java Language Specification where they are defined is not consistent across versions. In the Java SE 8 Specification unchecked
and deprecation
are listed as compiler warnings in sections 9.6.4.5. @SuppressWarnings and 9.6.4.6 @Deprecated, respectively.
For Sun's compiler, running javac -X
gives a list of all values recognized by that version. For 1.5.0_17, the list appears to be:
Just a side note if you have the same issue and is with Windows:
In my case the process in my way is just grafana-server.exe
. Because I first downloaded the binary version and double click the executable, and it now starts as a service by user SYSTEM
which I cannot taskkill
(no permission)
I have to go to "Service manager" of Windows and search for service "Grafana", and stop it. After that port 3000 is no longer occupied.
Hope that helps.
ASP .NET 2.0:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ir
ASP .NET 4.0:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
Run Command Prompt as Administrator to avoid the ...requested operation requires elevation
error
aspnet_regiis.exe
should no longer be used with IIS7 to install ASP.NET
Because break cannot be used to break out of an if - it can only break out of loops. That's the way Python (and most other languages) are specified to behave.
What are you trying to do? Perhaps you should use sys.exit()
or return
instead?
From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.
No need to define a new interface when you can use an existing one: android.os.Handler.Callback
. Pass an object of type Callback, and invoke callback's handleMessage(Message msg)
.
User can use this
Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)
this will format the date as required whereas user can change the string type dd/MM/yyyy or MM/dd/yyyy or yyyy/MM/dd or even can have this format to get the time from date
yyyy/MM/dd HH:mm:ss
import platform
platform.architecture()
From the Python docs:
Queries the given executable (defaults to the Python interpreter binary) for various architecture information.
Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.
Use:
android:screenOrientation="portrait"
Just write this line in your application's manifest file in each activity which you want to show in portrait mode only.
The Simplest approach:
String[] stringArray = {"Hey", "Hi", "Hello"};
List<String> list = Arrays.asList(stringArray);
Use below command:
$ git reset HEAD~1
After this you also able to view files what revert back like below response.
Unstaged changes after reset:
M application/config/config.php
M application/config/database.php
You could put a crontab file in /etc/cron.d
which would run a script that would run your command and then delete the crontab file in /etc/cron.d
. Of course, that means your script would need to run as root.
I run my MySQL on a virtual machine in Ubuntu, So what had happened was when I restarted my host and the VM, The IP had changed. I had configured mysql to run on IP 192.168.0.5 and now due to dynamic allocation of IP, my new IP was 192.168.0.8
If you have the same problem just check your ip with the command ifconfig
.
Check your MySQL binding with the command cat /etc/mysql/my.cnf | grep bind-address
If both IP are the Same, then reinstall your mysql server
If not, then change your IP in /etc/network/interfaces
using nano, vi, vim or anything of your preference.
I prefer sudo nano /etc/network/interfaces
and enter the following
auto eth0
iface eth0 inet static
address 192.168.0.5
netmask 255.255.255.0
Save the interfaces file, restart your interface sudo ifdown eth0
&& sudo ifup eth0
replace "eth0" with your network interface
Restart MySQL sudo service mysql stop
followed by sudo service mysql start
If you have the same issue as mine, You are good to go!
Similar to Java in PHP only set Select PARAMETER with value 'COUNT'
$result = $aws->query(array(
'TableName' => 'game_table',
'IndexName' => 'week-point-index',
'KeyConditions' => array(
'week' => array(
'ComparisonOperator' => 'EQ',
'AttributeValueList' => array(
array(Type::STRING => $week)
)
),
'point' => array(
'ComparisonOperator' => 'GE',
'AttributeValueList' => array(
array(Type::NUMBER => $my_point)
)
)
),
'Select' => 'COUNT'
));
and acces it just like this :
echo $result['Count'];
but as Saumitra mentioned above be careful with resultsets largers than 1 MB, in that case use LastEvaluatedKey til it returns null to get the last updated count value.
@echo off
echo.
set /p num1=Enter Prelim:
echo.
set /p num2=Enter Midterm:
echo.
set /p num3=Enter Semi:
echo.
set /p num4=Enter Finals:
echo.
set /a ans=%num1%+%num2%+%num3%+%num4%
set /a avg=%ans%/4
ECHO %avg%
if %avg%>=`95` goto true
:true
echo The two numbers you entered were the same.
echo.
pause
exit
As Johnathan Suggested, you would either want to save it in a cookie or a session.
The easier way would be to use a Session variable.
session_start();
if(!isset($_SESSION['org_referer']))
{
$_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}
Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.
You could use prop
as well. Check the following code below.
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").prop("readonly", false);
}
else{
$("#no_of_staff").prop("readonly", true);
}
});
});
The first option is simply to hide an error with disabling it by configuring errorOnUnhandledRejections
in $qProvider configuration as suggested Cengkuru Michael
BUT this will only switch off logging. The error itself will remain
The better solution in this case will be - handling a rejection with .catch(fn)
method:
resource.get().$promise
.then(function (response) {})
.catch(function (err) {});
LINKS:
As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.
However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.
In MySQL integer int(11)
has size is 4 bytes which equals 32 bit.
Signed value is : -2^(32-1) to 0 to 2^(32-1)-1
= -2147483648 to 0 to 2147483647
Unsigned values is : 0 to 2^32-1
= 0 to 4294967295
If you happen to use glibmm you can try Glib::file_get_contents.
#include <iostream>
#include <glibmm.h>
int main() {
auto filename = "my-file.txt";
try {
std::string contents = Glib::file_get_contents(filename);
std::cout << "File data:\n" << contents << std::endl;
catch (const Glib::FileError& e) {
std::cout << "Oops, an error occurred:\n" << e.what() << std::endl;
}
return 0;
}
Use backslash-escaped sed
.
On linux:
Replace all tabs with 1 hyphen inplace, in all *.txt files:
sed -i $'s/\t/-/g' *.txt
Replace all tabs with 1 space inplace, in all *.txt files:
sed -i $'s/\t/ /g' *.txt
Replace all tabs with 4 spaces inplace, in all *.txt files:
sed -i $'s/\t/ /g' *.txt
On a mac:
Replace all tabs with 4 spaces inplace, in all *.txt files:
sed -i '' $'s/\t/ /g' *.txt
I found this article at digital bazaar really interesting. Quoting their quotations from Norm:
About JSON pros:
If all you want to pass around are atomic values or lists or hashes of atomic values, JSON has many of the advantages of XML: it’s straightforwardly usable over the Internet, supports a wide variety of applications, it’s easy to write programs to process JSON, it has few optional features, it’s human-legible and reasonably clear, its design is formal and concise, JSON documents are easy to create, and it uses Unicode. ...
About XML pros:
XML deals remarkably well with the full richness of unstructured data. I’m not worried about the future of XML at all even if its death is gleefully celebrated by a cadre of web API designers.
And I can’t resist tucking an "I told you so!" token away in my desk. I look forward to seeing what the JSON folks do when they are asked to develop richer APIs. When they want to exchange less well strucured data, will they shoehorn it into JSON? I see occasional mentions of a schema language for JSON, will other languages follow? ...
I personally agree with Norm. I think that most attacks to XML come from Web Developers for typical applications, and not really from integration developers. But that's my opinion! ;)
There isn't a single answer for this.
Encryption will always consume more CPU. This can be offloaded to dedicated hardware in many cases, and the cost will vary by algorithm selected. 3des is more expensive than AES, for example. Some algorithms are more expensive for the encrypter than the decryptor. Some have the opposite cost.
More expensive than the bulk crypto is handshake cost. New connections will consume much more CPU. This can be reduced with session resumption, at the cost of keeping old session secrets around until they expire. This means that small requests from a client that doesn't come back for more are the most expensive.
For cross internet traffic you may not notice this cost in your data rate, because the bandwidth available is too low. But you will certainly notice it in CPU usage on a busy server.
I think this works:
int roundUp(int numToRound, int multiple) {
return multiple? !(numToRound%multiple)? numToRound : ((numToRound/multiple)+1)*multiple: numToRound;
}
There's a simply way of doing it. You define for all the rows, except the first one, the following class with properties:
.not-first-row
{
position: relative;
top: -20px;
}
Then you apply the class to all non-first rows and adjust the negative top value to fit your desired row space. It's easy and works way better. :) Hope it helped.
Here in your code demo
is id where you want to display your result after click event has occur and just nothing.
You can take anything
<p id="demo">
or
<div id="demo">
It is just node in a document where you just want to display your result.
SARose's answer worked for me until I updated from Ubuntu 20.04 LTS. The slight change I made to his code makes it work on the latest Ubuntu release.
import subprocess
def find_files(file_name):
command = ['locate'+ ' ' + file_name]
output = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
output = output.decode()
search_results = output.split('\n')
return search_results
I had the same problem.
Solution:
You can't modify strings; they're immutable. You can do this instead:
txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);
Some databases are designed to communicate over the web using ports assigned by the Internet Assigned Number Authority (IANA) and when run on individual PC use the ports with localhost. Some common databases with their default ports (the defualts can usually be overridden):
Port Database
1433 Microsoft SQL Server https://support.microsoft.com/en-us/kb/287932
3306 MySQL https://dev.mysql.com/doc/refman/4.1/en/connecting.html
5432 PostgreSQL
1527 Apache Derby (database)
Some web servers and databases are paired together such as Apache/MySQL (as in LAMP or XXAMP) or MS Internet Information Server (IIS)/MS SQL Server (IIS/SQL Server) in which case you have to be concerned with both the port of the database and the web server -- a common example of this is WordPress which uses Apache/MySQL.
You can use peseudo elements like this:
input[type=checkbox] {_x000D_
width: 30px;_x000D_
height: 30px;_x000D_
margin-right: 8px;_x000D_
cursor: pointer;_x000D_
font-size: 27px;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:after {_x000D_
content: " ";_x000D_
background-color: #9FFF9D;_x000D_
display: inline-block;_x000D_
visibility: visible;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked:after {_x000D_
content: "\2714";_x000D_
}
_x000D_
<label>Checkbox label_x000D_
<input type="checkbox">_x000D_
</label>
_x000D_
I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:
Hope that helps!
It is the severity level of the error
. The levels are from 11 - 20 which throw an error in SQL
. The higher the level, the more severe the level and the transaction
should be aborted.
You will get the syntax error when you do:
RAISERROR('Cannot Insert where salary > 1000').
Because you have not specified the correct parameters
(severity level
or state
).
If you wish to issue a warning and not an exception
, use levels 0 - 10.
From MSDN:
severity
Is the user-defined severity level associated with this message. When using msg_id to raise a user-defined message created using sp_addmessage, the severity specified on RAISERROR overrides the severity specified in sp_addmessage. Severity levels from 0 through 18 can be specified by any user. Severity levels from 19 through 25 can only be specified by members of the sysadmin fixed server role or users with ALTER TRACE permissions. For severity levels from 19 through 25, the WITH LOG option is required.
state
Is an integer from 0 through 255. Negative values or values larger than 255 generate an error. If the same user-defined error is raised at multiple locations, using a unique state number for each location can help find which section of code is raising the errors. For detailed description here
If you don't want to make it final, you can always just make it a global variable.
Typing in $(this)
will return the jQuery element instead of the HTML Element. Then it just depends on what you want to do in the click event.
alert($(this));
You have to disable or enable the individual elements. This is how I did it:
$(':input').keydown(function(e){
var allowTab = true;
var id = $(this).attr('name');
// insert your form fields here -- (:'') is required after
var inputArr = {username:'', email:'', password:'', address:''}
// allow or disable the fields in inputArr by changing true / false
if(id in inputArr) allowTab = false;
if(e.keyCode==9 && allowTab==false) e.preventDefault();
});
This worked for me:
-> uninstalled Jupyter
-> install jupyter in Python36 folder
-> open Jupyter from command prompt instead of git bash.
The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!
<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />
Change the window width and the image scales obligingly.
Try using the d as pointer y.append(*d)
I tried findAndModify()
to update a particular field in a pre-existing object.
https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/
The plain and simple answer is yes, VanillaJS === JavaScript, as prescribed by Dr B. Eich.
The following code works more or less as one would expect a type-switch that only looks at the actual type (e.g. what is returned by GetType()
).
public static void TestTypeSwitch()
{
var ts = new TypeSwitch()
.Case((int x) => Console.WriteLine("int"))
.Case((bool x) => Console.WriteLine("bool"))
.Case((string x) => Console.WriteLine("string"));
ts.Switch(42);
ts.Switch(false);
ts.Switch("hello");
}
Here is the machinery required to make it work.
public class TypeSwitch
{
Dictionary<Type, Action<object>> matches = new Dictionary<Type, Action<object>>();
public TypeSwitch Case<T>(Action<T> action) { matches.Add(typeof(T), (x) => action((T)x)); return this; }
public void Switch(object x) { matches[x.GetType()](x); }
}
Try this
Console.WriteLine("{0,10}{1,10}{2,10}{3,10}{4,10}",
customer[DisplayPos],
sales_figures[DisplayPos],
fee_payable[DisplayPos],
seventy_percent_value,
thirty_percent_value);
where the first number inside the curly brackets is the index and the second is the alignment. The sign of the second number indicates if the string should be left or right aligned. Use negative numbers for left alignment.
Or look at http://msdn.microsoft.com/en-us/library/aa331875(v=vs.71).aspx
According to http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/
[DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);
public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
{
IntPtr ip = source.GetHbitmap();
BitmapSource bs = null;
try
{
bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(ip);
}
return bs;
}
It gets System.Drawing.Bitmap (from WindowsBased) and converts it into BitmapSource, which can be actually used as image source for your Image control in WPF.
image1.Source = YourUtilClass.loadBitmap(SomeBitmap);
This worked for me (using WSL)
sudo /etc/init.d/redis start
(for any other service, check the init.d folder for filenames)
For compatibility with Tensorflow 2.0, you can use tf.get_logger
import logging
tf.get_logger().setLevel(logging.ERROR)
Let's explorer how the go get repository_remote_url
command manages the project structure under $GOPATH
. If we do a go get github.com/gohugoio/hugo
It will clone the repository under
$GOPATH/src/repository_remote/user_name/project_name
$GOPATH/src/github.com/gohugoio/hugo
This is a nice way to create your initial project path. Now let's explorer what are the project types out there and how their inner structures are organized. All golang projects in the community can be categorized under
Libraries
(no executable binaries)Single Project
(contains only 1 executable binary)Tooling Projects
(contains multiple executable binaries)Generally golang project files can be packaged under any design principles such as DDD, POD
Most of the available go projects follows this Package Oriented Design
Package Oriented Design encourage the developer to keeps the implementation only inside it's own packages, other than the /internal
package those packages can't can communicate with each other
/internal
package is mainly used to hide the implementation from other projects. ~/$GOPATH/
bin/
pkg/
src/
repository_remote/
user_name/
project_name/
internal/
other_pkg/
cmd/
package manages the number of binaries (tools) that we want to build ~/$GOPATH/
bin/
pkg/
src/
repository_remote/
user_name/
project_name/
cmd/
binary_one/
main.go
binary_two/
main.go
binary_three/
main.go
other_pkg/
One can use PrintWriter
to wrap the FileWriter
, as it has many additional useful methods.
try(PrintWriter pw = new PrintWriter(new FileWriter(new File("file.txt"), false))){
pw.println();//new line
pw.print("text");//print without new line
pw.println(10);//print with new line
pw.printf("%2.f", 0.567);//print double to 2 decimal places (without new line)
}
When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.
For example:
inputChangeHandler(event) {_x000D_
this.setState({ [event.target.name]: event.target.value });_x000D_
}
_x000D_
Maybe you want to try this: https://bootstrap-datepicker.readthedocs.org/en/latest/index.html
It's a flexible datepicker widget in the Bootstrap style.
select distinct * into newtablename from oldtablename
Now, the newtablename
will have no duplicate records.
Simply change the table name(newtablename
) by pressing F2 in object explorer in sql server.
Before you enter a command, hit the Esc key. After you enter it, hit the Return to confirm.
Esc finishes the current command and switches Vim to normal mode. Now if you press :, the :
will appear at the bottom of the screen. This confirms that you're actually typing a command and not editing the file.
Most commands have abbreviations, with optional part enclosed in brackets: c[ommand]
.
Commands marked with '*' are Vim-only (not implemented in Vi).
Safe-quit (fails if there are unsaved changes):
:q[uit]
Quit the current window. Quit Vim if this is the last window. This fails when changes have been made in current buffer.:qa[ll]
* Quit all windows and Vim, unless there are some buffers which have been changed.Prompt-quit (prompts if there are unsaved changes)
:conf[irm] q[uit]
* Quit, but give prompt when there are some buffers which have been changed.:conf[irm] xa[ll]
* Write all changed buffers and exit Vim. Bring up a prompt when some buffers cannot be written.Write (save) changes and quit:
:wq
Write the current file (even if it was not changed) and quit. Writing fails when the file is read-only or the buffer does not have a name. :wqa[ll]
* for all windows.:wq!
The same, but writes even read-only files. :wqa[ll]!
* for all windows.:x[it]
, ZZ
(with details). Write the file only if it was changed and quit, :xa[ll]
* for all windows.Discard changes and quit:
:q[uit]!
ZQ
* Quit without writing, also when visible buffers have changes. Does not exit when there are changed hidden buffers. :qa[ll]!
*, :quita[ll][!]
* Quit Vim, all changes to the buffers (including hidden) are lost.Press Return to confirm the command.
This answer doesn't reference all Vim write and quit commands and arguments. Indeed, they are referenced in the Vim documentation.
Vim has extensive built-in help, type Esc:help
Return to open it.
This answer was inspired by the other one, originally authored by @dirvine and edited by other SO users. I've included more information from Vim reference, SO comments and some other sources. Differences for Vi and Vim are reflected too.
Just Change the property based on your machine and all have done :-)
Project---> Properties--->Build--->Target Framework---> X64
or
Project---> Properties--->Build--->Target Framework---> X86
Simple just log into your GitHub account and on the far right side in the navigation menu choose Settings, in the Settings Tab choose Default Branch and return back to main page of your repository that did the trick for me.
For anyone that stumbles upon this page, none of the solutions here worked for me. I found this is the way to do it (in a batch file):
@for /f "skip=1" %%p in ('wmic cpu get loadpercentage /VALUE') do (
for /F "tokens=2 delims==" %%J in ("%%p") do echo %%J
)
Follow these steps, respectively for rename column migration file.
1- Is there Doctrine/dbal library in your project. If you don't have run the command first
composer require doctrine/dbal
2- create update migration file for update old migration file. Warning (need to have the same name)
php artisan make:migration update_oldFileName_table
for example my old migration file name: create_users_table update file name should : update_users_table
3- update_oldNameFile_table.php
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');
});
'from' my old column name and 'to' my new column name
4- Finally run the migrate command
php artisan migrate
Source link: laravel document
px = dp * (dpi / 160)
dp = px * (160 / dpi)
<input type="checkbox" id="Checkbox1" class = "chk" value = "1" />
<input type="checkbox" id="Checkbox2" class = "chk" value = "2" />
<input type="checkbox" id="Checkbox3" class = "chk" value = "3" />
<input type="checkbox" id="Checkbox4" class = "chk" value = "4" />
<input type="button" id="demo" value = "Demo" />
<script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$("#demo").live("click", function () {
$("input:checkbox[class=chk]:checked").each(function () {
alert("Id: " + $(this).attr("id") + " Value: " + $(this).val());
});
});
</script>
I know it sounds weird, but I'm pretty sure this is your problem:
Somewhere in MyGui.java you're using a generic collection without specifying the type. For example if you're using an ArrayList somewhere, you are doing this:
List list = new ArrayList();
When you should be doing this:
List<String> list = new ArrayList<String>();
There are also a package called Humanizr on Nuget, and it actually works really well, and is in the .NET Foundation.
DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday"
DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago"
DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow"
DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now"
TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks"
TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"
Scott Hanselman has a writeup on it on his blog
As well as making sure that you have first called $("#myForm").validate();
, make sure that your dynamic control has been added to the DOM before adding the validation rules.
DTO vs VO
DTO - Data transfer objects are just data containers which are used to transport data between layers and tiers.
Analogy:
Simple Registration form with attributes username, password and email id.
- When this form is submitted in RegistrationServlet file you will get all the attributes from view layer to business layer where you pass the attributes to java beans and then to the DAO or the persistence layer.
- DTO's helps in transporting the attributes from view layer to business layer and finally to the persistence layer.
DTO was mainly used to get data transported across the network efficiently, it may be even from JVM to another JVM.
DTOs are often java.io.Serializable
- in order to transfer data across JVM.
VO - A Value Object [1][2] represents itself a fixed set of data and is similar to a Java enum. A Value Object's identity is based on their state rather than on their object identity and is immutable. A real world example would be Color.RED, Color.BLUE, SEX.FEMALE etc.
POJO vs JavaBeans
[1] The Java-Beanness of a POJO is that its private attributes are all accessed via public getters and setters that conform to the JavaBeans conventions. e.g.
private String foo;
public String getFoo(){...}
public void setFoo(String foo){...};
[2] JavaBeans must implement Serializable and have a no-argument constructor, whereas in POJO does not have these restrictions.
I just distilled this bash
function from the suggestions here:
grab() {
grab=$("$@")
echo $grab
}
Then, you just do:
> grab date
Do 16. Feb 13:05:04 CET 2012
> echo $grab
Do 16. Feb 13:05:04 CET 2012
Update: an anonymous user suggested to replace echo
by printf '%s\n'
which has the advantage that it doesn't process options like -e
in the grabbed text. So, if you expect or experience such peculiarities, consider this suggestion. Another option is to use cat <<<$grab
instead.
<html>
<body onload = "load()">
<script>
function load(){
try {
var ax = new ActiveXObject("WScript.Network");
alert('User: ' + ax.UserName );
alert('Computer: ' + ax.ComputerName);
}
catch (e) {
document.write('Permission to access computer name is denied' + '<br />');
}
}
</script>
</body>
</html>
My utils class for save list to SharedPreferences
public class SharedPrefApi {
private SharedPreferences sharedPreferences;
private Gson gson;
public SharedPrefApi(Context context, Gson gson) {
this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
this.gson = gson;
}
...
public <T> void putObject(String key, T value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, gson.toJson(value));
editor.apply();
}
public <T> T getObject(String key, Class<T> clazz) {
return gson.fromJson(getString(key, null), clazz);
}
}
Using
// for save
sharedPrefApi.putList(SharedPrefApi.Key.USER_LIST, userList);
// for retrieve
List<User> userList = sharedPrefApi.getList(SharedPrefApi.Key.USER_LIST, User.class);
.
Full code of my utils // check using example in Activity code
React.findDOMNode(this.refs.myExample)
mentioned in another answer has been deprectaed.
use ReactDOM.findDOMNode
from 'react-dom'
instead
import ReactDOM from 'react-dom'
let myExample = ReactDOM.findDOMNode(this.refs.myExample)
It used to be possible to compile Matlab to C with older versions of Matlab. Check out other tools that Matlab comes with.
Newest Matlab code can be exported as a Java's jar or a .Net Dll, etc. You can then write an executable against that library - it will be obfuscated by the way. The users will have to install a freely available Matlab Runtime.
Like others mentioned, mcc / mcc.exe is what you want to convert matlab code to C code.
As a small enhancement to the accepted answer that was subsequently refined by ahoffner - it is possible to use a date format rather than timestamp. The advantages are:
to do this, change the DB repeat_start
to be stored as type 'date' and repeat_interval
now hold days rather than seconds. i.e. 7 for a repeat of 7 days.
change the sql line:
WHERE (( 1370563200 - repeat_start) % repeat_interval = 0 )
to:
WHERE ( DATEDIFF( '2013-6-7', repeat_start ) % repeat_interval = 0)
everything else remains the same. Simples!
I'm guessing EventDate
is a char or varchar and not a date otherwise your order by clause would be fine.
You can use CONVERT to change the values to a date and sort by that
SELECT *
FROM
vw_view
ORDER BY
CONVERT(DateTime, EventDate,101) DESC
The problem with that is, as Sparky points out in the comments, if EventDate has a value that can't be converted to a date the query won't execute.
This means you should either exclude the bad rows or let the bad rows go to the bottom of the results
To exclude the bad rows just add WHERE IsDate(EventDate) = 1
To let let the bad dates go to the bottom you need to use CASE
e.g.
ORDER BY
CASE
WHEN IsDate(EventDate) = 1 THEN CONVERT(DateTime, EventDate,101)
ELSE null
END DESC
I have tried www.wheresmymac.com they are cheap and they have great bandwith so their is low latency. You need teamviewer to log into the virtual system though
You should capitalize names of your classes. After doing that do this in your school class,
Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);
Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters
I'm using Maven (SpringBoot application) solution is:
Then, Intellij automatically import generated sources to project.
//If url is something.domain.com this returns -> domain.com
function getDomain() {
return window.location.hostname.replace(/([a-zA-Z0-9]+.)/,"");
}
Sorry for my bad English. Checking Mails using Python with MAPI is easier,
outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetFirst()
Here we can get the most first mail into the Mail box, or into any sub folder. Actually, we need to check the Mailbox number & orientation. With the help of this analysis we can check each mailbox & its sub mailbox folders.
Similarly please find the below code, where we can see, the last/ earlier mails. How we need to check.
`outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetLast()`
With this we can get most recent email into the mailbox. According to the above mentioned code, we can check our all mail boxes, & its sub folders.
As an extension to what have been proposed by Nico Coallier (apply to multiple columns) and U10-Forward(using apply style of methods), and summarising it into a one-liner I propose:
df.loc[:,['col1','col2']].transform(lambda x: x.map(lambda x: {1: "A", 2: "B"}.get(x,x))
The .transform()
processes each column as a series. Contrary to .apply()
which passes the columns aggregated in a DataFrame.
Consequently you can apply the Series method map()
.
Finally, and I discovered this behaviour thanks to U10, you can use the whole Series in the .get() expression. Unless I have misunderstood its behaviour and it processes sequentially the series instead of bitwisely.
The .get(x,x)
accounts for the values you did not mention in your mapping dictionary which would be considered as Nan otherwise by the .map()
method
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xlsx"');
header('Cache-Control: max-age=0');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate');
header ('Pragma: public');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
Note that Internet Explorer from version 5 up to 8 will throw an error when trying to download a file served via https and the server sending Cache-Control: no-cache
or Pragma: no-cache
headers.
See http://support.microsoft.com/kb/812935/en-us
The use of Cache-Control: no-store
and Pragma: private
seems to be the closest thing which still works.
Try this
git clone ssh://[email protected]:11111/home/git/repo.git
When you update the version of PHP (especially when going from version X.Y to version X.Z), you must update the PHP extensions as well.
This is because PHP extensions are developped in C, and are "close" to the internals of PHP -- which means that, if the APIs of those internals change, the extension must be re-compiled, to use the new versions.
And, between PHP 5.2 and PHP 5.3, for what I remember, there have been some modifications in the internal data-structures used by the PHP engine -- which means extensions must be re-compiled, in order to match that new version of those data-structures.
How to update your PHP extensions will depend on which system you are using.
If you are on windows, you can find the .dll
for some extensions here : http://downloads.php.net/pierre/
For more informations about the different versions, you can take a look at what's said on the left-sidebar of windows.php.net.
If you are on Linux, you must either :
pecl
command, to re-download the sources of the extensions in question, and re-compile them.I found the solution to the white bars here:
Set viewport-fit=cover
on the viewport <meta>
tag, i.e.:
<meta name="viewport" content="initial-scale=1, width=device-width, height=device-height, viewport-fit=cover">
The white bars in UIWebView then disappear:
The solution to remove the black areas (provided by @dpogue in a comment below) is to use LaunchStoryboard images with cordova-plugin-splashscreen
to replace the legacy launch images, used by Cordova by default. To do so, add the following to the iOS platform in config.xml
:
<platform name="ios">
<splash src="res/screen/ios/Default@2x~iphone~anyany.png" />
<splash src="res/screen/ios/Default@2x~iphone~comany.png" />
<splash src="res/screen/ios/Default@2x~iphone~comcom.png" />
<splash src="res/screen/ios/Default@3x~iphone~anyany.png" />
<splash src="res/screen/ios/Default@3x~iphone~anycom.png" />
<splash src="res/screen/ios/Default@3x~iphone~comany.png" />
<splash src="res/screen/ios/Default@2x~ipad~anyany.png" />
<splash src="res/screen/ios/Default@2x~ipad~comany.png" />
<!-- more iOS config... -->
</platform>
Then create the images with the following dimensions in res/screen/ios
(remove any existing ones):
Default@2x~iphone~anyany.png - 1334x1334
Default@2x~iphone~comany.png - 750x1334
Default@2x~iphone~comcom.png - 1334x750
Default@3x~iphone~anyany.png - 2208x2208
Default@3x~iphone~anycom.png - 2208x1242
Default@3x~iphone~comany.png - 1242x2208
Default@2x~ipad~anyany.png - 2732x2732
Default@2x~ipad~comany.png - 1278x2732
Once the black bars are removed, there's another thing that's different about the iPhone X to address: The status bar is larger than 20px due to the "notch", which means any content at the far top of your Cordova app will be obscured by it:
Rather than hard-coding a padding in pixels, you can handle this automatically in CSS using the new safe-area-inset-*
constants in iOS 11.
Note: in iOS 11.0 the function to handle these constants was called constant()
but in iOS 11.2 Apple renamed it to env()
(see here),
therefore to cover both cases you need to overload the CSS rule with both and rely on the CSS fallback mechanism to apply the appropriate one:
body{
padding-top: constant(safe-area-inset-top);
padding-top: env(safe-area-inset-top);
}
The result is then as desired: the app content covers the full screen, but is not obscured by the "notch":
I've created a Cordova test project which illustrates the above steps: webview-test.zip
Notes:
Footer buttons
safe-area-inset-bottom
to avoid them being overlapped by the virtual Home button on iPhone X. <body>
as the footer is absolutely positioned, so I needed to apply it directly to the footer:
.toolbar-footer{
margin-bottom: constant(safe-area-inset-bottom);
margin-bottom: env(safe-area-inset-bottom);
}
cordova-plugin-statusbar
cordova-plugin-statusbar
display incorrectly on iPhone X[email protected]
release, so make sure you're using at least this version to apply to safe-area-insetssplashscreen
[email protected]
, so make sure you're using a recent version of the cordova-ios
platform.device orientation
safe-area-inset
not to be re-applied, causing the content to be obscured by the notch again (as highlighted by jms in a comment below). cordova-plugin-wkwebview-engine
.For reference, this is the original Cordova issue I opened which captures this: https://issues.apache.org/jira/browse/CB-13273
The resolution is to use TypedQuery instead. When creating a query from the EntityManager instead call it like this:
TypedQuery<[YourClass]> query = entityManager.createQuery("[your sql]", [YourClass].class);
List<[YourClass]> list = query.getResultList(); //no type warning
This also works the same for named queries, native named queries, etc. The corresponding methods have the same names as the ones that would return the vanilla query. Just use this instead of a Query whenever you know the return type.
I learned something really useful and fundamental from here.
chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.
It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter
function showPhotos() {
$(this).find("span").slideToggle();
}
$(".photos")
.on("mouseenter", "li", showPhotos)
.on("mouseleave", "li", showPhotos);
Use the widget Wrap
.
For Column
like behavior try:
return Wrap(
direction: Axis.vertical,
spacing: 10,
children: <Widget>[...],);
For Row
like behavior try:
return Wrap(
direction: Axis.horizontal,
spacing: 10,
children: <Widget>[...],);
For more information: Wrap (Flutter Widget)
You can use:
<script type="text/javascript">
function prepareFrame() {
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://google.com/");
ifrm.style.width = "640px";
ifrm.style.height = "480px";
document.body.appendChild(ifrm);
}
</script>
also check basics of the iFrame element
I'd start by using one of the projects out there for Java and CUDA: http://www.jcuda.org/
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
git fetch && git merge origin/develop
http://blogs.mysql.com/peterg/2009/04/
In Mysql 6.1 you will be able to do FORMAT(X,D [,locale_name] )
As in
SELECT format(1234567,2,’de_DE’);
For now this ability does not exist, though you MAY be able to set your locale in your database my.ini check it out.
a % b
in c++ default:
(-7/3) => -2
-2 * 3 => -6
so a%b => -1
(7/-3) => -2
-2 * -3 => 6
so a%b => 1
in python:
-7 % 3 => 2
7 % -3 => -2
in c++ to python:
(b + (a%b)) % b
List files between 2 dates
find . -type f -newermt "2019-01-01" ! -newermt "2019-05-01"
or
find path -type f -newermt "2019-01-01" ! -newermt "2019-05-01"
Xampp
I guess you're using MySQL
.
mysql_fetch_array($result);
And make sure $result
is not empty.
Just by using select select
you can select particular columns, give them readable names and cast them. For example like this:
spark.read.csv(path).select(
'_c0.alias("stn").cast(StringType),
'_c1.alias("wban").cast(StringType),
'_c2.alias("lat").cast(DoubleType),
'_c3.alias("lon").cast(DoubleType)
)
.where('_c2.isNotNull && '_c3.isNotNull && '_c2 =!= 0.0 && '_c3 =!= 0.0)
I write this custom function this will help you. But make discussions about the Time complexity.
std::vector<std::string> words;
std::string s;
std::string separator = ",";
while(s.find(separator) != std::string::npos){
separatorIndex = s.find(separator)
vtags.push_back(s.substr(0, separatorIndex ));
words= s.substr(separatorIndex + 1, s.length());
}
words.push_back(s);
GitHub has a Markdown API you can use.
Putting the subquery in the WHERE clause and restricting it to n.control_number means it runs the subquery many times. This is called a correlated subquery, and it's often a performance killer.
It's better to run the subquery once, in the FROM clause, to get the max date per control number.
SELECT n.*
FROM tblpm n
INNER JOIN (
SELECT control_number, MAX(date_updated) AS date_updated
FROM tblpm GROUP BY control_number
) AS max USING (control_number, date_updated);
MVW stands for Model-View-Whatever.
For completeness, here are all the acronyms mentioned:
MVC - Model-View-Controller
MVP - Model-View-Presenter
MVVM - Model-View-ViewModel
MVW / MV* / MVx - Model-View-Whatever
And some more:
HMVC - Hierarchical Model-View-Controller
MMV - Multiuse Model View
MVA - Model-View-Adapter
MVI - Model-View-Intent
Earlier for almost 3hrs I did:
Here is how solve this:
Rotating the labels is certainly possible. Note though that doing so reduces the readability of the text. One alternative is to alternate label positions using a code like this:
import numpy as np
n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]
fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
ax.set_xticks(x)
labels = ax.set_xticklabels(xlabels)
for i, label in enumerate(labels):
label.set_y(label.get_position()[1] - (i % 2) * 0.075)
For more background and alternatives, see this post on my blog
Simply change 'Search String'
to whatever you seek and 'Replace String'
with whatever you want to replace it with.
--Getting all the databases and making a cursor
DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb') -- exclude these databases
DECLARE @databaseName nvarchar(1000)
--opening the cursor to move over the databases in this instance
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @databaseName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @databaseName
--Setting up temp table for the results of our search
DECLARE @Results TABLE(TableName nvarchar(370), RealColumnName nvarchar(370), ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @SearchStr nvarchar(100), @ReplaceStr nvarchar(100), @SearchStr2 nvarchar(110)
SET @SearchStr = 'Search String'
SET @ReplaceStr = 'Replace String'
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128)
SET @TableName = ''
--Looping over all the tables in the database
WHILE @TableName IS NOT NULL
BEGIN
DECLARE @SQL nvarchar(2000)
SET @ColumnName = ''
DECLARE @result NVARCHAR(256)
SET @SQL = 'USE ' + @databaseName + '
SELECT @result = MIN(QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME))
FROM [' + @databaseName + '].INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = ''BASE TABLE'' AND TABLE_CATALOG = ''' + @databaseName + '''
AND QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME) > ''' + @TableName + '''
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME)
), ''IsMSShipped''
) = 0'
EXEC master..sp_executesql @SQL, N'@result nvarchar(256) out', @result out
SET @TableName = @result
PRINT @TableName
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
DECLARE @ColumnResult NVARCHAR(256)
SET @SQL = '
SELECT @ColumnResult = MIN(QUOTENAME(COLUMN_NAME))
FROM [' + @databaseName + '].INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 1)
AND DATA_TYPE IN (''char'', ''varchar'', ''nchar'', ''nvarchar'')
AND TABLE_CATALOG = ''' + @databaseName + '''
AND QUOTENAME(COLUMN_NAME) > ''' + @ColumnName + ''''
PRINT @SQL
EXEC master..sp_executesql @SQL, N'@ColumnResult nvarchar(256) out', @ColumnResult out
SET @ColumnName = @ColumnResult
PRINT @ColumnName
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @Results
EXEC
(
'USE ' + @databaseName + '
SELECT ''' + @TableName + ''',''' + @ColumnName + ''',''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
--Declaring another temporary table
DECLARE @time_to_update TABLE(TableName nvarchar(370), RealColumnName nvarchar(370))
INSERT INTO @time_to_update
SELECT TableName, RealColumnName FROM @Results GROUP BY TableName, RealColumnName
DECLARE @MyCursor CURSOR;
BEGIN
DECLARE @t nvarchar(370)
DECLARE @c nvarchar(370)
--Looping over the search results
SET @MyCursor = CURSOR FOR
SELECT TableName, RealColumnName FROM @time_to_update GROUP BY TableName, RealColumnName
--Getting my variables from the first item
OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @t, @c
WHILE @@FETCH_STATUS = 0
BEGIN
-- Updating the old values with the new value
DECLARE @sqlCommand varchar(1000)
SET @sqlCommand = '
USE ' + @databaseName + '
UPDATE [' + @databaseName + '].' + @t + ' SET ' + @c + ' = REPLACE(' + @c + ', ''' + @SearchStr + ''', ''' + @ReplaceStr + ''')
WHERE ' + @c + ' LIKE ''' + @SearchStr2 + ''''
PRINT @sqlCommand
BEGIN TRY
EXEC (@sqlCommand)
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE()
END CATCH
--Getting next row values
FETCH NEXT FROM @MyCursor
INTO @t, @c
END;
CLOSE @MyCursor ;
DEALLOCATE @MyCursor;
END;
DELETE FROM @time_to_update
DELETE FROM @Results
FETCH NEXT FROM db_cursor INTO @databaseName
END
CLOSE db_cursor
DEALLOCATE db_cursor
Note: this isn't ideal, nor is it optimized
Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).
To specifically address your problem, you should remove the brackets after donothing
in your setTimeout
call, and make waitsecs
a number not a string:
console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');
But that won't stop execution; "after" will be logged before your function runs.
To wait properly, you can use anonymous functions:
console.log('before');
setTimeout(function(){
console.log('after');
},500);
All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval
/ clearInterval
if it needs to loop.
You can index and use a negative sign to drop the 3rd column:
data[,-3]
Or you can list only the first 2 columns:
data[,c("c1", "c2")]
data[,1:2]
Don't forget the comma and referencing data frames works like this: data[row,column]
The header()
function has a parameter for status code. If you specify it, the server will take care of it from there.
header('HTTP/1.1 401 Unauthorized', true, 401);
See Gajus' answer: https://stackoverflow.com/a/14223222/362536
I know this is a very old question but it may be that you need to set the request headers. This solved it for me.
For example 'user-agent', 'accept' etc. here is an example with user-agent:
url = 'your-url-here'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'}
r = requests.get(url, headers=headers)
Yes, this is a current issue in Chrome. There is an issue report here.
The fix will appear in 40.x.y.z versions.
Until then? I don't think you can resolve the issue yourself. But you can ignore it. The shown error is only related to the dev tools and does not influence the behavior of your website. If you have any other problems they are not related to this error.
Spring has an util class for that:
import org.springframework.util.FileCopyUtils;
InputStream is = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileCopyUtils.copy(is, bos);
String data = new String(bos.toByteArray());
For all struggling around with the #selector in Swift 3 or Swift 4, here a full code example:
// WE NEED A CLASS THAT SHOULD RECEIVE NOTIFICATIONS
class MyReceivingClass {
// ---------------------------------------------
// INIT -> GOOD PLACE FOR REGISTERING
// ---------------------------------------------
init() {
// WE REGISTER FOR SYSTEM NOTIFICATION (APP WILL RESIGN ACTIVE)
// Register without parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handleNotification), name: .UIApplicationWillResignActive, object: nil)
// Register WITH parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handle(withNotification:)), name: .UIApplicationWillResignActive, object: nil)
}
// ---------------------------------------------
// DE-INIT -> LAST OPTION FOR RE-REGISTERING
// ---------------------------------------------
deinit {
NotificationCenter.default.removeObserver(self)
}
// either "MyReceivingClass" must be a subclass of NSObject OR selector-methods MUST BE signed with '@objc'
// ---------------------------------------------
// HANDLE NOTIFICATION WITHOUT PARAMETER
// ---------------------------------------------
@objc func handleNotification() {
print("RECEIVED ANY NOTIFICATION")
}
// ---------------------------------------------
// HANDLE NOTIFICATION WITH PARAMETER
// ---------------------------------------------
@objc func handle(withNotification notification : NSNotification) {
print("RECEIVED SPECIFIC NOTIFICATION: \(notification)")
}
}
In this example we try to get POSTs from AppDelegate (so in AppDelegate implement this):
// ---------------------------------------------
// WHEN APP IS GOING TO BE INACTIVE
// ---------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {
print("POSTING")
// Define identifiyer
let notificationName = Notification.Name.UIApplicationWillResignActive
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
}
Add BindingResult parameter in your method. For reference please my code below.
save(@ModelAttribute Employee employee,BindingResult bindingResult)
I'm a bit confused by the quotes, however, below should work for you:
SELECT "Gc_Staff_Number",
"Start_Date", x.end_date
FROM "Employment_History" eh,
(SELECT "End_Date"
FROM "Employment_History"
WHERE "Current_Flag" != 'Y'
AND ROWNUM = 1
AND "Employee_Number" = eh.Employee_Number
ORDER BY "End_Date" ASC) x
WHERE "Current_Flag" = 'Y'
There are two issues here:
To overcome this, disable the button after the JavaScript onclick
event. An easy way to do this is to use setTimeout
as suggested by this answer.
Also, the OnClientClick
code runs even if ASP.NET validation fails, so it's probably a good idea to add a check for Page_IsValid
. This ensures that the button will not be disabled if validation fails.
OnClientClick="(function(button) { setTimeout(function () { if (Page_IsValid) button.disabled = true; }, 0); })(this);"
It's neater to put all of this JavaScript code in its own function as the question shows:
OnClientClick="disable(this);"
function disable(button) {
setTimeout(function () {
if (Page_IsValid)
button.disabled = true;
}, 0);
}
To overcome this, disable the button on the server side. For example, in the OnClick
event handler:
OnClick="Button1_Click"
protected void Button1_Click(object sender, EventArgs e)
{
((Button)sender).Enabled = false;
}
Lastly, keep in mind that preventing duplicate button presses doesn't prevent two different users from submitting the same data at the same time. Make sure to account for that on the server side.
A char consists of a single character and should be specified in single quotes. It can contain an alphabetic, numerical or even special character. below are a few examples:
char a = '4';
char b = '$';
char c = 'B';
A String defines a line can be used which is specified in double quotes. Below are a few examples:
String a = "Hello World";
String b = "1234";
String c = "%%";
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
/* The algorithm is from the book "Discrete Mathematics and Its
Applications 5th Edition" by Kenneth H. Rosen.
(base^exp)%mod
*/
int modular(int base, unsigned int exp, unsigned int mod)
{
int x = 1;
int power = base % mod;
for (int i = 0; i < sizeof(int) * 8; i++) {
int least_sig_bit = 0x00000001 & (exp >> i);
if (least_sig_bit)
x = (x * power) % mod;
power = (power * power) % mod;
}
return x;
}
It's simple explanation:
var data = {_x000D_
code: 42,_x000D_
items: [{_x000D_
id: 1,_x000D_
name: 'foo'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'bar'_x000D_
}]_x000D_
};_x000D_
_x000D_
/*_x000D_
1. `data` is object contain `item` object*/_x000D_
console.log(data);_x000D_
_x000D_
/*_x000D_
2. `item` object contain array of two objects as elements*/_x000D_
console.log(data.items);_x000D_
_x000D_
/*_x000D_
3. you need 2nd element of array - the `1` from `[0, 1]`*/_x000D_
console.log(data.items[1]);_x000D_
_x000D_
/*_x000D_
4. and you need value of `name` property of 2nd object-element of array)*/_x000D_
console.log(data.items[1].name);
_x000D_
According to the exception, Hibernate wants to write to the table "person", yet in your hbm.xml you define that there is a table "Person", are you sure the correct table exists in your database-schema?
I store encoded HTML in the database.
Imho you should not store your data html-encoded in the database. Just store in plain text (not encoded) and just display your data like this and your html will be automatically encoded:
<div class='content'>
@Model.Content
</div>
Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.
If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:
Original answer:
Here is a not-so-great "ng-if" directive:
myApp.directive('ngIf', function() {
return {
link: function(scope, element, attrs) {
if(scope.$eval(attrs.ngIf)) {
// remove '<div ng-if...></div>'
element.replaceWith(element.children())
} else {
element.replaceWith(' ')
}
}
}
});
that allows for this HTML syntax:
<div ng-repeat="message in data.messages" ng-class="message.type">
<hr>
<div ng-if="showFrom(message)">
<div>From: {{message.from.name}}</div>
</div>
<div ng-if="showCreatedBy(message)">
<div>Created by: {{message.createdBy.name}}</div>
</div>
<div ng-if="showTo(message)">
<div>To: {{message.to.name}}</div>
</div>
</div>
replaceWith() is used to remove unneeded content from the DOM.
Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?
The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.
E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from
, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.
You can Use both disabled or readonly attribute of input . Using disable attribute will omit that value at form submit, so if you want that values at submit event make them readonly instead of disable.
<input type="text" readonly>
or
<input type="text" disabled>