You could use euclidean distance from the point highest and nearest the viewer, except that is not quite right. It results in spherical sort order. You can straighten that out by looking from further away. Further away the curvature becomes flattened out. So just add say 1000 to each of the x,y and z components to give x',y' and z'. The sort on x'*x'+y'*y'+z'*z'.
I guess something like this would work:
Add System.ServiceProcess
to your project references (It's on the .NET tab).
using System.ServiceProcess;
ServiceController sc = new ServiceController(SERVICENAME);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
Edit: There is also a method sc.WaitforStatus()
that takes a desired status and a timeout, never used it but it may suit your needs.
Edit: Once you get the status, to get the status again you will need to call sc.Refresh()
first.
Reference: ServiceController object in .NET.
First lets see the similarities: Both StringBuilder and StringBuffer are mutable. That means you can change the content of them, with in the same location.
Differences: StringBuffer is mutable and synchronized as well. Where as StringBuilder is mutable but not synchronized by default.
Meaning of synchronized (synchronization): When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect. StringBuffer is synchronized, so you can use it with multiple threads with out any problem.
Which one to use when? StringBuilder : When you need a string, which can be modifiable, and only one thread is accessing and modifying it. StringBuffer : When you need a string, which can be modifiable, and multiple threads are accessing and modifying it.
Note : Don't use StringBuffer unnecessarily, i.e., don't use it if only one thread is modifying and accessing it because it has lot of locking and unlocking code for synchronization which will unnecessarily take up CPU time. Don't use locks unless it is required.
const static int newvals[] = {34,2,4,5,6};
std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);
best way is to use Java7: Java 7 introduces a new way of working with the filesystem, along with a new utility class – Files. Using the Files class, we can create, move, copy, delete files and directories as well; it also can be used to read and write to a file.
public void saveDataInFile(String data) throws IOException {
Path path = Paths.get(fileName);
byte[] strToBytes = data.getBytes();
Files.write(path, strToBytes);
}
Write with FileChannel If you are dealing with large files, FileChannel can be faster than standard IO. The following code write String to a file using FileChannel:
public void saveDataInFile(String data)
throws IOException {
RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
FileChannel channel = stream.getChannel();
byte[] strBytes = data.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
buffer.put(strBytes);
buffer.flip();
channel.write(buffer);
stream.close();
channel.close();
}
Write with DataOutputStream
public void saveDataInFile(String data) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
outStream.writeUTF(data);
outStream.close();
}
Write with FileOutputStream
Let’s now see how we can use FileOutputStream to write binary data to a file. The following code converts a String int bytes and writes the bytes to file using a FileOutputStream:
public void saveDataInFile(String data) throws IOException {
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = data.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
Write with PrintWriter we can use a PrintWriter to write formatted text to a file:
public void saveDataInFile() throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
Write with BufferedWriter: use BufferedWriter to write a String to a new file:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(data);
writer.close();
}
append a String to the existing file:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(data);
writer.close();
}
?legend
will tell you:
Arguments
x
, y
the x
and y
co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted by xy.coords
: See ‘Details’.
Details:
Arguments x
, y
, legend are interpreted in a non-standard way to allow the coordinates to be specified via one or two arguments. If legend is missing and y
is not numeric, it is assumed that the second argument is intended to be legend and that the first argument specifies the coordinates.
The coordinates can be specified in any way which is accepted by xy.coords
. If this gives the coordinates of one point, it is used as the top-left coordinate of the rectangle containing the legend. If it gives the coordinates of two points, these specify opposite corners of the rectangle (either pair of corners, in any order).
The location may also be specified by setting x
to a single keyword from the list bottomright
, bottom
, bottomleft
, left
, topleft
, top
, topright
, right
and center
. This places the legend on the inside of the plot frame at the given location. Partial argument matching is used. The optional inset argument specifies how far the legend is inset from the plot margins. If a single value is given, it is used for both margins; if two values are given, the first is used for x- distance, the second for y-distance.
use DATE
and CURDATE()
SELECT * FROM `table` WHERE DATE(`timestamp`) = CURDATE()
Warning! This query doesn't use an index efficiently. For the more efficient solution see the answer below
This is what worked for our particular situation.
Notes are from Wikipedia on Basic Auth from the Client Side. Thank you to @briantist's answer for the help!
Combine the username and password into a single string username:password
$user = "shaunluttin"
$pass = "super-strong-alpha-numeric-symbolic-long-password"
$pair = "${user}:${pass}"
Encode the string to the RFC2045-MIME variant of Base64, except not limited to 76 char/line.
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
Create the Auth value as the method, a space, and then the encoded pair Method Base64String
$basicAuthValue = "Basic $base64"
Create the header Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
$headers = @{ Authorization = $basicAuthValue }
Invoke the web-request
Invoke-WebRequest -uri "https://api.github.com/user" -Headers $headers
The PowerShell version of this is more verbose than the cURL version is. Why is that? @briantist pointed out that GitHub is breaking the RFC and PowerShell is sticking to it. Does that mean that cURL is also breaking with the standard?
You might be best starting with reading this post by Dan Abramov where he discusses various implementations of Flux and their trade-offs at the time he was writing redux: The Evolution of Flux Frameworks
Secondly that motivations page you link to does not really discuss the motivations of Redux so much as the motivations behind Flux (and React). The Three Principles is more Redux specific though still does not deal with the implementation differences from the standard Flux architecture.
Basically, Flux has multiple stores that compute state change in response to UI/API interactions with components and broadcast these changes as events that components can subscribe to. In Redux, there is only one store that every component subscribes to. IMO it feels at least like Redux further simplifies and unifies the flow of data by unifying (or reducing, as Redux would say) the flow of data back to the components - whereas Flux concentrates on unifying the other side of the data flow - view to model.
MongoDB has a simple web based administrative port at 28017 by default.
There is no HTTP access at the default port of 27017 (which is what the error message is trying to suggest). The default port is used for native driver access, not HTTP traffic.
To access MongoDB, you'll need to use a driver like the MongoDB native driver for NodeJS. You won't "POST" to MongoDB directly (but you might create a RESTful API using express which uses the native drivers). Instead, you'll use a wrapper library that makes accessing MongoDB convenient. You might also consider using Mongoose (which uses the native driver) which adds an ORM-like model for MongoDB in NodeJS.
If you can't get to the web interface, it may be disabled. Normally, I wouldn't expect that you'd need it for doing development unless you're checking logs and such.
An error message itself says:
"Invalid App Store Icon. The App Store Icon in the asset catalog in 'YourApp.app' can't be transparent nor contain an alpha channel."
All app icon must be square without transparency or semi transparent (alpha value != 1.0
).
Hint: App icon may have rounded corners. (Share your app icons here)
Here is Apple guidelines for App Icon - Human Interface
Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.
if (window.location.href.indexOf("?added-to-cart=555") > -1) {
alert("found it");
}
As @bmleite already mentioned in the comments, you probably forgot to load angular.js.
If I create a fiddle with angular directives in it, but don't include angular.js I get the exact same error in the Chrome console: Uncaught ReferenceError: angular is not defined
FLOAT stores floating point numbers with accuracy up to eight places and has four bytes while DOUBLE stores floating point numbers with accuracy upto 18 places and has eight bytes.
To get the number of votes for a specific item, you would use:
vote_count = Item.objects.filter(votes__contest=contestA).count()
If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:
contest = Contest.objects.get(pk=contest_id)
votes = contest.votes_set.select_related()
vote_counts = {}
for vote in votes:
if not vote_counts.has_key(vote.item.id):
vote_counts[vote.item.id] = {
'item': vote.item,
'count': 0
}
vote_counts[vote.item.id]['count'] += 1
This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.
you can install this package... https://github.com/UB-Mannheim/tesseract/wiki after that you should go this path C:\Program Files (x86)\Tesseract-OCR\ tesseract.exe then run tesseract file. I think this will help you...
If each item in the list is a string (and any strings inside those strings use " " rather than ' '), you can use regular expressions (re
module)
>>> flattener = re.compile("\'.*?\'")
>>> flattener
<_sre.SRE_Pattern object at 0x10d439ca8>
>>> stred = str(in_list)
>>> outed = flattener.findall(stred)
The above code converts in_list into a string, uses the regex to find all the substrings within quotes (i.e. each item of the list) and spits them out as a list.
For the Javadoc tag @see
, you don't need to use @link
; Javadoc will create a link for you. Try
@see com.my.package.Class#method()
Creating a .bashrc file in your home directory also works. That way you don't have to copy your .bash_profile every time you install a new version of git bash.
I have had a similar requirement. After a lot of testing I found a simple but not very elegant solution (not sure if it will work for you?)...
After my macro refresh's the data that Excel is getting, I added into my macro the line "Calculate" (normally used to recalculate the workbook if you have set calculation to manual).
While I don't need to do do this, it appears by adding this in, Excel waits while the data is refreshed before continuing with the rest of my macro.
Chalkey is correct, you need to use the src attribute to specify the page to be contained in the iframe. Providing you do this, and the document in the iframe is in the same domain as the parent document, you can use this:
var e = document.getElementById("id_description_iframe");
if(e != null) {
alert(e.contentWindow.document.body.innerHTML);
}
Obviously you can then do something useful with the contents instead of just putting them in an alert.
I found a very good answer here which explains when to use what in simple words:
The basic rule of thumb for which framework to use is how to plan on editing your data in your presentation layer.
Linq-To-Sql - use this framework if you plan on editing a one-to-one relationship of your data in your presentation layer. Meaning you don't plan on combining data from more than one table in any one view or page.
Entity Framework - use this framework if you plan on combining data from more than one table in your view or page. To make this clearer, the above terms are specific to data that will be manipulated in your view or page, not just displayed. This is important to understand.
With the Entity Framework you are able to "merge" tabled data together to present to the presentation layer in an editable form, and then when that form is submitted, EF will know how to update ALL the data from the various tables.
There are probably more accurate reasons to choose EF over L2S, but this would probably be the easiest one to understand. L2S does not have the capability to merge data for view presentation.
What you're looking for is date --date='06/12/2012 07:21:22' +"%s"
. Keep in mind that this assumes you're using GNU coreutils, as both --date
and the %s
format string are GNU extensions. POSIX doesn't specify either of those, so there is no portable way of making such conversion even on POSIX compliant systems.
Consult the appropriate manual page for other versions of date
.
Note: bash --date
and -d
option expects the date in US or ISO8601 format, i.e. mm/dd/yyyy
or yyyy-mm-dd
, not in UK, EU, or any other format.
Why not try this?:
import os
def touch(fname):
try:
os.utime(fname, None)
except OSError:
open(fname, 'a').close()
I believe this eliminates any race condition that matters. If the file does not exist then an exception will be thrown.
The only possible race condition here is if the file is created before open() is called but after os.utime(). But this does not matter because in this case the modification time will be as expected since it must have happened during the call to touch().
One issue with REPLACE
will be where city names contain the district name. You can use something like.
SELECT SUBSTRING(O.Ort, LEN(C.CityName) + 2, 8000)
FROM dbo.tblOrtsteileGeo O
JOIN dbo.Cities C
ON C.foo = O.foo
WHERE O.GKZ = '06440004'
Since Java 13 you have formatted
1 method on String, which was added along with text blocks as a preview feature 2.
You can use it instead of String.format()
Assertions.assertEquals(
"%s %d %.3f".formatted("foo", 123, 7.89),
"foo 123 7.890"
);
Think about what a pinch
event is: two fingers on an element, moving toward or away from each other.
Gesture events are, to my knowledge, a fairly new standard, so probably the safest way to go about this is to use touch events like so:
(ontouchstart
event)
if (e.touches.length === 2) {
scaling = true;
pinchStart(e);
}
(ontouchmove
event)
if (scaling) {
pinchMove(e);
}
(ontouchend
event)
if (scaling) {
pinchEnd(e);
scaling = false;
}
To get the distance between the two fingers, use the hypot
function:
var dist = Math.hypot(
e.touches[0].pageX - e.touches[1].pageX,
e.touches[0].pageY - e.touches[1].pageY);
There are lots of great answers here. But if your looking for a really simple way, and you don't mind a popular library, a great solution is filesize
https://www.npmjs.com/package/filesize
It has lots of options and the usage is simple e.g.
filesize(265318); // "259.1 KB"
Taken from their excellent examples
xrange
only stores the range params and generates the numbers on demand. However the C implementation of Python currently restricts its args to C longs:
xrange(2**32-1, 2**32+1) # When long is 32 bits, OverflowError: Python int too large to convert to C long
range(2**32-1, 2**32+1) # OK --> [4294967295L, 4294967296L]
Note that in Python 3.0 there is only range
and it behaves like the 2.x xrange
but without the limitations on minimum and maximum end points.
You can call bringToFront() on the view you want to get in the front
This is an example:
yourView.bringToFront();
Use this command before to run composer update/install:
git config --global http.sslverify false
Looks like you missed some options, try to add:
position: relative;
top: 25px;
In my case, the patch was generated perfectly fine by IDEA, however, I edited the patch and saved it which changed CRLF to LF and then the patch stopped working. Curiously, converting it back to CRLF did not work. I noticed in VI editor, that even after setting to DOS format, the '^M' were not added to the end of lines. This forced me to only make changes in VI, so that the EOLs were preserved.
This may apply to you, if you make changes in a non-Windows environment to a patch covering changes between two versions both coming from Windows environment. You want to be careful how you edit such files.
BTW ignore-whitespace
did not help.
If you do not copy and paste the full file path addess e.g. C:\Program Files\Git\bin\git.exe
, in the 'path to executable' field when configuring Git, it can lead to errors. Windows 8 & 10 for instance have a 'copy path' functionality which really works and helps to get full path name. Mac should have something similar. Its always best to use that rather clicking in the path address address bar and copying. This does not usually give the full file path and may cause a lot of troubles if you forget to edit the path at its destination.
Path copycopy is also very good add-on for copying full path
SQL injection is the attempt to issue SQL commands to a database through a website interface, to gain other information. Namely, this information is stored database information such as usernames and passwords.
First rule of securing any script or page that attaches to a database instance is Do not trust user input.
Your example is attempting to end a misquoted string in an SQL statement. To understand this, you first need to understand SQL statements. In your example of adding a '
to a paramater, your 'injection' is hoping for the following type of statement:
SELECT username,password FROM users WHERE username='$username'
By appending a '
to that statement, you could then add additional SQL paramaters or queries.: ' OR username --
SELECT username,password FROM users WHERE username='' OR username -- '$username
That is an injection (one type of; Query Reshaping). The user input becomes an injected statement into the pre-written SQL statement.
Generally there are three types of SQL injection methods:
Read up on SQL Injection, How to test for vulnerabilities, understanding and overcoming SQL injection, and this question (and related ones) on StackOverflow about avoiding injections.
Edit:
As far as TESTING your site for SQL injection, understand it gets A LOT more complex than just 'append a symbol'. If your site is critical, and you (or your company) can afford it, hire a professional pen tester. Failing that, this great exaxmple/proof can show you some common techniques one might use to perform an injection test. There is also SQLMap which can automate some tests for SQL Injection and database take over scenarios.
Wherever you want to save the model,
self.saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
...
self.saver.save(sess, filename)
Make sure, all your tf.Variable
have names, because you may want to restore them later using their names.
And where you want to predict,
saver = tf.train.import_meta_graph(filename)
name = 'name given when you saved the file'
with tf.Session() as sess:
saver.restore(sess, name)
print(sess.run('W1:0')) #example to retrieve by variable name
Make sure that saver runs inside the corresponding session.
Remember that, if you use the tf.train.latest_checkpoint('./')
, then only the latest check point will be used.
Actually is quite easy with this option at the end:
c:\start BATCH.bat -WindowStyle Hidden
You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.
If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:
SQL Developer has a similar feature. See the "Load" link below:
If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.
Assuming ACL is complete, you'd pull the image like this:
declare
l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
l_http_request UTL_HTTP.req;
l_http_response UTL_HTTP.resp;
l_raw RAW(2000);
l_blob BLOB;
begin
-- Important: setup ACL access list first!
DBMS_LOB.createtemporary(l_blob, FALSE);
l_http_request := UTL_HTTP.begin_request(l_url);
l_http_response := UTL_HTTP.get_response(l_http_request);
-- Copy the response into the BLOB.
BEGIN
LOOP
UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
END LOOP;
EXCEPTION
WHEN UTL_HTTP.end_of_body THEN
UTL_HTTP.end_response(l_http_response);
END;
insert into my_pics (pic_id, pic) values (102, l_blob);
commit;
DBMS_LOB.freetemporary(l_blob);
end;
Hope that helps.
Have you tried:
ifconfig 10:35978f0 down
As the physical interface is 10
and the virtual aspect is after the colon :
.
See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/
How about this... http://jsfiddle.net/gSaPb/
Check out my example on jsFiddle: http://jsfiddle.net/QzPGu. Code snippet:
td {
text-align: center;
/* center checkbox horizontally */
vertical-align: middle;
/* center checkbox vertically */
}
table {
border: 1px solid;
width: 200px;
}
tr {
height: 80px;
}
_x000D_
<table>
<tr>
<td>
<input type="checkbox" name="myTextEditBox" value="checked" /> checkbox
</td>
</tr>
</table>
_x000D_
Suppose you have void method that prints many objects;
public static void print( Object... values){
for(Object c : values){
System.out.println(c);
}
}
Above example I used vararge as an argument that accepts values from 0 to N.
From comments: What if 2 strings and 5 integers ??
Answer:
print("string1","string2",1,2,3,4,5);
The following query worked for me in Oracle Database 12c Release 12.1.0.1.0
SELECT COUNT(*)
FROM stats
GROUP BY
extract(MONTH FROM TIMESTAMP),
extract(MONTH FROM TIMESTAMP),
extract(YEAR FROM TIMESTAMP);
You can use the following
p{word-break: break-all;}
<p>LoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolor</p>
I solved the problem by cat'ing all the pems together:
cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD
(keytool didn't know what to do with a PKCS7 formatted key)
I got all the pems from letsencrypt
You only get that message if you try to use Designer or diagrams. If you use t-SQL it works fine:
Select *
into newdb.dbo.newtable
from olddb.dbo.yourtable
where olddb.dbo.yourtable
has been created in 2008 exactly as you want the table to be in 2012
Floated elements don’t take up any vertical space in their containing element.
All of your elements inside #albumhold
are floated, apart from #albumhead
, which doesn’t look like it’d take up much space.
However, if you add overflow: hidden;
to #albumhold
(or some other CSS to clear floats inside it), it will expand its height to encompass its floated children.
Simple 1-to-1 CSV to XLSX file conversion without enumerating/looping through the rows:
import pyexcel
sheet = pyexcel.get_sheet(file_name="myFile.csv", delimiter=",")
sheet.save_as("myFile.xlsx")
Notes:
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
Using angular-google-maps
$scope.bounds = new google.maps.LatLngBounds();
for (var i = $scope.markers.length - 1; i >= 0; i--) {
$scope.bounds.extend(new google.maps.LatLng($scope.markers[i].coords.latitude, $scope.markers[i].coords.longitude));
};
$scope.control.getGMap().fitBounds($scope.bounds);
$scope.control.getGMap().setCenter($scope.bounds.getCenter());
#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif
Make sure you have the checkbox to define DEBUG checked in your build properties.
for element in range(0,len(hello)):
d[element] = hello[element].strip()
In jsp you can do it like this:
<%
boolean checkboxDisabled = true; //do your logic here
String checkboxState = checkboxDisabled ? "disabled" : "";
%>
<input type="checkbox" <%=checkboxState%>>
a = [1,2,3,4,5,1,2,3,4,5,1,12]
for i in range (len(a)):
if a[i]==2:
a[i]=123
You can use a for and or while loop; however if u know the builtin Enumerate function, then it is recommended to use Enumerate.1
With async: false
you get yourself a blocked browser.
For a non blocking synchronous solution you can use the following:
With ES6 you can use a generator & the co library:
beforecreate: function (node, targetNode, type, to) {
co(function*(){
let result = yield jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value));
//Just use the result here
});
}
With ES7 you can just use asyc await:
beforecreate: function (node, targetNode, type, to) {
(async function(){
let result = await jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value));
//Just use the result here
})();
}
If you are using VBA to enter formulas, it is possible to accidentally enter them incompletely:
Sub AlmostAFormula()
With Range("A1")
.Clear
.NumberFormat = "@"
.Value = "=B1+C1"
.NumberFormat = "General"
End With
End Sub
A1 will appear to have a formula, but it is only text until you double-click the cell and touch Enter .
Make sure you have no bugs like this in your code.
UPDATE: Small one-liner function using the ES2017 String.prototype.padStart
method:
const zeroPad = (num, places) => String(num).padStart(places, '0')_x000D_
_x000D_
console.log(zeroPad(5, 2)); // "05"_x000D_
console.log(zeroPad(5, 4)); // "0005"_x000D_
console.log(zeroPad(5, 6)); // "000005"_x000D_
console.log(zeroPad(1234, 2)); // "1234"
_x000D_
Another ES5 approach:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)
I was searching "How to Fix WordPress Login Page Refreshing and Redirecting Issue?" and did not find any good fix. From this Stackoverflow question, I have got my help. I would like to share it with others so that in case they need it, they get the help.
On my website, when I was entering email and password, I was redirecting again and again to wp-admin and asked for passwords. This code helped me to fix the issue:
function admin_default_page() {
return '/';
}
add_filter('login_redirect', 'admin_default_page');
The only way to prevent SQL injection is with parameterized SQL. It simply isn't possible to build a filter that's smarter than the people who hack SQL for a living.
So use parameters for all input, updates, and where clauses. Dynamic SQL is simply an open door for hackers, and that includes dynamic SQL in stored procedures. Parameterize, parameterize, parameterize.
If using reactive forms, you can also disable the entire form or any sub-set of controls in a FormGroup with myFormGroup.disable()
.
function getOnemonthBefore($date){
$day = intval(date("t", strtotime("$date")));//get the last day of the month
$month_date = date("y-m-d",strtotime("$date -$day days"));//get the day 1 month before
return $month_date;
}
The resulting date is dependent to the number of days the input month is consist of. If input month is february (28 days), 28 days before february 5 is january 8. If input is may 17, 31 days before is april 16. Likewise, if input is may 31, resulting date will be april 30.
NOTE: the input takes complete date ('y-m-d') and outputs ('y-m-d') you can modify this code to suit your needs.
It is ^
http://msdn.microsoft.com/en-us/library/ms190277.aspx
See also some code here in the middle of the page How to flip a bit in SQL Server by using the Bitwise NOT operator
You don't say if this is a desktop or web app. I would use the getResourceAsStream()
method from an appropriate ClassLoader if it's a desktop or the Context if it's a web app.
try
System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
appLog.Source = "This Application's Name";
appLog.WriteEntry("An entry to the Application event log.");
are you done with the layout inflating? maybe you can try this!!
View myPoppyView = pw.getContentView();
Button myBelovedButton = (Button)myPoppyView.findViewById(R.id.my_beloved_button);
//do something with my beloved button? :p
Thanks everyone, you all helped me learn a lot. This is what I came up with using some of your suggestions
#this is apparently a better way of getting multiple inputs at the same time than the
#way I was doing it
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
numa = int(split_text[0])
numb = int(split_text[1])
#standing variables
total = 0
if numb > 0:
repeat = numb
else:
repeat = -numb
#for loops work better than while loops and are cheaper
#output the total
for count in range(repeat):
total += numa
#check to make sure the output is accurate
if numb < 0:
total = -total
print total
Thanks for all the help everyone.
Check out the manual: http://www.php.net/manual/en/datetime.format.php
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Will output: 2000-01-01 00:00:00
I am using a com.google.android.material.bottomnavigation.BottomNavigationView
(not the same as OP's) and I tried a variety of the suggested solutions above, but the only thing that worked was setting app:itemBackground
and app:itemIconTint
to my selector color worked for me.
<com.google.android.material.bottomnavigation.BottomNavigationView
style="@style/BottomNavigationView"
android:foreground="?attr/selectableItemBackground"
android:theme="@style/BottomNavigationView"
app:itemBackground="@color/tab_color"
app:itemIconTint="@color/tab_color"
app:itemTextColor="@color/bottom_navigation_text_color"
app:labelVisibilityMode="labeled"
app:menu="@menu/bottom_navigation" />
My color/tab_color.xml
uses android:state_checked
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/grassSelected" android:state_checked="true" />
<item android:color="@color/grassBackground" />
</selector>
and I am also using a selected state color for color/bottom_navigation_text_color.xml
Not totally relevant here but for full transparency, my BottomNavigationView
style is as follows:
<style name="BottomNavigationView" parent="Widget.Design.BottomNavigationView">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">@dimen/bottom_navigation_height</item>
<item name="android:layout_gravity">bottom</item>
<item name="android:textSize">@dimen/bottom_navigation_text_size</item>
</style>
The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.
That being said, I suggest looking at buildwith.com
You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.
You can use prepared statement with lucek's answer and export dynamically table with columns name in CSV :
--If your table has too many columns
SET GLOBAL group_concat_max_len = 100000000;
--Prepared statement
SET @SQL = ( select CONCAT('SELECT * INTO OUTFILE \'YOUR_PATH\' FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'"\' ESCAPED BY \'\' LINES TERMINATED BY \'\\n\' FROM (SELECT ', GROUP_CONCAT(CONCAT("'",COLUMN_NAME,"'")),' UNION select * from YOUR_TABLE) as tmp') from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YOUR_TABLE' AND TABLE_SCHEMA = 'YOUR_SCHEMA' order BY ORDINAL_POSITION );
--Execute it
PREPARE stmt FROM @SQL;
EXECUTE stmt;
Thank lucek.
From Windows Command Prompt, run curl through Git Bash
"C:\\Users\\sizu\\AppData\\Local\\Programs\\Git\\bin\\sh.exe" --login -i -c "curl https://www.google.com"
First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".
With that pedantry out of the way, I think that you're asking how to set object and array properties.
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';
That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.
If you are using C function fgetc
then you should check a next character whether it is equal to the new line character or to EOF. For example
unsigned int count = 0;
while ( 1 )
{
int c = fgetc( FileStream );
if ( c == EOF || c == '\n' )
{
printF( "The length of the line is %u\n", count );
count = 0;
if ( c == EOF ) break;
}
else
{
++count;
}
}
or maybe it would be better to rewrite the code using do-while loop. For example
unsigned int count = 0;
do
{
int c = fgetc( FileStream );
if ( c == EOF || c == '\n' )
{
printF( "The length of the line is %u\n", count );
count = 0;
}
else
{
++count;
}
} while ( c != EOF );
Of course you need to insert your own processing of read xgaracters. It is only an example how you could use function fgetc
to read lines of a file.
But if the program is written in C++ then it would be much better if you would use std::ifstream
and std::string
classes and function std::getline
to read a whole line.
As above.
I use stringbuilder.append().
Very straightforward, and you can then do xmldocument.load(strinbuilder object as parameter).
You will probably find yourself using string.concat within the append parameter, but this is a very straightforward approach.
In my case, the body parameters I was sending in the post request, and logic I have writting depending on the body parameters were wrong, so the response was not able to be sent. so I was getting this error.
example: post request body (a: alsldfjfj) which I was sending
but I had written the code for validating "b" instead of "a"
Set the [Console]::OuputEncoding
as encoding whatever you want, and print out with [Console]::WriteLine
.
If powershell ouput method has a problem, then don't use it. It feels bit bad, but works like a charm :)
Perhaps you need to know how urls are mapped too, since I suffered 404
for hours. There are two kinds of handlers handling requests. BeanNameUrlHandlerMapping
and SimpleUrlHandlerMapping
. When we defined a servlet-mapping
, we are using SimpleUrlHandlerMapping
. One thing we need to know is these two handlers share a common property called alwaysUseFullPath
which defaults to false
.
false
here means Spring will not use the full path to mapp a url to a controller. What does it mean? It means when you define a servlet-mapping
:
<servlet-mapping>
<servlet-name>viewServlet</servlet-name>
<url-pattern>/perfix/*</url-pattern>
</servlet-mapping>
the handler will actually use the *
part to find the controller. For example, the following controller will face a 404
error when you request it using /perfix/api/feature/doSomething
@Controller()
@RequestMapping("/perfix/api/feature")
public class MyController {
@RequestMapping(value = "/doSomething", method = RequestMethod.GET)
@ResponseBody
public String doSomething(HttpServletRequest request) {
....
}
}
It is a perfect match, right? But why 404
. As mentioned before, default value of alwaysUseFullPath
is false, which means in your request, only /api/feature/doSomething
is used to find a corresponding Controller, but there is no Controller cares about that path. You need to either change your url to /perfix/perfix/api/feature/doSomething
or remove perfix
from MyController base @RequestingMapping
.
One other answer to the same error message (this just fixed my problem) is that the System drive was low on disk space. Meaning about 700kb free. Deleting a lot of unused stuff on this really old server and then restarting IIS and the website (probably only IIS was necessary) cause the problem to disappear for me.
I'm sure the other answers are more useful for most people, but for a quick fix, just make sure that the System drive has some free space.
Check if the user has scrolled past the header ad, then display the footer ad.
if($(your header ad).position().top < 0) { $(your footer ad).show() }
Am I correct at what you are looking for?
The most important rationale for avoiding ++ or -- is that the operators return values and cause side effects at the same time, making it harder to reason about the code.
For efficiency's sake, I prefer:
I am a fan of Mr. Crockford, but in this case I have to disagree. ++i
is 25% less text to parse than i+=1
and arguably clearer.
Probably the most elegant way of doing this is to do it in one step. See val()
.
$("#text").val(function(i, val) {
return val.replace('.', ':');
});
compared to:
var val = $("#text").val();
$("#text").val(val.replace('.', ':'));
From the docs:
.val( function(index, value) )
function(index, value)A function returning the value to set.
This method is typically used to set the values of form fields. For
<select multiple="multiple">
elements, multiple s can be selected by passing in an array.The
.val()
method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:$('input:text.items').val(function(index, value) { return value + ' ' + this.className; });
This example appends the string " items" to the text inputs' values.
This requires jQuery 1.4+.
in "from queue import Queue
" there is no module called queue
, instead multiprocessing
should be used. Therefore, it should look like "from multiprocessing import Queue
"
Instead of using the placeholder text, you'll want to set the actual text
property of the field to MM/YYYY, set the delegate of the text field and listen for this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // update the text of the label }
Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.
Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).
The command line option
-verbose:gc
causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:[GC 325407K->83000K(776768K), 0.2300771 secs] [GC 325816K->83372K(776768K), 0.2454258 secs] [Full GC 267628K->83769K(776768K), 1.8479984 secs]
Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g.,
325407K->83000K
from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.The next number in parentheses (e.g.,
(776768K)
again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.The last item on the line (e.g.,
0.2300771 secs
) indicates the time taken to perform the collection; in this case approximately a quarter of a second.The format for the major collection in the third line is similar.
The format of the output produced by
-verbose:gc
is subject to change in future releases.
I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?
StringUtils is a utility class from Apache commons-lang (many libraries have it but this is the most common library). You need to download the jar and add it to your applications classpath.
<style>a:hover { }</style>
<a href="/">Go Home</a>
Hover is a pseudo class, and thus cannot be applied with a style attribute. It is part of the selector.
Please see Python OS X development environment. The best way is to use MacPorts. Download and install MacPorts, then install Python via MacPorts by typing the following commands in the Terminal:
sudo port install python26 python_select sudo port select --set python python26
OR
sudo port install python30 python_select sudo port select --set python python30
Use the first set of commands to install Python 2.6 and the second set to install Python 3.0. Then use:
sudo port install py26-packagename
OR
sudo port install py30-packagename
In the above commands, replace packagename with the name of the package, for example:
sudo port install py26-setuptools
These commands will automatically install the package (and its dependencies) for the given Python version.
For a full list of available packages for Python, type:
port list | grep py26-
OR
port list | grep py30-
Which command you use depends on which version of Python you chose to install.
You don't really need jQuery for this. You could do it with plain javascript using the setTimeout method:
// redirect to google after 5 seconds
window.setTimeout(function() {
window.location.href = 'http://www.google.com';
}, 5000);
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
I like to use Printable
with Raw Values
.
enum Audience: String, Printable {
case Public = "Public"
case Friends = "Friends"
case Private = "Private"
var description: String {
return self.rawValue
}
}
Then we can do:
let audience = Audience.Public.description // audience = "Public"
or
println("The value of Public is \(Audience.Public)")
// Prints "The value of Public is Public"
Shorter and dealing with a column (entire, not just a section of a column):
=COUNTA(A:A)
Beware, a cell containing just a space would be included in the count.
If you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your image and use 0 instead of 100 in quality.
Quality Accepts 0 - 100
0 = MAX Compression (Least Quality which is suitable for Small images)
100 = Least Compression (MAX Quality which is suitable for Big images)
.tpl
is the extension for Smarty files. It means "template".
Tip: if you are using NetBeans and you want a correct syntax highlighting for those files:
I had this problem after I added a new target, then created a new class using the 'New File' dialog but accidentally failed to check the new target as well as the original target in the creation dialog, so the object was only added to my original target. The solution was to delete the source files (remove reference only) then add them back using 'Add Files', this time checking both targets.
Use DateFormat.getDateInstance(int style, Locale locale) instead of creating your own patterns with SimpleDateFormat
.
Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:
$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")
You could then launch the script from the command line as per this example:
powershell.exe -noexit c:\scripts\test.ps1
Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage
command, making things easier.
Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.
Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:
Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Set objOutlook = CreateObject("Outlook.Application")
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
objOutlookRecip.Type = olTo
' Set the Subject, Body, and Importance of the message.
.Subject = "This is an Automation test with Microsoft Outlook"
.Body = "This is the body of the message." &vbCrLf & vbCrLf
.Importance = olImportanceHigh 'High importance
If Not IsMissing(AttachmentPath) Then
Set objOutlookAttach = .Attachments.Add(AttachmentPath)
End If
For Each ObjOutlookRecip In .Recipients
objOutlookRecip.Resolve
Next
.Save
.Send
End With
Set objOutlook = Nothing
End Sub
Then, launch Outlook from the command line with the /autorun
parameter, as per this answer (alter path/macroname as necessary):
C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname
Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.
You want code which produce string from arrayList,
Iterate through all elements in list and add it to your String result
you can do this in 2 ways: using String as result or StringBuffer/StringBuilder.
Example:
String result = "";
for (String s : list) {
result += s;
}
...but this isn't good practice because of performance reason. Better is using StringBuffer (threads safe) or StringBuilder which are more appropriate to adding Strings
System.out.print(values[i] + " ");
//in one number be printed
Dave Markle is correct. From W3School's website:
Always specify the type attribute for the button. The default type for Internet Explorer is "button", while in other browsers (and in the W3C specification) it is "submit".
In other words, the browser you're using is following W3C's specification.
If the column has a 0 value, you are fine, my guess is that you have a problem with a Null value, in that case you would need to use IsNull(Column, 0)
to ensure it is always 0 at minimum.
In my case, my website's output path is changed by somebody, the IIS Express even not load OWIN, and the setup class will not be hit of course. After I set the output path as "bin\", it works well.
1.
if(1 == @$manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
2.
if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
3.
if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}
First of all: Create a log4j.properties file
# Root logger option
log4j.rootLogger=INFO, stdout
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Place it in src/main/resources/
After that, use this 2 dependencies:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
It is necessary to add this final dependency to POM file:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
It depends of the language, and of the architecture you are using.
For example, in a php platform, you can format almost language with GeSHi
As bluish comments, GeSHi is a generic syntax highlighter, with no beautification feature. It is more used on the server side, and combine it with a beautification tool can be tricky, as illustrated with this GeSHi drupal ticket.
You have 2 options:
brew update
to update homebrew packages
brew install jmeter
to install jmeter
Read this blog to know how to map folders from standard jmeter to homebrew installed version.
Install using standard version which I would advise you to do. Steps are:
bin/jmeter
Go to Environmental Variables you will find this in Computer Properties->Advance system Setting->Environmental Variables -> Path
Add the path of your git installed int the system. eg: "C:\Program Files\Git\cmd"
Save it. Good to go now!!
Just Checkout This :
Solution 1 :
In Subgrid Function You have to write following :
var selectid = $(this).jqGrid('getCell', row_id, 'id');
alert(selectid);
Where row_id
is the variable which you define in subgrid as parameter.
And id
is the column name which you want to get value of the cell.
Solution 2 :
If You Get Jqgrid Row Id In alert Then set your primary key id as key:true
In ColModels. So You will get value of your database id in alert. Like this :
{name:"id",index:"id",hidden:true, width:15,key:true, jsonmap:"id"},
This is my solution for my scenario:
<div class="btn-group btn-group-justified">
<a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
{{ song.name }}
</a>
<a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
{{ match.name }}
</a>
</div>
default state:
on hover:
We can have this in 2 ways,
Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within
ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons
Or
Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code
if (Request.Form["btnSubmit1"] != null)
{
//
}
if (Request.Form["btnSubmit2"] != null)
{
//
}
LDAP stands for Lightweight Directory Access Protocol.It is used in Active Directory for communicating user queries..e.g.. LDAP can be used by users to search and locate a particular object like a laser printer in a domain.
You can't set CURRENT_TIMESTAMP as default value with DATETIME.
But you can do it with TIMESTAMP.
See the difference here.
Words from this blog
The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.
This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.
The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.
Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =
I had the same issue like below
"java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)". Problem was "WRONG PASSWORD".
Copy and paste the query as-it-is in the shell to check whether it gives the desired output or not. Small errors consumes more time.
Here are Windows wheel packages built by Chris Golke - Python Windows Binary packages - PyQt
In the filenames cp27
means C-python version 2.7, cp35
means python 3.5, etc.
Since Qt is a more complicated system with a compiled C++ codebase underlying the python interface it provides you, it can be more complex to build than just a pure python code package, which means it can be hard to install it from source.
Make sure you grab the correct Windows wheel file (python version, 32/64 bit), and then use pip to install it - e.g:
C:\path\where\wheel\is\> pip install PyQt4-4.11.4-cp35-none-win_amd64.whl
Should properly install if you are running an x64 build of Python 3.5.
First you need to now that you can use the implicit intent, android documentation provide us with a very detailed common intents for implementing the map intent you need to create a new intent with two parameters
For action we can use Intent.ACTION_VIEW
and for Uri we should Build it ,below i attached a sample code to create,build,start the activity.
String addressString = "1600 Amphitheatre Parkway, CA";
/*
Build the uri
*/
Uri.Builder builder = new Uri.Builder();
builder.scheme("geo")
.path("0,0")
.query(addressString);
Uri addressUri = builder.build();
/*
Intent to open the map
*/
Intent intent = new Intent(Intent.ACTION_VIEW, addressUri);
/*
verify if the devise can launch the map intent
*/
if (intent.resolveActivity(getPackageManager()) != null) {
/*
launch the intent
*/
startActivity(intent);
}
You have a couple of options. You could do this with a build / deploy step which would process your configuration file replacing your variables with the correct value.
Another option would be to define your own Configuration section which supported this. For example imagine this xml:
<variableAppSettings>
<variables>
<add key="@BaseDir" value="c:\Programs\Widget"/>
</variables>
<appSettings>
<add key="PathToDir" value="@BaseDir\Dir1"/>
</appSettings>
</variableAppSettings>
Now you would implement this using custom configuration objects which would handle replacing the variables for you at runtime.
You have to set the timezone, cf http://www.php.net/manual/en/book.datetime.php
Try using the Worksheet.Protect
method, like so:
Sub ProtectActiveSheet()
Dim ws As Worksheet
Set ws = ActiveSheet
ws.Protect DrawingObjects:=True, Contents:=True, _
Scenarios:=True, Password="SamplePassword"
End Sub
You should, however, be concerned about including the password in your VBA code. You don't necessarily need a password if you're only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.
Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That's a good way to get started in VBA.
I wold create a control named for example InfoProgresBar, that provide this functionality with a label or two (Main Job, Current Job) and ProgressBar and use it instead of that ProgressBar.
Usually I handle my operations within a transaction. As I've experienced, it is not enough to set the context command timeout, but the transaction needs a constructor with a timeout parameter. I had to set both time out values for it to work properly.
int? prevto = uow.Context.Database.CommandTimeout;
uow.Context.Database.CommandTimeout = 900;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(900))) {
...
}
At the end of the function I set back the command timeout to the previous value in prevto.
Using EF6
VTD-XML is the heavy duty XML parsing lib... it is better than others in virtually every way... here is a 2013 paper that analyzes all XML processing frameworks available in java platform...
http://sdiwc.us/digitlib/journal_paper.php?paper=00000582.pdf
The popstate event is fired when the active history entry changes. [...] The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript)
So, listening to popstate
event and sending a popstate
event when using history.pushState()
should be enough to take action on href
change:
window.addEventListener('popstate', listener);
const pushUrl = (href) => {
history.pushState({}, '', href);
window.dispatchEvent(new Event('popstate'));
};
Add <b>
tag
<p> <b> I am in Bold </b></p>
For more text formatting tags click here
Undoubtedly, for your purposes (which I assume is just a programming exercise), the best thing is to check your results against any of the listings of the digits of pi on the web.
And how do we know that those values are correct? Well, I could say that there are computer-science-y ways to prove that an implementation of an algorithm is correct.
More pragmatically, if different people use different algorithms, and they all agree to (pick a number) a thousand (million, whatever) decimal places, that should give you a warm fuzzy feeling that they got it right.
Historically, William Shanks published pi to 707 decimal places in 1873. Poor guy, he made a mistake starting at the 528th decimal place.
Very interestingly, in 1995 an algorithm was published that had the property that would directly calculate the nth digit (base 16) of pi without having to calculate all the previous digits!
Finally, I hope your initial algorithm wasn't pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...
That may be the simplest to program, but it's also one of the slowest ways to do so. Check out the pi article on Wikipedia for faster approaches.
Since x!=x
returns the same boolean array with np.isnan(x)
(because np.nan!=np.nan
would return True
), you could also write:
np.argwhere(x!=x)
However, I still recommend writing np.argwhere(np.isnan(x))
since it is more readable. I just try to provide another way to write the code in this answer.
Sounds like your initial migration was faked because the table already existed (probably with an outdated schema):
https://docs.djangoproject.com/en/1.7/topics/migrations/#adding-migrations-to-apps
"This will make a new initial migration for your app. Now, when you run migrate, Django will detect that you have an initial migration and that the tables it wants to create already exist, and will mark the migration as already applied."
Otherwise you would get an no-such-table error :)
[edit] did you clean up the applied-migrations table? That's also a common cause for non-applied migrations.
You can get a more detailed list (e.g. structured by defining class) with gems like debugging or looksee.
This works Properly in EF 5:
YourEntityModel myEntities = new YourEntityModel();
var objCtx = ((IObjectContextAdapter)myEntities).ObjectContext;
objCtx.ExecuteStoreCommand("TRUNCATE TABLE [TableName]");
it's better to include all *.jar files in the "lib" directory of the project folders tree. and in this way , you'll not need to define the build path by going to the properties of the project. "lib" is already a build path
You can also use query(), i.e.:
df_filtered = df.query('a == 4 & b != 2')
for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
String item = i.next();
System.out.println(item);
}
Note that if you need to use i.remove();
in your loop, or access the actual iterator in some way, you cannot use the for ( : )
idiom, since the actual iterator is merely inferred.
As was noted by Denis Bueno, this code works for any object that implements the Iterable
interface.
Also, if the right-hand side of the for (:)
idiom is an array
rather than an Iterable
object, the internal code uses an int index counter and checks against array.length
instead. See the Java Language Specification.
For me the following worked fine:
> docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
debian jessie 86baf4e8cde9 3 weeks ago 123MB
ubuntu yakkety 7d3f705d307c 3 weeks ago 107MB
alpine 3.5 074d602a59d7 7 weeks ago 3.99MB
Then go ahead and remove an image by running some like these:
> docker rmi debian:jessie
> docker rmi ubuntu:yakkety
> docker rmi alipine:3.5
I found this to work best
var data = [
{ label: "Choice 1", value: "choice_1" },
{ label: "Choice 2", value: "choice_2" },
{ label: "Choice 3", value: "choice_3" }
];
$("#example")
.autocomplete({
source: data,
minLength: 0
})
.focus(function() {
$(this).autocomplete('search', $(this).val())
});
It searches the labels and places the value into the element $(#example)
Another option is to use
int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr);
I like this one most.
Ok so in Windows sourcetree that is simple, on macOS I looked as well for a while..
Click Command + Shift + R while in source tree a hidden popup will be shown that will let you discard individual files OR ALL! Why is this hidden? We will never know.. but it works!
sudo netstat -lpn |grep :'3000'
3000 is port i was looking for, After first command you will have Process ID for that port
kill -9 1192
in my case 1192 was process Id of process running on 3000 PORT use -9 for Force kill the process
Your problem here is that the dtype of 'Date' remained as str/object. You can use the parse_dates
parameter when using read_csv
import pandas as pd
file = '/pathtocsv.csv'
df = pd.read_csv(file, sep = ',', parse_dates= [col],encoding='utf-8-sig', usecols= ['Date', 'ids'],)
df['Month'] = df['Date'].dt.month
From the documentation for the parse_dates
parameter
parse_dates : bool or list of int or names or list of lists or dict, default False
The behavior is as follows:
- boolean. If True -> try parsing the index.
- list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.
- list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column.
- dict, e.g. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’
If a column or index cannot be represented as an array of datetimes, say because of an unparseable value or a mixture of timezones, the column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use
pd.to_datetime
afterpd.read_csv
. To parse an index or column with a mixture of timezones, specifydate_parser
to be a partially-appliedpandas.to_datetime()
withutc=True
. See Parsing a CSV with mixed timezones for more.Note: A fast-path exists for iso8601-formatted dates.
The relevant case for this question is the "list of int or names" one.
col is the columns index of 'Date' which parses as a separate date column.
A very simple approach is the following:
import os
os.system('sshpass -p "password" scp user@host:/path/to/file ./')
No python library are required (only os), and it works, however using this method relies on another ssh client to be installed. This could result in undesired behavior if ran on another system.
Take a look at Blockspring - you do need to install the plugin, but then it's just another function you call like this:
=BLOCKSPRING("twodee-array-reduce","input_array",D5:F7)
The source code and other details are here.
If this doesn't suit and/or you want to build off my solution, you can fork
my function (Python) or use another supported scripting language (Ruby
, R
, JS
, etc...).
It's been a while but for future reference: the method shouldComponentUpdate() can be used.
An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
Use TextView
instead.
You need to use @EmbeddedId
:
@Entity
class Time {
@EmbeddedId
TimeId id;
String src;
String dst;
Integer distance;
Integer price;
}
@Embeddable
class TimeId implements Serializable {
Integer levelStation;
Integer confPathID;
}
Having unsigned
in variable declaration is more useful for the programmers themselves - don't treat the variables as negative. As you've noticed, both -1
and 4294967295
have exact same bit representation for a 4 byte integer. It's all about how you want to treat or see them.
The statement unsigned int a = -1;
is converting -1
in two's complement and assigning the bit representation in a
. The printf()
specifier x
, d
and u
are showing how the bit representation stored in variable a
looks like in different format.
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
As @alucic mentioned, use:
composer require vendor/package:version
or you can use:
composer update vendor/package:version
You should probably review this StackOverflow post about differences between composer install and composer update.
Related to question about version numbers, you can review Composer documentation on versions, but here in short:
So, with Tilde you will get automatic updates of patches but minor and major versions will not be updated. However, if you use Caret you will get patches and minor versions, but you will not get major (breaking changes) versions.
Tilde Version is considered a "safer" approach, but if you are using reliable dependencies (well-maintained libraries) you should not have any problems with Caret Version (because minor changes should not be breaking changes.
Track the remote branch
You can specify the default remote repository for pushing and pulling using git-branch’s track option. You’d normally do this by specifying the --track option when creating your local master branch, but as it already exists we’ll just update the config manually like so:
Edit your .git/config
[branch "master"]
remote = origin
merge = refs/heads/master
Now you can simply git push and git pull.
[source]
There is a bug https://bugs.php.net/bug.php?id=61045 in php-fpm from v5.3.9 and till now (5.3.14 and 5.4.4). Developer promised fix will go live in next release. If you don't want to wait - use patch on that page and re-build or rollback to 5.3.8.
"Date.now() - 86400000" won't work on the Daylight Saving end day (which has 25 hours that day)
Another option is to use Closure:
var d = new goog.date.Date();
d.add(new goog.date.Interval(0, 0, -1));
Add between <head>
tags:
<style>
td {background: #ffddaa; width: 20%;}
</style>
and in the body:
<div style="background: black; border-radius: 12px;">
<table width="100%" style="cell-spacing: 1px;">
<tr>
<td style="border-top-left-radius: 10px;">
Noordwest
</td>
<td> </td>
<td>Noord</td>
<td> </td>
<td style="border-top-right-radius: 10px;">
Noordoost
</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>West</td>
<td> </td>
<td>Centrum</td>
<td> </td>
<td>Oost</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td style="border-bottom-left-radius: 10px;">
Zuidwest
</td>
<td> </td>
<td>Zuid</td>
<td> </td>
<td style="border-bottom-right-radius: 10px;">
Zuidoost
</td>
</tr>
</table>
</div>
The cell color, contents and formatting are of course for example;
it's about spacing color-filled cells within a div.
Doing so, the black cell borders/table border are actually the div background color.
Note that you'll need to set the div-border-radius about 2 values greater than the separate cell corner border radii, to take a smooth rounded corner effect.
To use for..of loop on array and retrieve index you can you use array1.indexOf(element)
which will return the index value of an element in the loop. You can return both the index and the value using this method.
array1 = ['a', 'b', 'c']
for (element of array1) {
console.log(array1.indexOf(element), element) // 0 a 1 b 2 c
}
_x000D_
Use compareTo()
Return Values
0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Like
if(date1.compareTo(date2)>0)
What about this approach? Works for me. It is also used in django-registration.
def get_request_root_url(self):
scheme = 'https' if self.request.is_secure() else 'http'
site = get_current_site(self.request)
return '%s://%s' % (scheme, site)
You have:
foreach (var category in Model.Categories)
and then
@foreach (var product in Model)
Based on that view and model it seems that Model
is of type Product
if yes then the second foreach
is not valid. Actually the first one could be the one that is invalid if you return a collection of Product
.
UPDATE:
You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?
I'm surprised your code compiles when you said you are returning a model of Product
type. Here's how you can do it:
@foreach (var category in Model)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in category.Products)
{
<li>
put the rest of your code
</li>
}
</ul>
</div>
}
That suggest that instead of returning a Product
, you return a collection of Category
with Products. Something like this in EF:
// I am typing it here directly
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.
context.Categories.Include(o=>o.Product)
allocationSize=1
It is a micro optimization before getting query Hibernate tries to assign value in the range of allocationSize and so try to avoid querying database for sequence. But this query will be executed every time if you set it to 1. This hardly makes any difference since if your data base is accessed by some other application then it will create issues if same id is used by another application meantime .
Next generation of Sequence Id is based on allocationSize.
By defualt it is kept as 50
which is too much. It will also only help if your going to have near about 50
records in one session which are not persisted and which will be persisted using this particular session and transation.
So you should always use allocationSize=1
while using SequenceGenerator
. As for most of underlying databases sequence is always incremented by 1
.
Use this script in pgAdmin:
DO $$
DECLARE
brow record;
BEGIN
FOR brow IN (select 'drop table "' || tablename || '" cascade;' as table_name from pg_tables where schemaname = 'public') LOOP
EXECUTE brow.table_name;
END LOOP;
END; $$
Here's another approach using json and rouge:
require 'json'
require 'rouge'
formatter = Rouge::Formatters::Terminal256.new
json_lexer = Rouge::Lexers::JSON.new
puts formatter.format(json_lexer.lex(JSON.pretty_generate(JSON.parse(response))))
(parses response from e.g. RestClient
)
In addition to kieran's answer, apparently, modern browsers have an Object.keys
function. In this case, you could do this:
Object.keys(jsonArray).length;
More details in this answer on How to list the properties of a javascript object
Normal assignment (=
) is not possible inside a lambda
expression, although it is possible to perform various tricks with setattr
and friends.
Solving your problem, however, is actually quite simple:
input = [Object(name=""), Object(name="fake_name"), Object(name="")]
output = filter(
lambda o, _seen=set():
not (not o and o in _seen or _seen.add(o)),
input
)
which will give you
[Object(Object(name=''), name='fake_name')]
As you can see, it's keeping the first blank instance instead of the last. If you need the last instead, reverse the list going in to filter
, and reverse the list coming out of filter
:
output = filter(
lambda o, _seen=set():
not (not o and o in _seen or _seen.add(o)),
input[::-1]
)[::-1]
which will give you
[Object(name='fake_name'), Object(name='')]
One thing to be aware of: in order for this to work with arbitrary objects, those objects must properly implement __eq__
and __hash__
as explained here.
Download Lombok Jar File https://projectlombok.org/downloads/lombok.jar
Add maven dependency:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
Start Lombok Installation java -jar lombok-1.16.18.jar
find complete example in this link:
https://howtodoinjava.com/automation/lombok-eclipse-installation-examples/
You can actually use plyr
's rename
function as part of dplyr
chains. I think every function that a) takes a data.frame
as the first argument and b) returns a data.frame
works for chaining. Here is an example:
library('plyr')
library('dplyr')
DF = data.frame(var=1:5)
DF %>%
# `rename` from `plyr`
rename(c('var'='x')) %>%
# `mutate` from `dplyr` (note order in which libraries are loaded)
mutate(x.sq=x^2)
# x x.sq
# 1 1 1
# 2 2 4
# 3 3 9
# 4 4 16
# 5 5 25
UPDATE: The current version of dplyr
supports renaming directly as part of the select
function (see Romain Francois post above). The general statement about using non-dplyr functions as part of dplyr
chains is still valid though and rename
is an interesting example.
I created a library that will handle this much more easier with better syntax:
https://github.com/Jasperav/Storyboardable
Just change Storyboard.swift and let the ViewControllers
conform to Storyboardable
.
<ProgressBar
android:minHeight="20dip"
android:maxHeight="20dip"/>
The answer of @DanielPlaisted before generally works, but the generic method must be public or one must use BindingFlags.NonPublic | BindingFlags.Instance
! Couldn't post it as a comment for lack of reputation.
A "BEFORE-INSERT"-trigger is the only way to realize same-table updates on an insert, and is only possible from MySQL 5.5+. However, the value of an auto-increment field is only available to an "AFTER-INSERT" trigger - it defaults to 0 in the BEFORE-case. Therefore the following example code which would set a previously-calculated surrogate key value based on the auto-increment value id
will compile, but not actually work since NEW.id will always be 0:
create table products(id int not null auto_increment, surrogatekey varchar(10), description text);
create trigger trgProductSurrogatekey before insert on product
for each row set NEW.surrogatekey =
(select surrogatekey from surrogatekeys where id = NEW.id);
In your CSS Style tag put this:
body {
background: url('yourgif.gif') no-repeat center center fixed;
background-size: cover;
}
Convert.ToInt32()
takes uint
as a value.
How about this for IE?:
onmousedown: Hide all elements which could overlay the event. Because display:none visibility:hidden not realy works, push the overlaying div out of the screen for a fixed number of pixels. After a delay push back the overlaying div with the same number of pixels.
onmouseup: Meanwhile this is the event you like to fire.
//script
var allclickthrough=[];
function hidedivover(){
if(allclickthrough.length==0){
allclickthrough=getElementsByClassName(document.body,"clickthrough");// if so .parentNode
}
for(var i=0;i<allclickthrough.length;i++){
allclickthrough[i].style.left=parseInt(allclickthrough[i].style.left)+2000+"px";
}
setTimeout(function(){showdivover()},1000);
}
function showdivover(){
for(var i=0;i<allclickthrough.length;i++){
allclickthrough[i].style.left=parseInt(allclickthrough[i].style.left)-2000+"px";
}
}
//html
<span onmouseup="Dreck_he_got_me()">Click me if you can.</span>
<div onmousedown="hidedivover()" style="position:absolute" class="clickthrough">You'll don't get through!</div>
If you can save the workbook then you have the option to use ADO and Jet/ACE to treat the workbook as a database, and execute SQL against the sheet.
The MSDN information on how to hit Excel using ADO can be found here.
the wmic bios get serialnumber
command call the Win32_BIOS
wmi class and get the value of the SerialNumber
property, which retrieves the serial number of the BIOS Chip of your system.
This will work, make sure your control Event is assigned to this code, it has probably been lost, I also noticed that Double click will only work if the cell is not empty. Try double clicking on a cell with content, don't mess with the designer
private void dgvReport_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//do something
}
<?php $rand_no = rand(10000000, 99999999)?>
<script src="scripts/myjavascript.js?v=<?=$rand_no"></script>
This works for me in all browsers. Here I have used PHP to generate random no. You can use your own server side language.`
String element = "el5";
int x = element.charAt(2) - 48;
Subtracting ascii value of '0' = 48 from char
Assertions are generally used primarily as a means of checking the program's expected behavior. It should lead to a crash in most cases, since the programmer's assumptions about the state of the program are false. This is where the debugging aspect of assertions come in. They create a checkpoint that we simply can't ignore if we would like to have correct behavior.
In your case it does data validation on the incoming parameters, though it does not prevent clients from misusing the function in the future. Especially if they are not, (and should not) be included in release builds.
As of Dec 2020, I had the same issue when installing python v 3.8.6
via pyenv
. So, I started by:
brew install pyenv
brew install xz
pyenv install 3.8.6
pick the required versionpyenv global 3.8.6
make this version as globalpython -m pip install -U pip
to upgrade pippip install virtualenv
After that, I initialized my new env, installed pandas
via pip command, and everything worked again. The panda's version installed is 1.1.5 within my working project directory. I hope that might help!
Note: If you have installed python before xz, make sure to uninstall it first, otherwise the error might persist.
not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
The native lib is expected in one of the following locations
/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
and not in
tomcat/lib
The files in tomcat/lib
are all jar
file and are added by tomcat to the classpath
so that they are available to your application.
The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar
, for linux it could be a .so
file, for windows it could be a .dll
file.
Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.
Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.
org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms
EDIT
The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.
If you are troubling with running your servlet then after the run on sever
command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.
It should be something like that
http://localhost:8080/<your-context-name>/<your-servlet-name>
EDIT 2
Try to call your servlet using the following url
http://localhost:8080/com.filecounter/FileCounter
Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF
.
It is better to configure your servlets there using servlet-name
servlet-class
and url-mapping
. It could look like that:
<servlet>
<description></description>
<display-name>File counter - My first servlet</display-name>
<servlet-name>file_counter</servlet-name>
<servlet-class>com.filecounter.FileCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>file_counter</servlet-name>
<url-pattern>/FileFounter</url-pattern>
</servlet-mapping>
In eclipse dynamic web project the default context name is the same as your project name.
http://localhost:8080/<your-context-name>/FileCounter
will work too.
<a href="javascript:;" onclick="window.location = 'http://example.com/submit.php?url=' + escape(document.location.href);'">Go</a>;
The PEP 484 -- Type Hints says that the types of elements of a tuple
can be individually typed; so that you can say Tuple[str, int, float]
; but a list
, with List
typing class can take only one type parameter: List[str]
, which hints that the difference of the 2 really is that the former is heterogeneous, whereas the latter intrinsically homogeneous.
Also, the standard library mostly uses the tuple as a return value from such standard functions where the C would return a struct
.
to set a div at position fixed you can use
position:fixed
top:0;
left:0;
width:100%;
height:50px; /* change me */
this solved my problem
android:adjustViewBounds="true"
android:scaleType="fitXY"
install TypeScript :
npm install typescript
add tsc script to package.json:
"scripts": {
"tsc": "tsc"
},
run this:
npx tsc --init
Make sure your AUTO_INCREMENT
is not out of range. In that case, set a new value for it with:
ALTER TABLE table_name AUTO_INCREMENT=100 -- Change 100 to the desired number
AUTO_INCREMENT
can contain a number that is bigger than the maximum value allowed by the datatype. This can happen if you filled up a table that you emptied afterward but the AUTO_INCREMENT
stayed the same, but there might be different reasons as well. In this case a new entry's id would be out of range.
If this is the cause of your problem, you can fix it by setting AUTO_INCREMENT
to one bigger than the latest row's id. So if your latest row's id is 100 then:
ALTER TABLE table_name AUTO_INCREMENT=101
If you would like to check AUTO_INCREMENT
's current value, use this command:
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
i have the same problem from my office network.
i use this command but its not working for me
url,
so like this:
before
$ git clone https://gitlab.com/omsharma/Resume.git
After i Use this URL : $ git clone https://[email protected]/omsharma/Resume.git
try It.
You can achieve this with the background-size
property, which is now supported by most browsers.
To scale the background image to fit inside the div:
background-size: contain;
To scale the background image to cover the whole div:
background-size: cover;
There also exists a filter for IE 5.5+ support, as well as vendor prefixes for some older browsers.
small update for swift 5:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
self.present(refreshAlert, animated: true, completion: nil)
Basic debugging using Spring's DebugFilter
can be configured like this:
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.debug(true);
}
}
test.xml:
<?xml version="1.0" encoding="utf-8"?>
<Contacts>
<Node>
<ID>123</ID>
<Name>ABC</Name>
</Node>
<Node>
<ID>124</ID>
<Name>DEF</Name>
</Node>
</Contacts>
Select a single node:
XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected
XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
where xml2.Element("ID").Value == id
select xml2).FirstOrDefault();
Console.WriteLine(Contact.ToString());
Delete a single node:
XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";
var Contact = (from xml2 in XMLDoc.Descendants("Node")
where xml2.Element("ID").Value == id
select xml2).FirstOrDefault();
Contact.Remove();
XMLDoc.Save("test.xml");
Add new node:
XDocument XMLDoc = XDocument.Load("test.xml");
XElement newNode = new XElement("Node",
new XElement("ID", "500"),
new XElement("Name", "Whatever")
);
XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");
If you have jQuery, use isPlainObject.
if ($.isPlainObject(my_var)) {}
Here is a simple example overriding imageView, you can then also use it in layout designer to preview.
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public RoundedImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void setImageDrawable(Drawable drawable) {
float radius = 0.1f;
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
RoundedBitmapDrawable rid = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
rid.setCornerRadius(bitmap.getWidth() * radius);
super.setImageDrawable(rid);
}
}
This is for fast solution. Radius is used on all corners and is based of percentage of bitmap width.
I just overrided setImageDrawable
and used support v4 method for rounded bitmap drawable.
Usage:
<com.example.widgets.RoundedImageView
android:layout_width="39dp"
android:layout_height="39dp"
android:src="@drawable/your_drawable" />
Preview with imageView and custom imageView:
I actually ran into an issue where I had to define winsock2.h as the first include, it seems it has other issues with includes from other packages. Hope this is helpful to someone who runs into same issue, not just windows.h but all includes.
Having read the above answers i found that for my situation the following fixed the issue.
This threw the error
myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(getApplicationContext());
dialog.show();
}
});
Based on the previous answers that suggested the context was the wrong one, i changed the getApplicationContext() to retrieve the context from the View passed in to the buttons onClick method.
myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(v.getContext());
dialog.show();
}
});
I don't fully understand the workings of Java so i could be wrong, but I'm guessing that for my specific situation the cause could have been related to the fact that the above snippet was defined in an Abstract Activity class; inherited and used by many Activities, perhaps that contributed to the fact that getApplicationContext() doesn't return a valid context?? (Just a guess).
Partially for the sake of summarization (excluding LINQ solution), here's two one-liners that address the int maxLength
caveat of allowing negative values and also the case of null string:
Substring
way (from Paul Ruane's answer):public static string Truncate(this string s, uint maxLength) =>
s?.Substring(0, Math.Min(s.Length, (int)maxLength));
Remove
way (from kbrimington's answer):public static string Truncate(this string s, uint maxLength) =>
s?.Length > maxLength ? s.Remove((int)maxLength) : s;
You can use OR()
to group expressions (as well as AND()
):
=IF(OR(condition1, condition2), true, false)
=IF(AND(condition1, condition2), true, false)
So if you wanted to test for "cat" and "22":
=IF(AND(SEARCH("cat",a1),SEARCH("22",a1)),"cat and 22","none")
I would highly recommend you use a very simple templating language such as Freemarker
This occurred to me when I applied the 2017 Fall Creator Update. I was able to resolve by repairing IIS 10.0 Express (I do not have IIS installed on my box.)
Note: As a user pointed out in the comments,
Repair can be found in "Programs and Features" - the "classic" control panel.
I can attest to the fact that -webkit-transform: translate3d(0, 0, 0);
will mess with the new position: -webkit-sticky;
property. With a left drawer navigation pattern that I was working on, the hardware acceleration I wanted with the transform property was messing with the fixed positioning of my top nav bar. I turned off the transform and the positioning worked fine.
Luckily, I seem to have had hardware acceleration on already, because I had -webkit-font-smoothing: antialiased
on the html element. I was testing this behavior in iOS7 and Android.
git pull origin develop
Since pulling a branch into another directly merges them together
spent some time trying to import modules from a list, and this is the thread that got me most of the way there - but I didnt grasp the use of ___import____ -
so here's how to import a module from a string, and get the same behavior as just import. And try/except the error case, too. :)
pipmodules = ['pycurl', 'ansible', 'bad_module_no_beer']
for module in pipmodules:
try:
# because we want to import using a variable, do it this way
module_obj = __import__(module)
# create a global object containging our module
globals()[module] = module_obj
except ImportError:
sys.stderr.write("ERROR: missing python module: " + module + "\n")
sys.exit(1)
and yes, for python 2.7> you have other options - but for 2.6<, this works.
The syntax of a programming language is the form of its expressions, statements, and program units. Its semantics is the meaning of those expressions, statements, and program units. For example, the syntax of a Java while statement is
while (boolean_expr) statement
The semantics of this statement form is that when the current value of the Boolean expression is true, the embedded statement is executed. Then control implicitly returns to the Boolean expression to repeat the process. If the Boolean expression is false, control transfers to the statement following the while construct.