You were setting BCC but then overwriting the variable with the FROM
$to = "[email protected]";
$subject .= "".$emailSubject."";
$headers .= "Bcc: ".$emailList."\r\n";
$headers .= "From: [email protected]\r\n" .
"X-Mailer: php";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= 'THE MESSAGE FROM THE FORM';
if (mail($to, $subject, $message, $headers)) {
$sent = "Your email was sent!";
} else {
$sent = ("Error sending email.");
}
In this example you can identify different areas:
<html>
<style>
#divContainer {
width: 100%;
height: 100%;
}
#divHeader {
position: absolute;
left: 0px;
top: 0px;
right: 0px;
height: 28px;
background-color:blue;
}
#divContentArea {
position: absolute;
left: 0px;
top: 30px;
right: 0px;
bottom: 30px;
}
#divContentLeft {
position: absolute;
top: 0px;
left: 0px;
width: 200px;
bottom: 0px;
background-color:red;
}
#divContentCenter {
position: absolute;
top: 0px;
left: 200px;
bottom: 0px;
right:200px;
background-color:yellow;
}
#divContentRight {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
width:200px;
background-color:red;
}
#divFooter {
position: absolute;
height: 28px;
left: 0px;
bottom: 0px;
right: 0px;
background-color:blue;
}
</style>
<body >
<div id="divContainer">
<div id="divHeader"> top
</div>
<div id="divContentArea">
<div id="divContentLeft">left
</div>
<div id="divContentCenter">center
</div>
<div id="divContentRight">right
</div>
</div>
<div id="divFooter">bottom
</div>
</div>
</body>
</html>
Like others mentioned in this thread, replacing the entire body HTML is a bad idea because it reinserts the entire DOM and can potentially break any other javascript that was acting on those elements.
Instead, replace just the text on your page and not the DOM elements themselves using jQuery filter:
$('body :not(script)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace('-9o0-9909','The new string');
});
this.nodeType is the type of node we are looking to replace the contents of. nodeType 3 is text. See the full list here.
rbind()
needs the two object names to be the same. For example, the first object names: ID Age
, the next object names: ID Gender
,if you want to use rbind()
, it will print out:
names do not match previous names
I didn't see pyformat in the list so I thought I'd throw it in:
console.log(pyformat( 'The {} {} jumped over the {}'
, ['brown' ,'fox' ,'foobar']
))
console.log(pyformat('The {0} {1} jumped over the {1}'
, ['brown' ,'fox' ,'foobar']
))
console.log(pyformat('The {color} {animal} jumped over the {thing}'
, [] ,{color: 'brown' ,animal: 'fox' ,thing: 'foobaz'}
))
It's quite simple, use
Long.valueOf(String s);
For example:
String s;
long l;
Scanner sc=new Scanner(System.in);
s=sc.next();
l=Long.valueOf(s);
System.out.print(l);
You're done!!!
Here is a bash script for newer Maven copy and paste it...
# @author Yucca Nel
#!/bin/sh
#This installs maven2 & a default JDK
sudo apt-get install maven2;
#Makes the /usr/lib/mvn in case...
sudo mkdir -p /usr/lib/mvn;
#Clean out /tmp...
sudo rm -rf /tmp/*;
cd /tmp;
#Update this line to reflect newer versions of maven
wget http://mirrors.powertech.no/www.apache.org/dist//maven/binaries/apache-maven-3.0.3-bin.tar.gz;
tar -xvf ./*gz;
#Move it to where it to logical location
sudo mv /tmp/apache-maven-3.* /usr/lib/mvn/;
#Link the new Maven to the bin... (update for higher/newer version)...
sudo ln -s /usr/lib/mvn/apache-maven-3.0.3/bin/mvn /usr/bin/mvn;
#test
mvn -version;
exit 0;
I always did it in this way:
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
where this
is the JFrame involved.
Use defaultValue and onChange like this
const [myValue, setMyValue] = useState('');
<select onChange={(e) => setMyValue(e.target.value)} defaultValue={props.myprop}>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
Look closely at URI's for ordinary web resources. Those are your template. Think of directory trees; use simple Linux-like file and directory names.
HelloWorld
isn't a really good class of resources. It doesn't appear to be a "thing". It might be, but it isn't very noun-like. A greeting
is a thing.
user-id
might be a noun that you're fetching. It's doubtful, however, that the result of your request is only a user_id. It's much more likely that the result of the request is a User. Therefore, user
is the noun you're fetching
www.example.com/greeting/user/x/
Makes sense to me. Focus on making your REST request a kind of noun phrase -- a path through a hierarchy (or taxonomy, or directory). Use the simplest nouns possible, avoiding noun phrases if possible.
Generally, compound noun phrases usually mean another step in your hierarchy. So you don't have /hello-world/user/
and /hello-universe/user/
. You have /hello/world/user/
and hello/universe/user/
. Or possibly /world/hello/user/
and /universe/hello/user/
.
The point is to provide a navigation path among resources.
You can use PropertyInfo.SetValue(obj, null)
. If called on a value type it will give you the default. This behavior is documented in .NET 4.0 and in .NET 4.5.
Using something like selection.node().getBBox()
you get values like
{
height: 5,
width: 5,
y: 50,
x: 20
}
Use selection.node().getBoundingClientRect()
If you only need two search terms, arguably the most readable approach is to run each search and intersect the results:
comm -12 <(grep -rl word1 . | sort) <(grep -rl word2 . | sort)
Sorting by C and D needs to be put into number form for the corresponding column, ie 3 and 4, respectively. Eg Order By 2 asc")
set the attribute, not a property
$("#ms_num").attr("maxlength", 6);
The answer once accepted here is incorrect (it has since been unaccepted, so hooray!). It does not correctly eliminate all non-intersections. Trivially it may appear to work but it can fail, especially in the case that 0 and 1 are considered valid for h.
Consider the following case:
Lines at (4,1)-(5,1) and (0,0)-(0,2)
These are perpendicular lines which clearly do not overlap.
A=(4,1)
B=(5,1)
C=(0,0)
D=(0,2)
E=(5,1)-(4,1)=(-1,0)
F=(0,2)-(0,0)=(0,-2)
P=(0,1)
h=((4,1)-(0,0)) dot (0,1) / ((0,-2) dot (0,1)) = 0
According to the above answer, these two line segments meet at an endpoint (values of 0 and 1). That endpoint would be:
(0,0)+(0,-2)*0=(0,0)
So, apparently the two line segments meet at (0,0), which is on line CD, but not on line AB. So what is going wrong? The answer is that the values of 0 and 1 are not valid and only sometimes HAPPEN to correctly predict endpoint intersection. When the extension of one line (but not the other) would meet the line segment, the algorithm predicts an intersection of line segments, but this is not correct. I imagine that by testing starting with AB vs CD and then also testing with CD vs AB, this problem would be eliminated. Only if both fall between 0 and 1 inclusively can they be said to intersect.
I recommend using the vector cross product method if you must predict end-points.
-Dan
http://encosia.com/using-cors-to-access-asp-net-services-across-domains/
refer the above link for more details on Cross domain resource sharing.
you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.
sample below:
ajax call:
$(document).ready(function () {
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "<your middle man service url here>/GetQuote?callback=?",
data: { symbol: 'ctsh' },
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
});
service (asmx) which will return jsonp:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetQuote(String symbol,string callback)
{
WebProxy myProxy = new WebProxy("<proxy url here>", true);
myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
SQ.Proxy = myProxy;
String result = SQ.GetQuote(symbol);
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(result));
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
This might be an alternative solution. Paste the following code into the new module:
Public Function ModDate()
ModDate =
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm")
End Function
Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.
Paste the following code into the cell where you want to display the last modification time:
=ModDate()
I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel
There is a good explanation in the documentation of jQuery.fn.on
.
In short:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
.
Thus in the following example #dataTable tbody tr
must exist before the code is generated.
$("#dataTable tbody tr").on("click", function(event){
console.log($(this).text());
});
If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it:
$("#dataTable tbody").on("click", "tr", function(event){
console.log($(this).text());
});
In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody
, the first code example attaches a handler to 1,000 elements.
A delegated-events approach (the second code example) attaches an event handler to only one element, the tbody
, and the event only needs to bubble up one level (from the clicked tr
to tbody
).
Note: Delegated events do not work for SVG.
It is working for "greater than" functions not for less than.
For example:
select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) > '2000' limit 10;
is working fine.
but for
select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) < '2000' limit 10;
I am getting error.
Use the ASCII to Integer atoi()
function which accepts a string and converts it into an integer:
#include <stdlib.h>
int num = atoi("23"); // 23
If the string contains a decimal, the number will be truncated:
int num = atoi("23.21"); // 23
Here is SQL for setting up an example:
CREATE TABLE employee(name varchar, paymentType varchar, amount bigint);
INSERT INTO employee VALUES('Aaron', 'salary', 100);
INSERT INTO employee VALUES('Aaron', 'bonus', 50);
INSERT INTO employee VALUES('Bob', 'salary', 50);
INSERT INTO employee VALUES('Bob', 'bonus', 0);
The Inject class is vulnerable to SQL injection. The query is dynamically pasted together with user input. The intent of the query was to show information about Bob. Either salary or bonus, based on user input. But the malicious user manipulates the input corrupting the query by tacking on the equivalent of an 'or true' to the where clause so that everything is returned, including the information about Aaron which was supposed to be hidden.
import java.sql.*;
public class Inject {
public static void main(String[] args) throws SQLException {
String url = "jdbc:postgresql://localhost/postgres?user=user&password=pwd";
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
String sql = "SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='" + args[0] + "'";
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString("paymentType") + " " + rs.getLong("amount"));
}
}
}
Running this, the first case is with normal usage, and the second with the malicious injection:
c:\temp>java Inject salary
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='salary'
salary 50
c:\temp>java Inject "salary' OR 'a'!='b"
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='salary' OR 'a'!='b'
salary 100
bonus 50
salary 50
bonus 0
You should not build your SQL statements with string concatenation of user input. Not only is it vulnerable to injection, but it has caching implications on the server as well (the statement changes, so less likely to get a SQL statement cache hit whereas the bind example is always running the same statement).
Here is an example of Binding to avoid this kind of injection:
import java.sql.*;
public class Bind {
public static void main(String[] args) throws SQLException {
String url = "jdbc:postgresql://localhost/postgres?user=postgres&password=postgres";
Connection conn = DriverManager.getConnection(url);
String sql = "SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?";
System.out.println(sql);
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, args[0]);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("paymentType") + " " + rs.getLong("amount"));
}
}
}
Running this with the same input as the previous example shows the malicious code does not work because there is no paymentType matching that string:
c:\temp>java Bind salary
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?
salary 50
c:\temp>java Bind "salary' OR 'a'!='b"
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/images/json: dial unix /var/run/docker.sock: connect: permission denied
sudo chmod 666 /var/run/docker.sock
This fix my problem.
You can either use javascript url form with
<form action="javascript:handleClick()">
Or use onSubmit event handler
<form onSubmit="return handleClick()">
In the later form, if you return false from the handleClick it will prevent the normal submision procedure. Return true if you want the browser to follow normal submision procedure.
Your onSubmit event handler in the button also fails because of the Javascript:
part
EDIT: I just tried this code and it works:
<html>
<head>
<script type="text/javascript">
function handleIt() {
alert("hello");
}
</script>
</head>
<body>
<form name="myform" action="javascript:handleIt()">
<input name="Submit" type="submit" value="Update"/>
</form>
</body>
</html>
Using Java’s Float
class.
float f = Float.parseFloat("25");
String s = Float.toString(25.0f);
To compare it's always better to convert the string to float and compare as two floats. This is because for one float number there are multiple string representations, which are different when compared as strings (e.g. "25" != "25.0" != "25.00" etc.)
numpy.linspace()
gives you a one-dimensional NumPy array. For example:
>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
Therefore:
for index,point in my_array
cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:
>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])
Now you can do this:
>>> for x, y in two_d:
print(x, y)
1 2
4 5
HashMap<Emp, Emp> empHashMap = new HashMap<Emp, Emp>();
empHashMap.put(new Emp(1), new Emp(1));
empHashMap.put(new Emp(1), new Emp(1));
empHashMap.put(new Emp(1), new Emp());
empHashMap.put(new Emp(1), new Emp());
System.out.println(empHashMap.size());
}
}
class Emp{
public Emp(){
}
public Emp(int id){
this.id = id;
}
public int id;
@Override
public boolean equals(Object obj) {
return this.id == ((Emp)obj).id;
}
@Override
public int hashCode() {
return id;
}
}
OUTPUT : is 1
Means hash map wont allow duplicates, if you have properly overridden equals and hashCode() methods.
HashSet also uses HashMap internally, see the source doc
public class HashSet{
public HashSet() {
map = new HashMap<>();
}
}
I don't have R on this computer, but here is a crack at it. You can use par
to display multiple plots in a window, or like this to prompt for a click before displaying the next page.
plotfun <- function(col)
plot(data[ , col], ylab = names(data[col]), type = "l")
par(ask = TRUE)
sapply(seq(1, length(data), 1), plotfun)
restart MySQL server with --skip-grant-tables option And then set a new root password
$ mysql -u root
mysql> USE mysql;
mysql> UPDATE user SET password=PASSWORD("NEWPASSWORD") WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> quit
Now if you need, you can update mysql.user table(field password_expired='N') not to expire the password.
I found a nice one liner here >> http://www.pixelchef.net/remove-empty-lines-file-powershell. Just tested it out with several blanks lines including newlines only as well as lines with just spaces, just tabs, and combinations.
(gc file.txt) | ? {$_.trim() -ne "" } | set-content file.txt
See the original for some notes about the code. Nice :)
#!/bin/sh
#Procedures = update
#Scheduled at : Every 00.05
v_path=/etc/database_jobs
v_cnt=0
MAILTO="[email protected] [email protected] [email protected]"
touch "$v_path/db_db_log.log"
#test
mysql -uusername -ppassword -h111.111.111.111 db_name -e "CALL functionName()" > $v_path/db_db_log.log 2>&1
if [ "$?" -eq 0 ]
then
v_cnt=`expr $v_cnt + 1`
mail -s "db Attendance Update has been run successfully" $MAILTO < $v_path/db_db_log.log
else
mail -s "Alert : db Attendance Update has been failed" $MAILTO < $v_path/db_db_log.log
exit
fi
I created a custom git alias to do that for me:
alias.changes=!git log --name-status HEAD..
with that you can do this:
$git fetch
$git changes origin
This will get you a nice and easy way to preview changes before doing a merge
.
This is useful when you have your own origin
which is not upstream
. In other words, you might have your own origin
repo that you do development and local changes in and then occasionally merge upstream
changes. The difference between your example and the highlighted text is that your example assumes you're working with a clone of the upstream repo directly. The highlighted text assumes you're working on a clone of your own repo that was, presumably, originally a clone of upstream.
This works well when ng-class can't be used (for example when styling SVG):
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"
(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)
I have published an article on working with AngularJS+SVG. It talks about this issue and numerous others. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS
The return false
prevents the page from being navigated and unwanted scrolling of a window to the top or bottom.
onclick="return false"
Are you specifically trying to rotate the links only? Because doing it on the LI tags seems to work fine.
According to Snook transforms require the elements affected be block. He's also got some code there to make this work for IE using filters, if you care to add it on(though there appears to be some limitation on values).
You best see if you have a parent element of the div you are querying. If so get the parent element and perform an element.querySelectorAll("div")
. Once you get the nodeList
apply a filter on it over the innerText
property. Assume that a parent element of the div that we are querying has an id
of container
. You can normally access container directly from the id but let's do it the proper way.
var conty = document.getElementById("container"),
divs = conty.querySelectorAll("div"),
myDiv = [...divs].filter(e => e.innerText == "SomeText");
So that's it.
You can go to IE Tools -> Internet options -> Advanced Tab
. Under Advanced, check for security and put a check on the 1st 2 options which says,"Allow active content from CDs to run on My Computer* and Allow active content to run in files on My Computer*"
Restart your browser and the ActiveX scripts will not be shown.
I managed to get the ripple effect on the cardview by :
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:clickable="true"
android:foreground="@drawable/custom_bg"/>
and for the custom_bg that you can see in above code, you have to define a xml file for both lollipop(in drawable-v21 package) and pre-lollipop(in drawable package) devices. for custom_bg in drawable-v21 package the code is:
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:attr/colorControlHighlight">
<item
android:id="@android:id/mask"
android:drawable="@android:color/white"/>
</ripple>
for custom_bg in the drawable package, code is:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid android:color="@color/colorHighlight"></solid>
</shape>
</item>
<item>
<shape>
<solid android:color="@color/navigation_drawer_background"></solid>
</shape>
</item>
</selector>
so on pre-lollipop devices you will have a solid click effect and on lollipop devices you will have a ripple effect on the cardview.
Everyone is right: stick with POST for non-idempotent requests.
What about using both an URI query string and request content? Well it's valid HTTP (see note 1), so why not?!
It is also perfectly logical: URLs, including their query string part, are for locating resources. Whereas HTTP method verbs (POST - and its optional request content) are for specifying actions, or what to do with resources. Those should be orthogonal concerns. (But, they are not beautifully orthogonal concerns for the special case of ContentType=application/x-www-form-urlencoded, see note 2 below.)
Note 1: HTTP specification (1.1) does not state that query parameters and content are mutually exclusive for a HTTP server that accepts POST or PUT requests. So any server is free to accept both. I.e. if you write the server there's nothing to stop you choosing to accept both (except maybe an inflexible framework). Generally, the server can interpret query strings according to whatever rules it wants. It can even interpret them with conditional logic that refers to other headers like Content-Type too, which leads to Note 2:
Note 2: if a web browser is the primary way people are accessing your web application, and application/x-www-form-urlencoded is the Content-Type they are posting, then you should follow the rules for that Content-Type. And the rules for application/x-www-form-urlencoded are much more specific (and frankly, unusual): in this case you must interpret the URI as a set of parameters, and not a resource location. [This is the same point of usefulness Powerlord raised; that it may be hard to use web forms to POST content to your server. Just explained a little differently.]
Note 3: what are query strings originally for? RFC 3986 defines HTTP query strings as an URI part that works as a non-hierarchical way of locating a resource.
In case readers asking this question wish to ask what is good RESTful architecture: the RESTful architecture pattern doesn't require URI schemes to work a specific way. RESTful architecture concerns itself with other properties of the system, like cacheability of resources, the design of the resources themselves (their behavior, capabilities, and representations), and whether idempotence is satisfied. Or in other words, achieving a design which is highly compatible with HTTP protocol and its set of HTTP method verbs. :-) (In other words, RESTful architecture is not very presciptive with how the resources are located.)
Final note: sometimes query parameters get used for yet other things, which are neither locating resources nor encoding content. Ever seen a query parameter like 'PUT=true' or 'POST=true'? These are workarounds for browsers that don't allow you to use PUT and POST methods. While such parameters are seen as part of the URL query string (on the wire), I argue that they are not part of the URL's query in spirit.
You can do a variety of things. What I would do is this.
Create an array on scope that will be your data structure for the phone numbers.
$scope.telephone = '';
$scope.numbers = [];
Then in your html I would have this
<input type="text" ng-model="telephone">
<button ng-click="submitNumber()">Submit</button>
Then when your user clicks submit, run submitNumber(), which pushes the new telephone number into the numbers array.
$scope.submitNumber = function(){
$scope.numbers.push($scope.telephone);
}
LocalDate.of( 2018 , Month.JANUARY , 23 )
.format( DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US ) )
The modern approach uses the java.time classes.
LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;
Note how we specify a Locale
such as Locale.CANADA_FRENCH
to determine the human language used to translate the name of the day.
DateTimeFormatter f = DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US ) ;
String output = ld.format( f ) ;
By the way, you may be interested in the standard ISO 8601 week numbering scheme: yyyy-Www-d
.
2018-W01-2
Week # 1 has the first Thursday of the calendar-year. Week starts on a Monday. A year has either 52 or 53 weeks. The last/first few days of a calendar-year may land in the next/previous week-based-year.
The single digit on the end is day-of-week, 1-7 for Monday-Sunday.
Add the ThreeTen-Extra library class to your project for the YearWeek
class.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
What did it for me was the following, I've added the following directive in both the http <VirtualHost *:80>
and https <VirtualHost *:443>
virtual host blocks:
ServerName your-app.com
ServerAlias www.your-app.com
Header always unset X-Frame-Options
Header set X-Frame-Options "SAMEORIGIN"
The reasoning behind this? Well by default if set, the server does not reset the X-Frame-Options
header so we need to first always remove the default value, in my case it was DENY
, and then with the next rule we set it to the desired value, in my case SAMEORIGIN
. Of course you can use the Header set X-Frame-Options ALLOW-FROM ...
rule as well.
You can update with a join if you only affect one table like this:
UPDATE table1
SET table1.name = table2.name
FROM table1, table2
WHERE table1.id = table2.id
AND table2.foobar ='stuff'
But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.
However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.
But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.
I tried all of the different things but nothing seems to be working then I just restarted my IDE and it worked like charm.
Still, if it does not work then try restarting your system.
FYI, I am working on the following versions
opencv-contrib-python==4.4.0.46
opencv-python==4.1.2.30
@ECHO OFF
TITLE Addition
ECHO Type the first number you wish to add:
SET /P Num1Add=
ECHO Type the second number you want to add to the first number:
SET /P Num2Add=
ECHO.
SET /A Ans=%Num1Add%+%Num2Add%
ECHO The result is: %Ans%
ECHO.
ECHO Press any key to exit.
PAUSE>NUL
public View recentView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create a relative layout and add a button
relativeLayout = new RelativeLayout(this);
btn = new Button(this);
btn.setId((int)System.currentTimeMillis());
recentView = btn;
btn.setText("Click me");
relativeLayout.addView(btn);
setContentView(relativeLayout);
btn.setOnClickListener(new View.OnClickListener() {
@Overr ide
public void onClick(View view) {
//Create a textView, set a random ID and position it below the most recently added view
textView = new TextView(ActivityName.this);
textView.setId((int)System.currentTimeMillis());
layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW, recentView.getId());
textView.setText("Time: "+System.currentTimeMillis());
relativeLayout.addView(textView, layoutParams);
recentView = textView;
}
});
}
This can be modified to display each element of a String array in different TextViews.
Maybe you have no Comments record with such primary key, then you should use this code:
try:
comment = Comment.objects.get(pk=comment_id)
except Comment.DoesNotExist:
comment = None
One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:
SELECT a.ID,
a.AText,
(SELECT Count(ID)
FROM table1 b WHERE b.ID <= a.ID
AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;
Dir[File.dirname(__FILE__) + '/../lib/*.rb'].each do |file|
require File.basename(file, File.extname(file))
end
If you don't strip the extension then you may end up requiring the same file twice (ruby won't realize that "foo" and "foo.rb" are the same file). Requiring the same file twice can lead to spurious warnings (e.g. "warning: already initialized constant").
This works for me for BlueStacks 4:
Try this...
I am in Windows 7 with Code::Blocks
while (true)
{
char input;
input = getch();
switch(input)
{
case -32: //This value is returned by all arrow key. So, we don't want to do something.
break;
case 72:
printf("up");
break;
case 75:
printf("left");
break;
case 77:
printf("right");
break;
case 80:
printf("down");
break;
default:
printf("INVALID INPUT!");
break;
}
}
Java nio has options to access creationTime and other meta-data as long as the filesystem provides it. Check this link out
For example(Provided based on @ydaetskcoR's comment):
Path file = ...;
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
If you're willing to give up a hint of abstraction, then you could use a custom wrapper class which simply passes everything through to the PDO. Say, something like this: (Warning, code untested)
class SQLitePDOWrapper
{
private $pdo;
public function __construct( $dns, $uname = null, $pwd = null, $opts = null )
{
$this->pdo = new PDO( $dns, $unam, $pwd, $opts );
}
public function __call( $nm, $args )
{
$ret = call_user_func_array( array( $this->pdo, $nm ), $args );
if( $ret instanceof PDOStatement )
{
return new StatementWrapper( $this, $ret, $args[ 0 ] );
// I'm pretty sure args[ 0 ] will always be your query,
// even when binding
}
return $ret;
}
}
class StatementWrapper
{
private $pdo; private $stat; private $query;
public function __construct( PDO $pdo, PDOStatement $stat, $query )
{
$this->pdo = $pdo;
$this->stat = $stat;
this->query = $query;
}
public function rowCount()
{
if( strtolower( substr( $this->query, 0, 6 ) ) == 'select' )
{
// replace the select columns with a simple 'count(*)
$res = $this->pdo->query(
'SELECT COUNT(*)' .
substr( $this->query,
strpos( strtolower( $this->query ), 'from' ) )
)->fetch( PDO::FETCH_NUM );
return $res[ 0 ];
}
return $this->stat->rowCount();
}
public function __call( $nm, $args )
{
return call_user_func_array( array( $this->stat, $nm ), $args );
}
}
If you are on Mac OSX Maverick,
it's ~/.bash_profile
not ~/.bashrc
Try putting the code in there, close the terminal and then try again. Should be working
We can concat same column or also other column of the table.
I had to do something like this just now. I ended up doing:
function newWaitImg(id) {
var img = {
"id" : id,
"state" : "on",
"hide" : function () {
$(this.id).hide();
this.state = "off";
},
"show" : function () {
$(this.id).show();
this.state = "on";
},
"toggle" : function () {
if (this.state == "on") {
this.hide();
} else {
this.show();
}
}
};
};
.
.
.
var waitImg = newWaitImg("#myImg");
.
.
.
waitImg.hide(); / waitImg.show(); / waitImg.toggle();
Thanks for your answers, @mvp, @xero, I get what I want base on both of your answers.
git log --name-only
or
git log --name-only --oneline
for short.
You can also use Url.Action for the path instead like so:
$.ajax({
url: "@Url.Action("Holiday", "Calendar", new { area = "", year= (val * 1) + 1 })",
type: "GET",
success: function (partialViewResult) {
$("#refTable").html(partialViewResult);
}
});
After all those long tally of answers, i found this piece of code simple and easy to understand!
function end(str, target) {
return str.substr(-target.length) == target;
}
getopt Use command in your scripts to format any command line options or parameters.
#!/bin/bash
# Extract command line options & values with getopt
#
set -- $(getopt -q ab:cd "$@")
#
echo
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option" ;;
-b) param="$2"
echo "Found the -b option, with parameter value $param"
shift ;;
-c) echo "Found the -c option" ;;
--) shift
break ;;
*) echo "$1 is not an option";;
esac
shift
CMS has it right, but also if you use the server explorer in visual studio and play around with the performance counter tab then you can figure out how to get lots of useful metrics.
I had that problem before. I just solved it by expanding the tomcat tree and delete the folder that is causing the clash. in your case is /FirstApache
. after you delete it. then you rerun it, you should be able to run. If it happens again, delete it and try again.
The MOD
keyword only exists in the DAX
language (tabular dimensional queries), not TSQL
Use %
instead.
Ref: Modulo
You can do it with a WITH
clause.
For example:
WITH c AS (SELECT DISTINCT a, b, c FROM tableName)
SELECT * FROM tableName r, c WHERE c.rowid=r.rowid AND c.a=r.a AND c.b=r.b AND c.c=r.c
This also allows you to select only the rows selected in the WITH
clauses query.
The top answer didn't work for me: I had no environment variables defining the Java path or no Java in my path.
However, the path C:\ProgramData\Oracle\Java\javapath\javaw.exe was always present in the Eclipse 4.5 (Mars) error popup in the -vm
option even if I tried to override in file eclipse.ini.
I worked around this by opening a command prompt, cd'ing the directory where the eclipse.exe was and using MKLink:
C:\EclipseMars> mklink javaw.exe "C:\Program Files\Java\jdk1.7.0_79\bin"
symbolic link created for javaw.exe <<===>> C:\Program Files\Java\jdk1.7.0_79\bin
No changes to eclipse.ini were required.
I did try to specify the -vm
option of in eclipse.ini, and it was taken into account, but in the error popup a -vm
option was present twice even if only one -vm
was present in eclipse.ini.
In my eclipse.ini I have no -vm
option and just the symlink seems to have corrected it.
Here the working code.
// Encode byte array into string . TemplateBuffer1 is my bytearry variable.
String finger_buffer = Base64.encodeToString(templateBuffer1, Base64.DEFAULT);
Log.d(TAG, "Captured biometric device->" + finger_buffer);
// Decode String into Byte Array. decodedString is my bytearray[]
decodedString = Base64.decode(finger_buffer, Base64.DEFAULT);
Something like this?
The idea is to wrap the <table>
in a non-statically positioned <div>
which has an overflow:auto
CSS property. Then position the elements in the <thead>
absolutely.
#table-wrapper {_x000D_
position:relative;_x000D_
}_x000D_
#table-scroll {_x000D_
height:150px;_x000D_
overflow:auto; _x000D_
margin-top:20px;_x000D_
}_x000D_
#table-wrapper table {_x000D_
width:100%;_x000D_
_x000D_
}_x000D_
#table-wrapper table * {_x000D_
background:yellow;_x000D_
color:black;_x000D_
}_x000D_
#table-wrapper table thead th .text {_x000D_
position:absolute; _x000D_
top:-20px;_x000D_
z-index:2;_x000D_
height:20px;_x000D_
width:35%;_x000D_
border:1px solid red;_x000D_
}
_x000D_
<div id="table-wrapper">_x000D_
<div id="table-scroll">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th><span class="text">A</span></th>_x000D_
<th><span class="text">B</span></th>_x000D_
<th><span class="text">C</span></th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr> <td>1, 0</td> <td>2, 0</td> <td>3, 0</td> </tr>_x000D_
<tr> <td>1, 1</td> <td>2, 1</td> <td>3, 1</td> </tr>_x000D_
<tr> <td>1, 2</td> <td>2, 2</td> <td>3, 2</td> </tr>_x000D_
<tr> <td>1, 3</td> <td>2, 3</td> <td>3, 3</td> </tr>_x000D_
<tr> <td>1, 4</td> <td>2, 4</td> <td>3, 4</td> </tr>_x000D_
<tr> <td>1, 5</td> <td>2, 5</td> <td>3, 5</td> </tr>_x000D_
<tr> <td>1, 6</td> <td>2, 6</td> <td>3, 6</td> </tr>_x000D_
<tr> <td>1, 7</td> <td>2, 7</td> <td>3, 7</td> </tr>_x000D_
<tr> <td>1, 8</td> <td>2, 8</td> <td>3, 8</td> </tr>_x000D_
<tr> <td>1, 9</td> <td>2, 9</td> <td>3, 9</td> </tr>_x000D_
<tr> <td>1, 10</td> <td>2, 10</td> <td>3, 10</td> </tr>_x000D_
<!-- etc... -->_x000D_
<tr> <td>1, 99</td> <td>2, 99</td> <td>3, 99</td> </tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
I feed a 514 dimensional real-valued input to a Sequential
model in Keras.
My model is constructed in following way :
predictivemodel = Sequential()
predictivemodel.add(Dense(514, input_dim=514, W_regularizer=WeightRegularizer(l1=0.000001,l2=0.000001), init='normal'))
predictivemodel.add(Dense(257, W_regularizer=WeightRegularizer(l1=0.000001,l2=0.000001), init='normal'))
predictivemodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
When I print model.summary()
I get following result:
Layer (type) Output Shape Param # Connected to
================================================================
dense_1 (Dense) (None, 514) 264710 dense_input_1[0][0]
________________________________________________________________
activation_1 (None, 514) 0 dense_1[0][0]
________________________________________________________________
dense_2 (Dense) (None, 257) 132355 activation_1[0][0]
================================================================
Total params: 397065
________________________________________________________________
For the dense_1 layer , number of params is 264710. This is obtained as : 514 (input values) * 514 (neurons in the first layer) + 514 (bias values)
For dense_2 layer, number of params is 132355. This is obtained as : 514 (input values) * 257 (neurons in the second layer) + 257 (bias values for neurons in the second layer)
(char)myint;
for example:
Console.WriteLine("(char)122 is {0}", (char)122);
yields:
(char)122 is z
It was particular for me. I am sending a header named 'SESSIONHASH'. No problem for Chrome and Opera, but Firefox also wants this header in the list "Access-Control-Allow-Headers". Otherwise, Firefox will throw the CORS error.
For Indigo (and probably Helios) the checkboxes mentioned above are located here:
Window -> Preferences -> Maven
.img-responsive {
margin: 0 auto;
}
you can write like above code in your document so no need to add one another class in image tag.
This worked for me: Type npm audit fix
in the commandline. Afterwards I was able to use ng serve --open
again.
I removed the old web library such that are spring framework libraries. And build a new path of the libraries. Then it works.
You cannot validate alone with JS only. But if you want to check in the submit button that reCAPTCHA is validated or not that is user has clicked on reCAPTCHA then you can do that using below code.
let recaptchVerified = false;
firebase.initializeApp(firebaseConfig);
firebase.auth().languageCode = 'en';
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container',{
'callback': function(response) {
recaptchVerified = true;
// reCAPTCHA solved, allow signInWithPhoneNumber.
// ...
},
'expired-callback': function() {
// Response expired. Ask user to solve reCAPTCHA again.
// ...
}
});
Here I have used a variable recaptchVerified where I make it initially false and when Recaptcha is validated then I make it true.
So I can use recaptchVerified variable when the user click on the submit button and check if he had verified the captcha or not.
Because that's not what strip()
does. It removes leading and trailing characters that are present in the argument, but not those characters in the middle of the string.
You could do:
name= name.replace('(', '').replace(')', '').replace ...
or:
name= ''.join(c for c in name if c not in '(){}<>')
or maybe use a regex:
import re
name= re.sub('[(){}<>]', '', name)
It is also possible to open the pdf link in a new window and let the browser handle the rest:
window.open(pdfUrl, '_blank');
or:
window.open(pdfUrl);
I use let
to test my HTTP 404 responses in my API specs using contexts.
To create the resource, I use let!
. But to store the resource identifier, I use let
. Take a look how it looks like:
let!(:country) { create(:country) }
let(:country_id) { country.id }
before { get "api/countries/#{country_id}" }
it 'responds with HTTP 200' { should respond_with(200) }
context 'when the country does not exist' do
let(:country_id) { -1 }
it 'responds with HTTP 404' { should respond_with(404) }
end
That keeps the specs clean and readable.
the common short answer is: if you are using AJAX to make data requests, you can easily send and return objects as JSON strings. Available extensions for Javascript support toJSON() calls on all javascript types for sending data to the server in an AJAX request. AJAX responses can return objects as JSON strings which can be converted into Javascript objects by a simple eval call, e.g. if the AJAX function someAjaxFunctionCallReturningJson returned
"{ \"FirstName\" : \"Fred\", \"LastName\" : \"Flintstone\" }"
you could write in Javascript
var obj = eval("(" + someAjaxFunctionCallReturningJson().value + ")");
alert(obj.FirstName);
alert(obj.LastName);
JSON can also be used for web service payloads et al, but it is really convenient for AJAX results.
There is a boost range adaptor for this purpose:
#include <boost/range/adaptor/map.hpp>
#include <boost/range/algorithm/copy.hpp>
vector<int> keys;
boost::copy(m | boost::adaptors::map_keys, std::back_inserter(keys));
There is a similar map_values range adaptor for extracting the values.
I had this issue after my database was working fine for long time. It turned out it was some data corruption.
In the error log I had:
2017-02-07T10:11:42.270567Z 0 [ERROR] InnoDB: Ignoring the redo log due to missing MLOG_CHECKPOINT between the checkpoint 44002250712 and the end 44002250240.
2017-02-07T10:11:42.270606Z 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2017-02-07T10:11:42.577436Z 0 [ERROR] Plugin 'InnoDB' init function returned error.
2017-02-07T10:11:42.577470Z 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2017-02-07T10:11:42.577484Z 0 [ERROR] Failed to initialize plugins.
2017-02-07T10:11:42.577488Z 0 [ERROR] Aborting
Then I had to delete the 2 ib_logfile* files, and it restarted again.
Check out Quartz.NET. You can use it within a Windows service. It allows you to run a job based on a configured schedule, and it even supports a simple "cron job" syntax. I've had a lot of success with it.
Here's a quick example of its usage:
// Instantiate the Quartz.NET scheduler
var schedulerFactory = new StdSchedulerFactory();
var scheduler = schedulerFactory.GetScheduler();
// Instantiate the JobDetail object passing in the type of your
// custom job class. Your class merely needs to implement a simple
// interface with a single method called "Execute".
var job = new JobDetail("job1", "group1", typeof(MyJobClass));
// Instantiate a trigger using the basic cron syntax.
// This tells it to run at 1AM every Monday - Friday.
var trigger = new CronTrigger(
"trigger1", "group1", "job1", "group1", "0 0 1 ? * MON-FRI");
// Add the job to the scheduler
scheduler.AddJob(job, true);
scheduler.ScheduleJob(trigger);
Disclaimer: I first wrote this and then stumbled upon this question. I thought this solution wasn't yet posted, and saw that tlwhitec did post a similar answer. Still I'm posting this because I hope it's a useful and thorough explanation.
Short answer:
This seems quite a portable solution, as it works on quite some shells (see comment).
This way you can get a real newline into a variable.
The benefit of this solution is that you don't have to use newlines in your source code, so you can indent your code any way you want, and the solution still works. This makes it robust. It's also portable.
# Robust way to put a real newline in a variable (bash, dash, ksh, zsh; indentation-resistant).
nl="$(printf '\nq')"
nl=${nl%q}
Longer answer:
Explanation of the above solution:
The newline would normally lost due to command substitution, but to prevent that, we add a 'q' and remove it afterwards. (The reason for the double quotes is explained further below.)
We can prove that the variable contains an actual newline character (0x0A):
printf '%s' "$nl" | hexdump -C
00000000 0a |.|
00000001
(Note that the '%s'
was needed, otherwise printf will translate a literal '\n'
string into an actual 0x0A character, meaning we would prove nothing.)
Of course, instead of the solution proposed in this answer, one could use this as well (but...):
nl='
'
... but that's less robust and can be easily damaged by accidentally indenting the code, or by forgetting to dedent it afterwards, which makes it inconvenient to use in (indented) functions, whereas the earlier solution is robust.
Now, as for the double quotes:
The reason for the double quotes "
surrounding the command substitution as in nl="$(printf '\nq')"
is that you can then even prefix the variable assignment with the local
keyword or builtin (such as in functions), and it will still work on all shells, whereas otherwise the dash
shell would have trouble, in the sense that dash would otherwise lose the 'q' and you'd end up with an empty 'nl' variable (again, due to command substitution).
That issue is better illustrated with another example:
dash_trouble_example() {
e=$(echo hello world) # Not using 'local'.
echo "$e" # Fine. Outputs 'hello world' in all shells.
local e=$(echo hello world) # But now, when using 'local' without double quotes ...:
echo "$e" # ... oops, outputs just 'hello' in dash,
# ... but 'hello world' in bash and zsh.
local f="$(echo hello world)" # Finally, using 'local' and surrounding with double quotes.
echo "$f" # Solved. Outputs 'hello world' in dash, zsh, and bash.
# So back to our newline example, if we want to use 'local', we need
# double quotes to surround the command substitution:
# (If we didn't use double quotes here, then in dash the 'nl' variable
# would be empty.)
local nl="$(printf '\nq')"
nl=${nl%q}
}
Practical example of the above solution:
# Parsing lines in a for loop by setting IFS to a real newline character:
nl="$(printf '\nq')"
nl=${nl%q}
IFS=$nl
for i in $(printf '%b' 'this is line 1\nthis is line 2'); do
echo "i=$i"
done
# Desired output:
# i=this is line 1
# i=this is line 2
# Exercise:
# Try running this example without the IFS=$nl assignment, and predict the outcome.
In my case there was a conflict in the namespaces , I have:
using System.Web.Mvc;
and
using System.Collections.Generic;
I explicitly want to use the Mvc one so I declared it as :
new System.Web.Mvc.SelectList(...)
I'm using a 3rd party program that executes Oracle SQL and I encountered this error. Prior to a SELECT
statement, I had some commented notes that included special characters. Removing the comments resolved the issue.
First, the valid syntax is
jQuery("input[name=ticketID]")
second, have you tried:
jQuery(":radio")
instead?
third, why not assign a class to all the radio buttons, and select them by class?
I struggled for a while about this. Stupid rule for __init__
. It is two "_" together to be "__"
You can set it as a no title bar theme in the activity's xml in the AndroidManifest
<activity
android:name=".AnActivity"
android:label="@string/a_string"
android:theme="@android:style/Theme.NoTitleBar">
</activity>
An easier way to do this in the current stable version (1.0.6) requires a lot less code.
After setting up your module add a factory:
var app = angular.module('myApp', []);
// Configure routes and controllers and views associated with them.
app.config(function ($routeProvider) {
// route setups
});
app.factory('MyCache', function ($cacheFactory) {
return $cacheFactory('myCache');
});
Now you can pass this into your controller:
app.controller('MyController', function ($scope, $http, MyCache) {
$http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) {
// stuff with results
});
});
One downside is that the key names are also setup automatically, which could make clearing them tricky. Hopefully they'll add in some way to get key names.
git stash pop
throws away the (topmost, by default) stash after applying it, whereas git stash apply
leaves it in the stash list for possible later reuse (or you can then git stash drop
it).
This happens unless there are conflicts after git stash pop
, in which case it will not remove the stash, leaving it to behave exactly like git stash apply
.
Another way to look at it: git stash pop
is git stash apply && git stash drop
.
This simple trick works: Copy and Paste. Do NOT cut and paste. After you paste, then reselect the part you copied and go to EDIT, slide down to CLEAR, and CLEAR CONTENTS.
Just export you view and you will have all SQL need to make some change on it.
Just need to add your change in SQL query for the view and change :
CREATE for CREATE OR REPLACE
There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:
with open(filename, 'r') as f:
next(f)
for line in f:
and:
with open(filename,'r') as f:
lines = f.readlines()[1:]
I've found that modifying the textbox style (ie: controltemplate
) and then modifying the PART_ContentHost
vertical alignment to Center will do the trick
Yes, Mid
.
Dim sub_str
sub_str = Mid(source_str, 10, 5)
The first parameter is the source string, the second is the start index, and the third is the length.
@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid
results in "invalid procedure call or argument Mid".
This is an easier way to do it. Hope this helps...
<script type="text/javascript">
$(document).ready(function () {
$("#preview").toggle(function() {
$("#div1").hide();
$("#div2").show();
}, function() {
$("#div1").show();
$("#div2").hide();
});
});
<div id="div1">
This is preview Div1. This is preview Div1.
</div>
<div id="div2" style="display:none;">
This is preview Div2 to show after div 1 hides.
</div>
<div id="preview" style="color:#999999; font-size:14px">
PREVIEW
</div>
Links:
http://www.w3schools.com/jquery/default.asp (W3Schools)
http://thenewboston.org/list.php?cat=32 (Video Tutorials)
http://andreehansson.se/the-basics-of-jquery/ (Basic Tutorial)
Just add this line of code in your build.gradle file and it will work.
implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
Also add these below line if above did not work at all.
compile 'com.google.android.gms:play-services:+'
compile ('org.apache.httpcomponents:httpmime:4.2.6'){
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient:4.2.6'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
you have to add [System.Serializable]
to PlayerItem
class ,like this:
using System;
[System.Serializable]
public class PlayerItem {
public string playerId;
public string playerLoc;
public string playerNick;
}
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.BLACK);
String title = context.getString(R.string.agreement_popup_message);
SpannableStringBuilder ssBuilder = new SpannableStringBuilder(title);
ssBuilder.setSpan(
foregroundColorSpan,
0,
title.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(context);
alertDialogBuilderUserInput.setTitle(ssBuilder)
Relative:
An element with position: relative;
is positioned relative to its normal position.
If you add no positioning attributes (top, left, bottom or right) on a relative element it will have no effect on it's positioning at all. It will behave exactly as a position: static
element.
But if you do add some other positioning attribute, say, top: 10px;, it will shift its position 10 pixels down from where it would normally be.
An element with this type of positioning gets affected by other elements and it itself also affects others.
Absolute:
An element with position: absolute;
allows you to place any element exactly where you want it to be. You use the positioning attributes top, left, bottom. and right to set the location.
It is placed relative to the nearest non-static ancestor. If there is no such container, it is placed relative to the page itself.
It gets removed from the normal flow of elements on the page.
An element with this type of positioning is not affected by other elements and also it doesn't affect flow of other elements.
See this self-explanatory example for better clarity. https://codepen.io/nyctophiliac/pen/BJMqjX
While you can filter Models with =
, __gt
, __gte
, __lt
, __lte
, you cannot use ne
or !=
. However, you can achieve better filtering using the Q object.
You can avoid chaining QuerySet.filter()
and QuerySet.exclude()
, and use this:
from django.db.models import Q
object_list = QuerySet.filter(~Q(field='not wanted'), field='wanted')
This is my solution. you can download demo on my github. https://github.com/krossford/KrossLib/tree/master/android-project
This screenshot was a demo that maxLines = 4
, I think it works well.
package com.krosshuang.krosslib.lib.view;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.TextView;
import java.util.ArrayList;
/*
?????
How to use it?
> 1.?xml??java???????
> 1.use it like other views on xml and java code.
> 2.[??] setMaxLines ?????xml?? "android:maxLines" ??
> 2.[must] call the setMaxLines method to instead of the xml property android:maxLines.
> 3.[??] ???? setMultilineEllipsizeMode() ??,???????
> 3.[option] you can invoke setMultilineEllipsizeMode method, but I have not implement it.
*/
/**
* android???TextView???ellipsize?????
* Created by krosshuang on 2015/12/17.
*/
public class EllipsizeEndTextView extends TextView {
private static final String LOG_TAG = "EllipsizeTextView";
/** ???????? */
//TODO ??????
public static final int MODE_EACH_LINE = 1;
/** ????????? */
public static final int MODE_LAST_LINE = 2;
private static final String ELLIPSIZE = "...";
private ArrayList<String> mTextLines = new ArrayList<String>();
private CharSequence mSrcText = null;
private int mMultilineEllipsizeMode = MODE_LAST_LINE;
private int mMaxLines = 1;
private boolean mNeedIgnoreTextChangeAndSelfInvoke = false;
public EllipsizeEndTextView(Context context) {
super(context);
}
public EllipsizeEndTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EllipsizeEndTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
if (!mNeedIgnoreTextChangeAndSelfInvoke) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
mSrcText = text;
}
}
@Override
public void setMaxLines(int maxlines) {
super.setMaxLines(maxlines);
mMaxLines = maxlines;
}
public int getSupportedMaxLines() {
return mMaxLines;
}
@Override
protected void onDraw(Canvas canvas) {
setVisibleText();
super.onDraw(canvas);
mNeedIgnoreTextChangeAndSelfInvoke = false;
}
private void setVisibleText() {
if (mSrcText == null) {
return;
}
//??????width get available width
final int aw = getWidth() - getPaddingLeft() - getPaddingRight();
String srcText = mSrcText.toString();
//???????????????????????????
String[] lines = srcText.split("\n");
//Log.i(LOG_TAG, "?????: " + lines.length + " ? " + Arrays.toString(lines));
int maxLines = getSupportedMaxLines();
//????????????list
mTextLines.clear();
for (int i = 0; i < lines.length; i++) {
mTextLines.add(lines[i]);
}
switch (mMultilineEllipsizeMode) {
case MODE_EACH_LINE:
break;
default:
case MODE_LAST_LINE:
//????
String eachLine = null;
for (int i = 0; i < mTextLines.size() && i < maxLines - 1; i++) {
eachLine = mTextLines.get(i);
if (getPaint().measureText(eachLine, 0, eachLine.length()) > aw) {
//?????????
boolean isOut = true;
int end = eachLine.length() - 1;
while (isOut) {
if (getPaint().measureText(eachLine.substring(0, end), 0, end) > aw) {
end--;
} else {
isOut = false;
}
}
mTextLines.set(i, eachLine.substring(0, end)); //??????????
mTextLines.add(i + 1, eachLine.substring(end, eachLine.length())); //????????,?????,????????????????,???????
}
}
//??????,??????????????
break;
}
//?? maxLines ? ?????,?????????
int resultSize = Math.min(maxLines, mTextLines.size());
//????????
String lastLine = mTextLines.get(resultSize - 1);
//????????????...
//1.??????????,???????,?????????...
//2.????????,?????????,????????????,????...
if (getPaint().measureText(lastLine, 0, lastLine.length()) > aw || resultSize < mTextLines.size()) {
boolean isOut = true;
int end = lastLine.length();
while (isOut) {
if (getPaint().measureText(lastLine.substring(0, end) + ELLIPSIZE, 0, end + 3) > aw) {
end--;
} else {
isOut = false;
}
}
mTextLines.set(resultSize - 1, lastLine.substring(0, end) + ELLIPSIZE);
}
//??????
StringBuilder sb = new StringBuilder();
for (int i = 0; i < resultSize ; i++) {
sb.append(mTextLines.get(i));
if (i != resultSize - 1) {
sb.append('\n');
}
}
//????,set
if (sb.toString().equals(getText())) {
return;
} else {
mNeedIgnoreTextChangeAndSelfInvoke = true;
setText(sb.toString());
}
}
/**
* ??ellipsize mode,?????
* @deprecated
* */
public void setMultilineEllipsizeMode(int mode) {
mMultilineEllipsizeMode = mode;
}
}
The purpose of mocking types is to sever dependencies in order to isolate the test to a specific unit. Stubs are simple surrogates, while mocks are surrogates that can verify usage. A mocking framework is a tool that will help you generate stubs and mocks.
EDIT: Since the original wording mention "type mocking" I got the impression that this related to TypeMock. In my experience the general term is just "mocking". Please feel free to disregard the below info specifically on TypeMock.
TypeMock Isolator differs from most other mocking framework in that it works my modifying IL on the fly. That allows it to mock types and instances that most other frameworks cannot mock. To mock these types/instances with other frameworks you must provide your own abstractions and mock these.
TypeMock offers great flexibility at the expense of a clean runtime environment. As a side effect of the way TypeMock achieves its results you will sometimes get very strange results when using TypeMock.
I can't say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.
Anyway, you shouldn't hardcode your JSON as strings as you have done. Instead the proper way to send JSON data to the server is to use a JSON serializer:
data: JSON.stringify({ name : "AA" }),
Now on the server also make sure that you have the proper view model expecting to receive this input:
public class UserViewModel
{
public string Name { get; set; }
}
and the corresponding action:
[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
...
}
Now there's one more thing. You have specified dataType: 'json'
. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It's when jQuery attempts to parse the response from the server:
[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
...
return Json(new { Foo = "bar" });
}
This being said, in most cases, usually you don't need to set the dataType
property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult
(such as a ViewResult
or a JsonResult
), the framework will automatically set the correct Content-Type
response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.
I suspect that the problem you are having here is that your server didn't return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).
One more thing that I just noticed:
async: false,
Please, avoid setting this attribute to false. If you set this attribute to false
you are are freezing the client browser during the entire execution of the request. You could just make a normal request in this case. If you want to use AJAX, start thinking in terms of asynchronous events and callbacks.
You can use a min-heap to find the minimum element in constant time, or a max-heap to find the the maximum element. But what if you wanted to do both operations? You can use a Min-Max to do both operations in constant time. It works by using min max ordering: alternating between min and max heap comparison between consecutive tree levels.
This isn't straightforward, but
SELECT CHAR(CURRENT DATE, ISO) FROM SYSIBM.SYSDUMMY1
returns the current date in yyyy-mm-dd format. You would have to substring and concatenate the result to get yyyymmdd.
SELECT SUBSTR(CHAR(CURRENT DATE, ISO), 1, 4) ||
SUBSTR(CHAR(CURRENT DATE, ISO), 6, 2) ||
SUBSTR(CHAR(CURRENT DATE, ISO), 9, 2)
FROM SYSIBM.SYSDUMMY1
Having had the same sort of problem as well, requiring three divs next to each other with different content, with right-borders to 'seperate' them, the only solution that worked was a slightly modified version of the jQuery option in another answer. Remember you also need the script found here.
Below is my slightly modified version of the script, which just allows for a true min-height setting (as I needed my boxes to be at least a certain height).
/*--------------------------------------------------------------------
* JQuery Plugin: "EqualHeights"
* by: Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
*
* Copyright (c) 2008 Filament Group
* Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
*
* Description: Compares the heights or widths of the top-level children of a provided element
and sets their min-height to the tallest height (or width to widest width). Sets in em units
by default if pxToEm() method is available.
* Dependencies: jQuery library, pxToEm method (article:
http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)
* Usage Example: $(element).equalHeights();
Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
Optional: to specify an actual min-height (in px), pass an integer value, regardless of previous parameter: $(element).equalHeights(false,150);
* Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/
$.fn.equalHeights = function(px,minheightval) {
$(this).each(function(){
if (minheightval != undefined) {
var currentTallest = minheightval;
}
else {
var currentTallest = 0;
}
$(this).children().each(function(i){
if ($(this).height() > currentTallest) {
currentTallest = $(this).height();
}
});
if (!px || !Number.prototype.pxToEm)
currentTallest = currentTallest.pxToEm(); //Use ems unless px is specified.
// For Internet Explorer 6, set height since min-height isn't supported.
if ($.browser.msie && $.browser.version == 6.0) {
$(this).children().css({'height': currentTallest});
}
$(this).children().css({'min-height': currentTallest});
});
return this;
};
It works like a charm and doesn't slow anything down :)
Adding to the above-accepted answer so that it helps those who are using tensorflow 2.0
import tensorflow as tf
# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)
# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)
# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])
# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])
# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)
Result:
------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------
Use this to have multiple lines of text in UILabel
:
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;
Swift:
textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0
There actually is an example how to create a circle IconButton similar to the FloatingActionButton.
Ink(
decoration: const ShapeDecoration(
color: Colors.lightBlue,
shape: CircleBorder(),
),
child: IconButton(
icon: Icon(Icons.home),
onPressed: () {},
),
)
To create a local project with this code sample, run:
flutter create --sample=material.IconButton.2 mysample
You must use plt.show()
at the end in order to see the plot
One function can do the job,
void free_list(node *pHead)
{
node *pNode = pHead, *pNext;
while (NULL != pNode)
{
pNext = pNode->next;
free(pNode);
pNode = pNext;
}
}
Console.Read()
reads a single key, where Console.Readline()
waits for the Enter key.
I don't know if this what you want but try to remove overflow: hidden from #wrap
Are you trying to remove a single value or all matching values?
If you are trying to remove a single value, how do you define the value you wish to remove?
The reason you don't get a key back when querying on values is because the dictionary could contain multiple keys paired with the specified value.
If you wish to remove all matching instances of the same value, you can do this:
foreach(var item in dic.Where(kvp => kvp.Value == value).ToList())
{
dic.Remove(item.Key);
}
And if you wish to remove the first matching instance, you can query to find the first item and just remove that:
var item = dic.First(kvp => kvp.Value == value);
dic.Remove(item.Key);
Note: The ToList()
call is necessary to copy the values to a new collection. If the call is not made, the loop will be modifying the collection it is iterating over, causing an exception to be thrown on the next attempt to iterate after the first value is removed.
You may want to look into os dependent line separators, e.g.:
import os
with open('./output.txt', 'a') as f1:
f1.write(content + os.linesep)
You define these attributes in xml as you would anything else, for example:
<Button android:id="@+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/next"
android:background="@drawable/mybutton_background"
android:textSize="10sp" /> <!-- Use SP(Scale Independent Pixel) -->
You can find the allowed attributes in the api.
Or, if you want this to apply to all buttons in your application, create a style. See the Styles and Themes development documentation.
<span color="red">red</span>
#!/bin/bash
# convert ansi-colored terminal output to github markdown
# to colorize text on github, we use <span color="red">red</span> etc
# depends on: aha, xclip
# license: CC0-1.0
# note: some tools may need other arguments than `--color=always`
# sample use: colors-to-github.sh diff a.txt b.txt
cmd="$1"
shift
(
echo '<pre>'
$cmd --color=always "$@" 2>&1 | aha --no-header
echo '</pre>'
) \
| sed -E 's/<span style="[^"]*color:([^;"]+);"/<span color="\1"/g' \
| sed -E 's/ style="[^"]*"//g' \
| xclip -i -sel clipboard
trivial :)
I think you want to cast your dt
to a date
and fix the format of your date literal:
SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
Or the standard version:
SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
The extract
function doesn't understand "date" and it returns a number.
floor()
will go down.
ceil()
will go up.
round()
will go to nearest by default.
Divide by 10, do the ceil, then multiply by 10 to reduce the significant digits.
$number = ceil($input / 10) * 10;
Edit: I've been doing it this way for so long.. but TallGreenTree's answer is cleaner.
I took some time to check it in detail. I created an icon whose images have sizes of 16, 24, 32, 40, 48, 64, 96, 128 and 256. Then I checked which image is shown. All these were done with normal 96dpi. If using a larger DPI, the larger sizes may be used (only checked this a bit in Windows 7). The results:
Windows XP:
Windows 7:
Windows Runtime: (from here)
So the result: Windows XP uses 16, 32, 48-size icons, while Windows 7 (and presumably also Vista) also uses 256-size icons. All other intermediate icon sizes are ignored (they may be used in some area which I didn't check).
I also checked in Windows 7 what happens if icon sizes are missing:
The missing sizes are generated (obviously). With sizes of 16, 32, and 48, if one is missing, downscaling is preferred. So if we have icons with size 16 and 48, the 32 icon is created from the 48 icon. The 256 icon is only used for these if no other sizes are available! So if the icons are size 16 and 256, the other sizes are upscaled from the 16 icon!
Additionally, if the 256 icon is not there, the (possibly generated) 48 icon is used, but not resized anymore. So we have a (possibly large) empty area with the 48 icon in the middle.
Note that the default desktop icon size in XP was 32x32, while in Windows 7 it is 48x48. As a consequence, for Windows 7 it is relatively important to have a 48 icon. Otherwise, it is upscaled from a smaller icon, which may look quite ugly.
Just a note about Windows XP compatibility: If you reuse the icon as window icon, then note that this can crash your application if you use a compressed 256 icon. The solution is to either not compress the icon or create a second version without the (compressed) 256 icon. See here for more info.
According to HTML5 drafts, the checked
attribute is a “boolean attribute”, and “The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.” It is the name of the attribute that matters, and suffices. Thus, to make a checkbox initially checked, you use
<input type=checkbox checked>
By default, in the absence of the checked
attribute, a checkbox is initially unchecked:
<input type=checkbox>
Keeping things this way keeps them simple, but if you need to conform to XML syntax (i.e. to use HTML5 in XHTML linearization), you cannot use an attribute name alone. Then the allowed (as per HTML5 drafts) values are the empty string and the string checked
, case insensitively. Example:
<input type="checkbox" checked="checked" />
Robocopy, or "Robust File Copy", is a command-line directory and/or file replication command. Robocopy functionally replaces Xcopy, with more options. It has been available as part of the Windows Resource Kit starting with Windows NT 4.0, and was first introduced as a standard feature in Windows Vista and Windows Server 2008. The command is
robocopy
...
If you want to redirect, just use window.location
. Like so:
window.location = "http://www.redirectedsite.com"
I was trying to put together some JavaScript to validate a domain name (ex. google.com) and if it validates enable a submit button. I thought that I would share my code for those who are looking to accomplish something similar. It expects a domain without any http:// or www. value. The script uses a stripped down regular expression from above for domain matching, which isn't strict about fake TLD.
$(function () {
$('#whitelist_add').keyup(function () {
if ($(this).val() == '') { //Check to see if there is any text entered
//If there is no text within the input, disable the button
$('.whitelistCheck').attr('disabled', 'disabled');
} else {
// Domain name regular expression
var regex = new RegExp("^([0-9A-Za-z-\\.@:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
if (regex.test($(this).val())) {
// Domain looks OK
//alert("Successful match");
$('.whitelistCheck').removeAttr('disabled');
} else {
// Domain is NOT OK
//alert("No match");
$('.whitelistCheck').attr('disabled', 'disabled');
}
}
});
});
HTML FORM:
<form action="domain_management.php" method="get">
<input type="text" name="whitelist_add" id="whitelist_add" placeholder="domain.com">
<button type="submit" class="btn btn-success whitelistCheck" disabled='disabled'>Add to Whitelist</button>
</form>
Selected date at the example is interesting. Example code block is:
Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30); //January 30th 2000
Date sDate = c1.getTime();
System.out.println(sDate);
and output Wed Mar 01 19:32:21 JST 2000
.
When I first read the example i think that output is wrong but it is true:)
Calendar.Month
is starting from 0 so 1 means February.I came across this issue twice once in upgrading to 3.2.18 from 3.2.1 and 4.3.5 from 3.2.8. In both cases, this error is because of different version of spring modules
You may just remove all spaces and leverage LINQ All
:
Determines whether all elements of a sequence satisfy a condition.
Use it as shown below:
Dim number As String = "077 234 211"
If number.Replace(" ", "").All(AddressOf Char.IsDigit) Then
Console.WriteLine("The string is all numeric (spaces ignored)!")
Else
Console.WriteLine("The string contains a char that is not numeric and space!")
End If
To only check if a string consists of only digits use:
If number.All(AddressOf Char.IsDigit) Then
After Laravel 5.5 you can use now() function to get the current date and time.
In blade file, you can write like this to print date.
{{ now()->toDateTimeString('Y-m-d') }}
Very basic, but does what you need without any addon modules or PS version requirements:
while ($true) {Clear-Host; gc E:\test.txt | select -last 3; sleep 2 }
The question is a few months old but for other people looking --
A simpler way to import a large file is to make a sub directory 'upload' in your folder c:/wamp/apps/phpmyadmin3.5.2 and edit this line in the config.inc.php file in the same directory to include the folder name $cfg['UploadDir'] = 'upload';
Then place the incoming .sql file in the folder /upload.
Working from inside the phpmyadmin console, go to the new database and import. You will now see an additional option to upload files from that folder. Chose the correct file and be a little patient. It works.
If you still get a time out error try adding $cfg['ExecTimeLimit'] = 0; to the same config.inc.php file.
I have had difficulty importing an .sql file where the user name was root and the password differed from my the root password on my new server. I simply took off the password before I exported the .sql file and the import worked smoothly.
Just use
latch = new CountDownLatch(noThreads)
In each thread
latch.countDown();
and as barrier
latch.await();
Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.
Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:
window
objectSET @seq := 0;
SELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*
FROM your_table yt;
SELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*
FROM (SELECT @seq := 0) s, your_table yt;
The FLOOR()
function is used here to get an INTEGER
in place of a FLOAT
. Sometimes it is needed.
My answer was inspired by David Poor answer. Thanks David!
You can try something like this:
public interface PersonRepository extends CrudRepository<Person, Long> {
@Query("select p from Person AS p"
+ " ,Name AS n"
+ " where p.forename = n.forename "
+ " and p.surname = n.surname"
+ " and n = :name")
Set<Person>findByName(@Param("name") Name name);
}
elaborating @john-mee 's answer, if you have arbitrarily long data but don't need strictly unique colors:
for python 2:
from itertools import cycle
cycol = cycle('bgrcmk')
for X,Y in data:
scatter(X, Y, c=cycol.next())
for python 3:
from itertools import cycle
cycol = cycle('bgrcmk')
for X,Y in data:
scatter(X, Y, c=next(cycol))
this has the advantage that the colors are easy to control and that it's short.
This is how I solved my problem
Let's assume the upstream branch is the one that you forked from and origin is your repo and you want to send an MR/PR to the upstream branch.
You already have let's say about 4 commits and you are getting Updates were rejected because the tip of your current branch is behind.
Here is what I did
First, squash all your 4 commits
git rebase -i HEAD~4
You'll get a list of commits with pick
written on them. (opened in an editor)
example
pick fda59df commit 1
pick x536897 commit 2
pick c01a668 commit 3
pick c011a77 commit 4
to
pick fda59df commit 1
squash x536897 commit 2
squash c01a668 commit 3
squash c011a77 commit 4
After that, you can save your combined commit
You'll need to stash your commit
Here's how
git reset --soft HEAD~1
git stash
now rebase with your upstream branch
git fetch upstream beta && git rebase upstream/beta
Now pop your stashed commit
git stash pop
commit these changes and push them
git add -A
git commit -m "[foo] - foobar commit"
git push origin fix/#123 -f
Adding up an example using above mentioned solutions on jsfiddle. I have modified the code a bit as per my clients requirement. Hope this also helps someone.
/^\s*(?:\+?(\d{1,3}))?[- (]*(\d{3})[- )]*(\d{3})[- ]*(\d{4})(?: *[x/#]{1}(\d+))?\s*$/
... looking for an equivalent in python of
dict.get(key, default)
for lists
There is an itertools recipes that does this for general iterables. For convenience, you can > pip install more_itertools
and import this third-party library that implements such recipes for you:
Code
import more_itertools as mit
mit.nth([1, 2, 3], 0)
# 1
mit.nth([], 0, 5)
# 5
Detail
Here is the implementation of the nth
recipe:
def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(itertools.islice(iterable, n, None), default)
Like dict.get()
, this tool returns a default for missing indices. It applies to general iterables:
mit.nth((0, 1, 2), 1) # tuple
# 1
mit.nth(range(3), 1) # range generator (py3)
# 1
mit.nth(iter([0, 1, 2]), 1) # list iterator
# 1
Fromthe Javadoc of Method.invoke():
If the underlying method is static, then the specified obj argument is ignored. It may be null.
What happens when you
Class klass = ...; Method m = klass.getDeclaredMethod(methodName, paramtypes); m.invoke(null, args)
This answer currently only applies to using two Linux computers [or maybe works on Mac too?--untested on Mac] (syncing from one to the other) because I wrote this synchronization script in bash. It is simply a wrapper around git
, however, so feel free to take it and convert it into a cross-platform Python solution or something if you wish
This doesn't directly answer the OP's question, but it is so close I guarantee it will answer many other peoples' question who land on this page (mine included, actually, as I came here first before writing my own solution), so I'm posting it here anyway.
Let's call the first computer where I write the code "PC1" (Personal Computer 1), and the 2nd computer where I build the code "PC2". I need a tool to easily synchronize from PC1 to PC2. I tried rsync
, but it was insanely slow for large repos and took tons of bandwidth and data.
So, how do I do it? What workflow should I use? If you have this question too, here's the workflow that I decided upon. I wrote a bash script to automate the process by using git
to automatically push changes from PC1 to PC2 via a remote repository, such as github. So far it works very well and I'm very pleased with it. It is far far far faster than rsync
, more trustworthy in my opinion because each PC maintains a functional git repo, and uses far less bandwidth to do the whole sync, so it's easily doable over a cell phone hot spot without using tons of your data.
Install the script on PC1 (this solution assumes ~/bin is in your $PATH):
git clone https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.git
cd eRCaGuy_dotfiles/useful_scripts
mkdir -p ~/bin
ln -s "${PWD}/sync_git_repo_from_pc1_to_pc2.sh" ~/bin/sync_git_repo_from_pc1_to_pc2
cd ..
cp -i .sync_git_repo ~/.sync_git_repo
Now edit the "~/.sync_git_repo" file you just copied above, and update its parameters to fit your case. Here are the parameters it contains:
# The git repo root directory on PC2 where you are syncing your files TO; this dir must *already exist*
# and you must have *already `git clone`d* a copy of your git repo into it!
# - Do NOT use variables such as `$HOME`. Be explicit instead. This is because the variable expansion will
# happen on the local machine when what we need is the variable expansion from the remote machine. Being
# explicit instead just avoids this problem.
PC2_GIT_REPO_TARGET_DIR="/home/gabriel/dev/eRCaGuy_dotfiles" # explicitly type this out; don't use variables
PC2_SSH_USERNAME="my_username" # explicitly type this out; don't use variables
PC2_SSH_HOST="my_hostname" # explicitly type this out; don't use variables
Git clone your repo you want to sync on both PC1 and PC2.
Now cd
into any directory within the git repo on PC1, and run:
sync_git_repo_from_pc1_to_pc2
That's it! About 30 seconds later everything will be magically synced from PC1 to PC2, and it will be printing output the whole time to tell you what it's doing and where it's doing it on your disk and on which computer. It's safe too, because it doesn't overwrite or delete anything that is uncommitted. It backs it up first instead! Read more below for how that works.
rsync
s a copy of the script over to PC2, and does an ssh
call to tell PC2 to run the script with a special option to just do PC2 stuff.cd
s into the repo, and checks to see if any local uncommitted changes exist. If so, it creates a new backup branch forked off of the current branch (sample name: my_branch_SYNC_BAK_20200220-0028hrs-15sec
<-- notice that's YYYYMMDD-HHMMhrs--SSsec), and commits any uncommitted changes to that branch with a commit message such as DO BACKUP OF ALL UNCOMMITTED CHANGES ON PC2 (TARGET PC/BUILD MACHINE). Now, it checks out the SYNC branch, pulling it from the remote repository if it is not already on the local machine. Then, it fetches the latest changes on the remote repository, and does a hard reset to force the local SYNC repository to match the remote SYNC repository. You might call this a "hard pull". It is safe, however, because we already backed up any uncommitted changes we had locally on PC2, so nothing is lost! Note that the TIMEDIFF()
solution only works when the datetimes
are less than 35 days apart!
TIMEDIFF()
returns a TIME
datatype, and the max value for TIME is 838:59:59 hours (=34,96 days)
I've made a plugin vim-textobj-quotes
: https://github.com/beloglazov/vim-textobj-quotes
It provides text objects for the closest pairs of quotes of any type. Using only iq
or aq
it allows you to operate on the content of single ('), double ("), or back (`) quotes that currently surround the cursor, are in front of the cursor, or behind (in that order of preference). In other words, it jumps forward or backwards when needed to reach the quotes.
It's easier to understand by looking at examples (the cursor is shown with |
):
foo '1, |2, 3' bar
; after pressing diq
: foo '|' bar
foo| '1, 2, 3' bar
; after pressing diq
: foo '|' bar
foo '1, 2, 3' |bar
; after pressing diq
: foo '|' bar
foo '1, |2, 3' bar
; after pressing daq
: foo | bar
foo| '1, 2, 3' bar
; after pressing daq
: foo | bar
foo '1, 2, 3' |bar
; after pressing daq
: foo | bar
The examples above are given for single quotes, the plugin works exactly the same way for double (") and back (`) quotes.
You can also use any other operators: ciq
, diq
, yiq
, viq
, etc.
Please have a look at the github page linked above for more details.
and to delete a lot of folders, you could also create a batch file with the command spdenne posted.
1) make a text file that has the following contents replacing the folder names in quotes with your folder names:
rmdir /s /q "My Apps"
rmdir /s /q "My Documents"
rmdir /s /q "My Pictures"
rmdir /s /q "My Work Files"
2) save the batch file with a .bat extension (for example deletefiles.bat)
3) open a command prompt (Start > Run > Cmd) and execute the batch file. you can do this like so from the command prompt (substituting X for your drive letter):
X:
deletefiles.bat
you can simply use your own code but add name for the select tag
<form method="POST" action="index.php?action=contact_agent&agent_id=">
<select name="agent_id">
<option value="1">Agent Homer</option>
<option value="2">Agent Lenny</option>
<option value="3">Agent Carl</option>
</select>
then you can access it like this
String agent=request.getparameter("agent_id");
This can happen when your plot panel in RStudio is too small for the margins of the plot you are trying to create. Try making expanding it and then run your code again.
RStudio UI causes an error when the plot panel is too small to display the chart:
Simply expanding the plot panel fixes the bug and displays the chart:
Add your <script>
to the bottom of your <body>
, or add an event listener for DOMContentLoaded
following this StackOverflow question.
If that script executes in the <head>
section of the code, document.getElementsByClassName(...)
will return an empty array because the DOM is not loaded yet.
You're getting the Type Error
because you're referencing search_span[0]
, but search_span[0]
is undefined
.
This works when you execute it in Dev Tools because the DOM is already loaded.
If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10
, is good enough.
But if you want, say, a list of ten dict
s, do not use [{}]*10
-- that would give you a list with the same initially-empty dict
ten times, not ten distinct ones. Rather, use [{} for i in range(10)]
or similar constructs, to construct ten separate dict
s to make up your list.
You can't do that using open. use codecs.
when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:
import codecs
file = codecs.open('data.txt','w','utf-8')
Here is a code snippet that works with Hibernate 4 based on Dominik's answer
Connection getConnection() {
Session session = entityManager.unwrap(Session.class);
MyWork myWork = new MyWork();
session.doWork(myWork);
return myWork.getConnection();
}
private static class MyWork implements Work {
Connection conn;
@Override
public void execute(Connection arg0) throws SQLException {
this.conn = arg0;
}
Connection getConnection() {
return conn;
}
}
Just in case y'all end up here in 2013 - here is a pure css approach I found here: http://css-tricks.com/snippets/css/truncate-string-with-ellipsis/
.truncate {
width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
It works well.
I love the Monokai Theme (known from Sublime Text):
buf.erase(buf.size() - 1);
This assumes you know that the string is not empty. If so, you'll get an out_of_range
exception.
Yes there is a way to do it.
First declare a class.
//anyfile.ts
export class Custom
{
name: string,
empoloyeeID: number
}
Then in your component import the class
import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<Custom> = [];
constructor() {
}
ngOnInit() {
}
onEmpCreate(){
//console.log(this.name,this.empoloyeeID);
let customObj = new Custom();
customObj.name = "something";
customObj.employeeId = 12;
this.empList.push(customObj);
this.name ="";
this.empoloyeeID = 0;
}
}
Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html
Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2
Just run composer install
- it will make your vendor
directory reflect dependencies in composer.lock
file.
In other words - it will delete any vendor which is missing in composer.lock
.
Please update the composer itself before running this.
Easiest way:
// Prefs.h
#define PREFS_MY_CONSTANT @"prefs_my_constant"
Better way:
// Prefs.h
extern NSString * const PREFS_MY_CONSTANT;
// Prefs.m
NSString * const PREFS_MY_CONSTANT = @"prefs_my_constant";
One benefit of the second is that changing the value of a constant does not cause a rebuild of your entire program.
The methods are "basically" the same, except handling null.
Pen pen = null;
Convert.ToString(pen); // No exception thrown
pen.ToString(); // Throws NullReferenceException
From MSDN :
Convert.ToString Method
Converts the specified value to its equivalent string representation.
Returns a string that represents the current object.
I have a clearer proposal on automatic search in a DataGridView
this is an example
private void searchTb_TextChanged(object sender, EventArgs e)
{
try
{
(lecteurdgview.DataSource as DataTable).DefaultView.RowFilter = String.IsNullOrEmpty(searchTb.Text) ?
"lename IS NOT NULL" :
String.Format("lename LIKE '{0}' OR lecni LIKE '{1}' OR ledatenais LIKE '{2}' OR lelieu LIKE '{3}'", searchTb.Text, searchTb.Text, searchTb.Text, searchTb.Text);
}
catch (Exception ex) {
MessageBox.Show(ex.StackTrace);
}
}
In general the logs are in /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/
.
In NetBeans go to the "Services" tab open "Servers", right-click on your Glassfish instance and click "View Domain Server Log".
If this doesn't work right-click on the Glassfish instance and click "Properties", you can see the folder with the domains under "Domains folder". Go to this folder -> your-domain -> logs
If the server is already running you should see an Output
tab in NetBeans which is named similar to GlassFish Server x.x.x
You can also use cat
or tail -F
on /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/server.log
. If you are using a different domain then domain1
you have to adjust the path for that.
Use all the jackson dependencies(databind,core, annotations, scala(if you are using spark and scala)) with the same version.. and upgrade the versions to the latest releases..
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-scala_2.11</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>
Note: Use Scala dependency only if you are working with scala. Otherwise it is not needed.
Since many people arrive here debugging their slow website I would like to inform you about my case which none of the google explanations helped to resolve. My huge stalled times (sometimes 1min) were caused by Apache running on Windows having too few worker threads to handle the connections, therefore they were being queued.
This may apply to you if you apache log has following note:
Server ran out of threads to serve requests. Consider raising the ThreadsPerChild setting
This issue is resolved in Apache httpd.conf. Uncomment : Include conf/extra/httpd-mpm.conf
And edit httpd-mpm.conf
<IfModule mpm_winnt_module>
ThreadLimit 2000
ThreadsPerChild 2000
MaxConnectionsPerChild 0
</IfModule>
Note that you may not need 2000 threads, or may need more. 2000 was OK for my case.
click on this button out your phpAdmin home page
Even the other answers may work well, but I want tell best approach.
Binding class's inflate
as recommended in Android Documentation.One option is to inflate by DataBindingUtil
but when only you don't know have generated binding class.
--You have auto generated binding class
, use that class instead of using DataBindingUtil
.
In Java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
HomeFragmentBinding binding = HomeFragmentBinding.inflate(inflater, container, false);
//set binding variables here
return binding.getRoot();
}
In Kotlin
lateinit var binding: HomeFragmentBinding
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = HomeFragmentBinding.inflate(inflater, container, false)
return binding.root
}
In DataBindingUtil class documentation you can see.
inflate
T inflate (LayoutInflater inflater, int layoutId, ViewGroup parent, boolean attachToParent)
Use this version only if layoutId is unknown in advance. Otherwise, use the generated Binding's inflate method to ensure type-safe inflation.
If your layout biniding class is not generated @See this answer.
It works for me, try it.
for /f "delims=;" %g in ('echo %PATH%') do echo %g%
If you want to draw a horizontal line in the axes, you might also try ax.hlines()
method. You need to specify y
position and xmin
and xmax
in the data coordinate (i.e, your actual data range in the x-axis). A sample code snippet is:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1, 21, 200)
y = np.exp(-x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.hlines(y=0.2, xmin=4, xmax=20, linewidth=2, color='r')
plt.show()
The snippet above will plot a horizontal line in the axes at y=0.2
. The horizontal line starts at x=4
and ends at x=20
. The generated image is:
If you just need to check if there are ANY elements in the array
if (empty($playerlist)) {
// list is empty.
}
If you need to clean out empty values before checking (generally done to prevent explode
ing weird strings):
foreach ($playerlist as $key => $value) {
if (empty($value)) {
unset($playerlist[$key]);
}
}
if (empty($playerlist)) {
//empty array
}
_x000D_
table tbody_x000D_
{_x000D_
border:1px solid red;_x000D_
}_x000D_
table td_x000D_
{_x000D_
background:yellow;_x000D_
_x000D_
border-bottom:1px solid green;_x000D_
_x000D_
_x000D_
}_x000D_
.tr0{_x000D_
line-height:0;_x000D_
}_x000D_
.tr0 td{_x000D_
background:red;_x000D_
}
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr><td>test</td></tr>_x000D_
<tr><td>test</td></tr> _x000D_
<tr class="tr0"><td></td></tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
This question contains some useful links on headless builds, but they are mostly geared towards building plugins. I'm not sure how much of it can be applied to pure Java projects.
For small algorithms you can use the module timeit from python documentation:
def test():
"Stupid test function"
L = []
for i in range(100):
L.append(i)
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
Less accurately but still valid you can use module time like this:
from time import time
t0 = time()
call_mifuntion_vers_1()
t1 = time()
call_mifunction_vers_2()
t2 = time()
print 'function vers1 takes %f' %(t1-t0)
print 'function vers2 takes %f' %(t2-t1)
You can use CTE to get the distinct values of the second table, and then join that with the first table. You also need to get the distinct values based on LastName column. You do this with a Row_Number() partitioned by the LastName, and sorted by the FirstName.
Here's the code
;WITH SecondTableWithDistinctLastName AS
(
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY LastName ORDER BY FirstName) AS [Rank]
FROM AddTbl
)
AS tableWithRank
WHERE tableWithRank.[Rank] = 1
)
SELECT a.FirstName, a.LastName, S.District
FROM SecondTableWithDistinctLastName AS S
INNER JOIN AddTbl AS a
ON a.LastName = S.LastName
ORDER BY a.FirstName
Unity is a library like many others that allows you to get an instance of a requested type without having to create it yourself. So given.
public interface ICalculator
{
void Add(int a, int b);
}
public class Calculator : ICalculator
{
public void Add(int a, int b)
{
return a + b;
}
}
You would use a library like Unity to register Calculator to be returned when the type ICalculator is requested aka IoC (Inversion of Control) (this example is theoretical, not technically correct).
IoCLlibrary.Register<ICalculator>.Return<Calculator>();
So now when you want an instance of an ICalculator you just...
Calculator calc = IoCLibrary.Resolve<ICalculator>();
IoC libraries can usually be configured to either hold a singleton or create a new instance every time you resolve a type.
Now let's say you have a class that relies on an ICalculator to be present you could have..
public class BankingSystem
{
public BankingSystem(ICalculator calc)
{
_calc = calc;
}
private ICalculator _calc;
}
And you can setup the library to inject a object into the constructor when it's created.
So DI or Dependency Injection means to inject any object another might require.
Try the following instead:
<html>
<head>
<title>Table row styling</title>
<style type="text/css">
.bb td, .bb th {
border-bottom: 1px solid black !important;
}
</style>
</head>
<body>
<table>
<tr class="bb">
<td>This</td>
<td>should</td>
<td>work</td>
</tr>
</table>
</body>
</html>
It seems that if
Content-Type: application/json
andThen MVC doesn't really bind the POST body to any particular class. Nor can you just fetch the POST body as a param of the ActionResult (suggested in another answer). Fair enough. You need to fetch it from the request stream yourself and process it.
[HttpPost]
public ActionResult Index(int? id)
{
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
InputClass input = null;
try
{
// assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
input = JsonConvert.DeserializeObject<InputClass>(json)
}
catch (Exception ex)
{
// Try and handle malformed POST body
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do stuff
}
Update:
for Asp.Net Core, you have to add [FromBody]
attrib beside your param name in your controller action for complex JSON data types:
[HttpPost]
public ActionResult JsonAction([FromBody]Customer c)
Also, if you want to access the request body as string to parse it yourself, you shall use Request.Body
instead of Request.InputStream
:
Stream req = Request.Body;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value
{ * * "ProjectID" * * : {
"name": "ProjectID",
"value": "16,36,8,7",
"group": "Genel",
"editor": {
"type": "combobox",
"options": {
"url": "..\/jsonEntityVarServices\/?id=6&task=7",
"valueField": "value",
"textField": "text",
"multiple": "true"
}
},
"id": "14",
"entityVarID": "16",
"EVarMemID": "47"
}
}
One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).
What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then()
on the promise, and the result will be there when the promise has been resolved.
Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:
http://www.html5rocks.com/en/tutorials/es6/promises/
The method you are looking for is .limit.
Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.
Example usage:
df.limit(1000)
The file module doesn't copy files on the remote system. The src parameter is only used by the file module when creating a symlink to a file.
If you want to move/rename a file entirely on a remote system then your best bet is to use the command module to just invoke the appropriate command:
- name: Move foo to bar
command: mv /path/to/foo /path/to/bar
If you want to get fancy then you could first use the stat module to check that foo actually exists:
- name: stat foo
stat: path=/path/to/foo
register: foo_stat
- name: Move foo to bar
command: mv /path/to/foo /path/to/bar
when: foo_stat.stat.exists
If I'm going to be using values()
a lot:
enum Suit {
Hearts, Diamonds, Spades, Clubs;
public static final Suit values[] = values();
}
Meanwhile wherever.java:
Suit suit = Suit.values[ordinal];
If you want the array to be private, be my guest:
private static final Suit values[] = values();
public static Suit get(int ordinal) { return values[ordinal]; }
...
Suit suit = Suit.get(ordinal);
Mind your array bounds.
For information on php extensions
etc, on site.
Create a new file and name it info.php
(or some other name.php
)
Write this code in it:
<?php
phpinfo ();
?>
Save the file in the root
(home)of the site
example.com/info.php
All the php
information on your site will be displayed.Quite simple:
var a = [1, 2, 3];
var b = [4, 5, 6];
var breakCheck1 = false;
for (var i in a) {
for (var j in b) {
breakCheck1 = true;
break;
}
if (breakCheck1) break;
}
Your script is executing , you just can't use document.write
from it. Use an alert to test it and avoid using document.write
. The statements of your js file with document.write
will not be executed and the rest of the function will be executed.
Try following query to format datetime in sql server
FORMAT (frr.valid_from , 'dd/MM/yyyy hh:mm:ss')
/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
$('#link_other a').attr('target', '_blank');
});
// not using jquery
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
// jquery is prettier. :-)
You could also add a title tag to notify the user that you are doing this, to warn them, because as has been pointed out, it's not what users expect:
$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');
Although, the below code does the job, BUT its performance takes a big hit, as you deal with a DataFrame with # records 100k or more:
df.fillna(df.mean())
In my experience, one should replace NaN values (be it with Mean or Median), only where it is required, rather than applying fillna() all over the DataFrame.
I had a DataFrame with 20 variables, and only 4 of them required NaN values treatment (replacement). I tried the above code (Code 1), along with a slightly modified version of it (code 2), where i ran it selectively .i.e. only on variables which had a NaN value
#------------------------------------------------
#----(Code 1) Treatment on overall DataFrame-----
df.fillna(df.mean())
#------------------------------------------------
#----(Code 2) Selective Treatment----------------
for i in df.columns[df.isnull().any(axis=0)]: #---Applying Only on variables with NaN values
df[i].fillna(df[i].mean(),inplace=True)
#---df.isnull().any(axis=0) gives True/False flag (Boolean value series),
#---which when applied on df.columns[], helps identify variables with NaN values
Below is the performance i observed, as i kept on increasing the # records in DataFrame
DataFrame with ~100k records
DataFrame with ~200k records
DataFrame with ~1.6 Million records
DataFrame with ~13 Million records
Apologies for a long answer ! Hope this helps !
The .css()
function doesn't queue behind running animations, it's instantaneous.
To match the behaviour that you're after, you'd need to do the following:
$(document).ready(function() {
$("button").mouseover(function() {
var p = $("p#44.test").css("background-color", "yellow");
p.hide(1500).show(1500);
p.queue(function() {
p.css("background-color", "red");
});
});
});
The .queue()
function waits for running animations to run out and then fires whatever's in the supplied function.
In Kotlin, you can use simply use like this,
textview.textSize = 20f
In pyspark,SparkSql syntax:
where column_n like 'xyz%'
might not work.
Use:
where column_n RLIKE '^xyz'
This works perfectly fine.
Often when there is a drastic difference from run to run of a query I find that it is often one of 5 issues.
STATISTICS - Statistics are out of date. A database stores statistics on the range and distribution of the types of values in various column on tables and indexes. This helps the query engine to develop a "Plan" of attack for how it will do the query, for example the type of method it will use to match keys between tables using a hash or looking through the entire set. You can call Update Statistics on the entire database or just certain tables or indexes. This slows down the query from one run to another because when statistics are out of date, its likely the query plan is not optimal for the newly inserted or changed data for the same query (explained more later below). It may not be proper to Update Statistics immediately on a Production database as there will be some overhead, slow down and lag depending on the amount of data to sample. You can also choose to use a Full Scan or Sampling to update Statistics. If you look at the Query Plan, you can then also view the statistics on the Indexes in use such using the command DBCC SHOW_STATISTICS (tablename, indexname). This will show you the distribution and ranges of the keys that the query plan is using to base its approach on.
PARAMETER SNIFFING - The query plan that is cached is not optimal for the particular parameters you are passing in, even though the query itself has not changed. For example, if you pass in a parameter which only retrieves 10 out of 1,000,000 rows, then the query plan created may use a Hash Join, however if the parameter you pass in will use 750,000 of the 1,000,000 rows, the plan created may be an index scan or table scan. In such a situation you can tell the SQL statement to use the option OPTION (RECOMPILE) or an SP to use WITH RECOMPILE. To tell the Engine this is a "Single Use Plan" and not to use a Cached Plan which likely does not apply. There is no rule on how to make this decision, it depends on knowing the way the query will be used by users.
INDEXES - Its possible that the query haven't changed, but a change elsewhere such as the removal of a very useful index has slowed down the query.
ROWS CHANGED - The rows you are querying drastically changes from call to call. Usually statistics are automatically updated in these cases. However if you are building dynamic SQL or calling SQL within a tight loop, there is a possibility you are using an outdated Query Plan based on the wrong drastic number of rows or statistics. Again in this case OPTION (RECOMPILE) is useful.
THE LOGIC Its the Logic, your query is no longer efficient, it was fine for a small number of rows, but no longer scales. This usually involves more indepth analysis of the Query Plan. For example, you can no longer do things in bulk, but have to Chunk things and do smaller Commits, or your Cross Product was fine for a smaller set but now takes up CPU and Memory as it scales larger, this may also be true for using DISTINCT, you are calling a function for every row, your key matches don't use an index because of CASTING type conversion or NULLS or functions... Too many possibilities here.
In general when you write a query, you should have some mental picture of roughly how certain data is distributed within your table. A column for example, can have an evenly distributed number of different values, or it can be skewed, 80% of the time have a specific set of values, whether the distribution will varying frequently over time or be fairly static. This will give you a better idea of how to build an efficient query. But also when debugging query performance have a basis for building a hypothesis as to why it is slow or inefficient.
In my case, the problem was a folder in the project directory containing 300k+ files totaling 11Gb. This was just a temporary folder with images results of some computation. After moving this folder out of the project structure, the slowness disappeared. I hope this can help someone, please check your project structure to see if there is anything that is not necessary.
Adding new key/pair elements into the original object:
const obj = { a:1, b:2 }
const add = { c:3, d:4, e: ['x','y','z'] }
Object.entries(add).forEach(([key,value]) => { obj[key] = value })
obj new value:
{a: 1, b: 2, c: 3, d: 4, e: ["x", "y", "z"] }
If you initially installed Node.js with Homebrew, run:
brew update
brew upgrade node
npm install -g npm
Or as a one-liner:
brew update && brew upgrade node && npm install -g npm
A convenient way to change versions is to use nvm:
brew install nvm
To install the latest version of Node.js with nvm:
nvm install node
If you installed via a package, then download the latest version from nodejs.org. See Installing Node.js and updating npm.
This works with Windows 10, 8.x, 7, and possibly further back:
@echo Started: %date% %time%
.
.
.
@echo Completed: %date% %time%
Use the jQuery ajaxSetup function, that can set up default values for all ajax requests.
$.ajaxSetup({
headers: {
'Authorization': "Basic XXXXX"
}
});
The problem I was facing was that I was able to make a maven build from the command prompt but not from Eclipse.What worked for me in eclipse is that I changed the run configuration to point to JRE folder inside of JDK rather than leaving it in JDK folder only as per the standard.This solution may work for you as well but try this if and only if all the java paths are correct, java and javac are showing the same version as present in the target of pom.xml.
you can't make easisly a slideup slidedown with css3 tha's why I've turned JensT script into a plugin with javascript fallback and callback.
in this way if you have a modern brwowser you can use the css3 csstransition. if your browser does not support it gracefuly use the old fashioned slideUp slideDown.
/* css */
.csstransitions .mosneslide {
-webkit-transition: height .4s ease-in-out;
-moz-transition: height .4s ease-in-out;
-ms-transition: height .4s ease-in-out;
-o-transition: height .4s ease-in-out;
transition: height .4s ease-in-out;
max-height: 9999px;
overflow: hidden;
height: 0;
}
the plugin
(function ($) {
$.fn.mosne_slide = function (
options) {
// set default option values
defaults = {
delay: 750,
before: function () {}, // before callback
after: function () {} // after callback;
}
// Extend default settings
var settings = $.extend({},
defaults, options);
return this.each(function () {
var $this = $(this);
//on after
settings.before.apply(
$this);
var height = $this.height();
var width = $this.width();
if (Modernizr.csstransitions) {
// modern browsers
if (height > 0) {
$this.css(
'height',
'0')
.addClass(
"mosne_hidden"
);
} else {
var clone =
$this.clone()
.css({
'position': 'absolute',
'visibility': 'hidden',
'height': 'auto',
'width': width
})
.addClass(
'mosne_slideClone'
)
.appendTo(
'body'
);
var newHeight =
$(
".mosne_slideClone"
)
.height();
$(
".mosne_slideClone"
)
.remove();
$this.css(
'height',
newHeight +
'px')
.removeClass(
"mosne_hidden"
);
}
} else {
//fallback
if ($this.is(
":visible"
)) {
$this.slideUp()
.addClass(
"mosne_hidden"
);
} else {
$this.hide()
.slideDown()
.removeClass(
"mosne_hidden"
);
}
}
//on after
setTimeout(function () {
settings.after
.apply(
$this
);
}, settings.delay);
});
}
})(jQuery);;
how to use it
/* jQuery */
$(".mosneslide").mosne_slide({
delay:400,
before:function(){console.log("start");},
after:function(){console.log("done");}
});
you can find a demo page here http://www.mosne.it/playground/mosne_slide_up_down/
You can use this method.
public static File getRobotCacheFile(Context context) throws IOException {
File cacheFile = new File(context.getCacheDir(), "robot.png");
try {
InputStream inputStream = context.getAssets().open("robot.png");
try {
FileOutputStream outputStream = new FileOutputStream(cacheFile);
try {
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
} finally {
outputStream.close();
}
} finally {
inputStream.close();
}
} catch (IOException e) {
throw new IOException("Could not open robot png", e);
}
return cacheFile;
}
You should never use InputStream.available() in such cases. It returns only bytes that are buffered. Method with .available() will never work with bigger files and will not work on some devices at all.
In Kotlin (;D):
@Throws(IOException::class)
fun getRobotCacheFile(context: Context): File = File(context.cacheDir, "robot.png")
.also {
it.outputStream().use { cache -> context.assets.open("robot.png").use { it.copyTo(cache) } }
}
$(function () {
$( ".droppable-area" ).sortable({
connectWith: ".connected-sortable",
containment: ".droppable-area", //(parent div)
stack: '.connected-sortable div'
}).disableSelection();
});