UPDATE t
SET cumulative_sum = (
SELECT SUM(x.count)
FROM t x
WHERE x.id <= t.id
)
You can also denormalize - store running totals in the same table:
Selects work much faster than any other solutions, but modifications may be slower
You can also include these attributes in the modal definition itself:
<div class="modal hide fade" data-keyboard="false" data-backdrop="static">
How to POST mixed data: File, String[], String in one request.
You can use only what you need.
private String doPOST(File file, String[] array, String name) {
RestTemplate restTemplate = new RestTemplate(true);
//add file
LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("file", new FileSystemResource(file));
//add array
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
for (String item : array) {
builder.queryParam("array", item);
}
//add some String
builder.queryParam("name", name);
//another staff
String result = "";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
builder.build().encode().toUri(),
HttpMethod.POST,
requestEntity,
String.class);
HttpStatus statusCode = responseEntity.getStatusCode();
if (statusCode == HttpStatus.ACCEPTED) {
result = responseEntity.getBody();
}
return result;
}
The POST request will have File in its Body and next structure:
POST https://my_url?array=your_value1&array=your_value2&name=bob
select * from temptable
where rnum --unique key
in
(
SELECT RNUM --unique key
FROM temptable
WHERE ( HistoryStatus
) IN (SELECT HistoryStatus
FROM temptable
GROUP BY
HistoryStatus
HAVING COUNT(*) <= 1));
I have not tested this code. I have used similar code and it works. The syntax is in Oracle.
Just a slight addition to the above solution if you are having problem with downloaded file's name...
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
This will return the exact file name even if it contains spaces or other characters.
From Get-ScriptDirectory to the Rescue blog entry ...
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
I found this article
/// <summary>
/// Creates a new Image containing the same image only rotated
/// </summary>
/// <param name=""image"">The <see cref=""System.Drawing.Image"/"> to rotate
/// <param name=""offset"">The position to rotate from.
/// <param name=""angle"">The amount to rotate the image, clockwise, in degrees
/// <returns>A new <see cref=""System.Drawing.Bitmap"/"> of the same size rotated.</see>
/// <exception cref=""System.ArgumentNullException"">Thrown if <see cref=""image"/">
/// is null.</see>
public static Bitmap RotateImage(Image image, PointF offset, float angle)
{
if (image == null)
throw new ArgumentNullException("image");
//create a new empty bitmap to hold rotated image
Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
//make a graphics object from the empty bitmap
Graphics g = Graphics.FromImage(rotatedBmp);
//Put the rotation point in the center of the image
g.TranslateTransform(offset.X, offset.Y);
//rotate the image
g.RotateTransform(angle);
//move the image back
g.TranslateTransform(-offset.X, -offset.Y);
//draw passed in image onto graphics object
g.DrawImage(image, new PointF(0, 0));
return rotatedBmp;
}
The parent div (I assume the outermost div) is display: block
and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block
is probably what you are going for:
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command specified by string and then terminates
/k Carries out the command specified by string but remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
There is already a good solution to the problem you are having. Everyone has been forgetting the CSS property font-size
: the last but not least solution. One can decrease the font size by 2 to 3 pixels. It may still be visible to the user and for somewhat you can decrease the width of the table. This worked for me. My table has 5 columns with 4 showing perfectly, but the fifth column went out of the viewport. To fix the problem, I decreased the font size and all five columns were fitted onto the screen.
table th td {
font-size: 14px;
}
For your information, if your table has too many columns and you are not able to decrease, then make the font size small. It will get rid of the horizontal scroll. There are two advantages: your style for mobile web will remain the same (good without horizontal scroll) and when user sees small sizes, most users will zoom into the table to their comfort level.
You might wish to investigate Nuitka. It takes Python source code and converts it in to C++ API calls. Then it compiles into an executable binary (ELF on Linux). It has been around for a few years now and supports a wide range of Python versions.
You will probably also get a performance improvement if you use it. It is recommended.
I downgraded my Java version to 1.8 and its resolved, here is the link to download JDK8
Run the following command after installing JDK8
flutter doctor --android-licenses
Turn on Client Statistics by doing one of the following:
Then you get a new tab which records the timings, IO data and rowcounts etc for (up to) the last 10 exections (plus averages!):
For some git-commands you can specify --verbose
,
git 'command' --verbose
or
git 'command' -v
.
Make sure the switch is after the actual git command. Otherwise - it won't work!
Also useful:
git 'command' --dry-run
This should take care of it in your app.
$(":submit").closest("form").submit(function(){
$(':submit').attr('disabled', 'disabled');
});
AFAIK, {...}
can only be used as a path, not inside a query-param. Try this instead:
public interface FooService {
@GET("/maps/api/geocode/json?sensor=false")
void getPositionByZip(@Query("address") String address, Callback<String> cb);
}
If you have an unknown amount of parameters to pass, you can use do something like this:
public interface FooService {
@GET("/maps/api/geocode/json")
@FormUrlEncoded
void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);
}
<span onclick="event.stopPropagation(); alert('you clicked inside the header');">something inside the header</span>
For IE: window.event.cancelBubble = true
<span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>
-X [your method]
X lets you override the default 'Get'
** corrected lowercase x
to uppercase X
Finally got this error to go away on a restore. I moved to SQL2012 out of frustration, but I guess this would probably still work on 2008R2. I had to use the logical names:
RESTORE FILELISTONLY
FROM DISK = ‘location of your.bak file’
And from there I ran a restore statement with MOVE
using logical names.
RESTORE DATABASE database1
FROM DISK = '\\database path\database.bak'
WITH
MOVE 'File_Data' TO 'E:\location\database.mdf',
MOVE 'File_DOCS' TO 'E:\location\database_1.ndf',
MOVE 'file' TO 'E:\location\database_2.ndf',
MOVE 'file' TO 'E:\location\database_3.ndf',
MOVE 'file_Log' TO 'E:\location\database.ldf'
When it was done restoring, I almost wept with joy.
Good luck!
An integral type representing the smallest value possible. In other words your program should think in cents not in dollars/euros.
This should not stop you from having the gui translate it back to dollars/euros.
I had this issue as well, and the text-shadow
wasn't an option because the corners would look bad (unless I had many many shadows), and I didn't want any blur, therefore my only other option was to do the following: Have 2 divs, and for the background div, put a -webkit-text-stroke
on it, which then allows for as big of an outline as you like.
div {_x000D_
font-size: 200px;_x000D_
position: absolute;_x000D_
white-space: nowrap;_x000D_
}_x000D_
_x000D_
.front {_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
.outline {_x000D_
-webkit-text-stroke: 30px red;_x000D_
user-select: none;_x000D_
}
_x000D_
<div class="outline">_x000D_
outline text_x000D_
</div>_x000D_
_x000D_
<div class="front">_x000D_
outline text_x000D_
</div>
_x000D_
Using this, I was able to achieve an outline, because the stroke-width
method was not an option if you want your text to remain legible with a very large outline (because with stroke-width
the outline will start inside the lettering which makes it not legible when the width gets larger than the letters.
Note: the reason I needed such a fat outline was I was emulating the street labels in "google maps" and I wanted a fat white halo around the text. This solution worked perfectly for me.
The 00947 message indicates that the record which you are trying to send to Oracle lacks one or more of the columns which was included at the time the table was created. The 00913 message indicates that the record which you are trying to send to Oracle includes more columns than were included at the time the table was created. You just need to check the number of columns and its type in both the tables ie the tables that are involved in the sql.
Please try this:
<%= Page.ClientScript.GetPostBackEventReference(ddlVoucherType, String.Empty) %>;
ddlVoucherType is a control which the selected index change will call... And you can put any function on the selected index change of this control.
Use this:
return RedirectToAction("LogIn", "Account", new { area = "" });
This will redirect to the LogIn
action in the Account
controller in the "global" area.
It's using this RedirectToAction
overload:
protected internal RedirectToRouteResult RedirectToAction(
string actionName,
string controllerName,
Object routeValues
)
For converting number as varchar to int, you could also use simple
(column + 0)
I got the same error in ReactJS function component, using ReactJS useState hook. The solution was to declare the type of useState at initialisation:
const [items , setItems] = useState<IItem[]>([]); // replace IItem[] with your own typing: string, boolean...
No need to convert it in a string by using json.dumps()
r = {'is_claimed': 'True', 'rating': 3.5}
file.write(r['is_claimed'])
file.write(str(r['rating']))
You can get the values directly from the dict object.
From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":
The following works for me:
python -m http.server [<portNo>]
Because I am using Python 3 the module SimpleHTTPServer
has been replaced by http.server
, at least in Windows.
Even though too much of CLOSE_WAIT connections means there is something wrong with your code in the first and this is accepted not good practice.
You might want to check out: https://github.com/rghose/kill-close-wait-connections
What this script does is send out the ACK which the connection was waiting for.
This is what worked for me.
You probably forgot to give #
before id for id selector, you need to give #
before id
ie is ulId
You problably need to bind scroll event on div that contains the ul and scrolls. You need to bind the event with div instead of ul
$(document).on( 'scroll', '#idOfDivThatContainsULandScroll', function(){
console.log('Event Fired');
});
Edit
The above would not work because the scroll event does not bubble up in DOM which is used for event delegation, see this question why doesn't delegate work for scroll?
But with modern browsers > IE 8 you can do it by other way. Instead of delegating by using jquery you can do it using event capturing with java script document.addEventListener
, with the third argument as true
; see how bubbling and capturing work in this tuturial.
document.addEventListener('scroll', function (event) {
if (event.target.id === 'idOfUl') { // or any other filtering condition
console.log('scrolling', event.target);
}
}, true /*Capture event*/);
If you do not need event delegation then you can bind scroll event directly to the ul instead of delegating it through document
.
$("#idOfUl").on( 'scroll', function(){
console.log('Event Fired');
});
Old question, but this is what I typically do to make things a bit more readable:
Func<int, string, Tuple<int, string>> tc = Tuple.Create;
var tupleList = new List<Tuple<int, string>>
{
tc( 1, "cow" ),
tc( 5, "chickens" ),
tc( 1, "airplane" )
};
I had an excel file 24MB in Size, thanks to over a 100 images within. I reduced the size to less than 5MB by the following steps:
It took me 2 days to figure this out as this wasnt listed in any help forum. Hope this response helps someone
BR Gautam Dalal (India)
Node.js uses libuv behind the scenes. libuv has a thread pool (of size 4 by default). Therefore Node.js does use threads to achieve concurrency.
However, your code runs on a single thread (i.e., all of the callbacks of Node.js functions will be called on the same thread, the so called loop-thread or event-loop). When people say "Node.js runs on a single thread" they are really saying "the callbacks of Node.js run on a single thread".
To be more clear - there's no OneToMany in Django, only ManyToOne - which is Foreignkey described above. You can describe OneToMany relation using Foreignkey but that is very inexpressively.
A good article about it: https://amir.rachum.com/blog/2013/06/15/a-case-for-a-onetomany-relationship-in-django/
You can return the intersection.
a = [1,1,2,3]
a & a
This will also delete duplicates.
All work perfectly :)
NSString *test = @"test";
unichar a;
int index = 5;
@try {
a = [test characterAtIndex:index];
}
@catch (NSException *exception) {
NSLog(@"%@", exception.reason);
NSLog(@"Char at index %d cannot be found", index);
NSLog(@"Max index is: %lu", [test length] - 1);
}
@finally {
NSLog(@"Finally condition");
}
Log:
[__NSCFConstantString characterAtIndex:]: Range or index out of bounds
Char at index 5 cannot be found
Max index is: 3
Finally condition
1.1 ls
It will show you default location.
1.2 CD "C:\Users\user\Desktop\HTML" We need to assign project path
1.3 git init It will initialize the empty git repository in C:\Users\user\Desktop\HTML
1.4 ls It will list all files name
1.5 git remote add origin https://github.com/repository/test.git it is your https://github.com/repository/test.git is your repository path
1.6 git remote -v To check weather we have fetch or push permisson or not
1.7 git add . If you put . then it mean whatever we have in perticular folder publish all.
1.8 git commit -m "First time"
1.9 git push -u origin master
Very simple and few lines of code:
let viewShadow = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
viewShadow.center = self.view.center
viewShadow.backgroundColor = UIColor.yellow
viewShadow.layer.shadowColor = UIColor.red.cgColor
viewShadow.layer.shadowOpacity = 1
viewShadow.layer.shadowOffset = CGSize.zero
viewShadow.layer.shadowRadius = 5
self.view.addSubview(viewShadow)
I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects
import Image
import numpy as np
im = Image.load('foo.jpg')
im = im.convert('L')
arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)
arr ^= 0xFF # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()
"aoColumnDefs" : [
{
'bSortable' : false,
'aTargets' : [ 0 ]
}]
Here 0
is the index of the column, if you want multiple columns to be not sorted, mention column index values seperated by comma(,)
you don't need to declare Map groovy internally recognizes it
def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']
// print the values..
println "First Name: ${personDetails.firstName}"
println "Last Name: ${personDetails.lastName}"
The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.
There is a difference in performance.
Simply put HS256
is about 1 order of magnitude faster than RS256
for verification but about 2 orders of magnitude faster than RS256
for issuing (signing).
640,251 91,464.3 ops/s
86,123 12,303.3 ops/s (RS256 verify)
7,046 1,006.5 ops/s (RS256 sign)
Don't get hung up on the actual numbers, just think of them with respect of each other.
[Program.cs]
class Program
{
static void Main(string[] args)
{
foreach (var duration in new[] { 1, 3, 5, 7 })
{
var t = TimeSpan.FromSeconds(duration);
byte[] publicKey, privateKey;
using (var rsa = new RSACryptoServiceProvider())
{
publicKey = rsa.ExportCspBlob(false);
privateKey = rsa.ExportCspBlob(true);
}
byte[] key = new byte[64];
using (var rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(key);
}
var s1 = new Stopwatch();
var n1 = 0;
using (var hs256 = new HMACSHA256(key))
{
while (s1.Elapsed < t)
{
s1.Start();
var hash = hs256.ComputeHash(privateKey);
s1.Stop();
n1++;
}
}
byte[] sign;
using (var rsa = new RSACryptoServiceProvider())
{
rsa.ImportCspBlob(privateKey);
sign = rsa.SignData(privateKey, "SHA256");
}
var s2 = new Stopwatch();
var n2 = 0;
using (var rsa = new RSACryptoServiceProvider())
{
rsa.ImportCspBlob(publicKey);
while (s2.Elapsed < t)
{
s2.Start();
var success = rsa.VerifyData(privateKey, "SHA256", sign);
s2.Stop();
n2++;
}
}
var s3 = new Stopwatch();
var n3 = 0;
using (var rsa = new RSACryptoServiceProvider())
{
rsa.ImportCspBlob(privateKey);
while (s3.Elapsed < t)
{
s3.Start();
rsa.SignData(privateKey, "SHA256");
s3.Stop();
n3++;
}
}
Console.WriteLine($"{s1.Elapsed.TotalSeconds:0} {n1,7:N0} {n1 / s1.Elapsed.TotalSeconds,9:N1} ops/s");
Console.WriteLine($"{s2.Elapsed.TotalSeconds:0} {n2,7:N0} {n2 / s2.Elapsed.TotalSeconds,9:N1} ops/s");
Console.WriteLine($"{s3.Elapsed.TotalSeconds:0} {n3,7:N0} {n3 / s3.Elapsed.TotalSeconds,9:N1} ops/s");
Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n2 / s2.Elapsed.TotalSeconds),9:N1}x slower (verify)");
Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n3 / s3.Elapsed.TotalSeconds),9:N1}x slower (issue)");
// RS256 is about 7.5x slower, but it can still do over 10K ops per sec.
}
}
}
You can comput hashes using MessageDigest
, but this is wrong in terms of security. Hashes are not to be used for storing passwords, as they are easily breakable.
You should use another algorithm like bcrypt, PBKDF2 and scrypt to store you passwords. See here.
<form action="display.html" method="post">_x000D_
<input type="text" name="serialNumber" />_x000D_
<input type="submit" value="Submit" />_x000D_
</form>
_x000D_
In display.html you should add the following code.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var sn = getParameterByName('serialNumber');
document.getElementById("write").innerHTML = sn;
</script>
You can use XDocument.Parse
for this.
Taking a look at the source code of OpenPyXL (IterableWorksheet) I've figured out how to get the column and row count from an iterator worksheet:
wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]
row_count = sheet.get_highest_row() - 1
column_count = letter_to_index(sheet.get_highest_column()) + 1
IterableWorksheet.get_highest_column
returns a string with the column letter that you can see in Excel, e.g. "A", "B", "C" etc. Therefore I've also written a function to translate the column letter to a zero based index:
def letter_to_index(letter):
"""Converts a column letter, e.g. "A", "B", "AA", "BC" etc. to a zero based
column index.
A becomes 0, B becomes 1, Z becomes 25, AA becomes 26 etc.
Args:
letter (str): The column index letter.
Returns:
The column index as an integer.
"""
letter = letter.upper()
result = 0
for index, char in enumerate(reversed(letter)):
# Get the ASCII number of the letter and subtract 64 so that A
# corresponds to 1.
num = ord(char) - 64
# Multiply the number with 26 to the power of `index` to get the correct
# value of the letter based on it's index in the string.
final_num = (26 ** index) * num
result += final_num
# Subtract 1 from the result to make it zero-based before returning.
return result - 1
I still haven't figured out how to get the column sizes though, so I've decided to use a fixed-width font and automatically scaled columns in my application.
It also happens when I just want to compile opencv2.3.2 with mingw32 (in tdm-gcc suites). Often when I install the tdm-gcc, I would like to rename the mingw32-make.exe to make.exe. And I thinks this could be the question. If cmake is asked to generated a MinGW Makefiles, It would try to find ming32-make.exe instead of make.exe. So I copy the make.exe to mingw32-make.exe and reconfigure in Cmake-gui. Finally it works! So I'd like to advise to find whether you have mingw32-make.exe or not to solve this question.
%>%
is similar to pipe in Unix. For example, in
a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()
the output of combined_data_set
will go into group_by
and its output will go into tally
, then the final output is assigned to a
.
This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.
on Debian 10
I start mysql from ./opt/lampp/xampp start
I do strace ./opt/lampp/sbin/mysqld
and see that my.cnf is there:
stat("/opt/lampp/etc/my.cnf", {st_mode=S_IFREG|0644, st_size=5050, ...}) = 0
openat(AT_FDCWD, "/opt/lampp/etc/my.cnf", O_RDONLY|O_CLOEXEC) = 3
hence, I add sql_mode config to /opt/lampp/etc/my.cnf
instead of /etc/mysql/my.cnf
$total_ratings
is an array.
There isn't any difference between single and double quotes in JavaScript.
The specification is important:
Maybe there are performance differences, but they are absolutely minimum and can change any day according to browsers' implementation. Further discussion is futile unless your JavaScript application is hundreds of thousands lines long.
It's like a benchmark if
a=b;
is faster than
a = b;
(extra spaces)
today, in a particular browser and platform, etc.
JWT is an open standard that defines a compact and self-contained way for securely transmitting information between parties. It is an authentication protocol where we allow encoded claims (tokens) to be transferred between two parties (client and server) and the token is issued upon the identification of a client. With each subsequent request we send the token.
Whereas OAuth2 is an authorization framework, where it has a general procedures and setups defined by the framework. JWT can be used as a mechanism inside OAuth2.
You can read more on this here
Generally to count distinct values in single column, you can use Series.value_counts
:
df.domain.value_counts()
#'vk.com' 5
#'twitter.com' 2
#'facebook.com' 1
#'google.com' 1
#Name: domain, dtype: int64
To see how many unique values in a column, use Series.nunique
:
df.domain.nunique()
# 4
To get all these distinct values, you can use unique
or drop_duplicates
, the slight difference between the two functions is that unique
return a numpy.array
while drop_duplicates
returns a pandas.Series
:
df.domain.unique()
# array(["'vk.com'", "'twitter.com'", "'facebook.com'", "'google.com'"], dtype=object)
df.domain.drop_duplicates()
#0 'vk.com'
#2 'twitter.com'
#4 'facebook.com'
#6 'google.com'
#Name: domain, dtype: object
As for this specific problem, since you'd like to count distinct value with respect to another variable, besides groupby
method provided by other answers here, you can also simply drop duplicates firstly and then do value_counts()
:
import pandas as pd
df.drop_duplicates().domain.value_counts()
# 'vk.com' 3
# 'twitter.com' 2
# 'facebook.com' 1
# 'google.com' 1
# Name: domain, dtype: int64
The striping/replacement/scaping of single quotes from user input (input sanitation), has to be done before the SQL statement reaches the database.
Although, the actual question does not want to iterate over the list to generate the result, but all the solutions that has been proposed does exactly that under-neath the hood!
To refresh: You cannot add two vectors without looking into all the vector elements. So, the algorithmic complexity of most of these solutions are Big-O(n). Where n is the dimension of the vector.
So, from an algorithmic point of view, using a for loop to iteratively generate the resulting list is logical and pythonic too. However, in addition, this method does not have the overhead of calling or importing any additional library.
# Assumption: The lists are of equal length.
resultList = [list1[i] + list2[i] for i in range(len(list1))]
The timings that are being showed/discussed here are system and implementation dependent, and cannot be reliable measure to measure the efficiency of the operation. In any case, the big O complexity of the vector addition operation is linear, meaning O(n).
When you cherry-pick, it creates a new commit with a new SHA. If you do:
git cherry-pick -x <sha>
then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.
In the second version, you're passing the String returned from this.id
. Not the element itself.
So id.value
won't give you what you want.
You would need to pass the element with this
.
doSomething(this)
then:
function(el){
var value = el.value;
...
}
Note: In some browsers, the second one would work if you did:
window[id].value
because element IDs are a global property, but this is not safe.
It makes the most sense to just pass the element with this
instead of fetching it again with its ID.
You could hard code it.
<div class="col-md-6" style="background-color:blue;">
</div>
<div class="col-md-6" style="background-color:white;">
</div>
I was just implementing this actual problem in my current project. i did it for all ajax-POSTs that needed an authenticated user.
First off i decided to hook my jquery ajax calls so i do not to repeat myself too often. this javascript snippet ensures all ajax (post) calls will add my request validation token to the request. Note: the name __RequestVerificationToken is used by the .Net framework so i can utilize the standard Anti-CSRF features as shown below.
$(document).ready(function () {
var securityToken = $('[name=__RequestVerificationToken]').val();
$('body').bind('ajaxSend', function (elm, xhr, s) {
if (s.type == 'POST' && typeof securityToken != 'undefined') {
if (s.data.length > 0) {
s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
}
else {
s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
}
}
});
});
In your Views where you need the token to be available to the above javascript just use the common HTML-Helper. You can basically add this code whereever you want. I placed it within a if(Request.IsAuthenticated) statement:
@Html.AntiForgeryToken() // you can provide a string as salt when needed which needs to match the one on the controller
In your controller simply use the standard ASP.Net MVC Anti-CSRF mechanism. I did it like this (though i actually used Salt).
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public JsonResult SomeMethod(string param)
{
// do something
return Json(true);
}
With Firebug or a similar tool you can easily see how your POST requests now have a __RequestVerificationToken parameter appended.
You could store this into a temporary table.
So instead of doing the CTE/sub query you would use a temp table.
Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/
INSERT INTO mt_magazine_subscription SELECT *
FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC
try this instead $(".video-divs.focused")
. This works if you are looking for video-divs that are focused.
This is a bit of a Unix vs Linux battle. Most if not all Linux distributions have bash installed and ksh optional. Most Unix systems, like Solaris, AIX and HPUX have ksh as default.
Personally I always use ksh, I love the vi completion and I pretty much use Solaris for everything.
Use Datatable.Default.Sort
property and then bind it to the datagridview.
Also, you can create your own outerHeight
for HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle
, suggested in the answer above.
Object.defineProperty(Element.prototype, 'outerHeight', {
'get': function(){
var height = this.clientHeight;
var computedStyle = window.getComputedStyle(this);
height += parseInt(computedStyle.marginTop, 10);
height += parseInt(computedStyle.marginBottom, 10);
height += parseInt(computedStyle.borderTopWidth, 10);
height += parseInt(computedStyle.borderBottomWidth, 10);
return height;
}
});
This piece of code allow you to do something like this:
document.getElementById('foo').outerHeight
According to caniuse.com, getComputedStyle is supported by main browsers (IE, Chrome, Firefox).
Is there a reason you didn't just use this?
<select id="animal" name="animal">
<option value="0">--Select Animal--</option>
<option value="Cat">Cat</option>
<option value="Dog">Dog</option>
<option value="Cow">Cow</option>
</select>
if($_POST['submit'] && $_POST['submit'] != 0)
{
$animal=$_POST['animal'];
}
Since Java doesn't have an intersect function (really!?) you can do collision detection by simply comparying the X and Y, Width and Height values of the bounding boxes (rectangle) for each of the objects that could potentially collide.
So... in the base object of each colliding object... i.e. if your player and enemy have a common base you can put a simple Rectangle object called something like BoundingBox. If the common base is a built in Java class then you'll need to create a class that extends the build in class and have the player and enemy objects extend your new class or are instances of that class.
At creation (and each tick or update) you'll need to set the BoundingBox paremeters for both your player and enemy. I don't have the Rectangle class infront of me but its most likely something like X, Y, Width and finally Height. X and Y are that objects location in your game world. The width and height are self explanatory I think. They'll most likely come out from the right of the players location though so, if the X and Y were bothe at 0 and your Width and Height were both at 256 you wouldn't see anything because the character would be at the top left outside of the screen.
Anyways... to detect a collision, you'll want to compare the attributes of the player and enemy BoundingBoxes. So something like this...
if( Player.BoundingBox.X = Enemy.BoundingBox.X && If( Player.BoundingBox.Y = Enemy.BoundingBox.Y )
{
//Oh noes! The enemy and player are on top of eachother.
}
The logic can get sort of complicated but you'll need to compare the distances between each BoundingBox and compare locations.
dbctx.Database.EnsureDeleted(); dbctx.Database.EnsureCreated();
As of . 2015 / 02 / 24 . there is a website (youtubeinmp4) that allows you to download youtube videos in .mp4 format
, you can exploit this (with some JavaScript) to get away with embedding youtube videos in <video>
tags. Here is a demo of this in action.
##Pros
##Cons
It obviously depends on the youtubeinmp4.com
servers and their way of providing a downloading link (which can be passed as a <video>
source), so this answer may not be valid in the future.
You can't choose the video quality.
###JavaScript (after load
)
videos = document.querySelectorAll("video");
for (var i = 0, l = videos.length; i < l; i++) {
var video = videos[i];
var src = video.src || (function () {
var sources = video.querySelectorAll("source");
for (var j = 0, sl = sources.length; j < sl; j++) {
var source = sources[j];
var type = source.type;
var isMp4 = type.indexOf("mp4") != -1;
if (isMp4) return source.src;
}
return null;
})();
if (src) {
var isYoutube = src && src.match(/(?:youtu|youtube)(?:\.com|\.be)\/([\w\W]+)/i);
if (isYoutube) {
var id = isYoutube[1].match(/watch\?v=|[\w\W]+/gi);
id = (id.length > 1) ? id.splice(1) : id;
id = id.toString();
var mp4url = "http://www.youtubeinmp4.com/redirect.php?video=";
video.src = mp4url + id;
}
}
}
###Usage (Full)
<video controls="true">
<source src="www.youtube.com/watch?v=3bGNuRtlqAQ" type="video/mp4" />
</video>
_x000D_
Standard video format.
###Usage (Mini)
<video src="youtu.be/MLeIBFYY6UY" controls="true"></video>
_x000D_
A little less common but quite smaller, using the shortened url youtu.be
as the src
attribute directly in the <video>
tag.
if you want to emebed the canvas you can use this snippet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id=canvas width=200 height=200></canvas>
<iframe id='img' width=200 height=200></iframe>
<script>
window.onload = function() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "green";
context.fillRect(50, 50, 100, 100);
document.getElementById('img').src = canvas.toDataURL("image/jpeg");
console.log(canvas.toDataURL("image/jpeg"));
}
</script>
</body>
</html>
use this snippet!
$(document).ready(function() {
$.fn.dataTable.moment = function ( format, locale ) {
var types = $.fn.dataTable.ext.type;
// Add type detection
types.detect.unshift( function ( d ) {
return moment( d, format, locale, true ).isValid() ?
'moment-'+format :
null;
} );
// Add sorting method - use an integer for the sorting
types.order[ 'moment-'+format+'-pre' ] = function ( d ) {
return moment( d, format, locale, true ).unix();
};
};
$.fn.dataTable.moment('DD/MM/YYYY');
$('#example').DataTable();
});
the moment js works well for all date and time formats, add this snipper before you initialize the datatable like i've done earlier.
Also remember to load the http://momentjs.com/
It would be the former. Go by extensions as well instead of folder structure.
I.e. my example C# development ignore file:
#OS junk files
[Tt]humbs.db
*.DS_Store
#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad
#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*
#Project files
[Bb]uild/
#Subversion files
.svn
# Office Temp Files
~$*
Update
I thought I'd provide an update from the comments below. Although not directly answering the OP's question, see the following for more examples of .gitignore
syntax.
Community wiki (constantly being updated):
.gitignore for Visual Studio Projects and Solutions
More examples with specific language use can be found here (thanks to Chris McKnight's comment):
package com.example.broadcastreceiver;
import android.app.Activity;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
UserDefinedBroadcastReceiver broadCastReceiver = new UserDefinedBroadcastReceiver();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* This method enables the Broadcast receiver for
* "android.intent.action.TIME_TICK" intent. This intent get
* broadcasted every minute.
*
* @param view
*/
public void registerBroadcastReceiver(View view) {
this.registerReceiver(broadCastReceiver, new IntentFilter(
"android.intent.action.TIME_TICK"));
Toast.makeText(this, "Registered broadcast receiver", Toast.LENGTH_SHORT)
.show();
}
/**
* This method disables the Broadcast receiver
*
* @param view
*/
public void unregisterBroadcastReceiver(View view) {
this.unregisterReceiver(broadCastReceiver);
Toast.makeText(this, "unregistered broadcst receiver", Toast.LENGTH_SHORT)
.show();
}
}
This might sound stupid, but, in the first problem presented to you, you would have to see all the remaining numbers in the bag to actually add them up to find the missing number using that equation.
So, since you get to see all the numbers, just look for the number that's missing. The same goes for when two numbers are missing. Pretty simple I think. No point in using an equation when you get to see the numbers remaining in the bag.
If you have the char array null terminated, you can assign the char array to the string:
char[] chArray = "some characters";
String String(chArray);
As for your loop code, it looks right, but I will try on my controller to see if I get the same problem.
toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
Both methods do the same functionally - they compare values.
As is written on MSDN:
String.Equals
method - Determines whether this instance and
another specified String object have the same value. (http://msdn.microsoft.com/en-us/library/858x0yyx.aspx)==
- Although string is a reference type, the equality operators (==
and
!=
) are defined to compare the values of string objects, not
references. This makes testing for string equality more intuitive. (http://msdn.microsoft.com/en-en/library/362314fe.aspx)But if one of your string instances is null, these methods are working differently:
string x = null;
string y = "qq";
if (x == y) // returns false
MessageBox.Show("true");
else
MessageBox.Show("false");
if (x.Equals(y)) // returns System.NullReferenceException: Object reference not set to an instance of an object. - because x is null !!!
MessageBox.Show("true");
else
MessageBox.Show("false");
If you want to pass multiple values to RS via a query string all you need to do is repeat the report parameter for each value.
For example; I have a RS column called COLS and this column expects one or more values.
&rp:COLS=1&rp:COLS=1&rp:COLS=5 etc..
Here > a
to specifiy the color for root of li.active.menu-item
#primary-menu > li.active.menu-item > a
#primary-menu>li.active.menu-item>a {_x000D_
color: #c19b66;_x000D_
}
_x000D_
<ul id="primary-menu">_x000D_
<li class="active menu-item"><a>Coffee</a>_x000D_
<ul id="sub-menu">_x000D_
<li class="active menu-item"><a>aaa</a></li>_x000D_
<li class="menu-item"><a>bbb</a></li>_x000D_
<li class="menu-item"><a>ccc</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li class="menu-item"><a>Tea</a></li>_x000D_
<li class="menu-item"><a>Coca Cola</a></li>_x000D_
</ul>
_x000D_
Try this:
table {
border-spacing: 0;
border-collapse: collapse;
}
Try like this
var results = db.costumers.Where(X=>X.FullName.Contains(FirstName)&&(X=>X.FullName.EndsWith(LastName))
.Select(X=>X);
In Python 2 dict.keys() return a list, whereas in Python 3 it returns a generator.
You could only iterate over it's values else you may have to explicitly convert it to a list i.e. pass it to a list function.
My solution, after trying EVERYTHING:
Bad deployment, an old PrecompiledApp.config was hanging around my deploy location, and making everything not work.
My final settings that worked:
Nothing changes in the web.config - this means no special handlers for routing. Here's my snapshot of the sections a lot of other posts reference. I'm using FluorineFX, so I do have that handler added, but I did not need any others:
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="None"/>
<pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
<httpRuntime requestPathInvalidCharacters=""/>
<httpModules>
<add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx"/>
</httpModules>
</system.web>
<system.webServer>
<!-- Modules for IIS 7.0 Integrated mode -->
<modules>
<add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx" />
</modules>
<!-- Disable detection of IIS 6.0 / Classic mode ASP.NET configuration -->
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Global.ashx: (only method of any note)
void Application_Start(object sender, EventArgs e) {
// Register routes...
System.Web.Routing.Route echoRoute = new System.Web.Routing.Route(
"{*message}",
//the default value for the message
new System.Web.Routing.RouteValueDictionary() { { "message", "" } },
//any regular expression restrictions (i.e. @"[^\d].{4,}" means "does not start with number, at least 4 chars
new System.Web.Routing.RouteValueDictionary() { { "message", @"[^\d].{4,}" } },
new TestRoute.Handlers.PassthroughRouteHandler()
);
System.Web.Routing.RouteTable.Routes.Add(echoRoute);
}
PassthroughRouteHandler.cs - this achieved an automatic conversion from http://andrew.arace.info/stackoverflow to http://andrew.arace.info/#stackoverflow which would then be handled by the default.aspx:
public class PassthroughRouteHandler : IRouteHandler {
public IHttpHandler GetHttpHandler(RequestContext requestContext) {
HttpContext.Current.Items["IncomingMessage"] = requestContext.RouteData.Values["message"];
requestContext.HttpContext.Response.Redirect("#" + HttpContext.Current.Items["IncomingMessage"], true);
return null;
}
}
In oracle, generally speaking, there are number of facts that I will mention in following section:
Therefore, your question, "to see all tablespaces and datafiles belong to SCOTT" is s bit wrong.
However, there are some DBA views encompass information about all database objects, regardless of the owner. Only users with DBA privileges can access these views: DBA_DATA_FILES, DBA_TABLESPACES, DBA_FREE_SPACE, DBA_SEGMENTS.
So, connect to your DB as sysdba and run query through these helpful views. For example this query can help you to find all tablespaces and their data files that objects of your user are located:
SELECT DISTINCT sgm.TABLESPACE_NAME , dtf.FILE_NAME
FROM DBA_SEGMENTS sgm
JOIN DBA_DATA_FILES dtf ON (sgm.TABLESPACE_NAME = dtf.TABLESPACE_NAME)
WHERE sgm.OWNER = 'SCOTT'
If you declare the name for enumeration no error will occur.
If not declared, you have to use a typedef
:
enum enum_name {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = IMMEDIATE;
It will not display an error...
We can directly subtract dates to get difference in Days.
SET SERVEROUTPUT ON ;
DECLARE
V_VAR NUMBER;
BEGIN
V_VAR:=TO_DATE('2000-01-02', 'YYYY-MM-DD') - TO_DATE('2000-01-01', 'YYYY-MM-DD') ;
DBMS_OUTPUT.PUT_LINE(V_VAR);
END;
If you have some estimation about the distance between the 2 strings 'abc' and 'efg' you are looking for, you might use:
grep -r . -e 'abc' -A num1 -B num2 | grep 'efg'
That way, the first grep will return the line with the 'abc' plus #num1 lines after it, and #num2 lines after it, and the second grep will sift through all of those to get the 'efg'. Then you'll know at which files they appear together.
As it's an issue we face more than often, below are the steps to resolve it.
Open the Git perspective. In the Git Repository view, go to on Branches ? Local ? master and right click ? Merge...
It should auto select Remote Tracking ? *origin/master. Press Merge.
Launch stage view in Eclipse.
Double click the files which initially showed conflict
In the conflict merge view, by selecting the left arrow for all the non-conflict + conflict changes from left to right, you can resolve all the conflicts.
Save the merged file.
Do a Team ? pull from Eclipse again.
You are all set :)
For anyone reading who wants ONLY the time in the output, you can pass options to JavaScript's Date::toLocaleString() method. Example:
var date = new Date("February 04, 2011 19:00:00");_x000D_
var options = {_x000D_
hour: 'numeric',_x000D_
minute: 'numeric',_x000D_
hour12: true_x000D_
};_x000D_
var timeString = date.toLocaleString('en-US', options);_x000D_
console.log(timeString);
_x000D_
timeString will be set to:
8:00 AM
Add "second: 'numeric'" to your options if you want seconds too. For all option see this.
Open file/etc/nginx/nginx.conf
Add or change client_max_body_size 0;
There is now also the class org.apache.http.entity.ContentType
from package org.apache.httpcomponents.httpcore
, starting from 4.2 up.
Windows: Check permissions of destination folders. Take ownership if you must to give rights to the account running the rsync service.
For your first question, I have a code that I am comfortable with to get rid of all NAs. Thanks for @Gregor to make it simpler.
final[!(rowSums(is.na(final))),]
For the second question, the code is just an alternation from the previous solution.
final[as.logical((rowSums(is.na(final))-5)),]
Notice the -5 is the number of columns in your data. This will eliminate rows with all NAs, since the rowSums adds up to 5 and they become zeroes after subtraction. This time, as.logical is necessary.
Blockquote
Registering providers in a component
Here's a revised HeroesComponent that registers the HeroService in its providers array.
import { Component } from '@angular/core';
import { HeroService } from './hero.service';
@Component({
selector: 'my-heroes',
providers: [HeroService],
template: `
`
})
export class HeroesComponent { }
We have set compatibility mode for IE11 to resolve an issue: Settings>Compatibility View Settings>Add your site name or Check "Display intranet sites in Compatibility View" if your portal is in the intranet.
IE version 11.0.9600.16521
Worked for us, hope this helps someone.
I used this code that was cool. but have an error. " neterr_cleartext_not_permitted" show when you use this code then you will face this problem..
I got a solution of this.you have to add this in your AndroidManifest.xml near about Application
android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET" /> // ignore if you already added. outside of Application.
Are you trying to remove a single value or all matching values?
If you are trying to remove a single value, how do you define the value you wish to remove?
The reason you don't get a key back when querying on values is because the dictionary could contain multiple keys paired with the specified value.
If you wish to remove all matching instances of the same value, you can do this:
foreach(var item in dic.Where(kvp => kvp.Value == value).ToList())
{
dic.Remove(item.Key);
}
And if you wish to remove the first matching instance, you can query to find the first item and just remove that:
var item = dic.First(kvp => kvp.Value == value);
dic.Remove(item.Key);
Note: The ToList()
call is necessary to copy the values to a new collection. If the call is not made, the loop will be modifying the collection it is iterating over, causing an exception to be thrown on the next attempt to iterate after the first value is removed.
You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.
Also, I don't think you can use NOW()
as default value in OrderDate. Try to use the following:
OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
In my case removing/adding that assembly worked.
Open the following url with the latitude and longitude and zoom level.
Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:
-Xmx512m -ea -Djava.awt.headless=true
What I did it to ignore the settings.php file successfully:
I think if there's the committed file on Git then ignore doesn't work as expected. Just delete the file and commit. Afterwards it'll ignore.
In addition to Boaz's answer ....
@UniqueConstraint
allows you to name the constraint, while @Column(unique = true)
generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq
).
Sometimes it can be helpful to know what table a constraint is associated with. E.g.:
@Table(
name = "product_serial_group_mask",
uniqueConstraints = {
@UniqueConstraint(
columnNames = {"mask", "group"},
name="uk_product_serial_group_mask"
)
}
)
I don't know of any out-of-the-box way to achieve this. As you say, this is not how SharePoint lists are intended used. It might work to create a custom site column displaying the path to the document, as this might be used in a filter. Have never tried it, though.
document.getElementById('TextBoxID').readOnly = true; //to enable readonly
document.getElementById('TextBoxID').readOnly = false; //to disable readonly
First of all read in the data, then convert it to byte array:
byte b = Byte.parseByte(str, 16);
and then use String
constructor:
new String(byte[] bytes)
or if the charset is not system default then:
new String(byte[] bytes, String charsetName)
SELECT emp.LoginID, emp.JobTitle, emp.BirthDate, emp.ModifiedDate ,
CASE WHEN emp.JobTitle NOT LIKE '%Document Control%' THEN emp.JobTitle
ELSE SUBSTRING(emp.JobTitle,CHARINDEX('Document Control',emp.JobTitle),LEN('Document Control'))
END
,emp.gender,emp.MaritalStatus
FROM HumanResources.Employee [emp]
WHERE JobTitle LIKE '[C-F]%'
Here is the solution that worked for me. This is a generic function which works for all of the a
tags referring to a named a
$("a[href^=#]").on('click', function(event) {
event.preventDefault();
var name = $(this).attr('href');
var target = $('a[name="' + name.substring(1) + '"]');
$('html,body').animate({ scrollTop: $(target).offset().top }, 'slow');
});
Note 1: Make sure that you use double quotes "
in your html. If you use single quotes, change the above part of the code to var target = $("a[name='" + name.substring(1) + "']");
Note 2: In some cases, especially when you use the sticky bar from the bootstrap, the named a
will hide beneath the navigation bar. In those cases (or any similar case), you can reduce the number of the pixels from your scroll to achieve the optimal location. For example: $('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow');
will take you to the target
with 15 pixels left on the top.
after some test: If you send an email to an outlook client, and the subject is >77 chars, and it needs to use "=?ISO"
inside the subject (in my case because of accents) then OutLook will "cut" the subject in the middle of it and mesh it all that comes after, including body text, attaches, etc... all a mesh!
I have several examples like this one:
Subject: =?ISO-8859-1?Q?Actas de la obra N=BA.20100154 (Expediente N=BA.20100182) "NUEVA RED FERROVIARIA.=
TRAMO=20BEASAIN=20OESTE(Pedido=20PC10/00123-125),=20BEASAIN".?=
To:
As you see, in the subject line it cutted on char 78 with a "=" followed by 2 or 3 line feeds, then continued with the rest of the subject baddly.
It was reported to me from several customers who all where using OutLook, other email clients deal with those subjects ok.
If you have no ISO on it, it doesn't hurt, but if you add it to your subject to be nice to RFC, then you get this surprise from OutLook. Bit if you don't add the ISOs, then iPhone email will not understand it(and attach files with names using such characters will not work on iPhones).
Abstract classes are not required to implement the methods. So even though it implements an interface, the abstract methods of the interface can remain abstract. If you try to implement an interface in a concrete class (i.e. not abstract) and you do not implement the abstract methods the compiler will tell you: Either implement the abstract methods or declare the class as abstract.
How about creating an ArrayList of a set amount of Integers?
The below method returns an ArrayList of a set amount of Integers.
public static ArrayList<Integer> createRandomList(int sizeParameter)
{
// An ArrayList that method returns
ArrayList<Integer> setIntegerList = new ArrayList<Integer>(sizeParameter);
// Random Object helper
Random randomHelper = new Random();
for (int x = 0; x < sizeParameter; x++)
{
setIntegerList.add(randomHelper.nextInt());
} // End of the for loop
return setIntegerList;
}
To force a reload of the php.ini you should restart apache.
Try sudo service apache2 restart
from the command line.
Or sudo /etc/init.d/apache2 restart
If your npm version is lower than version 5 then install the higher version for getting the automatic generation of package-lock.json.
Example: Upgrade your current npm to version 6.14.0
npm i -g [email protected]
You could view the latest npm version list by
npm view npm versions
Please remove call to trustSrc
function and try again like this . {{trustSrc(currentProject.url)}} to {{currentProject.url}}.
Check this link http://plnkr.co/edit/caqS1jE9fpmMn5NofUve?p=preview
src
url. Have a look on the following code.
Before:
Javascript
scope.baseUrl = 'page';
scope.a = 1;
scope.b = 2;
Html
<!-- Are a and b properly escaped here? Is baseUrl controlled by user? -->
<iframe src="{{baseUrl}}?a={{a}&b={{b}}"
But for security reason they are recommending following method
Javascript
var baseUrl = "page";
scope.getIframeSrc = function() {
// One should think about their particular case and sanitize accordingly
var qs = ["a", "b"].map(function(value, name) {
return encodeURIComponent(name) + "=" +
encodeURIComponent(value);
}).join("&");
// `baseUrl` isn't exposed to a user's control, so we don't have to worry about escaping it.
return baseUrl + "?" + qs;
};
Html
<iframe src="{{getIframeSrc()}}">
Either:
row.name
inside the apply(..., axis=1)
call:df = pandas.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'], index=['x','y'])
a b c
x 1 2 3
y 4 5 6
df.apply(lambda row: row.name, axis=1)
x x
y y
iterrows()
(slower)DataFrame.iterrows() allows you to iterate over rows, and access their index:
for idx, row in df.iterrows():
...
Just copying the content of the zip-file to its prefered location from the zip-file will give you this error when you attempt to run the only executable that is visible in the archive. It is named similarly but it is not the real thing.
You should let the archive extract itself to make the installation complete correctly. Doing so gives you an executable named eclipse.exe with which you will not get this error.
It really also depends on how you name your variable.
When people are asking "which is better practice" - this implicitly implies that both are correct, so it's just a matter of which is easier to read and maintain.
If you name your variable "status" (which is the case in your example code), I would much prefer to see
if(status == false) // if status is false
On the other hand, if you had named your variable isXXX (e.g. isReadableCode), then the former is more readable. consider:
if(!isReadable) { // if not readable
System.out.println("I'm having a headache reading your code");
}
I believe it's in C:\Windows\System32\WindowsPowershell\v1.0\
. In order to confuse the innocent, MS kept it in a directory labeled "v1.0". Running this on Windows 7 and checking the version number via $Host.Version
(Determine installed PowerShell version) shows it's 2.0.
Another option is type $PSVersionTable
at the command prompt. If you are running v2.0, the output will be:
Name Value
---- -----
CLRVersion 2.0.50727.4927
BuildVersion 6.1.7600.16385
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
If you're running version 1.0, the variable doesn't exist and there will be no output.
Localization PowerShell version 1.0, 2.0, 3.0, 4.0:
The JavaDoc explains it very well:
With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
SO_TIMEOUT
is the timeout that a read()
call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read()
call will block until at least 1 byte could be read.
The second sample assigns a unique ID to the element in question. This element can then be manipulated or accessed using DHTML.
The first one, on the other hand, sets a named location within the document, akin to a bookmark. Attached to an "anchor", it makes perfect sense.
You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster
.cpp
files are not included (using #include
) into other files. Therefore they don't need include guarding. Main.cpp
will know the names and signatures of the class that you have implemented in class.cpp
only because you have specified all that in class.h
- this is the purpose of a header file. (It is up to you to make sure that class.h
accurately describes the code you implement in class.cpp
.) The executable code in class.cpp
will be made available to the executable code in main.cpp
thanks to the efforts of the linker.
Getting the correct line (example for line no. 6) is done with head and tail and the correct word (word no. 4) can be captured with awk:
command|head -n 6|tail -n 1|awk '{print $4}'
Why not use EF6 attribute based e-mail validation?
As you can see above, Regex validation for e-mail always has some hole in it. If you are using EF6 data annotations, you can easily achieve reliable and stronger e-mail validation with EmailAddress data annotation attribute available for that. I had to remove the regex validation I used before for e-mail when I got mobile device specific regex failure on e-mail input field. When the data annotation attribute used for e-mail validation, the issue on mobile was resolved.
public class LoginViewModel
{
[EmailAddress(ErrorMessage = "The email format is not valid")]
public string Email{ get; set; }
Although everyone answer "No" and I know that "No" is the right answer but if you really need to get local variables of a function there is a restricted way.
Consider this function:
var f = function() {
var x = 0;
console.log(x);
};
You can convert your function to a string:
var s = f + '';
You will get source of function as a string
'function () {\nvar x = 0;\nconsole.log(x);\n}'
Now you can use a parser like esprima to parse function code and find local variable declarations.
var s = 'function () {\nvar x = 0;\nconsole.log(x);\n}';
s = s.slice(12); // to remove "function () "
var esprima = require('esprima');
var result = esprima.parse(s);
and find objects with:
obj.type == "VariableDeclaration"
in the result (I have removed console.log(x)
below):
{
"type": "Program",
"body": [
{
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": "x"
},
"init": {
"type": "Literal",
"value": 0,
"raw": "0"
}
}
],
"kind": "var"
}
]
}
I have tested this in Chrome, Firefox and Node.
But the problem with this method is that you just have the variables defined in the function itself. For example for this one:
var g = function() {
var y = 0;
var f = function() {
var x = 0;
console.log(x);
};
}
you just have access to the x and not y. But still you can use chains of caller (arguments.callee.caller.caller.caller) in a loop to find local variables of caller functions. If you have all local variable names so you have scope variables. With the variable names you have access to values with a simple eval.
After installing Laminas, I got the same error message
"Translator component requires the intl PHP extension"
while wanting to view the web application with the php web server:
php -S 0.0.0.0:8080 -t public public/index.php
As I'm usgin XAMPP, in
c:\xampp\php\php.ini
I had to enable the PHP extension intl in this line ;extension=php_intl.dll
, remove the starting semicolon (;) and restart XAMPP. I hope this will help.
using jquery $.each
you can access all data and also set in table like this
<table style="width: 100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Category</th>
<th>Color</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
$.each(data, function (index, item) {
var eachrow = "<tr>"
+ "<td>" + item[1] + "</td>"
+ "<td>" + item[2] + "</td>"
+ "<td>" + item[3] + "</td>"
+ "<td>" + item[4] + "</td>"
+ "</tr>";
$('#tbody').append(eachrow);
});
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
it clears the all the bits that are not in the first byte
I think you need some sort of regular expression matching (the following code is in Python 3):
import string
import re
import nltk
s = "I can't do this now, because I'm so tired. Please give me some time."
l = nltk.word_tokenize(s)
ll = [x for x in l if not re.fullmatch('[' + string.punctuation + ']+', x)]
print(l)
print(ll)
Output:
['I', 'ca', "n't", 'do', 'this', 'now', ',', 'because', 'I', "'m", 'so', 'tired', '.', 'Please', 'give', 'me', 'some', 'time', '.']
['I', 'ca', "n't", 'do', 'this', 'now', 'because', 'I', "'m", 'so', 'tired', 'Please', 'give', 'me', 'some', 'time']
Should work well in most cases since it removes punctuation while preserving tokens like "n't", which can't be obtained from regex tokenizers such as wordpunct_tokenize
.
Its so simple to get logs in React-Native
Use console.log and console.warn
console.log('character', parameter)
console.warn('character', parameter)
This log you can view in browser console. If you want to check device log or say production APK log you can use
adb logcat
adb -d logcat
DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";
// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");
Ref: http://www.csharp-examples.net/dataview-rowfilter/
http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx
The API Guide has it all wrong (really Google?). With Maps API v2 you do not need to enable a layer to show yourself, there is a simple call to the GoogleMaps instance you created with your map.
The actual documentation that Google provides gives you your answer. You just need to
// map is a GoogleMap object
map.isMyLocationEnabled = true
// map is a GoogleMap object
map.setMyLocationEnabled(true);
and watch the magic happen.
Just make sure that you have location permission and requested it at runtime on API Level 23 (M) or above
you can use LayoutInflater to inflate your dynamic data as a layout file.
UPDATE : first create a LinearLayout inside your CardView's layout and assign an ID for it.
after that create a layout file that you want to inflate. at last in your onBindViewHolder
method in your "RAdaper" class. write these codes :
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = mInflater.inflate(R.layout.my_list_custom_row, parent, false);
after that you can initialize data and ClickListeners with your RAdapter Data. hope it helps.
Try using:
Console.WriteLine()
The call to Debug.WriteLine
will only be made during when DEBUG is defined.
Other suggestions are to use: Trace.WriteLine
as well, but I haven't tried this.
There is also an option (not sure if Visual Studio 2008 has it), but you can still Use Debug.WriteLine
when you run the test with Test With Debugger
option in the IDE.
split takes regex as a parameter.|
has special meaning in regex.. use \\|
instead of |
to escape it.
There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )
The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.
To make this work, your function needs to loop through each of the Areas
in the input ranges. For example:
Function calculateIt(Sessions As Range, Customers As Range) As Single
' check we passed the same number of areas
If (Sessions.Areas.Count <> Customers.Areas.Count) Then
calculateIt = CVErr(xlErrNA)
Exit Function
End If
Dim mySession, myCustomers As Range
' run through each area and calculate
For a = 1 To Sessions.Areas.Count
Set mySession = Sessions.Areas(a)
Set myCustomers = Customers.Areas(a)
' calculate them...
Next a
End Function
The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9)
.
Hope that helps :)
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
No, you can't return multiple values from a function in C# (for versions lower than C# 7), at least not in the way you can do it in Python.
However, there are a couple alternatives:
You can return an array of type object with the multiple values you want in it.
private object[] DoSomething()
{
return new [] { 'value1', 'value2', 3 };
}
You can use out
parameters.
private string DoSomething(out string outparam1, out int outparam2)
{
outparam1 = 'value2';
outparam2 = 3;
return 'value1';
}
200 is just the normal HTTP header for a successful request. If that's all you need, just have the controller return new EmptyResult();
The only problem with threads is accessing the same object from different threads without synchronization.
If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.
plot.legend(loc = 'lower right', decimal_places = 2, fontsize = '11', title = 'Hey there', title_fontsize = '20')
What exactly are the rules for requesting retransmission of lost data?
The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.
Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ
are detailed in the RFC 3366.
At what time frequency are the retransmission requests performed?
The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)
The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.
Is there an upper bound on the number?
Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.
Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?
The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)
TypeScript 0.9+ has a specification for enums:
enum AnimationType {
BOUNCE,
DROP,
}
The final comma is optional.
Example for OUT : Variable gets value initialized after going into the method. Later the same value is returned to the main method.
namespace outreftry
{
class outref
{
static void Main(string[] args)
{
yyy a = new yyy(); ;
// u can try giving int i=100 but is useless as that value is not passed into
// the method. Only variable goes into the method and gets changed its
// value and comes out.
int i;
a.abc(out i);
System.Console.WriteLine(i);
}
}
class yyy
{
public void abc(out int i)
{
i = 10;
}
}
}
Output:
10
===============================================
Example for Ref : Variable should be initialized before going into the method. Later same value or modified value will be returned to the main method.
namespace outreftry
{
class outref
{
static void Main(string[] args)
{
yyy a = new yyy(); ;
int i = 0;
a.abc(ref i);
System.Console.WriteLine(i);
}
}
class yyy
{
public void abc(ref int i)
{
System.Console.WriteLine(i);
i = 10;
}
}
}
Output:
0 10
=================================
Hope its clear now.
>>> a = [5, 7, 11, 4, 5]
>>> for n,k in enumerate(a[:-1]):
... print a[n],a[n+1]
...
5 7
7 11
11 4
4 5
If you read through any of the discussions on the android development group you will see that they discourage the use of anything that isn't in the public SDK because the rest is subject to extensive change.
just put Wait() to wait until task completed
GetInputReportViaInterruptTransfer().Wait();
I faced the encoding half of this problem the other day. Unhappy with the available options, and after taking a look at this C sample code, i decided to roll my own C++ url-encode function:
#include <cctype>
#include <iomanip>
#include <sstream>
#include <string>
using namespace std;
string url_encode(const string &value) {
ostringstream escaped;
escaped.fill('0');
escaped << hex;
for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
string::value_type c = (*i);
// Keep alphanumeric and other accepted characters intact
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
continue;
}
// Any other characters are percent-encoded
escaped << uppercase;
escaped << '%' << setw(2) << int((unsigned char) c);
escaped << nouppercase;
}
return escaped.str();
}
The implementation of the decode function is left as an exercise to the reader. :P
You could use the undocumented
DBCC LOG(databasename, typeofoutput)
where typeofoutput:
0: Return only the minimum of information for each operation -- the operation, its context and the transaction ID. (Default)
1: As 0, but also retrieve any flags and the log record length.
2: As 1, but also retrieve the object name, index name, page ID and slot ID.
3: Full informational dump of each operation.
4: As 3 but includes a hex dump of the current transaction log row.
For example, DBCC LOG(database, 1)
You could also try fn_dblog.
For rolling back a transaction using the transaction log I would take a look at Stack Overflow post Rollback transaction using transaction log.
Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.
In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden')
which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.
For IntelliJ in Mac
View -> Quick Switch theme (^`)-> color schema
com.sun.tools.javac.util.Pair is an simple implementation of a pair. It can be found in jdk1.7.0_51\lib\tools.jar.
Other than the org.apache.commons.lang3.tuple.Pair, it's not just an interface.
My issue was nested folders.
I had my image in assets/images/logo/xyz.png
and thought that - assets/images/
would catch all subfolders.
You have to explicitly add each nested subfolder
Solution:
- assets/images/logo/
etc.
This will Fill images to a specific size, without stretching it or without cropping it
img{
width:150px; //your requirement size
height:100px; //your requirement size
/*Scale down will take the necessary specified space that is 150px x 100px without stretching the image*/
object-fit:scale-down;
}
int randomWithRange(int min, int max)
{
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
Output of randomWithRange(2, 5)
10 times:
5
2
3
3
2
4
4
4
5
4
The bounds are inclusive, ie [2,5], and min
must be less than max
in the above example.
EDIT: If someone was going to try and be stupid and reverse min
and max
, you could change the code to:
int randomWithRange(int min, int max)
{
int range = Math.abs(max - min) + 1;
return (int)(Math.random() * range) + (min <= max ? min : max);
}
EDIT2: For your question about double
s, it's just:
double randomWithRange(double min, double max)
{
double range = (max - min);
return (Math.random() * range) + min;
}
And again if you want to idiot-proof it it's just:
double randomWithRange(double min, double max)
{
double range = Math.abs(max - min);
return (Math.random() * range) + (min <= max ? min : max);
}
It seems the docs/tool have been updated and you can now add the image
tag to your script. This was successful for me.
Example:
version: '2'
services:
baggins.api.rest:
image: my.image.name:rc2
build:
context: ../..
dockerfile: app/Docker/Dockerfile.release
ports:
...
If you can NOT find the .m3u8
file you will need to do a couple of steps different.
1) Go to the network tab and sort by Media
2) You will see something here and select the first item. In my example, it's an mpd
file. then copy the Request URL.
3) Next, download the file using your favorite command line tool using the URL from step 2.
youtube-dl -f bestvideo+bestaudio https://url.com/destination/stream.mpd
4) Depending on the encoding you might have to join the audio and video files together but this will depend on a video by video case.
You can't move the mouse pointer using javascript, and thus for obvious security reasons. The best way to achieve this effect would be to actually place the control under the mouse pointer.
Some type of input hasn't got the :after or :before pseudo-element, so you can use a background-image with an SVG text element:
input {
background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='50px' width='120px'><text x='0' y='15' fill='gray' font-size='15'>Type Something...</text></svg>");
background-repeat: no-repeat;
}
input:focus {
background-image: none;
}
My codepen: https://codepen.io/Scario/pen/BaagbeZ
Visit https://play.golang.org/p/dx6PTtuBXQW
package main
import (
"fmt"
"sort"
)
func main() {
mapEg := map[string]string{"c":"a","a":"c","b":"b"}
keys := make([]string, 0, len(mapEg))
for k := range mapEg {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Println(keys)
}
This is what worked for my, and its pure css
css
html {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
}
body {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
}
#bg {
width: 100%;
height: 100%;
background: url('/image.jpg/') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
-webkit-animation: myfirst 5s ; /* Chrome, Safari, Opera */
animation: myfirst 5s ;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
from {opacity: 0.2;}
to {opacity: 1;}
}
/* Standard syntax */
@keyframes myfirst {
from {opacity: 0.2;}
to {opacity: 1;}
}
html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="bg">
<!-- content here -->
</div> <!-- end bg -->
</body>
</html>
Unless you redirect stdout and stderr as the accepted answer suggests, this is not possible with execSync or spawnSync. Without redirecting stdout and stderr those commands only return stdout and stderr when the command is completed.
To do this without redirecting stdout and stderr, you are going to need to use spawn to do this but it's pretty straight forward:
var spawn = require('child_process').spawn;
//kick off process of listing files
var child = spawn('ls', ['-l', '/']);
//spit stdout to screen
child.stdout.on('data', function (data) { process.stdout.write(data.toString()); });
//spit stderr to screen
child.stderr.on('data', function (data) { process.stdout.write(data.toString()); });
child.on('close', function (code) {
console.log("Finished with code " + code);
});
I used an ls command that recursively lists files so that you can test it quickly. Spawn takes as first argument the executable name you are trying to run and as it's second argument it takes an array of strings representing each parameter you want to pass to that executable.
However, if you are set on using execSync and can't redirect stdout or stderr for some reason, you can open up another terminal like xterm and pass it a command like so:
var execSync = require('child_process').execSync;
execSync("xterm -title RecursiveFileListing -e ls -latkR /");
This will allow you to see what your command is doing in the new terminal but still have the synchronous call.
I suggest using Render, as the ElementRef API doc suggests:
... take a look at Renderer which provides API that can safely be used even when direct access to native elements is not supported. Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker or Universal.
Always use the Renderer for it will make you code (or library you right) be able to work when using Universal or WebWorkers.
import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';
export class HighlightDirective {
constructor(el: ElementRef, renderer: Renderer) {
renderer.setElementProperty(el.nativeElement, 'innerHTML', 'some new value');
}
}
It doesn't look like Render has a getElementProperty() method though, so I guess we still need to use NativeElement for that part. Or (better) pass the content in as an input property to the directive.
I read it like "When the iterable
is exhausted completely, and the execution is about to proceed to the next statement after finishing the for
, the else clause will be executed." Thus, when the iteration is broken by break
, this will not be executed.
You have two options here.
Make a proper cron job that calls your script. Cron is a common name for a GNU/Linux daemon that periodically launches scripts according to a schedule you set. You add your script into a crontab or place a symlink to it into a special directory and the daemon handles the job of launching it in the background. You can read more at Wikipedia. There is a variety of different cron daemons, but your GNU/Linux system should have it already installed.
Use some kind of python approach (a library, for example) for your script to be able to daemonize itself. Yes, it will require a simple event loop (where your events are timer triggering, possibly, provided by sleep function).
I wouldn't recommend you to choose 2., because you would be, in fact, repeating cron functionality. The Linux system paradigm is to let multiple simple tools interact and solve your problems. Unless there are additional reasons why you should make a daemon (in addition to trigger periodically), choose the other approach.
Also, if you use daemonize with a loop and a crash happens, no one will check the mail after that (as pointed out by Ivan Nevostruev in comments to this answer). While if the script is added as a cron job, it will just trigger again.
HTMLUnit can be used to do web scraping, it supports invoking pages, filling & submitting forms. I have used this in my project. It is good java library for web scraping. read here for more
From This page, the container dies after running everything correctly but crashes because all the commands ended. Either you make your services run on the foreground, or you create a keep alive script. By doing so, Kubernetes will show that your application is running. We have to note that in the Docker
environment, this problem is not encountered. It is only Kubernetes that wants a running app.
Update (an example):
Here's how to avoid CrashLoopBackOff, when launching a Netshoot container:
kubectl run netshoot --image nicolaka/netshoot -- sleep infinity
VTD-XML is the heavy duty XML parsing lib... it is better than others in virtually every way... here is a 2013 paper that analyzes all XML processing frameworks available in java platform...
http://sdiwc.us/digitlib/journal_paper.php?paper=00000582.pdf
You can use numpy's slicing, simply start:stop:step
.
>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])
This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2] # O(1), constant time
>>> b[:] = 0 # modifying the view changes original array
>>> a # original array is modified
array([0, 2, 0, 4, 0])
so if either of the above things are a problem, you can make a copy explicitly:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy() # explicit copy, O(n)
>>> b[:] = 0 # modifying the copy
>>> a # original is intact
array([1, 2, 3, 4, 5])
This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.
The traceback indicates that probably you have an empty line at the end of the file. You can fix it like this:
f = open('test.txt','r')
g = open('test1.txt','w')
while True:
x = f.readline()
x = x.rstrip()
if not x: break
print >> g, int(x, 16)
On the other hand it would be better to use for x in f
instead of readline
. Do not forget to close your files or better to use with
that close them for you:
with open('test.txt','r') as f:
with open('test1.txt','w') as g:
for x in f:
x = x.rstrip()
if not x: continue
print >> g, int(x, 16)
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
console.log('someProcess() has been called');
// If some condition is true clear the interval
if (stopIntervalIsTrue) {
window.clearInterval(intervalListener);
}
}
This one works for me:
modal
<div class="modal fade" id="searchKaryawan" tabindex="-1" role="dialog" aria-labelledby="SearchKaryawanLabel" aria-hidden="true"> <div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="SearchKaryawanLabel">Cari Karyawan</h4>
</div>
<div class="modal-body">
<input type="hidden" name="location">
<input name="cariNama" type="text" class="form-control" onkeyup="if (this.value.length > 3) cariNikNama();" />
<div class="links-area" id="links-area"></div>
</div>
<div class="modal-footer">
</div>
</div> </div></div>
script
<script type="text/javascript">$('body').on('hidden.bs.modal', '.modal', function () { $(".links-area").empty() }); </script>
links-area is area where i put the data and need to clear
I came across the same nagging error, which I realized has something to do with a cool feature PyCharm automatically detects...just add the @staticmethod decorator, and it will automatically remove that error where the method is used
Clearly you aren't sending the data with ObjectOutputStream:
you are just writing the bytes.
readObject()
you must write with writeObject().
readUTF()
you must write with writeUTF().
readXXX()
you must write with writeXXX(),
for most values of XXX.Best case for human logic to computer generated bytecode would be to utilize code like the following:
private double translateSlider(int sliderVal) {
float retval = 1.0;
switch (sliderVal) {
case 1: retval = 0.9; break;
case 2: retval = 0.8; break;
case 3: retval = 0.7; break;
case 4: retval = 0.6; break;
case 0:
default: break;
}
return retval;
}
Thus eliminating multiple exits from the method and utilizing the language logically. (ie while sliderVal is an integer range of 1-4 change float value else if sliderVal is 0 and all other values, retval stays the same float value of 1.0)
However something like this with each integer value of sliderVal being (n-(n/10))
one really could just do a lambda and get a faster results:
private double translateSlider = (int sliderVal) -> (1.0-(siderVal/10));
Edit:
A modulus of 4 may be in order to keep logic (ie (n-(n/10))%4)
)
-XX:MaxPermSize=size
Sets the maximum permanent generation space size (in bytes). This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize
option.
-XX:PermSize=size
Sets the space (in bytes) allocated to the permanent generation that triggers a garbage collection if it is exceeded. This option was deprecated in JDK 8, and superseded by the -XX:MetaspaceSize
option.
You can use blank.gif (1px transparent image) as target in your tag
<input type="image" src="img/blank.gif" class="button">
and then style background in css:
.button {border:0;background:transparent url("../img/button.png") no-repeat 0 0;}
.button:hover {background:transparent url("../img/button-hover.png") no-repeat 0 0;}
As said in the documentation:
Must: The clause (query) must appear in matching documents.
Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.
In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.
Since you want your results to satisfy all the queries, you should use must.
You can indeed use filters inside a boolean query.
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
You do this via attributes on the properties, like this:
[Description("Test text displayed in the textbox"),Category("Data")]
public string Text {
get => myInnerTextBox.Text;
set => myInnerTextBox.Text = value;
}
The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.
the only thing that worked for me was to run pod deintegrate
and pod install
Creating a Dump File SQL.gz on the current server
$ sudo apt-get install pigz pv
$ pv | mysqldump --user=<yourdbuser> --password=<yourdbpassword> <currentexistingdbname> --single-transaction --routines --triggers --events --quick --opt -Q --flush-logs --allow-keywords --hex-blob --order-by-primary --skip-comments --skip-disable-keys --skip-add-locks --extended-insert --log-error=/var/log/mysql/<dbname>_backup.log | pigz > /path/to/folder/<dbname>_`date +\%Y\%m\%d_\%H\%M`.sql.gz
Optional: Command Arguments for connection
--host=127.0.0.1 / localhost / IP Address of the Dump Server
--port=3306
Importing the dumpfile created above to a different Server
$ sudo apt-get install pigz pv
$ zcat /path/to/folder/<dbname>_`date +\%Y\%m\%d_\%H\%M`.sql.gz | pv | mysql --user=<yourdbuser> --password=<yourdbpassword> --database=<yournewdatabasename> --compress --reconnect --unbuffered --net_buffer_length=1048576 --max_allowed_packet=1073741824 --connect_timeout=36000 --line-numbers --wait --init-command="SET GLOBAL net_buffer_length=1048576;SET GLOBAL max_allowed_packet=1073741824;SET FOREIGN_KEY_CHECKS=0;SET UNIQUE_CHECKS = 0;SET AUTOCOMMIT = 1;FLUSH NO_WRITE_TO_BINLOG QUERY CACHE, STATUS, SLOW LOGS, GENERAL LOGS, ERROR LOGS, ENGINE LOGS, BINARY LOGS, LOGS;"
Optional: Command Arguments for connection
--host=127.0.0.1 / localhost / IP Address of the Import Server
--port=3306
mysql: [Warning] Using a password on the command line interface can be insecure. 1.0GiB 00:06:51 [8.05MiB/s] [<=> ]
The optional software packages are helpful to import your database SQL file faster
for faster zipping of the output
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
You need to break;
, throw
, goto
, or return
from each of your case labels. In a loop you may also continue
.
switch (searchType)
{
case "SearchBooks":
Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
break;
case "SearchAuthors":
Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
break;
}
The only time this isn't true is when the case labels are stacked like this:
case "SearchBooks": // no code inbetween case labels.
case "SearchAuthors":
// handle both of these cases the same way.
break;
by XML:
<EditText
android:id="@+id/search_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/search"
android:imeOptions="actionSearch"
android:inputType="text" />
By Java:
editText.clearFocus();
InputMethodManager in = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
My opinion,
Task.Delay()
is asynchronous. It doesn't block the current thread. You can still do other operations within current thread. It returns a Task return type (Thread.Sleep()
doesn't return anything ). You can check if this task is completed(use Task.IsCompleted
property) later after another time-consuming process.
Thread.Sleep()
doesn't have a return type. It's synchronous. In the thread, you can't really do anything other than waiting for the delay to finish.
As for real-life usage, I have been programming for 15 years. I have never used Thread.Sleep()
in production code. I couldn't find any use case for it.
Maybe that's because I mostly do web application development.
The following example builds on MARTIN DE LA FUENTE SAAVEDRA's excellent work and accepted answer. In particular, two enumerations are introduced. The first allows for easy specification of how an elevated program is to be opened, and the second helps when errors need to be easily identified. Please note that if you want all command line arguments passed to the new process, sys.argv[0]
should probably be replaced with a function call: subprocess.list2cmdline(sys.argv)
.
#! /usr/bin/env python3
import ctypes
import enum
import subprocess
import sys
# Reference:
# msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx
# noinspection SpellCheckingInspection
class SW(enum.IntEnum):
HIDE = 0
MAXIMIZE = 3
MINIMIZE = 6
RESTORE = 9
SHOW = 5
SHOWDEFAULT = 10
SHOWMAXIMIZED = 3
SHOWMINIMIZED = 2
SHOWMINNOACTIVE = 7
SHOWNA = 8
SHOWNOACTIVATE = 4
SHOWNORMAL = 1
class ERROR(enum.IntEnum):
ZERO = 0
FILE_NOT_FOUND = 2
PATH_NOT_FOUND = 3
BAD_FORMAT = 11
ACCESS_DENIED = 5
ASSOC_INCOMPLETE = 27
DDE_BUSY = 30
DDE_FAIL = 29
DDE_TIMEOUT = 28
DLL_NOT_FOUND = 32
NO_ASSOC = 31
OOM = 8
SHARE = 26
def bootstrap():
if ctypes.windll.shell32.IsUserAnAdmin():
main()
else:
# noinspection SpellCheckingInspection
hinstance = ctypes.windll.shell32.ShellExecuteW(
None,
'runas',
sys.executable,
subprocess.list2cmdline(sys.argv),
None,
SW.SHOWNORMAL
)
if hinstance <= 32:
raise RuntimeError(ERROR(hinstance))
def main():
# Your Code Here
print(input('Echo: '))
if __name__ == '__main__':
bootstrap()
This was the best solution I found after more time than I care to admit. Basically, add target="_self" to each link that you need to insure a page reload.
http://blog.panjiesw.com/posts/2013/09/angularjs-normal-links-with-html5mode/
Use:
find . 2>/dev/null > files_and_folders
This hides not just the Permission denied
errors, of course, but all error messages.
If you really want to keep other possible errors, such as too many hops on a symlink, but not the permission denied ones, then you'd probably have to take a flying guess that you don't have many files called 'permission denied' and try:
find . 2>&1 | grep -v 'Permission denied' > files_and_folders
If you strictly want to filter just standard error, you can use the more elaborate construction:
find . 2>&1 > files_and_folders | grep -v 'Permission denied' >&2
The I/O redirection on the find
command is: 2>&1 > files_and_folders |
.
The pipe redirects standard output to the grep
command and is applied first. The 2>&1
sends standard error to the same place as standard output (the pipe). The > files_and_folders
sends standard output (but not standard error) to a file. The net result is that messages written to standard error are sent down the pipe and the regular output of find
is written to the file. The grep
filters the standard output (you can decide how selective you want it to be, and may have to change the spelling depending on locale and O/S) and the final >&2
means that the surviving error messages (written to standard output) go to standard error once more. The final redirection could be regarded as optional at the terminal, but would be a very good idea to use it in a script so that error messages appear on standard error.
There are endless variations on this theme, depending on what you want to do. This will work on any variant of Unix with any Bourne shell derivative (Bash, Korn, …) and any POSIX-compliant version of find
.
If you wish to adapt to the specific version of find
you have on your system, there may be alternative options available. GNU find
in particular has a myriad options not available in other versions — see the currently accepted answer for one such set of options.
A combination of @Jack's answer and @ranierbit's answer should do the trick.
Set the ng build flag for --output-hashing so:
ng build --output-hashing=all
Then add this class either in a service or in your app.module
@Injectable()
export class NoCacheHeadersInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authReq = req.clone({
setHeaders: {
'Cache-Control': 'no-cache',
Pragma: 'no-cache'
}
});
return next.handle(authReq);
}
}
Then add this to your providers in your app.module
:
providers: [
... // other providers
{
provide: HTTP_INTERCEPTORS,
useClass: NoCacheHeadersInterceptor,
multi: true
},
... // other providers
]
This should prevent caching issues on live sites for client machines
reVerse's answer is great but it didn't point out how to remove the floating error tooltip kind of thing
You'll need edittext.setError(null)
to remove that.
Also, as someone pointed out, you don't need TextInputLayout.setErrorEnabled(true)
Layout
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter something" />
</android.support.design.widget.TextInputLayout>
Code
TextInputLayout til = (TextInputLayout) editText.getParent();
til.setError("Your input is not valid...");
editText.setError(null);
The only way I could do it in VS 2010 IDE was to highlight the block of code and hit ctrl-E and then C
Try this:
<meta http-equiv="refresh" content="5;URL= your url">
or
<meta http-equiv="refresh" content="5">