I found slimier problem. Please import the HttpClientModule in your app.module.ts file as follow:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
You can try the following and it worked for me.
Import following scripts and css files as there are used by the date picker.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
The JS coding for the Date Picker I use.
<script>
$(document).ready(function(){
// alert ('Cliecked');
var date_input=$('input[name="orangeDateOfBirthForm"]'); //our date input has the name "date"
var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
var options={
format: 'dd/mm/yyyy', //format of the date
container: container,
changeYear: true, // you can change the year as you need
changeMonth: true, // you can change the months as you need
todayHighlight: true,
autoclose: true,
yearRange: "1930:2100" // the starting to end of year range
};
date_input.datepicker(options);
});
</script>
The HTML Coding:
<input type="text" id="orangeDateOfBirthForm" name="orangeDateOfBirthForm" class="form-control validate" required>
<label data-error="wrong" data-success="right" for="orangeForm-email">Date of Birth</label>
PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.
Alternatively, try MobaXterm. It has an X server builtin.
Technically, the Integrity attribute helps with just that - it enables the proper verification of the data source. That is, it merely allows the browser to verify the numbers in the right source file with the amounts requested by the source file located on the CDN server.
Going a bit deeper, in case of the established encrypted hash value of this source and its checked compliance with a predefined value in the browser - the code executes, and the user request is successfully processed.
Crossorigin attribute helps developers optimize the rates of CDN performance, at the same time, protecting the website code from malicious scripts.
In particular, Crossorigin downloads the program code of the site in anonymous mode, without downloading cookies or performing the authentication procedure. This way, it prevents the leak of user data when you first load the site on a specific CDN server, which network fraudsters can easily replace addresses.
Source: https://yon.fun/what-is-link-integrity-and-crossorigin/
JQUERY FORM VALIDATION CUSTOM ERROR MESSAGE
$(document).ready(function(){_x000D_
$("#registration").validate({_x000D_
// Specify validation rules_x000D_
rules: {_x000D_
firstname: "required",_x000D_
lastname: "required",_x000D_
email: {_x000D_
required: true,_x000D_
email: true_x000D_
}, _x000D_
phone: {_x000D_
required: true,_x000D_
digits: true,_x000D_
minlength: 10,_x000D_
maxlength: 10,_x000D_
},_x000D_
password: {_x000D_
required: true,_x000D_
minlength: 5,_x000D_
}_x000D_
},_x000D_
messages: {_x000D_
firstname: {_x000D_
required: "Please enter first name",_x000D_
}, _x000D_
lastname: {_x000D_
required: "Please enter last name",_x000D_
}, _x000D_
phone: {_x000D_
required: "Please enter phone number",_x000D_
digits: "Please enter valid phone number",_x000D_
minlength: "Phone number field accept only 10 digits",_x000D_
maxlength: "Phone number field accept only 10 digits",_x000D_
}, _x000D_
email: {_x000D_
required: "Please enter email address",_x000D_
email: "Please enter a valid email address.",_x000D_
},_x000D_
},_x000D_
_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>jQuery Form Validation Using validator()</title>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> _x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>_x000D_
<style>_x000D_
.error{_x000D_
color: red;_x000D_
}_x000D_
label,_x000D_
input,_x000D_
button {_x000D_
border: 0;_x000D_
margin-bottom: 3px;_x000D_
display: block;_x000D_
width: 100%;_x000D_
}_x000D_
.common_box_body {_x000D_
padding: 15px;_x000D_
border: 12px solid #28BAA2;_x000D_
border-color: #28BAA2;_x000D_
border-radius: 15px;_x000D_
margin-top: 10px;_x000D_
background: #d4edda;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="common_box_body test">_x000D_
<h2>Registration</h2>_x000D_
<form action="#" name="registration" id="registration">_x000D_
_x000D_
<label for="firstname">First Name</label>_x000D_
<input type="text" name="firstname" id="firstname" placeholder="John"><br>_x000D_
_x000D_
<label for="lastname">Last Name</label>_x000D_
<input type="text" name="lastname" id="lastname" placeholder="Doe"><br>_x000D_
_x000D_
<label for="phone">Phone</label>_x000D_
<input type="text" name="phone" id="phone" placeholder="8889988899"><br> _x000D_
_x000D_
<label for="email">Email</label>_x000D_
<input type="email" name="email" id="email" placeholder="[email protected]"><br>_x000D_
_x000D_
<label for="password">Password</label>_x000D_
<input type="password" name="password" id="password" placeholder=""><br>_x000D_
_x000D_
<input name="submit" type="submit" id="submit" class="submit" value="Submit">_x000D_
</form>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
I know this is an old post but I had a lot of issues trying to solve this and I finally did so I wanted to share.
My issue was that I was adding an event listener within the ontouchstart and removing it in the ontouchend functions - something like this
function onTouchStart() {
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
}
function onTouchEnd() {
window.removeEventListener("touchmove", handleTouchMove, {
passive: true
});
}
function handleTouchMove(e) {
e.preventDefault();
}
For some reason adding it removing it like this was causing this issue of the event randomly not being cancelable. So to solve this I kept the listener active and toggled a boolean on whether or not it should prevent the event - something like this:
let stopScrolling = false;
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
function handleTouchMove(e) {
if (!stopScrolling) {
return;
}
e.preventDefault();
}
function onTouchStart() {
stopScrolling = true;
}
function onTouchEnd() {
stopScrolling = false;
}
I was actually using React so my solution involved setting state, but I've simplified it for a more generic solution. Hopefully this helps someone!
This works, been tested...
SELECT n.c.value('OrganizationReportReferenceIdentifier[1]','varchar(128)') AS 'OrganizationReportReferenceNumber',
n.c.value('(OrganizationNumber)[1]','varchar(128)') AS 'OrganizationNumber'
FROM Batches t
Cross Apply RawXML.nodes('/GrobXmlFile/Grob/ReportHeader') n(c)
Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:
00 00 00 07
: four byte length prefix (7 bytes)73 73 68 2d 72 73 61
: "ssh-rsa"00 00 00 01
: four byte length prefix (1 byte)25
: RSA Exponent (e
): 2500 00 01 00
: four byte length prefix (256 bytes)RSA Modulus (n
):
7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46
dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9
cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32
70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60
1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1
90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d
3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0
e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb
d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b
ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d
e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8
76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1
fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f
5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b
60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b
The closest validation of my theory i can find it from RFC 4253:
The "ssh-rsa" key format has the following specific encoding:
string "ssh-rsa" mpint e mpint n
Here the 'e' and 'n' parameters form the signature key blob.
But it doesn't explain the length prefixes.
Taking the random RSA PUBLIC KEY
i found (in the question), and decoding the base64 into hex:
30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a
63 02 03 01 00 01
From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:
A.1.1 RSA public key syntax
An RSA public key should be represented with the ASN.1 type
RSAPublicKey
:RSAPublicKey ::= SEQUENCE { modulus INTEGER, -- n publicExponent INTEGER -- e }
The fields of type RSAPublicKey have the following meanings:
- modulus is the RSA modulus n.
- publicExponent is the RSA public exponent e.
Using Microsoft's excellent (and the only real) ASN.1 documentation:
30 82 01 0a ;SEQUENCE (0x010A bytes: 266 bytes)
| 02 82 01 01 ;INTEGER (0x0101 bytes: 257 bytes)
| | 00 ;leading zero because high-bit, but number is positive
| | fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68
| | e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e
| | 11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d
| | dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80
| | fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94
| | 23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0
| | 9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3
| | 4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd
| | 41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e
| | 97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f
| | fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a
| | 63
| 02 03 ;INTEGER (3 bytes)
| 01 00 01
giving the public key modulus and exponent:
0xfb1199ff0733f6e805a4fd3b36ca68...837a63
First, if you develop an application with Java EE 6 within a server (JBoss), you should better use a DataSource. Then you can obtain the Connection from this DataSource. It's better to use connections pools.
Then, as of JBoss AS 7, the JDBC driver must be declared as a module. This is described here.
With OJDBC 6 (11.x), the name of the driver should be "oracle.jdbc.OracleDriver".
This is the name registered in SPI mode (see the content of this file : META-INF/services/java.sql.Driver).
Since Java 6 and JDBC 4.0, the JDBC Drivers are auto-registered.
Finally you will have to declare a DataSource within JBoss : DataSource configuration.
References :
If you're triggering your code from Jenkins, enabling the option "Start Xvfb before the build, and shut it down after" might help. It helped me.
I would use xlrd - it's faster, cross platform and works directly with the file. One thing to note - it doesn't work on xlsx files - so you'd have to save your Excel file as xls. Edit: As of version 0.8.0, xlrd
reads both XLS and XLSX files.
import xlrd
import csv
def csv_from_excel():
wb = xlrd.open_workbook('your_workbook.xls')
sh = wb.sheet_by_name('Sheet1')
your_csv_file = open('your_csv_file.csv', 'wb')
wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
for rownum in xrange(sh.nrows):
wr.writerow(sh.row_values(rownum))
your_csv_file.close()
You should have access to the POST dictionary on the request object.
Me too got this error, When I change my WPF project's Target Framework to Framework Version 4.0 Client Profile -> Framework 4.0. It's solved by itself.
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
Instead of killing the window manager, try running the new one with --replace
or -replace
if available.
You might want to explore using the data URI. It would look something like.
window.open("data:application/pdf," + escape(pdfString));
I wasn't immediately able to get this to work, possible because formating of the binary string provided. I also usually use base64 encoded data when using the data URI. If you are able to pass the content from the backend encoded you can use..
window.open("data:application/pdf;base64, " + base64EncodedPDF);
Hopefully this is the right direction for what you need. Also note this will not work at all in IE6/7 because they do not support Data URIs.
Here is what i did for logback.
I created a TestAppender class:
public class TestAppender extends AppenderBase<ILoggingEvent> {
private Stack<ILoggingEvent> events = new Stack<ILoggingEvent>();
@Override
protected void append(ILoggingEvent event) {
events.add(event);
}
public void clear() {
events.clear();
}
public ILoggingEvent getLastEvent() {
return events.pop();
}
}
Then in the parent of my testng unit test class I created a method:
protected TestAppender testAppender;
@BeforeClass
public void setupLogsForTesting() {
Logger root = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
testAppender = (TestAppender)root.getAppender("TEST");
if (testAppender != null) {
testAppender.clear();
}
}
I have a logback-test.xml file defined in src/test/resources and I added a test appender:
<appender name="TEST" class="com.intuit.icn.TestAppender">
<encoder>
<pattern>%m%n</pattern>
</encoder>
</appender>
and added this appender to the root appender:
<root>
<level value="error" />
<appender-ref ref="STDOUT" />
<appender-ref ref="TEST" />
</root>
Now in my test classes that extend from my parent test class I can get the appender and get the last message logged and verify the message, the level, the throwable.
ILoggingEvent lastEvent = testAppender.getLastEvent();
assertEquals(lastEvent.getMessage(), "...");
assertEquals(lastEvent.getLevel(), Level.WARN);
assertEquals(lastEvent.getThrowableProxy().getMessage(), "...");
MVC 4 @Html.CheckBoxFor generally people want to action on check and uncheck of mvc checkbox.
<div class="editor-field"> @Html.CheckBoxFor(model => model.IsAll, new { id = "cbAllEmp" }) </div>
you can define id for the controls you want to change and in javascript do the folowing
<script type="text/javascript">
$(function () {
$("#cbAllEmp").click("", function () {
if ($("#cbAllEmp").prop("checked") == true) {
$("#txtEmpId").hide();
$("#lblEmpId").hide();
}
else {
$("#txtEmpId").show();
$("#txtEmpId").val("");
$("#lblEmpId").show();
}
});
});
you can also change the property like
$("#txtEmpId").prop("disabled", true);
$("#txtEmpId").prop("readonly", true);
I agree with Sam in that the SOAP definition does not match what is expected. Here is just ONE solution it could be, I had to manually figure this error for myself:
My problem was that I changed the name of the web method but did not change the "MessageName" in the metadata tag.
[WebMethod(MessageName = "foo")]
public string bar()
{
}
It should be
[WebMethod(MessageName = "foo")]
public string foo()
{
}
hope that helps someone
Update in 2019:
This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.
Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!
Another nice approach can be seen here: http://blogs.microsoft.co.il/blogs/eladkatz/archive/2011/05/29/what-is-the-easiest-way-to-set-spacing-between-items-in-stackpanel.aspx Link is broken -> this is webarchive of this link.
It shows how to create an attached behavior, so that syntax like this would work:
<StackPanel local:MarginSetter.Margin="5">
<TextBox Text="hello" />
<Button Content="hello" />
<Button Content="hello" />
</StackPanel>
This is the easiest & fastest way to set Margin to several children of a panel, even if they are not of the same type. (I.e. Buttons, TextBoxes, ComboBoxes, etc.)
Also the $wshell = New-Object -ComObject wscript.shell;
helped a script that was running in the background, it worked fine with just but adding $wshell
. fixed it from running as background! [Microsoft.VisualBasic.Interaction]::AppActivate("App Name")
There are 3 ways to solve this issue while development. Any one from below can solve this issue.
1) provide the changes in new migration sql file with incrementing version
2) change the schema name in db url we provide
datasource.flyway.url=jdbc:h2:file:~/cart3
datasource.flyway.url=jdbc:h2:file:~/cart4
3) delete the .mv and .trace files in users home directory
ex: cart3.mv and cart3.trace under c://users/username/
Good question.
True regular languages can not decide arbitrarily deeply nested well-formed parenthesis. If your alphabet contains '('
and ')'
the goal is to decide if a string of these has well-formed matching parenthesis. Since this is a necessary requirement for regular expressions the answer is no.
However, if you loosen the requirement and add recursion you can probably do it. The reason is that the recursion can act as a stack letting you "count" the current nesting depth by pushing onto this stack.
Russ Cox wrote "Regular Expression Matching Can Be Simple And Fast" which is a wonderful treatise on regex engine implementation.
Why dont you just use addAll
method:
List a = new ArrayList();
a.add("1");
a.add("abc");
List b = b.addAll(listA);
//b will be 1, abc
even if you have existing items in b or you want to pend some elements after it, such as:
List a = new ArrayList();
a.add("1");
a.add("abc");
List b = new ArrayList();
b.add("x");
b.addAll(listA);
b.add("Y");
//b will be x, 1, abc, Y
Actually I don't like the GOTO command too, but it's in official Microsoft materials, and here are all allowed syntaxes.
If the end point of the statement list of a switch section is reachable, a compile-time error occurs. This is known as the "no fall through" rule. The example
switch (i) {
case 0:
CaseZero();
break;
case 1:
CaseOne();
break;
default:
CaseOthers();
break;
}
is valid because no switch section has a reachable end point. Unlike C and C++, execution of a switch section is not permitted to "fall through" to the next switch section, and the example
switch (i) {
case 0:
CaseZero();
case 1:
CaseZeroOrOne();
default:
CaseAny();
}
results in a compile-time error. When execution of a switch section is to be followed by execution of another switch section, an explicit goto case or goto default statement must be used:
switch (i) {
case 0:
CaseZero();
goto case 1;
case 1:
CaseZeroOrOne();
goto default;
default:
CaseAny();
break;
}
Multiple labels are permitted in a switch-section. The example
switch (i) {
case 0:
CaseZero();
break;
case 1:
CaseOne();
break;
case 2:
default:
CaseTwo();
break;
}
I believe in this particular case, the GOTO can be used, and it's actually the only way to fallthrough.
This is not an answer, but too long for a comment.
In reply to JP's answers / comments, I have run the following test to compare the performance of the 2 methods. The Profiler
object is a custom class - but in summary, it uses a kernel32 function which is fairly accurate (Private Declare Sub GetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)
).
Sub test()
Dim origNum As String
Dim creditOrDebit As String
Dim b As Boolean
Dim p As Profiler
Dim i As Long
Set p = New_Profiler
origNum = "30062600006"
creditOrDebit = "D"
p.startTimer ("nested_ifs")
For i = 1 To 1000000
If creditOrDebit = "D" Then
If origNum = "006260006" Then
b = True
ElseIf origNum = "30062600006" Then
b = True
End If
End If
Next i
p.stopTimer ("nested_ifs")
p.startTimer ("or_and")
For i = 1 To 1000000
If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
b = True
End If
Next i
p.stopTimer ("or_and")
p.printReport
End Sub
The results of 5 runs (in ms for 1m loops):
20-Jun-2012 19:28:25
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 12520-Jun-2012 19:28:26
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 12520-Jun-2012 19:28:27
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 125 - Last Run: 125 - Average Run: 12520-Jun-2012 19:28:28
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 141 - Last Run: 141 - Average Run: 14120-Jun-2012 19:28:29
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125
Note
If creditOrDebit
is not "D"
, JP's code runs faster (around 60ms vs. 125ms for the or/and code).
It require to include Content-Type:application/json
in web api request header section when not mention any content then by default it is Content-Type:text/plain
passes to request.
Best way to test api on postman tool.
Here's a an answer how to find country calling code without using third-party libraries (as real developer does):
Get list of all available country codes, Wikipedia can help here: https://en.wikipedia.org/wiki/List_of_country_calling_codes
Parse data in a tree structure where each digit is a branch.
Traverse your tree digit by digit until you are at the last branch - that's your country code.
To piggypack on Ben's answer on how to solve this problem using lodash's _.pickBy
, you can also solve this problem in the sister library: Underscore.js's _.pick
.
var obj = {name: 'John', age: null};
var compacted = _.pick(obj, function(value) {
return value !== null && value !== undefined;
});
See: JSFiddle Example
You need to apply the following CSS property to the container block (div):
overflow-wrap: break-word;
According to the specifications (source CSS | MDN):
The
overflow-wrap
CSS property specifies whether or not the browser should insert line breaks within words to prevent text from overflowing its content box.
With the value set to break-word
To prevent overflow, normally unbreakable words may be broken at arbitrary points if there are no otherwise acceptable break points in the line.
Worth mentioning...
The property was originally a nonstandard and unprefixed Microsoft extension called
word-wrap
, and was implemented by most browsers with the same name. It has since been renamed tooverflow-wrap
, withword-wrap
being an alias.
If you care about legacy browsers support it's worth specifying both:
word-wrap : break-word;
overflow-wrap: break-word;
Ex. IE9 does not recognize overflow-wrap
but works fine with word-wrap
$("#example").dataTable(
{
"aoColumnDefs": [{
"bSortable": false,
"aTargets": [0, 1, 2, 3, 4, 5]
}]
}
);
Its a old question, but lets to show in the REST way (JAX-RS):
import java.util.Arrays;
import javax.ws.rs.*
(...)
Response response = client
.target( url )
.request()
.get();
// Looking if response is "200", "201" or "202", for example:
if( Arrays.asList( Status.OK, Status.CREATED, Status.ACCEPTED ).contains( response.getStatusInfo() ) ) {
// lets something...
}
(...)
there are several good answers here. to summarize what is already here and correct: using contains, startswith, endswith are good answers for most needs. regular expressions are what you want for more advanced needs.
something that is not mentioned in these answers, though, is that for a collection of strings, linq can be used to apply these filters in a call to the where method.
Right click on the file in your solution explorer and make sure it's build action is set to "C# Compiler"
Solution Explorer --> Right Click File --> "Properties" --> Build Action = "C# Compiler"
I would just like to add that if the String is originally encoded using the wrong encoding it might be impossible to change it to another encoding without errors. The question does not state that the conversion here is made from wrong encoding to correct encoding but I personally stumbled to this question just because of this situation so just a heads up for others as well.
This answer in other question gives an explanation why the conversion does not always yield correct results https://stackoverflow.com/a/2623793/4702806
public static void main(String[] args){
ArrayList<Object> al = new ArrayList<Object>();
al.add("abc");
al.add('a');
al.add('b');
al.add('a');
al.add("abc");
al.add(10.3);
al.add('c');
al.add(10);
al.add("abc");
al.add(10);
System.out.println("Before Duplicate Remove:"+al);
for(int i=0;i<al.size();i++){
for(int j=i+1;j<al.size();j++){
if(al.get(i).equals(al.get(j))){
al.remove(j);
j--;
}
}
}
System.out.println("After Removing duplicate:"+al);
}
Remove the width:100%;
declarations.
Block elements should take up the whole available width by default.
I installed php-soap to CentOS Linux release 7.1.1503 (Core) using following way.
1) yum install php-soap
================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
php-soap x86_64 5.4.16-36.el7_1 base 157 k
Updating for dependencies:
php x86_64 5.4.16-36.el7_1 base 1.4 M
php-cli x86_64 5.4.16-36.el7_1 base 2.7 M
php-common x86_64 5.4.16-36.el7_1 base 563 k
php-devel x86_64 5.4.16-36.el7_1 base 600 k
php-gd x86_64 5.4.16-36.el7_1 base 126 k
php-mbstring x86_64 5.4.16-36.el7_1 base 503 k
php-mysql x86_64 5.4.16-36.el7_1 base 99 k
php-pdo x86_64 5.4.16-36.el7_1 base 97 k
php-xml x86_64 5.4.16-36.el7_1 base 124 k
Transaction Summary
================================================================================
Install 1 Package
Upgrade ( 9 Dependent packages)
Total download size: 6.3 M
Is this ok [y/d/N]: y
Downloading packages:
------
------
------
Installed:
php-soap.x86_64 0:5.4.16-36.el7_1
Dependency Updated:
php.x86_64 0:5.4.16-36.el7_1 php-cli.x86_64 0:5.4.16-36.el7_1
php-common.x86_64 0:5.4.16-36.el7_1 php-devel.x86_64 0:5.4.16-36.el7_1
php-gd.x86_64 0:5.4.16-36.el7_1 php-mbstring.x86_64 0:5.4.16-36.el7_1
php-mysql.x86_64 0:5.4.16-36.el7_1 php-pdo.x86_64 0:5.4.16-36.el7_1
php-xml.x86_64 0:5.4.16-36.el7_1
Complete!
2) yum search php-soap
============================ N/S matched: php-soap =============================
php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
3) service httpd restart
To verify run following
4) php -m | grep -i soap
soap
form.reset()
is a DOM element method (not one on the jQuery object), so you need:
$("#client.frm")[0].reset();
//faster version:
$("#client")[0].reset();
Or without jQuery:
document.getElementById("client").reset();
This should work:
SELECT * FROM Accounts WHERE Username LIKE '%$query%'
Abderrahmane response is correct: add ?createDatabaseIfNotExist=true
in the url property.
It seems that ddl-auto
won't do anything.
You can also do this in ASP.NET Core 2 by defining the connection string in your appSettings.json
file. Then in your Startup.cs
you specify which connection string to use.
appSettings.json
{
"connectionStrings": {
"YourDBConnectionString": "Server=(localdb)\\mssqllocaldb;Database=YourDB;Trusted_Connection=True"
}
}
Startup.cs
public static IConfiguration Configuration { get; private set;}
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
var connectionString = Configuration["connectionStrings:YourDBConnectionString"];
services.AddDbContext<YourDbContext>(x => x.UseSqlServer(connectionString));
The default constructor has no arguments. You need to specify a constructor:
public Friends( String firstName, String age) { ... }
Try Atatus which provides Advanced Error Tracking and Real User Monitoring for modern web apps.
Let me explain how to get stacktraces that are reasonably complete in all browsers.
Modern Chrome and Opera fully support the HTML 5 draft spec for ErrorEvent and window.onerror
. In both of these browsers you can either use window.onerror
, or bind to the 'error' event properly:
// Only Chrome & Opera pass the error object.
window.onerror = function (message, file, line, col, error) {
console.log(message, "from", error.stack);
// You can send data to your server
// sendError(data);
};
// Only Chrome & Opera have an error attribute on the event.
window.addEventListener("error", function (e) {
console.log(e.error.message, "from", e.error.stack);
// You can send data to your server
// sendError(data);
})
Unfortunately Firefox, Safari and IE are still around and we have to support them too. As the stacktrace is not available in window.onerror
we have to do a little bit more work.
It turns out that the only thing we can do to get stacktraces from errors is to wrap all of our code in a try{ }catch(e){ }
block and then look at e.stack
. We can make the process somewhat easier with a function called wrap that takes a function and returns a new function with good error handling.
function wrap(func) {
// Ensure we only wrap the function once.
if (!func._wrapped) {
func._wrapped = function () {
try{
func.apply(this, arguments);
} catch(e) {
console.log(e.message, "from", e.stack);
// You can send data to your server
// sendError(data);
throw e;
}
}
}
return func._wrapped;
};
This works. Any function that you wrap manually will have good error handling, but it turns out that we can actually do it for you automatically in most cases.
By changing the global definition of addEventListener
so that it automatically wraps the callback we can automatically insert try{ }catch(e){ }
around most code. This lets existing code continue to work, but adds high-quality exception tracking.
var addEventListener = window.EventTarget.prototype.addEventListener;
window.EventTarget.prototype.addEventListener = function (event, callback, bubble) {
addEventListener.call(this, event, wrap(callback), bubble);
}
We also need to make sure that removeEventListener
keeps working. At the moment it won't because the argument to addEventListener
is changed. Again we only need to fix this on the prototype
object:
var removeEventListener = window.EventTarget.prototype.removeEventListener;
window.EventTarget.prototype.removeEventListener = function (event, callback, bubble) {
removeEventListener.call(this, event, callback._wrapped || callback, bubble);
}
You can send error data using image tag as follows
function sendError(data) {
var img = newImage(),
src = 'http://yourserver.com/jserror&data=' + encodeURIComponent(JSON.stringify(data));
img.crossOrigin = 'anonymous';
img.onload = function success() {
console.log('success', data);
};
img.onerror = img.onabort = function failure() {
console.error('failure', data);
};
img.src = src;
}
Disclaimer: I am a web developer at https://www.atatus.com/.
Use the bash built-in variable SECONDS
. Each time you reference the variable it will return the elapsed time since the script invocation.
Example:
echo "Start $SECONDS"
sleep 10
echo "Middle $SECONDS"
sleep 10
echo "End $SECONDS"
Output:
Start 0
Middle 10
End 20
To add a column using a UDF:
df = sqlContext.createDataFrame(
[(1, "a", 23.0), (3, "B", -23.0)], ("x1", "x2", "x3"))
from pyspark.sql.functions import udf
from pyspark.sql.types import *
def valueToCategory(value):
if value == 1: return 'cat1'
elif value == 2: return 'cat2'
...
else: return 'n/a'
# NOTE: it seems that calls to udf() must be after SparkContext() is called
udfValueToCategory = udf(valueToCategory, StringType())
df_with_cat = df.withColumn("category", udfValueToCategory("x1"))
df_with_cat.show()
## +---+---+-----+---------+
## | x1| x2| x3| category|
## +---+---+-----+---------+
## | 1| a| 23.0| cat1|
## | 3| B|-23.0| n/a|
## +---+---+-----+---------+
If you use Git Extensions GUI it can show you a graphical visualization of dangling commits if you check "View -> Show reflog references". This will show dangling commits in the tree, just like all other referenced ones. This way it is way easier to find what you are looking for.
See this image for demonstration. Commits C2, C3, C4, and C5 on the image are dangling but still visible.
Also, you can use this...
DECLARE @SeqID varchar(150);
DECLARE @TableName varchar(150);
SET @TableName = (Select TableName from Table);
SET @SeqID = 'SELECT NEXT VALUE FOR ' + @TableName + '_Data'
exec (@SeqID)
head
works too:
head -c 100 file # returns the first 100 bytes in the file
..will extract the first 100 bytes and return them.
What's nice about using head
for this is that the syntax for tail
matches:
tail -c 100 file # returns the last 100 bytes in the file
You can combine these to get ranges of bytes. For example, to get the second 100 bytes from a file, read the first 200 with head
and use tail to get the last 100:
head -c 200 file | tail -c 100
<script type = "text/javascript">
function get_values(input_id)
{
var input = document.getElementById(input_id).value;
document.write(input);
}
</script>
<!--Insert more code here-->
<input type = "text" id = "textfield">
<input type = "button" onclick = "get('textfield')" value = "submit">
Next time you ask a question here, include more detail and what you have tried.
The webpages on an online server reside in a location which looks somewhat like this: http://www.somerandomsite.com/index.php
Since xampp is Offline, it sets up a local server whose address is like this
http://localhost/
Basically, xampp sets up a server (apache and others) in your system. And all the files such as index.php, somethingelse.php, etc., reside in the xampp\htdocs\
folder.
The browser locates the server in localhost and will search through the above folder for any resources available in there.
So create any number of folders inside the "xampp\htdocs\" each folder thus forming a website (as you build it).
Sometimes apache won't even start. This is due to the clashing of ports with some applications. Some of them I commonly encounter is Skype. See to that it is killed completely and restart apache
In CLI
$ webpack --version
webpack-cli 4.1.0
webpack 5.3.2
In Code (node runtime)
process.env.npm_package_devDependencies_webpack // ^5.3.2
or
process.env.npm_package_dependencies_webpack // ^5.3.2
In Plugin
compiler.webpack.version // 5.3.2
Neither. You set the isolation level to READ UNCOMMITTED
which is always better than giving individual lock hints. Or, better still, if you care about details like consistency, use snapshot isolation.
USE YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES
('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)
Strictly speaking you shouldn't need to use !important if you've structured your CSS well and don't have too many degrees of specificity.
The most appropriate time to use !important is when you have one exceptional style that you want to style outside of your site's normal cascade.
You can also use List's inbuilt foreach, such as:
List<T>.ForEach(item => Console.Write(item));
This code also runs significantly faster!
The above code also makes you able to manipulate Console.WriteLine, such as doing:
List<T>.ForEach(item => Console.Write(item + ",")); //Put a,b etc.
Yes, jQuery
can be used with Node.js
.
Steps to include jQuery in node project:-
npm i jquery --save
Include jquery in codes
import jQuery from 'jquery';
const $ = jQuery;
I do use jquery in node.js projects all the time specifically in the chrome extension's project.
e.g. https://github.com/fxnoob/gesture-control-chrome-extension/blob/master/src/default_plugins/tab.js
Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.
For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".
Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html
Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx
I had to work a bit to make this fit my use case.
I have a form where all fields must have a value before submitting.
Here's what I did:
$(document).ready(function() {
$('#form_id button[type="submit"]').prop('disabled', true);
$('#form_id input, #form_id select').keyup(function() {
var disable = false;
$('#form_id input, #form_id select').each(function() {
if($(this).val() == '') { disable = true };
});
$('#form_id button[type="submit"]').prop('disabled', disable);
});
});
Thanks to everyone for their answers here.
It is a file ext that some folks used for a while to denote that it was PHP generated HTML. As servers like Apache don't care what you use as a file ext as long as it is mapped to something, you could go ahead and call all your PHP files .jimyBobSmith and it would happily run them. PHTML just happened to be a trend that caught on for a while.
I would fire up Visual Studio, create a web project (or console app - doesn't matter).
For .Net Standard:
If there is no error, you should simply set the NameSpace you want to use to access the service and it'll be generated for you.
For .Net Core
Any of the methods above will generate a simple, very basic WCF client for you to use. You should find a "YourservicenameClient" class in the generated code.
For reference purpose, the generated cs file can be found in your Obj/debug(or release)/XsdGeneratedCode and you can still find the dlls in the TempPE folder.
The created Service(s) should have methods for each of the defined methods on the WSDL contract.
Instantiate the client and call the methods you want to call - that's all there is!
YourServiceClient client = new YourServiceClient();
client.SayHello("World!");
If you need to specify the remote URL (not using the one created by default), you can easily do this in the constructor of the proxy client:
YourServiceClient client = new YourServiceClient("configName", "remoteURL");
where configName
is the name of the endpoint to use (you will use all the settings except the URL), and the remoteURL
is a string representing the URL to connect to (instead of the one contained in the config).
I Did that and it works for redirecting to other view I think If you add the #sectionLink after It will work
<a class="btn yellow" href="/users/Create/@Model.Id" target="_blank">
Add As User
</a>
It's better (but wordier) to use:
var element = document.getElementById('something');
if (element != null && element.value == '') {
}
Please note, the first version of my answer was wrong:
var element = document.getElementById('something');
if (typeof element !== "undefined" && element.value == '') {
}
because getElementById()
always return an object (null object if not found) and checking for"undefined"
would never return a false
, as typeof null !== "undefined"
is still true
.
this can be achieved with the css calc()
operator
@media screen and (min-width: 480px) {
body {
background-color: lightgreen;
zoom:calc(100% / 480);
}
}
Bit late to the party but above solutions did not work for me , so sharing my 0.02$
Mokcito version: 1.10.19
MyClass.java
private int handleAction(List<String> argList, String action)
Test.java
MyClass spy = PowerMockito.spy(new MyClass());
1.
doReturn(0).when(spy , "handleAction", ListUtils.EMPTY_LIST, new String());
2.
doReturn(0).when(spy , "handleAction", any(), anyString());
3.
doReturn(0).when(spy , "handleAction", null, null);
doReturn(0).when(spy , "handleAction", any(List.class), anyString());
According to Jason´s answer we can address only devices that doesn't support hover with pure css media queries. We can also address only devices that support hover, like moogal´s answer in a similar question, with
@media not all and (hover: none)
. It looks weird but it works.
I made a Sass mixin out of this for easier use:
@mixin hover-supported {
@media not all and (hover: none) {
&:hover {
@content;
}
}
}
Update 2019-05-15: I recommend this article from Medium that goes through all different devices that we can target with CSS. Basically it's a mix of these media rules, combine them for specific targets:
@media (hover: hover) {
/* Device that can hover (desktops) */
}
@media (hover: none) {
/* Device that can not hover with ease */
}
@media (pointer: coarse) {
/* Device with limited pointing accuracy (touch) */
}
@media (pointer: fine) {
/* Device with accurate pointing (desktop, stylus-based) */
}
@media (pointer: none) {
/* Device with no pointing */
}
Example for specific targets:
@media (hover: none) and (pointer: coarse) {
/* Smartphones and touchscreens */
}
@media (hover: hover) and (pointer: fine) {
/* Desktops with mouse */
}
I love mixins, this is how I use my hover mixin to only target devices that supports it:
@mixin on-hover {
@media (hover: hover) and (pointer: fine) {
&:hover {
@content;
}
}
}
button {
@include on-hover {
color: blue;
}
}
In my case, it's because I deleted the chrome update folder. After chrome reinstall, it's working fine.
You can also use TempVars - note '!' syntax is essential
You use the CoreLocation framework to access location information about your user. You will need to instantiate a CLLocationManager object and call the asynchronous startUpdatingLocation message. You will get callbacks with the user's location via the CLLocationManagerDelegate that you supply.
If you don't give any position to parent then by default it takes static
. If you want to understand that difference refer to this example
Example 1::
#mainall
{
background-color:red;
height:150px;
overflow:scroll
}
Here parent class has no position so element is placed according to body.
Example 2::
#mainall
{
position:relative;
background-color:red;
height:150px;
overflow:scroll
}
In this example parent has relative position hence element are positioned absolute inside relative parent.
The tibble
package now has a dedicated function that converts row names to an explicit variable.
library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head
Gives:
das_Auto mpg cyl disp hp drat wt qsec vs am gear carb
1 Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
2 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
3 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
4 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
5 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
6 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
You need upper case property names in your structs in order to be used by the json packages.
Upper case property names are exported properties
. Lower case property names are not exported.
You also need to pass the your data object by reference (&data
).
package main
import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
type tracks struct {
Toptracks []toptracks_info
}
type toptracks_info struct {
Track []track_info
Attr []attr_info
}
type track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable []streamable_info
Artist []artist_info
Attr []track_attr_info
}
type attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type streamable_info struct {
Text string
Fulltrack string
}
type artist_info struct {
Name string
Mbid string
Url string
}
type track_attr_info struct {
Rank string
}
func get_content() {
// json data
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data tracks
json.Unmarshal(body, &data)
fmt.Printf("Results: %v\n", data)
os.Exit(0)
}
func main() {
get_content()
}
wtluo, great ! May I propose a slight modification of your code 2. ? Here it is:
for i, detected_box in enumerate(detect_boxes):
box = detected_box["box"]
face_img = img[ box[1]:box[1] + box[3], box[0]:box[0] + box[2] ]
cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)
Looks like you have a typo -- "trustStrore" should be "trustStore", i.e.
System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");
should be:
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
An array can be initialized by using the new Object {}
syntax.
For example, an array of String
can be declared by either:
String[] s = new String[] {"One", "Two", "Three"};
String[] s2 = {"One", "Two", "Three"};
Primitives can also be similarly initialized either by:
int[] i = new int[] {1, 2, 3};
int[] i2 = {1, 2, 3};
Or an array of some Object
:
Point[] p = new Point[] {new Point(1, 1), new Point(2, 2)};
All the details about arrays in Java is written out in Chapter 10: Arrays in The Java Language Specifications, Third Edition.
You have to destroy the datatable and empty the table body before binding DataTable by doing this below,
function Create() {
if ($.fn.DataTable.isDataTable('#dataTable')) {
$('#dataTable').DataTable().destroy();
}
$('#dataTable tbody').empty();
//Here call the Datatable Bind function;}
For simulating a 2-dimensional array, I first load the first n-elements (the elements of the first column)
local pano_array=()
i=0
for line in $(grep "filename" "$file")
do
url=$(extract_url_from_xml $line)
pano_array[i]="$url"
i=$((i+1))
done
To add the second column, I define the size of the first column and calculate the values in an offset variable
array_len="${#pano_array[@]}"
i=0
while [[ $i -lt $array_len ]]
do
url="${pano_array[$i]}"
offset=$(($array_len+i))
found_file=$(get_file $url)
pano_array[$offset]=$found_file
i=$((i+1))
done
If you are using meclipse do
window --> maven --> Download Artifact Sources (select check)
(If you still get attach source window, then click on attach file button and close the attach source window. The next time you try to see the source it will open the correct source)
Surajz
I wrote this purely SQLPlus script to dump tables to CSV in 1994.
As noted in the script comments, someone at Oracle put my script in an Oracle Support note, but without attribution.
https://github.com/jkstill/oracle-script-lib/blob/master/sql/dump.sql
The script also also builds a control file and a parameter file for SQL*LOADER
First of all, it is totally possible to write apps with React without Flux.
Also this visual diagram which I've created to show a quick view of both, probably a quick answer for the people who don't want to read the whole explanation:
But if you still interested knowing more, read on.
I believe you should start with pure React, then learn Redux and Flux. After you will have some REAL experience with React, you will see whether Redux is helpful for you or not.
Maybe you will feel that Redux is exactly for your app and maybe you will find out, that Redux is trying to solve a problem you are not really experiencing.
If you start directly with Redux, you may end up with over-engineered code, code harder to maintain and with even more bugs and than without Redux.
From Redux docs:
Motivation
As the requirements for JavaScript single-page applications have become increasingly complicated, our code must manage more state than ever before. This state can include server responses and cached data, as well as locally created data that has not yet been persisted to the server. UI state is also increasing in complexity, as we need to manage active routes, selected tabs, spinners, pagination controls, and so on.Managing this ever-changing state is hard. If a model can update another model, then a view can update a model, which updates another model, and this, in turn, might cause another view to update. At some point, you no longer understand what happens in your app as you have lost control over the when, why, and how of its state. When a system is opaque and non-deterministic, it's hard to reproduce bugs or add new features.
As if this wasn't bad enough, consider the new requirements becoming common in front-end product development. As developers, we are expected to handle optimistic updates, server-side rendering, fetching data before performing route transitions, and so on. We find ourselves trying to manage a complexity that we have never had to deal with before, and we inevitably ask the question: Is it time to give up? The answer is No.
This complexity is difficult to handle as we're mixing two concepts that are very hard for the human mind to reason about: mutation and asynchronicity. I call them Mentos and Coke. Both can be great when separated, but together they create a mess. Libraries like React attempt to solve this problem in the view layer by removing both asynchrony and direct DOM manipulation. However, managing the state of your data is left up to you. This is where Redux comes in.
Following in the footsteps of Flux, CQRS, and Event Sourcing, Redux attempts to make state mutations predictable by imposing certain restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.
Also from Redux docs:
Core Concepts
Redux itself is very simple.Imagine your app's state is described as a plain object. For example, the state of a todo app might look like this:
{ todos: [{ text: 'Eat food', completed: true }, { text: 'Exercise', completed: false }], visibilityFilter: 'SHOW_COMPLETED' }
This object is like a "model" except that there are no setters. This is so that different parts of the code can’t change the state arbitrarily, causing hard-to-reproduce bugs.
To change something in the state, you need to dispatch an action. An action is a plain JavaScript object (notice how we don't introduce any magic?) that describes what happened. Here are a few example actions:
{ type: 'ADD_TODO', text: 'Go to swimming pool' } { type: 'TOGGLE_TODO', index: 1 } { type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' }
Enforcing that every change is described as an action lets us have a clear understanding of what’s going on in the app. If something changed, we know why it changed. Actions are like breadcrumbs of what has happened. Finally, to tie state and actions together, we write a function called a reducer. Again, nothing magic about it — it's just a function that takes state and action as arguments, and returns the next state of the app. It would be hard to write such a function for a big app, so we write smaller functions managing parts of the state:
function visibilityFilter(state = 'SHOW_ALL', action) { if (action.type === 'SET_VISIBILITY_FILTER') { return action.filter; } else { return state; } } function todos(state = [], action) { switch (action.type) { case 'ADD_TODO': return state.concat([{ text: action.text, completed: false }]); case 'TOGGLE_TODO': return state.map((todo, index) => action.index === index ? { text: todo.text, completed: !todo.completed } : todo ) default: return state; } }
And we write another reducer that manages the complete state of our app by calling those two reducers for the corresponding state keys:
function todoApp(state = {}, action) { return { todos: todos(state.todos, action), visibilityFilter: visibilityFilter(state.visibilityFilter, action) }; }
This is basically the whole idea of Redux. Note that we haven't used any Redux APIs. It comes with a few utilities to facilitate this pattern, but the main idea is that you describe how your state is updated over time in response to action objects, and 90% of the code you write is just plain JavaScript, with no use of Redux itself, its APIs, or any magic.
Some useful are:
Free:
Paid:
The best entries in my opinion are Flexigrid and jQuery Grid.
'\r' = carriage return and '\n' = line feed.
In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.
Just use the length
property of a JavaScript
array like so:
$scope.names.length
Also, I don't see a starting <script>
tag in your code.
If you want the length inside your view, do it like so:
{{ names.length }}
Shell works for me.
Simply to say, Shell is the same as you run a shell script.
Notes:
The following example shows an error in shell, but it's success at the end of the execution.
- name: test shell with an error
become: no
shell: |
rm -f /test1 # This should be an error.
echo "test2"
echo "test1"
echo "test3" # success
This example shows stopinng shell with exit 1 error.
- name: test shell with exit 1
become: no
shell: |
rm -f /test1 # This should be an error.
echo "test2"
exit 1 # this stops ansible due to returning an error
echo "test1"
echo "test3" # success
reference: https://docs.ansible.com/ansible/latest/modules/shell_module.html
The time diff in milliseconds
firstDate.getTime() - secondDate.getTime()
I wondered this myself for a while. Without setters how does AngularJS
notice changes to the $scope
object? Does it poll them?
What it actually does is this: Any "normal" place you modify the model was already called from the guts of AngularJS
, so it automatically calls $apply
for you after your code runs. Say your controller has a method that's hooked up to ng-click
on some element. Because AngularJS
wires the calling of that method together for you, it has a chance to do an $apply
in the appropriate place. Likewise, for expressions that appear right in the views, those are executed by AngularJS
so it does the $apply
.
When the documentation talks about having to call $apply
manually for code outside of AngularJS
, it's talking about code which, when run, doesn't stem from AngularJS
itself in the call stack.
eg:
// .vscode/settings.json in workspace
{
"files.associations": {
"*Container.js": "javascriptreact",
"**/components/*/*.js": "javascriptreact",
"**/config/routes.js": "javascriptreact"
}
}
You want to use the ParameterizedThreadStart
delegate for thread methods that take parameters. (Or none at all actually, and let the Thread
constructor infer.)
Example usage:
var thread = new Thread(new ParameterizedThreadStart(download));
//var thread = new Thread(download); // equivalent
thread.Start(filename)
You should add a .gitignore file to your project and add /.idea
to it. You should add each directory / file in one line.
If you have an existing .gitignore file then you should simply add a new line to the file and put /.idea
to the new line.
After that run git rm -r --cached .idea
command.
If you faced an error you can run git rm -r -f --cached .idea
command. After all run git add .
and then git commit -m "Removed .idea directory and added a .gitignore file"
and finally push the changes by running git push
command.
SIMPLE..
First check with the closing tag of project. It should be placed after all the dependency tags are closed.This way I solved my error. --Sush happy coding :)
Yes, via the text-overflow
property in CSS 3. Caveat: it is not universally supported yet in browsers.
After updating PHP to 7.3, PHP scripts where run with www-data instead of $USER like before.
I needed to reinstall and activate PHP-FPM :
sudo apt-get install php-fpm
sudo a2enmod proxy_fcgi setenvif
sudo service apache2 restart
sudo a2enconf php7.3-fpm
sudo service apache2 restart
To ensure everything was ok for Virtualmin, i used the Re-Check Configuration wizard /virtual-server/check.cgi
, under Vitualmin/System Settings.
After that, Apache/PHP was downloading php files instead of running them. So i needed to edit /etc/apache2/mods-available/php7.3.conf
to comment the row SetHandler application/x-httpd-php
like below :
<FilesMatch ".+\.ph(ar|p|tml)$">
# SetHandler application/x-httpd-php
</FilesMatch>
After restarting Apache, it solved my issue, hope this help.
Take care of browser cache too.
My system :
Ubuntu 16.04.6 LTS
Webmin version 1.932
Usermin version 1.780
Virtualmin version 6.08
Apache version 2.4.41
PHP versions 7.3.12
PHP-FPM 7.3.12 Server
I know this is a pretty old thread, but I was searching for something similar and came up with this.
Given that you had a comma-separated string, you could use string_split
select distinct value from string_split('1, 1, 1, 2, 5, 1, 6',',')
This should return
1
2
5
6
String split takes two parameters, the string input, and the separator character.
you can add an optional where statement using value
as the column name
select distinct value from string_split('1, 1, 1, 2, 5, 1, 6',',')
where value > 1
produces
2
5
6
to make it as globally reuse function using jquery
HTML
<select class="select_location">
<option value="http://localhost.com/app/page1.html">Page 1</option>
<option value="http://localhost.com/app/page2.html">Page 2</option>
<option value="http://localhost.com/app/page3.html">Page 3</option>
</select>
Javascript using jquery
$('.select_location').on('change', function(){
window.location = $(this).val();
});
now you will able to reuse this function by adding .select_location class to any Select element class
Use vm.$set('varName', value)
. Look for details into Change_Detection_Caveats.
The solutions is in fact
p{
white-space:normal;
}
You can change the break behaviors by modifying, word-break property
p{
word-break: break-all; // will break at end of line
}
break-all: Will break the string at the very end, breaking at the last word word-break: is more of pretty brake, will break nicely for example at ? point normal: same as word-break
The solution I came up with is fragile; it relies on django's naming convention for foreign keys.
USE information_schema;
tee mysql_output
SELECT * FROM TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_SCHEMA = 'database_name';
notee
Then, in the shell,
grep 'refs_tablename_id' mysql_output
I use Blue Ocean plugin and did not like each environment entry getting its own block. I want one block with all the lines.
Prints poorly:
sh 'echo `env`'
Prints poorly:
sh 'env > env.txt'
for (String i : readFile('env.txt').split("\r?\n")) {
println i
}
Prints well:
sh 'env > env.txt'
sh 'cat env.txt'
Prints well: (as mentioned by @mjfroehlich)
echo sh(script: 'env', returnStdout: true)
I'd recommend that you take a look at java.util.ResourceBundle. You should care about I18N, but it's worth it even if you don't. Externalizing the messages is a very good idea. I've found that it was useful to be able to give a spreadsheet to business folks that allowed them to put in the exact language they wanted to see. We wrote an Ant task to generate the .properties files at compile time. It makes I18N trivial.
If you're also using Spring, so much the better. Their MessageSource class is useful for these sorts of things.
The M2_HOME
environment variable for the global one. See Settings Reference:
The
settings
element in thesettings.xml
file contains elements used to define values which configure Maven execution in various ways, like thepom.xml
, but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information. There are two locations where a settings.xml file may live:
- The Maven install:
$M2_HOME/conf/settings.xml
- A user's install:
${user.home}/.m2/settings.xml
A .tex file should be a LaTeX source file.
If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.
Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.
Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.
You can also check out this question and answer for how to do it: How to compile a LaTeX document?
Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.
It seems like you are essentially looking into computing the z-score or standard score of your data, which is calculated through the formula: z = (x-mean(x))/std(x)
This should work:
%% Original data (Normal with mean 1 and standard deviation 2)
x = 1 + 2*randn(100,1);
mean(x)
var(x)
std(x)
%% Normalized data with mean 0 and variance 1
z = (x-mean(x))/std(x);
mean(z)
var(z)
std(z)
No.
You can use grouping selectors and/or multiple classes on a single element, or you can use a template language and process it with software to write your CSS.
See also my article on CSS inheritance.
You can get columns number from ResultSetMetaData:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
date -j -f "%Y-%m-%d" "2010-10-02" "+%s"
ViewGroup class provides API for child views management in run-time, allowing to add/remove views as well.
Some other links on the subject:
Android, add new view without XML Layout
Android Runtime Layout Tutorial
http://developer.android.com/reference/android/view/View.html
http://developer.android.com/reference/android/widget/LinearLayout.html
With Kotlin, you can avoid a loop by wrapping the JSONArray with a MutableList, e.g.
val artistMetadata = player.metadata.optJSONArray("artist")
val artists = MutableList<String>(artistMetadata.length()) { i -> artistMetadata.getString(i)}
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
Can JAX-RS do Asynchronous Request like JAX-WS?
1) I don't know if the JAX-RS API includes a specific mechanism for asynchronous requests, but this answer could still change based on the client implementation you use.
Can JAX-RS access a web service that is not running on the Java platform, and vice versa?
2) I can't think of any reason it wouldn't be able to.
What does it mean by "REST is particularly useful for limited-profile devices, such as PDAs and mobile phones"?
3) REST based architectures typically will use a lightweight data format, like JSON, to send data back and forth. This is in contrast to JAX-WS which uses XML. I don't see XML by itself so significantly heavier than JSON (which some people may argue), but with JAX-WS it's how much XML is used that ends up making REST with JSON the lighter option.
What does it mean by "JAX-RS do not require XML messages or WSDL service–API definitions?
4) As stated in 3, REST architectures often use JSON to send and receive data. JAX-WS uses XML. It's not that JSON is so significantly smaller than XML by itself. It's mostly that JAX-WS specification includes lots overhead in how it communicates.
On the point about WSDL and API definitions, REST will more frequently use the URI structure and HTTP commands to define the API rather than message types, as is done in the JAX-WS. This means that you don't need to publish a WSDL document so that other users of your service can know how to talk to your service. With REST you will still need to provide some documentation to other users about how the REST service is organized and what data and HTTP commands need to be sent.
I'm using Argos reporting system as a front end and Oracle in back. I just encountered this error and it was caused by a string with a double quote at the start and a single quote at the end. Replacing the double quote with a single solved the issue.
Execution Timeout is 90 seconds for .NET
Framework 1.0 and 1.1, 110 seconds otherwise.
If you need to change defult settings you need to do it in your web.config
under <httpRuntime>
<httpRuntime executionTimeout = "number(in seconds)"/>
But Remember:
This time-out applies only if the debug attribute in the compilation element is False.
Have look at in detail about compilation Element
Have look at this document about httpRuntime Element
More info
To find a compiler, you'll have 1 per .net version installed, type in a command prompt.
dir c:\Windows\Microsoft.NET\vbc.exe /a/s
Windows Forms
For a Windows Forms version (no console window and we don't get around to actually creating any forms - though you can if you want).
Compile line in a command prompt.
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe "%userprofile%\desktop\VBS2Exe.vb"
Text for VBS2EXE.vb
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34)
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
End With
sc.addcode(Scrpt)
End Sub
End Class
Using these optional parameters gives you an icon and manifest. A manifest allows you to specify run as normal, run elevated if admin, only run elevated.
/win32icon: Specifies a Win32 icon file (.ico) for the default Win32 resources.
/win32manifest: The provided file is embedded in the manifest section of the output PE.
In theory, I have UAC off so can't test, but put this text file on the desktop and call it vbs2exe.manifest, save as UTF-8.
The command line
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" "%userprofile%\desktop\VBS2Exe.vb"
The manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0"
processorArchitecture="*" name="VBS2EXE" type="win32" />
<description>Script to Exe</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security> <requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"
uiAccess="false" /> </requestedPrivileges>
</security> </trustInfo> </assembly>
Hopefully it will now ONLY run as admin.
Give Access To a Host's Objects
Here's an example giving the vbscript access to a .NET object.
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34) & ":msgbox meScript.state"
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.addobject("meScript", SC, true)
End With
sc.addcode(Scrpt)
End Sub
End Class
To Embed version info
Download vbs2exe.res file from https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 and put on desktop.
Download ResHacker from http://www.angusj.com/resourcehacker
Open vbs2exe.res file in ResHacker. Edit away. Click Compile button. Click File menu - Save.
Type
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" /win32resource:"%userprofile%\desktop\VBS2Exe.res" "%userprofile%\desktop\VBS2Exe.vb"
I found this post helpful:
"It can happen when res folder contains unexpected folder names. In my case after merge mistakes I had a folder src/main/res/res. And it caused problems."
from: "https://groups.google.com/forum/#!msg/adt-dev/0pEUKhEBMIA/ZxO5FNRjF8QJ"
execute npm config list it will list down all proxy values.. in my case proxy value was fetched form global npmrc file, removed it and was able to complete npm install on my windows machine
Use this, it works 100% _your_videocode?rel=0&vq=hd1080"
if by .add
you mean .append
, then the result is the same if #myDiv
is empty.
is the performance the same? dont know.
.html(x)
ends up doing the same thing as .empty().append(x)
std::string::npos
is implementation defined index that is always out of bounds of any std::string
instance. Various std::string
functions return it or accept it to signal beyond the end of the string situation. It is usually of some unsigned integer type and its value is usually std::numeric_limits<std::string::size_type>::max ()
which is (thanks to the standard integer promotions) usually comparable to -1
.
More recent answer in the case you want to delete every entries in every tables:
def reset
Rails.application.eager_load!
ActiveRecord::Base.descendants.each { |c| c.delete_all unless c == ActiveRecord::SchemaMigration }
end
More information about the eager_load
here.
After calling it, we can access to all of the descendants of ActiveRecord::Base
and we can apply a delete_all
on all the models.
Note that we make sure not to clear the SchemaMigration table.
Your this check:
if (!lines2.Contains(lines3.ToString()))
is invalid. You are checking if your lines2
contains System.String[]
since lines3.ToString()
will give you that. You need to check if item from lines3
exists in lines2
or not.
You can iterate each item in lines3
check if it exists in the lines2
and then add it. Something like.
foreach (string str in lines3)
{
if (!lines2.Contains(str))
lines2.Add(str);
}
Or if your lines2
is any empty list, then you can simply add the lines3
distinct values to the list like:
lines2.AddRange(lines3.Distinct());
then your lines2
will contain distinct values.
Alt simplification of https://stackoverflow.com/users/1969435/gx1sptdtda above:
cond <-c(1,2,3)
rating <-c(100,200,300)
df <- data.frame(cond, rating)
df
cond rating
1 1 100
2 2 200
3 3 300
Since no one else said it, the short-cut to compile (build) a C# app in Visual Studio Code (VSCode) is SHIFT+CTRL+B
.
If you want to see the build errors (because they don't pop-up by default), the shortcut is SHIFT+CTRL+M
.
(I know this question was asking for more than just the build shortcut. But I wanted to answer the question in the title, which wasn't directly answered by other answers/comments.)
SELECT
student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student
ON student.studentId = grade.fk_studentId
INNER JOIN exam
ON exam.examId = grade.fk_examId
GROUP BY grade.gradeId
ORDER BY exam.date
A segmentation fault is caused by a request for a page that the process does not have listed in its descriptor table, or an invalid request for a page that it does have listed (e.g. a write request on a read-only page).
A dangling pointer is a pointer that may or may not point to a valid page, but does point to an "unexpected" segment of memory.
I landed up on this page when searching for a solution for “Could not open input file” error. Here's my 2 cents for this error.
I faced this same error while because I was using parameters in my php file path like this:
/usr/bin/php -q /home/**/public_html/cron/job.php?id=1234
But I found out that this is not the proper way to do it. The proper way of sending parameters is like this:
/usr/bin/php -q /home/**/public_html/cron/job.php id=1234
Just replace the "?"
with a space " "
.
A better JQuery answer would be:
$('#ParentContainer').scroll(function() {
$('#FixedDiv').animate({top:$(this).scrollTop()});
});
You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.
A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.
$('#ParentContainer').scroll(function() {
$('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})
Assuming:
(unsigned long)
you mean unsigned 32-bit integer,then you just need to add 2**32 (or 1 << 32)
to the negative value.
For example, apply this to -1:
>>> -1
-1
>>> _ + 2**32
4294967295L
>>> bin(_)
'0b11111111111111111111111111111111'
Assumption #1 means you want -1 to be viewed as a solid string of 1 bits, and assumption #2 means you want 32 of them.
Nobody but you can say what your hidden assumptions are, though. If, for example, you have 1's-complement representations in mind, then you need to apply the ~
prefix operator instead. Python integers work hard to give the illusion of using an infinitely wide 2's complement representation (like regular 2's complement, but with an infinite number of "sign bits").
And to duplicate what the platform C compiler does, you can use the ctypes
module:
>>> import ctypes
>>> ctypes.c_ulong(-1) # stuff Python's -1 into a C unsigned long
c_ulong(4294967295L)
>>> _.value
4294967295L
C's unsigned long
happens to be 4 bytes on the box that ran this sample.
Another solution is to use the address
http://localhost:8732/Design_Time_Addresses/YOUR_ADDRESS .
.NET Framework (3.5) automatically register this address (http://*:8732/Design_Time_Addresses) for debugging scope. This is useful when you need to host services inside visual studio for debugging or testing. Don't use this on production...
Some browser differences to be aware of:
Given the CSS:
div#a { ... }
div#b, div#c { ... }
and given InsDel's example, classes will have 2 classes in FF and 3 classes in IE7.
My example illustrates this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
div#a { }
div#b, div#c { }
</style>
<script>
function PrintRules() {
var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules
for(var x=0;x<rules.length;x++) {
document.getElementById("rules").innerHTML += rules[x].selectorText + "<br />";
}
}
</script>
</head>
<body>
<input onclick="PrintRules()" type="button" value="Print Rules" /><br />
RULES:
<div id="rules"></div>
</body>
</html>
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.
For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11
To edit the Compatibility View list:
Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.
To add on nathan gonzalez answer, please note you need to assign the replaced object after calling replace
function since it is not a mutator function:
myString = myString.replace('username1','');
I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0
, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes
import matplotlib.pyplot as plt
plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()
Personally I think that "" + i does look as the original question poster states "smelly". I have used a lot of OO languages besides Java. If that syntax was intended to be appropriate then Java would just interpret the i alone without needing the "" as desired to be converted to a string and do it since the destination type is unambiguous and only a single value would be being supplied on the right. The other seems like a 'trick" to fool the compiler, bad mojo when different versions of Javac made by other manufacturers or from other platforms are considered if the code ever needs to be ported. Heck for my money it should like many other OOL's just take a Typecast: (String) i. winks
Given my way of learning and for ease of understanding such a construct when reading others code quickly I vote for the Integer.toString(i) method. Forgetting a ns or two in how Java implements things in the background vs. String.valueOf(i) this method feels right to me and says exactly what is happening: I have and Integer and I wish it converted to a String.
A good point made a couple times is perhaps just using StringBuilder up front is a good answer to building Strings mixed of text and ints or other objects since thats what will be used in the background anyways right?
Just my two cents thrown into the already well paid kitty of the answers to the Mans question... smiles
EDIT TO MY OWN ANSWER AFTER SOME REFLECTION:
Ok, Ok, I was thinking on this some more and String.valueOf(i) is also perfectly good as well it says: I want a String that represents the value of an Integer. lol, English is by far more difficult to parse then Java! But, I leave the rest of my answer/comment... I was always taught to use the lowest level of a method/function chain if possible and still maintains readablity so if String.valueOf calls Integer.toString then Why use a whole orange if your just gonna peel it anyways, Hmmm?
To clarify my comment about StringBuilder, I build a lot of strings with combos of mostly literal text and int's and they wind up being long and ugly with calls to the above mentioned routines imbedded between the +'s, so seems to me if those become SB objects anyways and the append method has overloads it might be cleaner to just go ahead and use it... So I guess I am up to 5 cents on this one now, eh? lol...
From the documentation page
To set the page type pass the value in constructor
jsPDF(orientation, unit, format)
Creates new jsPDF document objectinstance Parameters:
orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'
To set font size
setFontSize(size)
Sets font size for upcoming text elements.
Parameters:
{Number} size Font size in points.
I think this one will answer your question :P
$url="https://.../api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=??desc&limit=1&grab_content&content_limit=1";
Using cURL
// Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
Using file_get_contents
$result = file_get_contents($url);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
Accessing
$array["threads"][13/* thread id */]["title"/* thread key */]
And
$array["threads"][13/* thread id */]["content"/* thread key */]["content"][23/* post id */]["message" /* content key */];
As explained in the documentation, by using an @RequestParam
annotation:
public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
+ foo;
}
using System.IO;
using System.Text;
using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{
sw.WriteLine("my text...");
}
An alternate way of getting your encoding:
using System.IO;
using System.Text;
using (var sw = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
sw.WriteLine("my text...");
}
Check out the docs for the StreamWriter constructor.
I've added some code to my project, so it's more convenient.
HtmlExtensions.cs:
namespace System.Web.Mvc.Html
{
public static class HtmlExtensions
{
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formId)
{
return htmlHelper.BeginForm(null, null, FormMethod.Post, new { id = formId });
}
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formId, FormMethod method)
{
return htmlHelper.BeginForm(null, null, method, new { id = formId });
}
}
}
MySignupForm.cshtml:
@using (Html.BeginForm("signupform"))
{
@* Some fields *@
}
In my case, I resolved it by adding this path C:\xampp\mysql\bin
to system variables
path and then restarted pash/cmd
.
Note: Click me if you don't know how to set the path and system variables.
You can use emojis
Done? | Name
:---:| ---
??| Nope
?| Yep
Never construct BigDecimals from floats or doubles. Construct them from ints or strings. floats and doubles loose precision.
This code works as expected (I just changed the type from double to String):
public static void main(String[] args) {
String doubleVal = "1.745";
String doubleVal1 = "0.745";
BigDecimal bdTest = new BigDecimal( doubleVal);
BigDecimal bdTest1 = new BigDecimal( doubleVal1 );
bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("bdTest:"+bdTest); //1.75
System.out.println("bdTest1:"+bdTest1);//0.75, no problem
}
Not exactly the way to go about this, but if the situation is trivial and you value your time, you can try this for nullable types.
Foos[index] = null
and later check for null entries in your logic..
First, make sure that the source page and the target page are both served through the file
URI scheme. You can't force an http
page to open a file
page (but it works the other way around).
Next, your script that calls window.open()
should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling window.open()
won't work.
You can test this right here in this question page. Run these in Chrome's JavaScript console:
// Does nothing
window.open('http://google.com');
// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });
// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });
You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
</head>
<body>
<h5>Feel the presha</h5>
<h3>Come play my game, I'll test ya</h3>
<h1>Psycho- somatic- addict- insane!</h1>
</body>
</html>
Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.
Try to add the following settings to web.config
file.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
You can use java.net.HttpUrlConnection.
Example (from here), with improvements. Included in case of link rot:
public static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Did you try to reroute the result to a file? Like whatever.bat >log.txt
You have to make sure that in this case every other called script is also logging to the file like >>log.txt
Also if you put a date /T and time /T in the beginning and in the end of that batch file, you will get the times it was at that point and you can map your script running time and order.
Without additional temp-vars or brackets.
var width= $(this).width(), height= $(this).height()
, maxWidth=100, maxHeight= 100;
if(width > maxWidth){
height = Math.floor( maxWidth * height / width );
width = maxWidth
}
if(height > maxHeight){
width = Math.floor( maxHeight * width / height );
height = maxHeight;
}
Keep in Mind: Search engines don't like it, if width and height attribute does not fit the image, but they don't know JS.
Even easier: just store the R.drawable
id in the view's id: use v.setId()
. Then get it back with v.getId()
.
You need to use the AND function for the multiple conditions:
=IF(AND(A2>=75, A2<=79),0.255,IF(AND(A2>=80, X2<=84),0.327,IF(A2>=85,0.559,0)))
Here is how I got this working https://stackoverflow.com/a/27563953/2845977
$.ajax({
url: '<URL_TO_FILE>',
success: function(data) {
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="<FILENAME_TO_SAVE_WITH_EXTENSION>";
link.click();
}
});
_x000D_
$.ajax({
url: '<URL_TO_FILE>',
success: download.bind(true, "<FILENAME_TO_SAVE_WITH_EXTENSION>", "<FILE_MIME_TYPE>")
});
_x000D_
All u need do is to change the lowercase 'hh' in the pattern to an uppercase letter 'HH'
for Kotlin:
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val currentDate = sdf.format(Date())
for java:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss") Date currentDate = sdf.format(new Date())
404 would be very confusing for any client if you return just because there is no data in response.
For me, Response Code 200 with an empty body is sufficient enough to understand that everything is perfect but there is no data matching the requirements.
As much as I hate to use eval, it seemed like the easiest way for me, without causing a lot of problems depending on different circumstances. Similar to the javascript settimeout function.
<a href="#" onclick="javascript:confirm('do_function(params)');">Confirm</a>
<div id="dialog-confirm" title="Confirm" style="display:none;">
<p>Are you sure you want to do this?</p>
</div>
<script>
function confirm(callback){
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: false,
buttons: {
"Ok": function() {
$( this ).dialog( "close" );
eval(callback)
},
Cancel: function() {
$( this ).dialog( "close" );
return false;
}
}
});
}
function do_function(params){
console.log('approved');
}
</script>
New, simplified answer to an old, commonly asked question...
Always (90% important to remember)
Attribute Values (9% important to remember)
attr="
'
Single quotes'
are ok within double quotes."
attr='
"
Double quotes"
are ok within single quotes.'
"
as "
and '
as '
otherwise.Comments, CDATA, and Processing Instructions (0.9% important to remember)
Esoterica (0.1% important to remember)
]]>
as ]]>
unless ]]>
is ending a CDATA section. Hows about this:
$json=Get-Content -Raw -Path 'my.json' | Out-String | ConvertFrom-Json
$foo="TheVariableYourUsingToSelectSomething"
$json.SomePathYouKnow.psobject.properties.Where({$_.name -eq $foo}).value
which would select from json structured
{"SomePathYouKnow":{"TheVariableYourUsingToSelectSomething": "Tada!"}
This is based on this accessing values in powershell SO question . Isn't powershell fabulous!
You should be able to do this by simply typing npm install -g [email protected]
. If this does not work, I am beginning to wonder what version of node and npm you are on. Try node -v
and npm -v
to find these out. You should be on node >4.5 and npm >3
Start new Activity From a Fragment:
Intent intent = new Intent(getActivity(), TargetActivity.class);
startActivity(intent);
Start new Activity From a Activity:
Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);
You are using <input name='C[]'
in your HTML. This creates an array in PHP when the form is sent.
You are using echo $_POST['C'];
to echo that array - this will not work, but instead emit that notice and the word "Array".
Depending on what you did with the rest of the code, you should probably use echo $_POST['C'][0];
you could do it with a template, if the matrix size is known at compile-time :
template <int width, int height>
class Matrix{
double data[height][width];
//...member functions
};
You're looking for the /Y
switch.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
I am just adding example here because I think examples make it easier to understand.
In printf() they behave identically so you can use any either %d or %i. But they behave differently in scanf().
For example:
int main()
{
int num,num2;
scanf("%d%i",&num,&num2);// reading num using %d and num2 using %i
printf("%d\t%d",num,num2);
return 0;
}
Output:
You can see the different results for identical inputs.
num
:
We are reading num
using %d
so when we enter 010
it ignores the first 0
and treats it as decimal 10
.
num2
:
We are reading num2
using %i
.
That means it will treat decimals, octals, and hexadecimals differently.
When it give num2
010
it sees the leading 0
and parses it as octal.
When we print it using %d
it prints the decimal equivalent of octal 010
which is 8
.
Here's a simple c# solution using Linq.
internal class Program
{
public static IEnumerable<Coin> Coins = new List<Coin>
{
new Coin {Name = "Dime", Value = 10},
new Coin {Name = "Penny", Value = 1},
new Coin {Name = "Nickel", Value = 5},
new Coin {Name = "Quarter", Value = 25}
};
private static void Main(string[] args)
{
PrintChange(34);
Console.ReadKey();
}
public static void PrintChange(int amount)
{
decimal remaining = amount;
//Order coins by value in descending order
var coinsDescending = Coins.OrderByDescending(v => v.Value);
foreach (var coin in coinsDescending)
{
//Continue to smaller coin when current is larger than remainder
if (remaining < coin.Value) continue;
// Get # of coins that fit in remaining amount
var quotient = (int)(remaining / coin.Value);
Console.WriteLine(new string('-',28));
Console.WriteLine("{0,10}{1,15}", coin.Name, quotient);
//Subtract fitting coins from remaining amount
remaining -= quotient * coin.Value;
if (remaining <= 0) break; //Exit when no remainder left
}
Console.WriteLine(new string('-', 28));
}
public class Coin
{
public string Name { get; set; }
public int Value { get; set; }
}
}
Step1. $ cd [your working path of code]
Step2. $ svn commit [your server path ] -m 'Add commit message'
For help use $ svn help commit
You can use System Internals PSEXEC command to remotely execute a net stop yourservice, then net start yourservice
I try all the above, if you did all steps in the above answers, and you not solve the problem, then:
I thing that because of, when I create the "METHOD REQUEST" (see step 2 how to go to this menu) , in "Authorization" I select "AWS_IAM" after testing api, in aws test option, I try it in "postman" then I understand the in "METHOD REQUEST" , in "Authorization", I should select "none"
I change it to none, but I thing the AWS, need to deploy it again, as I explain
If you need to give a distance between two rows use this tag
margin-top: 10px !important;
It's not possible with ES3 as the properties have an internal DontEnum
attribute which prevents us from enumerating these properties. ES5, on the other hand, provides property descriptors for controlling the enumeration capabilities of properties so user-defined and native properties can use the same interface and enjoy the same capabilities, which includes being able to see non-enumerable properties programmatically.
The getOwnPropertyNames
function can be used to enumerate over all properties of the passed in object, including those that are non-enumerable. Then a simple typeof
check can be employed to filter out non-functions. Unfortunately, Chrome is the only browser that it works on currently.
?function getAllMethods(object) {
return Object.getOwnPropertyNames(object).filter(function(property) {
return typeof object[property] == 'function';
});
}
console.log(getAllMethods(Math));
logs ["cos", "pow", "log", "tan", "sqrt", "ceil", "asin", "abs", "max", "exp", "atan2", "random", "round", "floor", "acos", "atan", "min", "sin"]
in no particular order.
have you tried display:inline-block;
?
If you have to use credentials try this:
export HTTP_PROXY="http://username:[email protected]:port"
As programmers we want the quickest, most fool-proof way to get our tools in order so we can start hacking. Here are how I got it to work in MacOS 10.13.1 (High Sierra):
Option 1: Go to System Preferences | Keyboard | Shortcut | Services
.
Under Files and Folders
section, enable New Terminal at Folder
and/or New Terminal Tab at Folder
and assign a shortcut key to it.
Option 2: If you want the shortcut key to work anywhere, create a new Service using Automator, then go to the Keyboard Shortcut to assign a shortcut key to it. Known limitation: not work from the desktop
Notes:
MacOS
, that's not necessary.Both of the above answers assume that you only have one row for each user and time_stamp. Depending on the application and the granularity of your time_stamp this may not be a valid assumption. If you need to deal with ties of time_stamp for a given user, you'd need to extend one of the answers given above.
To write this in one query would require another nested sub-query - things will start getting more messy and performance may suffer.
I would have loved to have added this as a comment but I don't yet have 50 reputation so sorry for posting as a new answer!
This will disable autorotation of the view:
override func shouldAutorotate() -> Bool {
return false;
}
Update
override func shouldAutorotate() -> Bool {
if (UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft ||
UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight ||
UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
return false;
}
else {
return true;
}
}
If app is in landscape mode and you show a view which must be showed in portrait mode, this will allow app to change it's orientation to portrait (of course when device will be rotated to such orientation).
If initially typed the name of the database incorrectly. Then did a Php artisan migrate .You will then receive an error message .Later even if fixed the name of the databese you need to turn off the server and restart server
I usually add separate
safe pipe
reusable component as following
# Add Safe Pipe
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {
}
public transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
# then create shared pipe module as following
import { NgModule } from '@angular/core';
import { SafePipe } from './safe.pipe';
@NgModule({
declarations: [
SafePipe
],
exports: [
SafePipe
]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module
@NgModule({
declarations: [],
imports: [
SharedPipesModule,
],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
<iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>
In some cases - when not so many columns - useful the WINDOW functions FIRST_VALUE() and LAST_VALUE().
SELECT
FIRST_VALUE(timestamp) over (ORDER BY timestamp ASC) as created_dt,
LAST_VALUE(timestamp) over (ORDER BY timestamp ASC) as last_update_dt,
LAST_VALUE(action) over (ORDER BY timestamp ASC) as last_action
FROM events
This query sort data only once.
It can be used for getting fisrt and last rows by some ID
SELECT DISTINCT
order_id,
FIRST_VALUE(timestamp) over (PARTITION BY order_id ORDER BY timestamp ASC) as created_dt,
LAST_VALUE(timestamp) over (PARTITION BY order_id ORDER BY timestamp ASC) as last_update_dt,
LAST_VALUE(action) over (PARTITION BY order_id ORDER BY timestamp ASC) as last_action
FROM events as x
Your route isn't ok, it should be like this (with ':')
app.get('/documents/:format/:type', function (req, res) {
var format = req.params.format,
type = req.params.type;
});
Also you cannot interchange parameter order unfortunately.
For more information on req.params
(and req.query
) check out the api reference here.
CTRL-F6 in Eclipse, like ALT-TAB (on windows), brings up a list of tabs/windows available (if you keep the CTRL / ALT key depressed) and highlights the one you will jump to when you let go of this key. You do not have to select the window. If you want to traverse several tabs at once hold down the CTRL button and tap the TAB button. This is identical behaviour to ALT-TAB on Windows.
In this sense, CTRL-SHIFT-F6 in eclipse is the ALT-SHIFT-TAB analog. Personally, I change these bindings in Eclipse to be like Visual Studio. I.e. CTRL-TAB and CTRL-SHIFT-TAB and I do it like this:
Window>Preferences>General>Keys
Then set "Next Editor"=Ctrl+Tab and "Previous Editor"=Ctrl+Shift+Tab. Don't forget to click "Unbind Command" before setting the new binding.
This is CTRL-PageDown to go right, CTRL-PageUp to go left. Frustratingly, when you get to the end of the list of tabs (say far right hand tab) and then try to go right again Eclipse does not cycle round to the first tab (far left) like most browsers would.
One point: you have to set NumberFormat property BEFORE loading the value into the cell. I had a nine digit number that still displayed as 9.14E+08 when the NumberFormat was set after the cell was loaded. Setting the property before loading the value made the number appear as I wanted, as straight text.
OR:
Could you try an autofit first:
Excel_Obj.Columns("A:V").EntireColumn.AutoFit
All those answers are good, but in fact, if you want to understand, the extension directory need to be right if you want all you uncommented extensions to work. Can write a physical or relative path like
extension_dir = "C:/myStack/php/ext"
or
extension_dir = "../../php/ext"
It's relative to the httpd.exe Apache web server (C:\myStack\apache\bin) But if you want it to work with Composer or anything you need the physical path because the cli mode doesn't use the web server !
The proper way to get LF endings in Windows is to first set core.autocrlf
to false
:
git config --global core.autocrlf false
You need to do this if you are using msysgit, because it sets it to true
in its system settings.
Now git won’t do any line ending normalization. If you want files you check in to be normalized, do this: Set text=auto
in your .gitattributes
for all files:
* text=auto
And set core.eol
to lf
:
git config --global core.eol lf
Now you can also switch single repos to crlf (in the working directory!) by running
git config core.eol crlf
After you have done the configuration, you might want git to normalize all the files in the repo. To do this, go to to the root of your repo and run these commands:
git rm --cached -rf .
git diff --cached --name-only -z | xargs -n 50 -0 git add -f
If you now want git to also normalize the files in your working directory, run these commands:
git ls-files -z | xargs -0 rm
git checkout .
TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).
As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.
BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.
You Can simply Use One Jsp Page To accomplish the task.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.
You were close:
if (typeof a_string === 'string') {
// this is a string
}
On a related note: the above check won't work if a string is created with new String('hello')
as the type will be Object
instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.
Try str_detect()
from the stringr package, which detects the presence or absence of a pattern in a string.
Here is an approach that also incorporates the %>%
pipe and filter()
from the dplyr package:
library(stringr)
library(dplyr)
CO2 %>%
filter(str_detect(Treatment, "non"))
Plant Type Treatment conc uptake
1 Qn1 Quebec nonchilled 95 16.0
2 Qn1 Quebec nonchilled 175 30.4
3 Qn1 Quebec nonchilled 250 34.8
4 Qn1 Quebec nonchilled 350 37.2
5 Qn1 Quebec nonchilled 500 35.3
...
This filters the sample CO2 data set (that comes with R) for rows where the Treatment variable contains the substring "non". You can adjust whether str_detect
finds fixed matches or uses a regex - see the documentation for the stringr package.
I had the same problem. Adding new rows to WPF DataGrid
requires a trick. DataGrid
relies on property fields of an item object. ExpandoObject
enables to add new properties dynamically. The code below explains how to do it:
// using System.Dynamic;
DataGrid dataGrid;
string[] labels = new string[] { "Column 0", "Column 1", "Column 2" };
foreach (string label in labels)
{
DataGridTextColumn column = new DataGridTextColumn();
column.Header = label;
column.Binding = new Binding(label.Replace(' ', '_'));
dataGrid.Columns.Add(column);
}
int[] values = new int[] { 0, 1, 2 };
dynamic row = new ExpandoObject();
for (int i = 0; i < labels.Length; i++)
((IDictionary<String, Object>)row)[labels[i].Replace(' ', '_')] = values[i];
dataGrid.Items.Add(row);
//edit:
Note that this is not the way how the component should be used, however, it simplifies a lot if you have only programmatically generated data (eg. in my case: a sequence of features and neural network output).
functionName() : ReturnType { ... }
I was having a similar problem, however my program would crash when I tried to set the text. I was attempting to set the text value from within a class that extends AsyncTask, and that was what was causing the problem.
To resolve it, I moved my setText to the onPostExecute method
protected void onPostExecute(Void result) {
super.onPostExecute(result);
TextView text = (TextView) findViewById(R.id.errorsToday);
text.setText("new string value");
}
An Euler path is a path that passes through every edge exactly once. If it ends at the initial vertex then it is an Euler cycle.
A Hamiltonian path is a path that passes through every vertex exactly once (NOT every edge). If it ends at the initial vertex then it is a Hamiltonian cycle.
In an Euler path you might pass through a vertex more than once.
In a Hamiltonian path you may not pass through all edges.
Without using jQuery, only vanilla JavaScript:
var inactivityTime = function () {
var time;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.html'
}
function resetTimer() {
clearTimeout(time);
time = setTimeout(logout, 3000)
// 1000 milliseconds = 1 second
}
};
And init the function where you need it (for example: onPageLoad).
window.onload = function() {
inactivityTime();
}
You can add more DOM events if you need to. Most used are:
document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer; // touchscreen presses
document.ontouchstart = resetTimer;
document.onclick = resetTimer; // touchpad clicks
document.onkeydown = resetTimer; // onkeypress is deprectaed
document.addEventListener('scroll', resetTimer, true); // improved; see comments
Or register desired events using an array
window.addEventListener('load', resetTimer, true);
var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
events.forEach(function(name) {
document.addEventListener(name, resetTimer, true);
});
DOM Events list: http://www.w3schools.com/jsref/dom_obj_event.asp
Remember use window
, or document
according your needs. Here you can see the differences between them: What is the difference between window, screen, and document in Javascript?
Code Updated with @frank-conijn and @daxchen improve: window.onscroll
will not fire if scrolling is inside a scrollable element, because scroll events don't bubble. window.addEventListener('scroll', resetTimer, true)
, the third argument tells the listener to catch event during capture phase instead of bubble phase.
On top of what John B said, it seems like setting the __package__
variable should help, instead of changing __main__
which could screw up other things. But as far as I could test, it doesn't completely work as it should.
I have the same problem and neither PEP 328 or 366 solve the problem completely, as both, by the end of the day, need the head of the package to be included in sys.path
, as far as I could understand.
I should also mention that I did not find how to format the string that should go into those variables. Is it "package_head.subfolder.module_name"
or what?
read hash < <(genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5)
This technique uses Bash's "process substitution" not to be confused with "command substitution".
Here are a few good references:
With Selenium2Library you can use get_source()
import Selenium2Library
s = Selenium2Library.Selenium2Library()
s.open_browser("localhost:7080", "firefox")
source = s.get_source()
this will work
String myName="domanokz";
String p=myName.replace(myName.charAt(4),'x');
System.out.println(p);
Output : domaxokz
You can get the device ip address by this way:
adb shell ip route > addrs.txt
#Case 1:Nexus 7
#192.168.88.0/23 dev wlan0 proto kernel scope link src 192.168.89.48
#Case 2: Smartsian T1,Huawei C8813
#default via 192.168.88.1 dev eth0 metric 30
#8.8.8.8 via 192.168.88.1 dev eth0 metric 30
#114.114.114.114 via 192.168.88.1 dev eth0 metric 30
#192.168.88.0/23 dev eth0 proto kernel scope link src 192.168.89.152 metric 30
#192.168.88.1 dev eth0 scope link metric 30
ip_addrs=$(awk {'if( NF >=9){print $9;}'} addrs.txt)
echo "the device ip address is $ip_addrs"
At any channel page with "user" url for example http://www.youtube.com/user/klauskkpm
, without API call, from YouTube UI, click a video of the channel (in its "VIDEOS" tab) and click the channel name on the video. Then you can get to the page with its "channel" url for example https://www.youtube.com/channel/UCfjTOrCPnAblTngWAzpnlMA
.
//Get
var bla = $('#txt_name').val();
//Set
$('#txt_name').val(bla);
In docker container phpmyadmin/phpmyadmin no php.ini file. But there are two files : php.ini-debug and php.ini-production
To solve the problem, simply rename one of the files to php.ini and restart docker container.
You've got a couple of issues here.
Firstly, you're defining your code within an anonymous function. This construct:
(function() {
...
)();
does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.
You're passing in a code block to setTimeout()
. The problem is that update()
is not within scope when executed like that. It however if you pass in a function pointer instead so this works:
(function() {
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
)();
because the function pointer update
is within scope of that block.
But like I said, there is no need for the anonymous function so you can rewrite it like this:
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
or
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout('update()', 1000); }
}
and both of these work. The second works because the update()
within the code block is within scope now.
I also prefer the $(function() { ... }
shortened block form and rather than calling setTimeout()
within update()
you can just use setInterval()
instead:
$(function() {
setInterval(update, 1000);
});
function update() {
$("#board").append(".");
}
Hope that clears that up.
Node_modules contains user-installed packages so change the directory to node_modules and list the items. Core Modules are defined in node's source in the lib/
folder.
Example:
example@example:~/:~/node_modules$ ls
express maxmind-native node-whois socket.io ua-parser-js
geoip mongoskin pdfkit tail zeromq
maxmind nodemailer request ua-parser zmq
Be aware that there is an additional setting in jQuery UI v1.10. There is an appendTo setting that has been added, to address the ASP.NET workaround you're using to re-add the element to the form.
Try:
$("#dialog").dialog({
autoOpen: false,
height: 280,
width: 440,
modal: true,
**appendTo**:"form"
});
Try this one (right):
<string name="content" formatted="false">Great application %s ? %s ? %s \\n\\nGo to download this application %s</string>
Using hbm.xml
<composite-id>
<!--<key-many-to-one name="productId" class="databaselayer.users.UserDB" column="user_name"/>-->
<key-property name="productId" column="PRODUCT_Product_ID" type="int"/>
<key-property name="categoryId" column="categories_id" type="int" />
</composite-id>
Using Annotation
Composite Key Class
public class PK implements Serializable{
private int PRODUCT_Product_ID ;
private int categories_id ;
public PK(int productId, int categoryId) {
this.PRODUCT_Product_ID = productId;
this.categories_id = categoryId;
}
public int getPRODUCT_Product_ID() {
return PRODUCT_Product_ID;
}
public void setPRODUCT_Product_ID(int PRODUCT_Product_ID) {
this.PRODUCT_Product_ID = PRODUCT_Product_ID;
}
public int getCategories_id() {
return categories_id;
}
public void setCategories_id(int categories_id) {
this.categories_id = categories_id;
}
private PK() { }
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
PK pk = (PK) o;
return Objects.equals(PRODUCT_Product_ID, pk.PRODUCT_Product_ID ) &&
Objects.equals(categories_id, pk.categories_id );
}
@Override
public int hashCode() {
return Objects.hash(PRODUCT_Product_ID, categories_id );
}
}
Entity Class
@Entity(name = "product_category")
@IdClass( PK.class )
public class ProductCategory implements Serializable {
@Id
private int PRODUCT_Product_ID ;
@Id
private int categories_id ;
public ProductCategory(int productId, int categoryId) {
this.PRODUCT_Product_ID = productId ;
this.categories_id = categoryId;
}
public ProductCategory() { }
public int getPRODUCT_Product_ID() {
return PRODUCT_Product_ID;
}
public void setPRODUCT_Product_ID(int PRODUCT_Product_ID) {
this.PRODUCT_Product_ID = PRODUCT_Product_ID;
}
public int getCategories_id() {
return categories_id;
}
public void setCategories_id(int categories_id) {
this.categories_id = categories_id;
}
public void setId(PK id) {
this.PRODUCT_Product_ID = id.getPRODUCT_Product_ID();
this.categories_id = id.getCategories_id();
}
public PK getId() {
return new PK(
PRODUCT_Product_ID,
categories_id
);
}
}
Ended up writing this today and seems to be ok. Your usage could be:
await TaskEx.WaitUntil(isExcelInteractive);
public static class TaskEx
{
/// <summary>
/// Blocks while condition is true or timeout occurs.
/// </summary>
/// <param name="condition">The condition that will perpetuate the block.</param>
/// <param name="frequency">The frequency at which the condition will be check, in milliseconds.</param>
/// <param name="timeout">Timeout in milliseconds.</param>
/// <exception cref="TimeoutException"></exception>
/// <returns></returns>
public static async Task WaitWhile(Func<bool> condition, int frequency = 25, int timeout = -1)
{
var waitTask = Task.Run(async () =>
{
while (condition()) await Task.Delay(frequency);
});
if(waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout)))
throw new TimeoutException();
}
/// <summary>
/// Blocks until condition is true or timeout occurs.
/// </summary>
/// <param name="condition">The break condition.</param>
/// <param name="frequency">The frequency at which the condition will be checked.</param>
/// <param name="timeout">The timeout in milliseconds.</param>
/// <returns></returns>
public static async Task WaitUntil(Func<bool> condition, int frequency = 25, int timeout = -1)
{
var waitTask = Task.Run(async () =>
{
while (!condition()) await Task.Delay(frequency);
});
if (waitTask != await Task.WhenAny(waitTask,
Task.Delay(timeout)))
throw new TimeoutException();
}
}
Example usage: https://dotnetfiddle.net/Vy8GbV
The problem shows up when you're using mysql_connect
in your code lines so just add it as in mysqli_cOnnect
and it will solve the Problem.
you also Have to then use mysqli
throughout your code lines or the Problem would surface again.
example mysql_select_db
will then be mysqL_select_db
.
That's for selecting Database.
Thanks hope this helps
For your property example do:
mvn install "-Dmyproperty=my property from command line"
Note quotes around whole property definition. You'll need them if your property contains spaces.
You can also use Json.NET. Just download it at http://james.newtonking.com/pages/json-net.aspx, extract the compressed file and add it as a reference.
Then just serialize the list (or whatever object you want) with the following:
using Newtonsoft.Json;
string json = JsonConvert.SerializeObject(listTop10);
Update: you can also add it to your project via the NuGet Package Manager (Tools --> NuGet Package Manager --> Package Manager Console):
PM> Install-Package Newtonsoft.Json
Documentation: Serializing Collections
I successfully used "soap" package (https://www.npmjs.com/package/soap) on more than 10 tracking WebApis (Tradetracker, Bbelboon, Affilinet, Webgains, ...).
Problems usually come from the fact that programmers does not investigate to much about what remote API needs in order to connect or authenticate.
For instance PHP resends cookies from HTTP headers automatically, but when using 'node' package, it have to be explicitly set (for instance by 'soap-cookie' package)...
Depending on your version:
Python 2.x:
for key, val in PIX0.iteritems():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))
Python 3.x:
for key, val in PIX0.items():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))
You should also get in the habit of using the new string formatting syntax ({}
instead of %
operator) from PEP 3101:
With the release of Android Studio 4.1 Canary and Dev preview , you can use a new tool called
Install AS 4.1+, run the app, open database inspector, now you can view your database files on the left side of the database inspector panel then select the table to view the content.
Either you can run you queries using Run SQL option or if you are using Room then open database inspector and run the app then, you can run the DAO queries in your interface by clicking on the run button on left of @Query
annotation.
If you want to modify the line width flexibly you can use "scale_size_manual," this is the same procedure for picking the color, fill, alpha, etc.
library(ggplot2)
library(tidyr)
x = seq(0,10,0.05)
df <- data.frame(A = 2 * x + 10,
B = x**2 - x*6,
C = 30 - x**1.5,
X = x)
df = gather(df,A,B,C,key="Model",value="Y")
ggplot( df, aes (x=X, y=Y, size=Model, colour=Model ))+
geom_line()+
scale_size_manual( values = c(4,2,1) ) +
scale_color_manual( values = c("orange","red","navy") )
<!-- HTML4 and (x)HTML -->
<script type="text/javascript"></script>
<!-- HTML5 -->
<script></script>
type attribute identifies the scripting language of code embedded within a script element or referenced via the element’s src attribute. This is specified as a MIME type; examples of supported MIME types include text/javascript, text/ecmascript, application/javascript, and application/ecmascript. If this attribute is absent, the script is treated as JavaScript.
Ref: https://developer.mozilla.org/en/docs/Web/HTML/Element/script
... 7 years later, in the desert, a tumbleweed blows by ...
I wasn't satisfied with the accepted answer so I created some scripts to do this for you available on Github. These should help anyone who wants to use git svn clone
but doesn't want to clone the entire repository and doesn't want to hunt for a specific revision to clone from in the middle of the history (maybe you're cloning a bunch of repos). Here we can just clone the last N revisions:
Use git svn clone
to clone the last 50 revisions
# -u The SVN URL to clone
# -l The limit of revisions
# -o The output directory
./git-svn-cloneback.sh -u https://server/project/trunk -l 50 -o myproj --authors-file=svn-authors.txt
Find the previous N revision from an SVN repo
# -u The SVN URL to clone
# -l The limit of revisions
./svn-lookback.sh -u https://server/project/trunk -l 5
In my case @component
was not working because I initialized that class instance by using new <classname>()
.
If we initialize instance by conventional Java way anywhere in code, then spring won't add that component in IOC container.
The code below worked for me.
df.append(pd.Series([np.nan]), ignore_index = True)
There is an official Python receipe for the more generalized case of splitting an array into smaller arrays of size n
.
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
This code snippet is from the python itertools doc page.
That may be overhead but should work.
double yourDouble = 1.05;
string stringForm = yourDouble.ToString();
int dotPosition = stringForm.IndexOf(".");
decimal decimalPart = Decimal.Parse("0" + stringForm.Substring(dotPosition));
Console.WriteLine(decimalPart); // 0.05