If the log indicates java.lang.UnsupportedClassVersionError: JVM**** bad major version.
Then the code and server is not compiled with the same JDK version.
To fix this, please switch the JDK version either in code or server JDK.
Try this:- In the below use case, im switching to 1.7_64 (JDK 1.7 64 bit)
c:\IBM\WebSphere\WSRR\v8.5\bin\managesdk.bat -enableProfile -profileName WSRRSrv01 -sdkname 1.7_64
Version 51 is Java 7, you probably use the wrong JDK. Check JAVA_HOME.
If you are using Guava, you statically import newArrayList
method from Lists class:
List<String> l = newArrayList(setOfAuthors);
I was having issues attaching screenshots to ExtentReports using a relative path to my image file. My current directory when executing is "C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic". Under this, I created the folder ExtentReports for both the report.html and the image.png screenshot as below.
private String className = getClass().getName();
private String outputFolder = "ExtentReports\\";
private String outputFile = className + ".html";
ExtentReports report;
ExtentTest test;
@BeforeMethod
// initialise report variables
report = new ExtentReports(outputFolder + outputFile);
test = report.startTest(className);
// more setup code
@Test
// test method code with log statements
@AfterMethod
// takeScreenShot returns the relative path and filename for the image
String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);
This creates the report and image in the ExtentReports folder, but when the report is opened and the (blank) image inspected, hovering over the image src shows "Could not load the image" src=".\ExtentReports\QXKmoVZMW7.png".
This is solved by prefixing the relative path and filename for the image with the System Property "user.dir". So this works perfectly and the image appears in the html report.
Chris
String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);
string1.equals(string2)
is right way to do it.
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually results WRONG.
if (s.equals(t)) // RIGHT way to check the two strings
/* == will fail in following case:*/
String s1 = new String("abc");
String s2 = new String("abc");
if(s1==s2) //it will return false
See my case on another similar question:
In my case, I was trying to parse an empty JSON:
JSON.parse(stringifiedJSON);
In other words, what happened was the following:
JSON.parse("");
A way to write a common subset of HTML and XHTML
In the hope of greater portability.
In HTML, <script>
is magic escapes everything until </script>
appears.
So you can write:
<script>x = '<br/>';
and <br/>
won't be considered a tag.
This is why strings such as:
x = '</scripts>'
must be escaped like:
x = '</scri' + 'pts>'
See: Why split the <script> tag when writing it with document.write()?
But XML (and thus XHTML, which is a "subset" of XML, unlike HTML), doesn't have that magic: <br/>
would be seen as a tag.
<![CDATA[
is the XHTML way to say:
don't parse any tags until the next
]]>
, consider it all a string
The //
is added to make the CDATA work well in HTML as well.
In HTML <![CDATA[
is not magic, so it would be run by JavaScript. So //
is used to comment it out.
The XHTML also sees the //
, but will observe it as an empty comment line which is not a problem:
//
That said:
<!DOCTYPE html>
vs <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
script
syntaxBut that violates the golden rule of the Internet:
don't trust third parties, or your product will break
There is a which.py script in a standard Python distribution (e.g. on Windows '\PythonXX\Tools\Scripts\which.py'
).
EDIT: which.py
depends on ls
therefore it is not cross-platform.
You could use:
with open('data.txt', 'r') as file:
data = file.read().replace('\n', '')
Have a look at the sizemode property of the picturebox.
pictureBox1.SizeMode =PictureBoxSizeMode.StretchImage;
good question... I've been looking for this functionality for long too...
after several tests and tricks it seem the better solution is the more obvious one...
--> best way I found to do it, preventing parser integrity fail, is reusing REM:
echo this will show until the next REM &REM this will not show
you can also use multiline with the "NULL LABEL" trick... (dont forget the ^ at the end of the line for continuity)
::(^
this is a multiline^
comment... inside a null label!^
dont forget the ^caret at the end-of-line^
to assure continuity of text^
)
There are a lot of comments arguing the pros and cons of MVVM here. For me, I agree with Nir; it's a matter of using the pattern appropriately and MVVM doesn't always fit. People seems to have become willing to sacrifice all of the most important principles of software design JUST to get it to fit MVVM.
That said,..i think your case could be a good fit with a bit of refactoring.
In most cases I've come across, WPF enables you to get by WITHOUT multiple Window
s. Maybe you could try using Frame
s and Page
s instead of Windows with DialogResult
s.
In your case my suggestion would be have LoginFormViewModel
handle the LoginCommand
and if the login is invalid, set a property on LoginFormViewModel
to an appropriate value (false
or some enum value like UserAuthenticationStates.FailedAuthentication
). You'd do the same for a successful login (true
or some other enum value). You'd then use a DataTrigger
which responds to the various user authentication states and could use a simple Setter
to change the Source
property of the Frame
.
Having your login Window return a DialogResult
i think is where you're getting confused; that DialogResult
is really a property of your ViewModel. In my, admittedly limited experience with WPF, when something doesn't feel right it usually because I'm thinking in terms of how i would've done the same thing in WinForms.
Hope that helps.
I've been looking for the same thing ... some good ideas here, but I ran a few micro benchmarks. I found the following to be the fastest (modified from Ayman's above and about 2x as fast, and about 50% faster than Steve's just above this one):
public static String hash(String text, String algorithm)
throws NoSuchAlgorithmException {
byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes());
return new BigInteger(1, hash).toString(16);
}
Edit: Oops - missed that this is essentially the same as kgiannakakis's and so may strip off a leading 0. Still, modifying this to the following, it's still the fastest:
public static String hash(String text, String algorithm)
throws NoSuchAlgorithmException {
byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes());
BigInteger bi = new BigInteger(1, hash);
String result = bi.toString(16);
if (result.length() % 2 != 0) {
return "0" + result;
}
return result;
}
For script creation at Windows cmd or powershell prompt:
C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3
conda list
pip list
var str = 'Hello World',
i = 3,
result = str.substr(0, i-1)+str.substring(i);
alert(result);
Value of i
should not be less then 1
.
The reason is the browser can not understand it and try to somehow translate it to what it can understand and in this case into a hexadecimal value!...
chucknorris
starts with c
which is recognised character in hexadecimal, also it's converting all unrecognised characters into 0
!
So chucknorris
in hexadecimal format becomes: c00c00000000
, all other characters become 0
and c
remains where they are...
Now they get divided by 3 for RGB
(red, green, blue)... R: c00c, G: 0000, B:0000
...
But we know valid hexadecimal for RGB is just 2 characters, means R: c0, G: 00, B:00
So the real result is:
bgcolor="#c00000";
I also added the steps in the image as a quick reference for you:
Note that probability is different than probability density pdf()
, which some of the previous answers refer to. Probability is the chance that the variable has a specific value, whereas the probability density is the chance that the variable will be near a specific value, meaning probability over a range. So to obtain the probability you need to compute the integral of the probability density function over a given interval. As an approximation, you can simply multiply the probability density by the interval you're interested in and that will give you the actual probability.
import numpy as np
from scipy.stats import norm
data_start = -10
data_end = 10
data_points = 21
data = np.linspace(data_start, data_end, data_points)
point_of_interest = 5
mu = np.mean(data)
sigma = np.std(data)
interval = (data_end - data_start) / (data_points - 1)
probability = norm.pdf(point_of_interest, loc=mu, scale=sigma) * interval
The code above will give you the probability that the variable will have an exact value of 5 in a normal distribution between -10 and 10 with 21 data points (meaning interval is 1). You can play around with a fixed interval value, depending on the results you want to achieve.
You can create a countdown timer using applet, below is the code,
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer; // not java.util.Timer
import java.text.NumberFormat;
import java.net.*;
/**
* An applet that counts down from a specified time. When it reaches 00:00,
* it optionally plays a sound and optionally moves the browser to a new page.
* Place the mouse over the applet to pause the count; move it off to resume.
* This class demonstrates most applet methods and features.
**/
public class Countdown extends JApplet implements ActionListener, MouseListener
{
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00
// Called when the applet is first loaded
public void init() {
// Figure out how long to count for by reading the "minutes" parameter
// defined in a <param> tag inside the <applet> tag. Convert to ms.
String minutes = getParameter("minutes");
if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
else remaining = 600000; // 10 minutes by default
// Create a JLabel to display remaining time, and set some properties.
label = new JLabel();
label.setHorizontalAlignment(SwingConstants.CENTER );
label.setOpaque(true); // So label draws the background color
// Read some parameters for this JLabel object
String font = getParameter("font");
String foreground = getParameter("foreground");
String background = getParameter("background");
String imageURL = getParameter("image");
// Set label properties based on those parameters
if (font != null) label.setFont(Font.decode(font));
if (foreground != null) label.setForeground(Color.decode(foreground));
if (background != null) label.setBackground(Color.decode(background));
if (imageURL != null) {
// Load the image, and save it so we can release it later
image = getImage(getDocumentBase(), imageURL);
// Now display the image in the JLabel.
label.setIcon(new ImageIcon(image));
}
// Now add the label to the applet. Like JFrame and JDialog, JApplet
// has a content pane that you add children to
getContentPane().add(label, BorderLayout.CENTER);
// Get an optional AudioClip to play when the count expires
String soundURL = getParameter("sound");
if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);
// Obtain a NumberFormat object to convert number of minutes and
// seconds to strings. Set it up to produce a leading 0 if necessary
format = NumberFormat.getNumberInstance();
format.setMinimumIntegerDigits(2); // pad with 0 if necessary
// Specify a MouseListener to handle mouse events in the applet.
// Note that the applet implements this interface itself
addMouseListener(this);
// Create a timer to call the actionPerformed() method immediately,
// and then every 1000 milliseconds. Note we don't start the timer yet.
timer = new Timer(1000, this);
timer.setInitialDelay(0); // First timer is immediate.
}
// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }
// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates
// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates
// Return information about the applet
public String getAppletInfo() {
return "Countdown applet Copyright (c) 2003 by David Flanagan";
}
// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }
// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
{"minutes", "number", "time, in minutes, to countdown from"},
{"font", "font", "optional font for the time display"},
{"foreground", "color", "optional foreground color for the time"},
{"background", "color", "optional background color"},
{"image", "image URL", "optional image to display next to countdown"},
{"sound", "sound URL", "optional sound to play when we reach 00:00"},
{"newpage", "document URL", "URL to load when timer expires"},
};
// Start or resume the countdown
void resume() {
// Restore the time we're counting down from and restart the timer.
lastUpdate = System.currentTimeMillis();
timer.start(); // Start the timer
}
// Pause the countdown
void pause() {
// Subtract elapsed time from the remaining time and stop timing
long now = System.currentTimeMillis();
remaining -= (now - lastUpdate);
timer.stop(); // Stop the timer
}
// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
long now = System.currentTimeMillis(); // current time in ms
long elapsed = now - lastUpdate; // ms elapsed since last update
remaining -= elapsed; // adjust remaining time
lastUpdate = now; // remember this update time
// Convert remaining milliseconds to mm:ss format and display
if (remaining < 0) remaining = 0;
int minutes = (int)(remaining/60000);
int seconds = (int)((remaining)/1000);
label.setText(format.format(minutes) + ":" + format.format(seconds));
// If we've completed the countdown beep and display new page
if (remaining == 0) {
// Stop updating now.
timer.stop();
// If we have an alarm sound clip, play it now.
if (sound != null) sound.play();
// If there is a newpage URL specified, make the browser
// load that page now.
String newpage = getParameter("newpage");
if (newpage != null) {
try {
URL url = new URL(getDocumentBase(), newpage);
getAppletContext().showDocument(url);
}
catch(MalformedURLException ex) { showStatus(ex.toString()); }
}
}
}
// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }
// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
pause(); // pause countdown
showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
resume(); // resume countdown
showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
The WHERE
clause is misplaced, it has to follow the table references and JOIN operations.
Something like this:
FROM tartikel p1
JOIN tartikelpict p2
ON p1.kArtikel = p2.kArtikel
AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC
EDIT (three plus years later)
The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"
As to a question about writing a condition that checks a date range of "last 7 days"...
That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.
To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".
If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT
SELECT DATE(NOW()) + INTERVAL -1 DAY
and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:
WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY
For a DATETIME or TIMESTAMP column, we can use >=
and <
inequality comparisons to specify a range
WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY
For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...
WHERE datetimecol >= NOW() + INTERVAL -7 DAY
AND datetimecol < NOW() + INTERVAL 0 DAY
the last seven complete days, not including today
WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY
or past six complete days plus so far today ...
WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
AND datetimecol < NOW() + INTERVAL 0 DAY
I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.
SET @clock = '2017-11-17 11:47:47' ;
SELECT DATE(@clock)
, DATE(@clock) + INTERVAL -7 DAY
, @clock + INTERVAL -6 DAY
Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.
(Some developers prefer to use the DATE_ADD
and DATE_SUB
functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR
syntax.
And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,
Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is
WHERE datetimecol >= '2017-11-10 00:00'
AND datetimecol < '2017-11-17 00:00'
And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...
WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
AND datetimecol < '2017-11-17 00:00' + INTERVAL 0 SECOND
The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy'
, m/d/yyyy
, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.
The problem is that data:image/png;base64,
is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.
function base64_to_jpeg($base64_string, $output_file) {
// open the output file for writing
$ifp = fopen( $output_file, 'wb' );
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $base64_string );
// we could add validation here with ensuring count( $data ) > 1
fwrite( $ifp, base64_decode( $data[ 1 ] ) );
// clean up the file resource
fclose( $ifp );
return $output_file;
}
If you are dealing with a large df (40m x 700 in my case) it works much faster and memory savvy through iteration on columns with something like.
for col in df.columns:
df[col][df[col] < 0] = 0
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
Depends on what your definition of "offscreen" is. Is that within the viewport, or within the defined boundaries of your page?
Using Element.getBoundingClientRect() you can easily detect whether or not your element is within the boundries of your viewport (i.e. onscreen or offscreen):
jQuery.expr.filters.offscreen = function(el) {
var rect = el.getBoundingClientRect();
return (
(rect.x + rect.width) < 0
|| (rect.y + rect.height) < 0
|| (rect.x > window.innerWidth || rect.y > window.innerHeight)
);
};
You could then use that in several ways:
// returns all elements that are offscreen
$(':offscreen');
// boolean returned if element is offscreen
$('div').is(':offscreen');
$("#t").text($("#cb").find(":checked").val())
This is an old thread, but purely using os.system
, the following's a valid way of accessing the data returned by the ps
call. Note: it does use a pipe to write the data to a file on disk. And OP didn't specifically ask for a solution using os.system
.
>>> os.system("ps > ~/Documents/ps.txt")
0 #system call is processed.
>>> os.system("cat ~/Documents/ps.txt")
PID TTY TIME CMD
9927 pts/0 00:00:00 bash
10063 pts/0 00:00:00 python
12654 pts/0 00:00:00 sh
12655 pts/0 00:00:00 ps
0
accordingly,
>>> os.system("ps -p 10063 -o time --no-headers > ~/Documents/ps.txt")
0
>>> os.system("cat ~/Documents/ps.txt")
00:00:00
0
No idea why they are all returning zeroes though.
Once you have a reference to your image, you can set its height and width like so:
var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style) {
yourImg.style.height = '100px';
yourImg.style.width = '200px';
}
In the html, it would look like this:
<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>
The problem with using string literal I find is that it can make your code look a bit "weird" because in order to not get spaces in the string itself, it has to be completely left aligned:
var someString = @"The
quick
brown
fox...";
Yuck.
So the solution I like to use, which keeps everything nicely aligned with the rest of your code is:
var someString = String.Join(
Environment.NewLine,
"The",
"quick",
"brown",
"fox...");
And of course, if you just want to logically split up lines of an SQL statement like you are and don't actually need a new line, you can always just substitute Environment.NewLine
for " "
.
If you do so, and you're using fail2ban, you will need to enable the proper filters/actions:
Put the following lines in /etc/fail2ban/jail.d/sshd.local
[ssh-iptables]
enabled = true
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
logpath = /var/log/secure
maxretry = 5
bantime = 86400
Enable and start fail2ban:
systemctl enable fail2ban
systemctl start fail2ban
Reference: http://blog.iopsl.com/fail2ban-on-centos-7-to-protect-ssh-part-ii/
For future reference,
I have encountered the same problem -- pylab was not showing under ipython. The problem was fixed by changing ipython's config file {ipython_config.py}. In the config file
c.InteractiveShellApp.pylab = 'auto'
I changed 'auto' to 'qt' and now I see graphs
As mentioned before, the use of x(end+1) = newElem
has the advantage that it allows you to concatenate your vector with a scalar, regardless of whether your vector is transposed or not. Therefore it is more robust for adding scalars.
However, what should not be forgotten is that x = [x newElem]
will also work when you try to add multiple elements at once. Furthermore, this generalizes a bit more naturally to the case where you want to concatenate matrices. M = [M M1 M2 M3]
All in all, if you want a solution that allows you to concatenate your existing vector x
with newElem
that may or may not be a scalar, this should do the trick:
x(end+(1:numel(newElem)))=newElem
If the types of the parameters are all the same (varchar2
for example), you can have a package like this which will do the following:
CREATE OR REPLACE PACKAGE testuser.test_pkg IS
TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);
END test_pkg;
CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
BEGIN
FOR i IN p_parm.first .. p_parm.last
LOOP
dbms_output.put_line(p_parm(i));
END LOOP;
END;
END test_pkg;
Then, to call it you'd need to set up the array and pass it:
DECLARE
l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
l_array(0) := 'hello';
l_array(1) := 'there';
testuser.test_pkg.your_proc(l_array);
END;
/
There's a difference between C++ and C# in this specific case. In C++ the object is not initialized and therefore it is unsafe to call a virutal function inside a constructor. In C# when a class object is created all its members are zero initialized. It is possible to call a virtual function in the constructor but if you'll might access members that are still zero. If you don't need to access members it is quite safe to call a virtual function in C#.
Make a selector for Individaual item of Nav Drawer
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/darkBlue" android:state_pressed="true"/>
<item android:drawable="@color/darkBlue" android:state_checked="true"/>
<item android:drawable="@color/textBlue" />
</selector>
Make a few changes in your NavigationView
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:itemBackground="@drawable/drawer_item"
android:background="@color/textBlue"
app:itemIconTint="@color/white"
app:itemTextColor="@color/white"
app:menu="@menu/activity_main_drawer"
/>
To install ncurses-compat-libs
on Fedora 24 helped me on this issue
(unable to start adb error while loading shared libraries: libncurses.so.5
)
I got exactly the same error in Windows 8 while trying to export decision tree digraph using tree.export_graphviz! Then I installed GraphViz from this link. And then I followed the below steps which resolved my issue:
In principle, you can style it using option[selected] as selector, but that doesn't work in many browsers. Also, that only allows you to style the selected option, not the option that has hover focus.
Tested to work in Chrome 9 and Firefox 3.6, doesn't work in Internet Explorer 8.
Recommendation. Do not use user-added REM statements to block batch steps. Use conditional GOTO instead. That way you can predefine and test the steps and options. The users also get much simpler changes and better confidence.
@Echo on
rem Using flags to control command execution
SET ExecuteSection1=0
SET ExecuteSection2=1
@echo off
IF %ExecuteSection1%==0 GOTO EndSection1
ECHO Section 1 Here
:EndSection1
IF %ExecuteSection2%==0 GOTO EndSection2
ECHO Section 2 Here
:EndSection2
Try using "nlargest" on the groupby object. The advantage of using nlargest is that it returns the index of the rows where "the nlargest item(s)" were fetched from. Note: we slice the second(1) element of our index since our index in this case consist of tuples(eg.(s1, 0)).
df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})
d = df.groupby('mt')['count'].nlargest(1) # pass 1 since we want the max
df.iloc[[i[1] for i in d.index], :] # pass the index of d as list comprehension
Import QuartzCore
framework in you class:
#import <QuartzCore/QuartzCore.h>
and for changing the border color use the following code snippet (I'm setting it to redColor),
textField.layer.cornerRadius=8.0f;
textField.layer.masksToBounds=YES;
textField.layer.borderColor=[[UIColor redColor]CGColor];
textField.layer.borderWidth= 1.0f;
For reverting back to the original layout just set border color to clear color,
serverField.layer.borderColor=[[UIColor clearColor]CGColor];
in swift code
textField.layer.borderWidth = 1
textField.layer.borderColor = UIColor.whiteColor().CGColor
Replace a Fragment using following code:
Fragment fragment = new AddPaymentFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, fragment, "Tag_AddPayment")
.addToBackStack("Tag_AddPayment")
.commit();
Activity's onBackPressed() is :
@Override
public void onBackPressed() {
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 1) {
fm.popBackStack();
} else {
finish();
}
Log.e("popping BACKSTRACK===> ",""+fm.getBackStackEntryCount());
}
Use include("class.classname.php");
And class should use <?php //code ?> not <? //code ?>
The negative margin
would help a lot!
The html DOM looks like below:
<div class="main">
<div class="main_body">Main content</div>
</div>
<div class="left">Left Images or something else</div>
And the CSS:
.main {
float:left;
width:100%;
}
.main_body{
margin-left:210px;
height:200px;
}
.left{
float:left;
width:200px;
height:200px;
margin-left:-100%;
}
The main_body
will responsive it's with, may it helps you!
Instead of gdb
, run gdbtui
. Or run gdb
with the -tui
switch. Or press C-x C-a after entering gdb
. Now you're in GDB's TUI mode.
Enter layout asm
to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish
etc. are abbreviated to a single key, allowing you to walk through your program very quickly.
+---------------------------------------------------------------------------+ B+>|0x402670 <main> push %r15 | |0x402672 <main+2> mov %edi,%r15d | |0x402675 <main+5> push %r14 | |0x402677 <main+7> push %r13 | |0x402679 <main+9> mov %rsi,%r13 | |0x40267c <main+12> push %r12 | |0x40267e <main+14> push %rbp | |0x40267f <main+15> push %rbx | |0x402680 <main+16> sub $0x438,%rsp | |0x402687 <main+23> mov (%rsi),%rdi | |0x40268a <main+26> movq $0x402a10,0x400(%rsp) | |0x402696 <main+38> movq $0x0,0x408(%rsp) | |0x4026a2 <main+50> movq $0x402510,0x410(%rsp) | +---------------------------------------------------------------------------+ child process 21518 In: main Line: ?? PC: 0x402670 (gdb) file /opt/j64-602/bin/jconsole Reading symbols from /opt/j64-602/bin/jconsole...done. (no debugging symbols found)...done. (gdb) layout asm (gdb) start (gdb)
If your command is available in cmd.exe (something like python ./script.py
, but not PowerShell command like ii .
(this means to open the current directory by Windows Explorer)), you can run cmd.exe within PowerShell. The syntax is like this:
cmd /c "command1 && command2"
Here, &&
is provided by cmd syntax described in this question.
Example: Inside myWindow() on line 3 is the code you need to set the window in the center of the screen.
JFrame window;
public myWindow() {
window = new JFrame();
window.setSize(1200,800);
window.setLocationRelativeTo(null); // this line set the window in the center of thr screen
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.BLACK);
window.setLayout(null); // disable the default layout to use custom one.
window.setVisible(true); // to show the window on the screen.
}
Use like this.
List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");
String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
If you want to select the same item in a listbox
using a listview
, you can use:
Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged
For aa As Integer = 0 To ListView1.SelectedItems.Count - 1
ListBox1.SelectedIndex = ListView1.SelectedIndices(aa)
Next
End Sub
Documentation says:
DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. [...] Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. [...] The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s).
So you'll have to add the address_id
to the order by.
Alternatively, if you're looking for the full row that contains the most recent purchased product for each address_id
and that result sorted by purchased_at
then you're trying to solve a greatest N per group problem which can be solved by the following approaches:
The general solution that should work in most DBMSs:
SELECT t1.* FROM purchases t1
JOIN (
SELECT address_id, max(purchased_at) max_purchased_at
FROM purchases
WHERE product_id = 1
GROUP BY address_id
) t2
ON t1.address_id = t2.address_id AND t1.purchased_at = t2.max_purchased_at
ORDER BY t1.purchased_at DESC
A more PostgreSQL-oriented solution based on @hkf's answer:
SELECT * FROM (
SELECT DISTINCT ON (address_id) *
FROM purchases
WHERE product_id = 1
ORDER BY address_id, purchased_at DESC
) t
ORDER BY purchased_at DESC
Problem clarified, extended and solved here: Selecting rows ordered by some column and distinct on another
window.navigate
is NOT supported in some browsers, so that one should be avoided. Any of the other methods using the location property are the most reliable and consistent approach
The problem might be missing the class file in your build folder. One solution is clean the project and rebuild it.
There are three options:
Using jQuery (download from jQuery website) - jquery.com
var lines = $("#ptest").val().split("\n");
return lines.length;
Using Regex
var lines = str.split(/\r\n|\r|\n/);
return lines.length;
Or, a recreation of a for each loop
var length = 0;
for(var i = 0; i < str.length; ++i){
if(str[i] == '\n') {
length++;
}
}
return length;
even there is no right or wrong answer for this question , but I personally prefer 960px width . since all modern monitors support at least 1024 × 768 pixel resolution. 960 is divisible by 2, 3, 4, 5, 6, 8, 10, 12, 15, 16, 20, 24, 30, 32, 40, 48, 60, 64, 80, 96, 120, 160, 192, 240, 320 and 480. This makes it a highly flexible base number to work with.
see this article that shows most popular screens resolutions 2013-2014 in US and UK : http://www.hobo-web.co.uk/best-screen-size/
So, let me give you sample code:
<div class="news">
Blah, blah, blah. I'm hidden.
</div>
<a class="trigger">Hide/Show News</a>
The link will be the trigger to show the div when clicked. So your Javascript will be:
$('.trigger').click(function() {
$('.news').toggle();
});
You're almost always better off letting jQuery handle the styling for hiding and showing elements.
Edit: I see people above are recommending using .show
and .hide
for this. .toggle
allows you to do both with just one effect. So that's cool.
Here's what I use:
function strhex($string) {
$hexstr = unpack('H*', $string);
return array_shift($hexstr);
}
private void _MenuExit_Click(object sender, RoutedEventArgs e)
{
System.Windows.Application.Current.MainWindow.Close();
}
//Override the onClose method in the Application Main window
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult result = MessageBox.Show("Do you really want to close", "",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.Cancel)
{
e.Cancel = true;
}
base.OnClosing(e);
}
The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
var id=5;
$.ajax({
type: "get",
url: "url of server side script",
data:{id:id},
success: function(res){
console.log(res);
},
error:function(error)
{
console.log(error);
}
});
At server side receive it using $_GET variable.
$_GET['id'];
you can try this without any java script you can do that just by using CSS
img:active,
img:focus,
img:hover{
border: 10px solid red !important
}
of if your case is to add any other css class by clicking you can use query selector like
<img id="image1" ng-click="changeClass(id)" >
<img id="image2" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >
in controller first search for any image with red border and remove it then by passing the image id add the border class to that image
$scope.changeClass = function(id){
angular.element(document.querySelector('.some-class').removeClass('.some-class');
angular.element(document.querySelector(id)).addClass('.some-class');
}
Which statement is preferable? Depends on what you are doing.
Are there other performance implications? If the table is a permanent table, you can create indexes at the time of table creation which has implications for performance both negatively and positiviely. Select into does not recreate indexes that exist on current tables and thus subsequent use of the table may be slower than it needs to be.
What is a good use case for SELECT...INTO over INSERT INTO ...? Select into is used if you may not know the table structure in advance. It is faster to write than create table and an insert statement, so it is used to speed up develoment at times. It is often faster to use when you are creating a quick temp table to test things or a backup table of a specific query (maybe records you are going to delete). It should be rare to see it used in production code that will run multiple times (except for temp tables) because it will fail if the table was already in existence.
It is sometimes used inappropriately by people who don't know what they are doing. And they can cause havoc in the db as a result. I strongly feel it is inappropriate to use SELECT INTO for anything other than a throwaway table (a temporary backup, a temp table that will go away at the end of the stored proc ,etc.). Permanent tables need real thought as to their design and SELECT INTO makes it easy to avoid thinking about anything even as basic as what columns and what datatypes.
In general, I prefer the use of the create table and insert statement - you have more controls and it is better for repeatable processes. Further, if the table is a permanent table, it should be created from a separate create table script (one that is in source control) as creating permanent objects should not, in general, in code are inserts/deletes/updates or selects from a table. Object changes should be handled separately from data changes because objects have implications beyond the needs of a specific insert/update/select/delete. You need to consider the best data types, think about FK constraints, PKs and other constraints, consider auditing requirements, think about indexing, etc.
select CAST(COUNT(*) AS BIT) FROM [User] WHERE (UserID = 20070022)
If count(*) = 0 returns false. If count(*) > 0 returns true.
If you already have the databinding in place John Myczek answer is complete. If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in line with most guidelines, like MVVM)
Then you just bind to Users collections and columns are autogenerated as you speficy them. Strings passed to property descriptors are names for column headers. At runtime you can add more PropertyDescriptors to 'Users' add another column to the grid.
This is how I was able to group by with Linq. Hope it helps.
var query = collection.GroupBy(x => x.title).Select(y => y.FirstOrDefault());
Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.
This is actually really easy:
by setting Empty string you can clear your edittext
editext.setText("");
Strings concatenate in Swift language.
let string1 = "one"
let string2 = "two"
var concate = " (string1) (string2)"
playgroud output is "one two"
Build Solution - Build solution will build your application with building the number of projects which are having any file change. And it does not clear any existing binary files and just replacing updated assemblies in bin or obj folder.
Rebuild Solution - Rebuild solution will build your entire application with building all the projects are available in your solution with cleaning them. Before building it clears all the binary files from bin and obj folder.
Clean Solution - Clean solution is just clears all the binary files from bin and obj folder.
It doesn't remove the folders, but it does remove the build by-products. Is there any reason you want the actual build folders removed?
Data content is so variable, I think the best form is to define it as "ObjectNode" and next create his own class to parse:
Finally:
private ObjectNode data;
As of C++11, you have two major additional options. First, you can use insert()
with list initialization syntax:
function.insert({0, 42});
This is functionally equivalent to
function.insert(std::map<int, int>::value_type(0, 42));
but much more concise and readable. As other answers have noted, this has several advantages over the other forms:
operator[]
approach requires the mapped type to be assignable, which isn't always the case.operator[]
approach can overwrite existing elements, and gives you no way to tell whether this has happened.insert
that you list involve an implicit type conversion, which may slow your code down.The major drawback is that this form used to require the key and value to be copyable, so it wouldn't work with e.g. a map with unique_ptr
values. That has been fixed in the standard, but the fix may not have reached your standard library implementation yet.
Second, you can use the emplace()
method:
function.emplace(0, 42);
This is more concise than any of the forms of insert()
, works fine with move-only types like unique_ptr
, and theoretically may be slightly more efficient (although a decent compiler should optimize away the difference). The only major drawback is that it may surprise your readers a little, since emplace
methods aren't usually used that way.
Try this: Directory.Exists(TheFolderName)
and Directory.CreateDirectory(TheFolderName)
(You may need: Imports System.IO
)
I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>
I encountered the same issue with https and solved it by checking the HTTPS Decryption
I'm thinking unload is called all but at hard exist in 4.7. But, if you are playing around with older versions of .Net, try doing this in your loading method:
e.Handled = true;
I don't think older versions will unload until loading is handled. Just posting because I see others still asking this question, and haven't seen this proposed as a solution. I only touch .Net a few times a year, and ran into this a few years back. But, I wonder if it's as simple as unload not being called until loading has finished. Seems like it works for me, but again in newer .Net it seems to always call unload even if loading isn't marked as handled.
This is a nice way to do it with material / angular file upload. You could do the same with a bootstrap button.
Note I used <a>
instead of <button>
this allows the click events to bubble up.
<label>
<input type="file" (change)="setFile($event)" style="display:none" />
<a mat-raised-button color="primary">
<mat-icon>file_upload</mat-icon>
Upload Document
</a>
</label>
GitLab by default marks master
branch as protected
(See part Protecting your code
in https://about.gitlab.com/2014/11/26/keeping-your-code-protected/ why). If so in your case, then this can help:
Open your project > Settings > Repository and go to "Protected branches", find "master" branch into the list and click "Unprotect" and try again.
via https://gitlab.com/gitlab-com/support-forum/issues/40
For version 8.11 and above how-to here: https://docs.gitlab.com/ee/user/project/protected_branches.html#restricting-push-and-merge-access-to-certain-users
I know this is old, but just thought I would add my solution just in case someone finds it useful.
I wanted to compare the local naive datetime with an aware datetime from a timeserver. I basically created a new naive datetime object using the aware datetime object. It's a bit of a hack and doesn't look very pretty but gets the job done.
import ntplib
import datetime
from datetime import timezone
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)
try:
ntpt = ntplib.NTPClient()
response = ntpt.request('pool.ntp.org')
date = utc_to_local(datetime.datetime.utcfromtimestamp(response.tx_time))
sysdate = datetime.datetime.now()
...here comes the fudge...
temp_date = datetime.datetime(int(str(date)[:4]),int(str(date)[5:7]),int(str(date)[8:10]),int(str(date)[11:13]),int(str(date)[14:16]),int(str(date)[17:19]))
dt_delta = temp_date-sysdate
except Exception:
print('Something went wrong :-(')
You can resolve it by using org.springframework.web.servlet.mvc.support.RedirectAttributes.
Here is my controller sample.
@RequestMapping(method = RequestMethod.POST)
public String eligibilityPost(
@ModelAttribute("form") @Valid EligibiltyForm form,
Model model,
RedirectAttributes redirectAttributes) {
if(eligibilityService.validateEligibility(form)){
redirectAttributes.addFlashAttribute("form", form);
return "redirect:<redirect to your page>";
}
return "eligibility";
}
read more on my blog at http://mayurshah.in/596/how-do-i-redirect-to-page-keeping-model-value
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
Try this code with different inputs of String
:
String a = "10";
String a = "10ssda";
String a = null;
String a = "12102";
if(null != a) {
try {
int x = Integer.ParseInt(a.trim());
Integer y = Integer.valueOf(a.trim());
// It will throw a NumberFormatException in case of invalid string like ("10ssda" or "123 212") so, put this code into try catch
} catch(NumberFormatException ex) {
// ex.getMessage();
}
}
It is very dangerous to create an access_key_id in "My Account ==> Security Credentials". Because the key has all authority. Please create "IAM" user and attach only some policies you need.
I realize this is an old post but as I just ran into the same issue and had trouble finding the answer I thought I'd add a bit.
So @hammar's answer is correct. Using push.default simple
is, in a way, like configuring tracking on your branches so you don't need to specify remotes and branches when pushing and pulling. The matching
option will push all branches to their corresponding counterparts on the default remote (which is the first one that was set up unless you've configured your repo otherwise).
One thing I hope others find useful in the future is that I was running Git 1.8 on OS X Mountain Lion and never saw this error. Upgrading to Mavericks is what suddenly made it show up (running git --version
will show git version 1.8.3.4 (Apple Git-47)
which I'd never seen until the update to the OS.
You could try something like this (copied from the jQuery Ajax examples)
var request = $.ajax({
url: "script.php",
type: "POST",
data: {id : menuId},
dataType: "html"
});
request.done(function(msg) {
console.log( msg );
});
request.fail(function(jqXHR, textStatus) {
console.log( "Request failed: " + textStatus );
});
The problem with your original code is that the error argument you pass into your on function isn't actually coming from anywhere. JQuery on doesn't return a second argument, and even if it did, it would relate to the click event not the Ajax call.
Viper is a golang configuration management system that works with JSON, YAML, and TOML. It looks pretty interesting.
EF 4.1 to EF 6
There is a strongly typed .Include
which allows the required depth of eager loading to be specified by providing Select expressions to the appropriate depth:
using System.Data.Entity; // NB!
var company = context.Companies
.Include(co => co.Employees.Select(emp => emp.Employee_Car))
.Include(co => co.Employees.Select(emp => emp.Employee_Country))
.FirstOrDefault(co => co.companyID == companyID);
The Sql generated is by no means intuitive, but seems performant enough. I've put a small example on GitHub here
EF Core
EF Core has a new extension method, .ThenInclude()
, although the syntax is slightly different:
var company = context.Companies
.Include(co => co.Employees)
.ThenInclude(emp => emp.Employee_Car)
.Include(co => co.Employees)
.ThenInclude(emp => emp.Employee_Country)
With some notes
Employees.Employee_Car
and Employees.Employee_Country
), if you need to include 2 or more child properties of an intermediate child collection, you'll need to repeat the .Include
navigation for the collection for each child of the collection..ThenInclude
to preserve your sanity.You can use:
var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);
For example, since there are 30 days in April, the following code will output May 1:
var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000
var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000
See fiddle.
A very simple written explanation can be found here
http://binstock.blogspot.in/2008/01/excellent-explanation-of-dependency.html
It says -
"Any nontrivial application is made up of two or more classes that collaborate with each other to perform some business logic. Traditionally, each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). When applying DI, the objects are given their dependencies at creation time by some external entity that coordinates each object in the system. In other words, dependencies are injected into objects."
To make the execution after the boolean has changed and avoid the usage of timeout you can do:
import { ChangeDetectorRef } from '@angular/core';
constructor(private cd: ChangeDetectorRef) {}
showSearch(){
this.show = !this.show;
this.cd.detectChanges();
this.searchElement.nativeElement.focus();
}
I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.
public abstract class ExternalScript extends Script {
private String source;
public void setSource(String file) {
source = file;
}
public String getSource() {
return source;
}
}
Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:
Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.
As cardern has said list will do the job.
Here is how you can use a named range.
Select your range and enter a new name:
Select your cell that you want a drop down to be in and goto data tab -> data validation.
Select 'List' from the 'Allow' Drop down menu.
Enter your named range like this:
Now you have a drop down linked to your range. If you insert new rows in your range everything will update automatically.
Is this value intended? if (scroll <= 500) { ...
This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"
SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'
Then parse this value with Reg Exp (it's easy) which could looks similar to this: [(.*?)]
Alternatively you can use:
PRAGMA table_info(table_name)
Locale locale = new Locale(langCode);
Locale.setDefault(locale);
Configuration configuration = context.getResources().getConfiguration();
configuration.locale = locale;
preferences.setLocalePref(langCode);
context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
Here, langCode is the required language code. You can save the language code as string in sharedPreferences. and you can call this code super.onCreate(savedInstanceState)
in onCreate
.
You just subindex it with [:5]
indicating that you want (up to) the first 5 elements.
>>> [1,2,3,4,5,6,7,8][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
>>> x = [6,7,8,9,10,11,12]
>>> x[:5]
[6, 7, 8, 9, 10]
Also, putting the colon on the right of the number means count from the nth element onwards -- don't forget that lists are 0-based!
>>> x[5:]
[11, 12]
You can't use Template expression operators(pipe, save navigator) within template statement:
(ngModelChange)="Template statements"
(ngModelChange)="item.value | useMyPipeToFormatThatValue=$event"
https://angular.io/guide/template-syntax#template-statements
Like template expressions, template statements use a language that looks like JavaScript. The template statement parser differs from the template expression parser and specifically supports both basic assignment (=) and chaining expressions (with ; or ,).
However, certain JavaScript syntax is not allowed:
- new
- increment and decrement operators, ++ and --
- operator assignment, such as += and -=
- the bitwise operators | and &
- the template expression operators
So you should write it as follows:
<input [ngModel]="item.value | useMyPipeToFormatThatValue"
(ngModelChange)="item.value=$event" name="inputField" type="text" />
Okay I modifed @AndroidMechanics Code, because on devices were facebook is disabled the app crashes!
here is the modifed getFacebookUrl:
public String getFacebookPageURL(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
boolean activated = packageManager.getApplicationInfo("com.facebook.katana", 0).enabled;
if(activated){
if ((versionCode >= 3002850)) {
return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
} else {
return "fb://page/" + FACEBOOK_PAGE_ID;
}
}else{
return FACEBOOK_URL;
}
} catch (PackageManager.NameNotFoundException e) {
return FACEBOOK_URL;
}
}
The only added thing is to look if the app is disabled or not if it is disabled the app will call the webbrowser!
For xCode 10, first you need to add the image in your assetsCatalogue and then type this:
let imageView = UIImageView(image: #imageLiteral(resourceName: "type the name of your image here..."))
For beginners, let imageView
is the name of the UIImageView
object we are about to create.
An example for embedding an image into a viewControler
file would look like this:
import UIKit
class TutorialViewCotroller: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView(image: #imageLiteral(resourceName: "intoImage"))
view.addSubview(imageView)
}
}
Please notice that I did not use any extension for the image file name, as in my case it is a group of images.
Everything seems to be perfect in your code except the fact that handleClick() isn't working because this function lacks a parameter in its function call invocation(but the function definition within has an argument which makes a function mismatch to occur).
The following is a sample working code for calculating all semester's total marks and corresponding grade. It demonstrates the use of a JavaScript function(call) within a html file and also solves the problem you are facing.
<!DOCTYPE html>
<html>
<head>
<title> Semester Results </title>
</head>
<body>
<h1> Semester Marks </h1> <br>
<script type = "text/javascript">
function checkMarks(total)
{
document.write("<h1> Final Result !!! </h1><br>");
document.write("Total Marks = " + total + "<br><br>");
var avg = total / 6.0;
document.write("CGPA = " + (avg / 10.0).toFixed(2) + "<br><br>");
if(avg >= 90)
document.write("Grade = A");
else if(avg >= 80)
document.write("Grade = B");
else if(avg >= 70)
document.write("Grade = C");
else if(avg >= 60)
document.write("Grade = D");
else if(avg >= 50)
document.write("Grade = Pass");
else
document.write("Grade = Fail");
}
</script>
<form name = "myform" action = "javascript:checkMarks(Number(s1.value) + Number(s2.value) + Number(s3.value) + Number(s4.value) + Number(s5.value) + Number(s6.value))"/>
Semester 1: <input type = "text" id = "s1"/> <br><br>
Semester 2: <input type = "text" id = "s2"/> <br><br>
Semester 3: <input type = "text" id = "s3"/> <br><br>
Semester 4: <input type = "text" id = "s4"/> <br><br>
Semester 5: <input type = "text" id = "s5"/> <br><br>
Semester 6: <input type = "text" id = "s6"/> <br><br><br>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>
More recent versions have a different syntax:
var table = $('#example').DataTable();
// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
table.search(this.value).draw();
});
Note that this example uses the variable table
assigned when datatables is first initialised. If you don't have this variable available, simply use:
var table = $('#example').dataTable().api();
// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
table.search(this.value).draw();
});
Since: DataTables 1.10
Okay, but you all know that the * is a wildcard and allows cross site scripting from every domain?
You would like to send multiple Access-Control-Allow-Origin
headers for every site that's allowed to - but unfortunately its officially not supported to send multiple Access-Control-Allow-Origin
headers, or to put in multiple origins.
You can solve this by checking the origin, and sending back that one in the header, if it is allowed:
$origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = [
'http://mysite1.com',
'https://www.mysite2.com',
'http://www.mysite2.com',
];
if (in_array($origin, $allowed_domains)) {
header('Access-Control-Allow-Origin: ' . $origin);
}
Thats much safer. You might want to edit the matching and change it to a manual function with some regex, or something like that. At least this will only send back 1 header, and you will be sure its the one that the request came from. Please do note that all HTTP headers can be spoofed, but this header is for the client's protection. Don't protect your own data with those values. If you want to know more, read up a bit on CORS and CSRF.
Why is it safer?
Allowing access from other locations then your own trusted site allows for session highjacking. I'm going to go with a little example - image Facebook allows a wildcard origin - this means that you can make your own website somewhere, and make it fire AJAX calls (or open iframes) to facebook. This means you can grab the logged in info of the facebook of a visitor of your website. Even worse - you can script POST
requests and post data on someone's facebook - just while they are browsing your website.
Be very cautious when using the ACAO
headers!
sys.exit() will do exactly what you want.
import sys
sys.exit("Error message")
I also faced the same issue , and none of these worked. In my case this was fixed by adding these lines in config file.
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="100000" />
</appSettings>
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="false" enableCaching="true"/>
</scripting>
</system.web.extensions>
Try this ..
txtview.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.image, 0, 0, 0);
Also see this.. http://developer.android.com/reference/android/widget/TextView.html
Try this in xml file
<TextView
android:id="@+id/txtStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:drawableLeft="@drawable/image"
android:drawablePadding="5dp"
android:maxLines="1"
android:text="@string/name"/>
$( '#iframe' ).attr( 'src', function ( i, val ) { return val; });
I took @Dmitriusan's answer and made it into an alias:
alias docker-run-prev-container='prev_container_id="$(docker ps -aq | head -n1)" && docker commit "$prev_container_id" "prev_container/$prev_container_id" && docker run -it --entrypoint=bash "prev_container/$prev_container_id"'
Add this into your ~/.bashrc
aliases file, and you'll have a nifty new docker-run-prev-container
alias which'll drop you into a shell in the previous container.
Helpful for debugging failed docker build
s.
Try Microsoft's NEWT, it worked perfect for me. It supplies customized latency, packet drop techniques and more :)
http://blog.mrpol.nl/2010/01/14/network-emulator-toolkit/
Update 1:
Here is a good video tutorial for NEWT - Network Emulator For Windows Toolkit Tutorial (Credits to Jimmery)
For general command-line automation, Expect is the classic tool. Or try pexpect if you're more comfortable with Python.
Here's a similar question that suggests using Expect: Use expect in bash script to provide password to SSH command
Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...
[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
public MyServiceInstallerProcess()
{
this.Account = ServiceAccount.NetworkService;
}
}
[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
public MyServiceInstaller()
{
this.Description = "Service Description";
this.DisplayName = "Service Name";
this.ServiceName = "ServiceName";
this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
}
}
static void Install(bool undo, string[] args)
{
try
{
Console.WriteLine(undo ? "uninstalling" : "installing");
using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
{
IDictionary state = new Hashtable();
inst.UseNewContext = true;
try
{
if (undo)
{
inst.Uninstall(state);
}
else
{
inst.Install(state);
inst.Commit(state);
}
}
catch
{
try
{
inst.Rollback(state);
}
catch { }
throw;
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
You can use Kodem's Image Resize Service. You can resize any image with just a http call. Can be used casually in the browser or used in your production app.
The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.
Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.
Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.
Enough explanation, the solution (JS, CSS, HTML):
$(window).on("load",function() {_x000D_
$(window).scroll(function() {_x000D_
var windowBottom = $(this).scrollTop() + $(this).innerHeight();_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
_x000D_
/* If the element is completely within bounds of the window, fade it in */_x000D_
if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}_x000D_
} else { //object goes out of view (scrolling up)_x000D_
if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}_x000D_
}_x000D_
});_x000D_
}).scroll(); //invoke scroll-handler on page-load_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
if ($(this).css("opacity")==0) {...}
. This makes sure the object is only faded in when the opacity
is 0
. Same goes for fading out. And this prevents the fade-in and fade-out from working against each other, because now there's ever only one of the two running at one time on an object..animate()
to .fadeTo()
. It's jQuery's specialized function for opacity, a lot shorter to write and probably lighter than animate..position()
to .offset()
. This always calculates relative to the body, whereas position is relative to the parent. For your case I believe offset is the way to go.$(window).height()
to $(window).innerHeight()
. The latter is more reliable in my experience.$(window).scroll();
. Now you can give all desired objects on the page the .fade
class, and objects that should be invisible at page-load, will be faded out immediately.#container
from both HTML and CSS, because (at least for this answer) it isn't necessary. (I thought maybe you needed the height:2000px
because you used .position()
instead of .offset()
, otherwise I don't know. Feel free of course to leave it in your code.)If you want opacity values other than 0
and 1
, use the following code:
$(window).on("load",function() {_x000D_
function fade(pageLoad) {_x000D_
var windowBottom = $(window).scrollTop() + $(window).innerHeight();_x000D_
var min = 0.3;_x000D_
var max = 0.7;_x000D_
var threshold = 0.01;_x000D_
_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
_x000D_
/* If the element is completely within bounds of the window, fade it in */_x000D_
if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
if ($(this).css("opacity")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}_x000D_
} else { //object goes out of view (scrolling up)_x000D_
if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}_x000D_
}_x000D_
});_x000D_
} fade(true); //fade elements on page-load_x000D_
$(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
threshold
and for min/max
at the start of the function. In the rest of the function these variables are referenced. This way, if you ever want to change the values again, you only have to do it in one place.|| pageLoad
to the if-clause. This was necessary to make sure all objects are faded to the correct opacity on page-load. pageLoad
is a boolean that is send along as an argument when fade()
is invoked.function fade() {...}
, in order to be able to send along the pageLoad
boolean when the scroll-handler is invoked.Explanation:
The reason the code in your fiddle didn't work, is because the actual opacity values are always a little off from the value you set it to. So if you set the opacity to 0.3
, the actual value (in this case) is 0.300000011920929
. That's just one of those little bugs you have to learn along the way by trail and error. That's why this if-clause won't work: if ($(this).css("opacity") == 0.3) {...}
.
I added a threshold, to take that difference into account: == 0.3
becomes <= 0.31
.
(I've set the threshold to 0.01
, this can be changed of course, just as long as the actual opacity will fall between the set value and this threshold.)
The operators are now changed from ==
to <=
and >=
.
If you want to fade the elements based on their visible percentage, use the following code:
$(window).on("load",function() {_x000D_
function fade(pageLoad) {_x000D_
var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();_x000D_
var min=0.3, max=0.7, threshold=0.01;_x000D_
_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;_x000D_
_x000D_
/* Fade element in/out based on its visible percentage */_x000D_
if (objectTop < windowTop) {_x000D_
if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}_x000D_
else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
} else if (objectBottom > windowBottom) {_x000D_
if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}_x000D_
else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
} else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}_x000D_
});_x000D_
} fade(true); //fade elements on page-load_x000D_
$(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
Even though a bit old thread, for those who still looking for the differences:
Aside from layout (space) taken in Hidden and not taken in Collapsed, there is another difference.
If we have custom controls inside this 'Collapsed' main control, the next time we set it to Visible, it will "load" all custom controls. It will not pre-load when window is started.
As for 'Hidden', it will load all custom controls + main control which we set as hidden when the "window" is started.
From a relational database theory point of view, there should be absolutely no problem on updating the primary key of a table, provided that there are no duplicates among the primary keys and that you do not try to put a NULL value in any of the primary key columns.
No need to used grep here, Try this:
df . -B MB | tail -1 | awk {'print substr($5, 1, length($5)-1)'}
For some reason, some of the other methods don't work until the field has been focused/blured/changed, or a submit has been attempted... this works for me.
$("#formid").data('validator').element('#element').valid();
Had to dig through the jquery.validate script to find it...
If you have a pristine repo (or HEAD isn't set)[1] you could simply
rm .git/index
Of course, this will require you to re-add the files that you did want to be added.
[1] Note (as explained in the comments) this would usually only happen when the repo is brand-new ("pristine") or if no commits have been made. More technically, whenever there is no checkout or work-tree.
Just making it more clear :)
http://jsbeautifier.org/ is helpful to indent your minified JS code.
Also, with Google Chrome you can use "pretty print". See the example screenshot below showing jquery.min.js
from Stack Overflow nicely indented right from my browser :)
Ben is completely correct in his answer - so keep what he says in mind. What I'm about to tell you isn't a full explanation, but it's a very easy way to remember how e.target
, e.currentTarget
work in relation to mouse events and the display list:
e.target
= The thing under the mouse (as ben says... the thing that triggers the event).
e.currentTarget
= The thing before the dot... (see below)
So if you have 10 buttons inside a clip with an instance name of "btns" and you do:
btns.addEventListener(MouseEvent.MOUSE_OVER, onOver);
// btns = the thing before the dot of an addEventListener call
function onOver(e:MouseEvent):void{
trace(e.target.name, e.currentTarget.name);
}
e.target
will be one of the 10 buttons and e.currentTarget
will always be the "btns" clip.
It's worth noting that if you changed the MouseEvent to a ROLL_OVER or set the property btns.mouseChildren
to false, e.target
and e.currentTarget
will both always be "btns".
Here's a working jsfiddle
Things to note:
In saying that, validation is a solved problem there are frameworks that implement this functionality.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
I'd suggest using one of these rather than reimplementing Validation for every app you write.
For me somehow the Project properties; Android; Project Build Target was not set. I chose a Android version there (e.g. 4.2) and it fixed it.
This is way more simpler with Maven dependency feature:
Hope this will help!
If you can't find it in numpy or scipy, here are a couple of quick functions and a point class:
import math
def rect(r, theta):
"""theta in degrees
returns tuple; (float, float); (x,y)
"""
x = r * math.cos(math.radians(theta))
y = r * math.sin(math.radians(theta))
return x,y
def polar(x, y):
"""returns r, theta(degrees)
"""
r = (x ** 2 + y ** 2) ** .5
theta = math.degrees(math.atan2(y,x))
return r, theta
class Point(object):
def __init__(self, x=None, y=None, r=None, theta=None):
"""x and y or r and theta(degrees)
"""
if x and y:
self.c_polar(x, y)
elif r and theta:
self.c_rect(r, theta)
else:
raise ValueError('Must specify x and y or r and theta')
def c_polar(self, x, y, f = polar):
self._x = x
self._y = y
self._r, self._theta = f(self._x, self._y)
self._theta_radians = math.radians(self._theta)
def c_rect(self, r, theta, f = rect):
"""theta in degrees
"""
self._r = r
self._theta = theta
self._theta_radians = math.radians(theta)
self._x, self._y = f(self._r, self._theta)
def setx(self, x):
self.c_polar(x, self._y)
def getx(self):
return self._x
x = property(fget = getx, fset = setx)
def sety(self, y):
self.c_polar(self._x, y)
def gety(self):
return self._y
y = property(fget = gety, fset = sety)
def setxy(self, x, y):
self.c_polar(x, y)
def getxy(self):
return self._x, self._y
xy = property(fget = getxy, fset = setxy)
def setr(self, r):
self.c_rect(r, self._theta)
def getr(self):
return self._r
r = property(fget = getr, fset = setr)
def settheta(self, theta):
"""theta in degrees
"""
self.c_rect(self._r, theta)
def gettheta(self):
return self._theta
theta = property(fget = gettheta, fset = settheta)
def set_r_theta(self, r, theta):
"""theta in degrees
"""
self.c_rect(r, theta)
def get_r_theta(self):
return self._r, self._theta
r_theta = property(fget = get_r_theta, fset = set_r_theta)
def __str__(self):
return '({},{})'.format(self._x, self._y)
I guess there are plenty of ways to reach this error!
On my side, I had a loop in my package.json
. Project A had a dependency on project B, that had a dependency on project A.
I had issue that starting the service mongodb failed, without logs. what i did to fix the error is to give write access to the directory /var/log/mongodb for user mongodb
Whatsapp store all messages in an encrypted database (pyCrypt) which is very easy to decipher using Python.
You can fetch this database easily on Android, iPhone, Blackberry and dump it into html file. Here are complete instructions: Read, Extract WhatsApp Messages backup on Android, iPhone, Blackberry
Disclaimer: I researched and wrote this extensive guide.
In Crockford's JavaScript The Good Parts, there is a function to check if the given argument is an array:
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
He explains:
First, we ask if the value is truthy. We do this to reject null and other falsy values. Second, we ask if the typeof value is 'object'. This will be true for objects, arrays, and (weirdly) null. Third, we ask if the value has a length property that is a number. This will always be true for arrays, but usually not for objects. Fourth, we ask if the value contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?). That will be false for all arrays. This is the most reliable test for arrayness that I have found. It is unfortunate that it is so complicated.
I think a better approach will be to set app:tabMode="auto"
and app:tabGravity="fill"
because setting tabMode to fixed can make headings congested and cause headings to occupy multiple lines on the other side setting it to scrollable could make them leave spaces at the end in some screen sizes. manually setting tabMode would give a problem when dealing with multiple screen sizes
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
app:tabGravity="fill"
android:textAlignment="center"
app:tabMode="auto"
/>
With JDK/11, an alternate way of converting a Collection<Foo>
to an Foo[]
could be to make use of Collection.toArray(IntFunction<T[]> generator)
as:
Foo[] foos = fooCollection.toArray(new Foo[0]); // before JDK 11
Foo[] updatedFoos = fooCollection.toArray(Foo[]::new); // after JDK 11
As explained by @Stuart on the mailing list(emphasis mine), the performance of this should essentially be the same as that of the existing Collection.toArray(new T[0])
--
The upshot is that implementations that use
Arrays.copyOf(
) are the fastest, probably because it's an intrinsic.It can avoid zero-filling the freshly allocated array because it knows the entire array contents will be overwritten. This is true regardless of what the public API looks like.
The implementation of the API within the JDK reads:
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(0));
}
The default implementation calls
generator.apply(0)
to get a zero-length array and then simply callstoArray(T[])
. This goes through theArrays.copyOf()
fast path, so it's essentially the same speed astoArray(new T[0])
.
Note:- Just that the API use shall be guided along with a backward incompatibility when used for code with null
values e.g. toArray(null)
since these calls would now be ambiguous because of existing toArray(T[] a)
and would fail to compile.
Lock files are generally not used on Windows (and rarely on Unix). Typically when a Windows program wants to see if another instance of itself is already running, it will call FindWindow
with a known title or class name.
def iTunesRunning():
import win32ui
# may need FindWindow("iTunes", None) or FindWindow(None, "iTunes")
# or something similar
if FindWindow("iTunes", "iTunes"):
print "Found an iTunes window"
return True
I've had this problem many times before with my Galaxy Nexus. Despite having the Android SDK's USB drivers installed, it did not seem to suffice.
I've always solved this by installing a program called PdaNet. While I don't know exactly what it is used for and where it gets its drivers - it comes with the drivers that has always fixed the problem for me. You can uninstall the program itself once it has finished.
One of frequent mistakes might be typo in another file name.
You example is quite straightforward but what may sometimes confuse are
messages of make
itself. Lets consider an example.
My folder contents is:
$ ls -1
another_file
index.md
makefile
Whereas my makefile
looks like
all: index.html
%.html: %.md wrong_path_to_another_file
@echo $@ $<
Although I do have index.md
where it should be and there is no mistake in the name of it, the message from make
will be
make: *** No rule to make target `index.html', needed by `all'. Stop.
To be honest the message is confusing. It just says, that there is no rule. In fact, it means that the rule is wrong, but due to wildcard (pattern) rules make
cannot determine what exactly caused the issue.
Lets alter makefile
a little, which is to say replace patterns with explicit rules:
index.html: index.md wrong_path_to_another_file
And now the message we get will be:
make: *** No rule to make target `wrong_path_to_another_file', needed by `index.html'. Stop.
Miracle! The following might be concluded:
Messages of make
depends on rules and does not always point to the root of problems
There might be other problems in your makefile
different from specified by this message
Now we've come up with the idea of checking other dependencies in a rule as well:
all: index.html
%.html: %.md another_file
@echo $@ $<
Only this will provide us with the desired result:
$ make
index.html index.md
It depends upon what operations you will be doing more on the List.
ArrayList
is faster to access an indexed value. It is much worse when inserting or deleting objects.
To find out more, read any article that talks about the difference between arrays and linked lists.
You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).
Your code could be like:
const myArray = [
{
"id":25,
"name":"Anakin Skywalker",
"createdAt":"2017-04-12T12:48:55.000Z",
"updatedAt":"2017-04-12T12:48:55.000Z"
},
{
"id":1,
"name":"Luke Skywalker",
"createdAt":"2017-04-12T11:25:03.000Z",
"updatedAt":"2017-04-12T11:25:03.000Z"
}
]
const myOrderedArray = _.sortBy(myArray, o => o.name)
I don't think that you should be using an array to maintain tokens. Neither you need a guid as a token.
You can easily use context.SerializeTicket().
See my below code.
public class RefreshTokenProvider : IAuthenticationTokenProvider
{
public async Task CreateAsync(AuthenticationTokenCreateContext context)
{
Create(context);
}
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
Receive(context);
}
public void Create(AuthenticationTokenCreateContext context)
{
object inputs;
context.OwinContext.Environment.TryGetValue("Microsoft.Owin.Form#collection", out inputs);
var grantType = ((FormCollection)inputs)?.GetValues("grant_type");
var grant = grantType.FirstOrDefault();
if (grant == null || grant.Equals("refresh_token")) return;
context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);
context.SetToken(context.SerializeTicket());
}
public void Receive(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
if (context.Ticket == null)
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
context.Response.ReasonPhrase = "invalid token";
return;
}
if (context.Ticket.Properties.ExpiresUtc <= DateTime.UtcNow)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
context.Response.ReasonPhrase = "unauthorized";
return;
}
context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);
context.SetTicket(context.Ticket);
}
}
I guess you should start with the basics from w3
https://www.w3schools.com/cssref/css3_pr_text-overflow.asp
div {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Simple one
To remove it:
.form-control, .btn {
box-shadow: none !important;
outline: none !important;
}
To change it
.form-control, .btn {
box-shadow: new-value !important;
outline: new-value !important;
}
This should do the trick:
$('#thisElement').find('.classToSelect')
I was facing the same problem! I've added the code below in wp-config.php file (in any line) and it's working now!
define('FS_METHOD', 'direct');
You can use dd to extract arbitrary chunks of bytes.
For example,
dd skip=1234 count=5 bs=1
would copy bytes 1235 to 1239 from its input to its output, and discard the rest.
To just get the first five bytes from standard input, do:
dd count=5 bs=1
Note that, if you want to specify the input file name, dd has old-fashioned argument parsing, so you would do:
dd count=5 bs=1 if=filename
Note also that dd verbosely announces what it did, so to toss that away, do:
dd count=5 bs=1 2>&-
or
dd count=5 bs=1 2>/dev/null
Another way is using set data type.
Some characteristic of Sets: Sets are unordered, can include mixed data types, elements in a set cannot be repeated, are mutable.
Solving your question:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
sorted(set(df.A))
The answer in List type:
[1, 2, 3, 6, 8]
Say you want to fill with number 13.
int[] myarr = Enumerable.Range(0, 10).Select(n => 13).ToArray();
or
List<int> myarr = Enumerable.Range(0,10).Select(n => 13).ToList();
if you prefer a list.
A solution without your indentation:
for path, dirs, files in os.walk(given_path):
print path
for f in files:
print f
os.walk already does the top-down, depth-first walk you are looking for.
Ignoring the dirs list prevents the overlapping you mention.
I don't know for how long this post has been here. But I stumbled upon similar problem now. Hence posting the solution so that it might help others.
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use GD::Graph::pie;
use MIME::Base64;
my @data = (['A','O','S','I'],[3,16,12,47]);
my $mygraph = GD::Graph::pie->new(200, 200);
my $myimage = $mygraph->plot(\@data)->png;
print <<end_html;
<html><head><title>Current Stats</title></head>
<body>
<p align="center">
<img src="data:image/png;base64,
end_html
print encode_base64($myimage);
print <<end_html;
" style="width: 888px; height: 598px; border-width: 2px; border-style: solid;" /></p>
</body>
</html>
end_html
If Your issue is when you touch/tap on android and whole div covered by blue transparent color! Then you need to just change the
CURSOR : POINTER; to CURSOR : DEFAULT;
use mediaQuery to hide in mobile phone/Tablet.
This works for me.
On Ubuntu with Apache2 and the deflate module already installed (which it is by default), you can enable deflate gzip compression in two easy steps:
a2enmod deflate
/etc/init.d/apache2 force-reload
And you're away! I found pages I served over my adsl connection loaded much faster.
Edit: As per @GertvandenBerg's comment, this enables gzip compression, not deflate.
Is there any 64 bit Visual Studio at all?
Yes literally there is one called "Visual Studio" and is 64bit, but well,, on Mac not on Windows
Why not?
Decision making is electro-chemical reaction made in our brain and that have an activation point (Nerdest answer I can come up with, but follow). Same situation happened in history: Windows 64!...
So in order to answer this fully I want you to remember old days. Imagine reasons for "why not we see 64bit Windows" are there at the time. I think at the time for Windows64 they had exact same reasons others have enlisted here about "reasons why not 64bit VS on windows" were on "reasons why not 64bit Windows" too. Then why they did start development for Windows 64bit? Simple! If they didn't succeed in making 64bit Windows I bet M$ would have been a history nowadays. If same reasons forcing M$ making 64bit Windows starts to appear on need for 64Bit VS then I bet we will see 64bit VS, even though very same reasons everyone else here enlisted will stay same! In time the limitations of 32bit may hit VS as well, so most likely something like below start to happen:
I put my bets on Visual Studio Code taking the place in time; I guess bifurcation point for it will be some CPU manufacturer X starts to compete x86_64 architecture taking its place on mainstream market for laptop and/or workstation,
Another variant:
List<MyType> items = new List<MyType>();
items.AddRange(myDico.values);
open Excel file
System.Diagnostics.Process.Start(@"c:\document.xls");
One more solution (in Java, because you didn't tell us your language - but it works the same way in all languages with Keys
class):
String selectAll = Keys.chord(Keys.CONTROL, "a");
driver.findElement(By.whatever("anything")).sendKeys(selectAll);
You can use this to select the whole text in an <input>
, or on the whole page (just find the html
element and send this to it).
For using Selenium Ruby bindings:
There's no chord()
method in the Keys
class in Ruby bindings. Therefore, as suggested by Hari Reddy, you'll have to use Selenium Advanced user interactions API, see ActionBuilder
:
driver.action.key_down(:control)
.send_keys("a")
.key_up(:control)
.perform
Filter
app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
Usage
<ANY ng-bind-html="value | unsafe"></ANY>
A Date doesn't have any time zone. What you're seeing is only the formatting of the date by the Date.toString()
method, which uses your local timezone, always, to transform the timezone-agnostic date into a String that you can understand.
If you want to display the timezone-agnostic date as a string using the UTC timezone, then use a SimpleDateFormat with the UTC timezone (as you're already doing in your question).
In other terms, the timezone is not a property of the date. It's a property of the format used to transform the date into a string.
I realise this is an old post, but just in case anyone else is looking, you can use Contains
by providing the case insensitive string equality comparer like so:
using System.Linq;
// ...
if (testList.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
Console.WriteLine("Keyword Exists");
}
This has been available since .net 2.0 according to msdn.
Since Entity Framework 5.0 you can use following code in order to solve your issue:
public abstract class YourContext : DbContext
{
public YourContext()
{
(this as IObjectContextAdapter).ObjectContext.ContextOptions.UseCSharpNullComparisonBehavior = true;
}
}
This should solve your problems as Entity Framerwork will use 'C# like' null comparison.
According to https://bugzilla.mozilla.org/show_bug.cgi?id=592284, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.
I encountered this error while executing
SELECT * FROM table;
I traced the error to cursor.py line 195.
if args is not None:
if isinstance(args, dict):
nargs = {}
for key, item in args.items():
if isinstance(key, unicode):
key = key.encode(db.encoding)
nargs[key] = db.literal(item)
args = nargs
else:
args = tuple(map(db.literal, args))
try:
query = query % args
except TypeError as m:
raise ProgrammingError(str(m))
Given that I am entering any extra parameters, I got rid of all of "if args ..." branch. Now it works.
The algorithm (HS256
) used to sign the JWT means that the secret is a symmetric key that is known by both the sender and the receiver. It is negotiated and distributed out of band. Hence, if you're the intended recipient of the token, the sender should have provided you with the secret out of band.
If you're the sender, you can use an arbitrary string of bytes as the secret, it can be generated or purposely chosen. You have to make sure that you provide the secret to the intended recipient out of band.
For the record, the 3 elements in the JWT are not base64-encoded but base64url-encoded, which is a variant of base64 encoding that results in a URL-safe value.
The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:
import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square')
plt.xlabel('x')
plt.ylabel('y')
plt.xticks(xi, x)
plt.title('compare')
plt.legend()
plt.show()
use
if in vim:
:s/{\|}/"/g
will replace { and } on " so {lol} becomes "lol"
To direct to the point , you can easily use xapth .The exact and simple way to do this using the below code . Kindly try and provide feedback .Thank you .
JavascriptExecutor js = (JavascriptExecutor) driver;
//To click an element
WebElement element=driver.findElement(By.xpath(Xpath));
js.executeScript(("arguments[0].click();", element);
//To gettext
String theTextIWant = (String) js.executeScript("return arguments[0].value;",driver.findElement(By.xpath("//input[@id='display-name']")));
Further readings - https://medium.com/@smeesheady/webdriver-javascriptexecutor-interact-with-elements-and-open-and-handle-multiple-tabs-and-get-url-dcfda49bfa0f
Enough to using eval javascript function to convert string to boolean
eval('true')
eval('false')
Use convert
from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)
Running as administrator didn't seem to make a difference when I got this.
iisexpress.exe
processes had been closed<path_to_your_solution>\Solution\.vs\config\applicationhost.config
Change the site name.
<site name="MySite" id="1" serverAutoStart="true">
to :
<site name="MySite2" id="1" serverAutoStart="true">
In my case carate table script is:
CREATE TABLE public."Survey_symptom_binds"
(
id integer NOT NULL DEFAULT nextval('"Survey_symptom_binds_id_seq"'::regclass),
survey_id integer,
"order" smallint,
symptom_id integer,
CONSTRAINT "Survey_symptom_binds_pkey" PRIMARY KEY (id)
)
SO:
SELECT nextval('"Survey_symptom_binds_id_seq"'::regclass),
MAX(id)
FROM public."Survey_symptom_binds";
SELECT nextval('"Survey_symptom_binds_id_seq"'::regclass) less than MAX(id) !!!
Try to fix the proble:
SELECT setval('"Survey_symptom_binds_id_seq"', (SELECT MAX(id) FROM public."Survey_symptom_binds")+1);
Good Luck every one!
I don't know if you can do it on-demand, but you can enable the option "Track Active Item in Solution Explorer" (Tools->Options->Projects and Solutions->General) which will always select the active tab item in the solution explorer.
under etc/apache2/apache2.conf
, you can find one or more blocks that describe the server directories and permissions
As an example, this is the default configuration
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
you can replicate this but change the directory path /var/www/
with the new directory.
Finally, you need to restart the apache server, you can do that from a terminal with the command: sudo service apache2 restart
You could tell javascript to perform the action "onload"... Try with this:
<script type ="text/javascript">
window.onload = function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
If you're using VSCODE, you can get this extension to handle the task for you. It watches your workspace each time you save your work and helps you to automatically ignore the files and folders you specified in your vscode settings.json ignoreit (vscode extension)
I have encountered this issue ONLY on the simulator. It seems to be related to some invalid Entitlements in our application, but the issue doesn't appear when we run on a device.
This error can occur even if the name of the function is valid if some mandatory arguments are missing (i.e you did not provide enough arguments).
I got this in an Rcpp context, where I wrote a C++ function with optionnal arguments, and did not provided those arguments in R. It appeared that optionnal arguments from the C++ were seen as mandatory by R. As a result, R could not find a matching function for the correct name but an incorrect number of arguments.
Rcpp Function : SEXP RcppFunction(arg1, arg2=0) {}
R Calls :
RcppFunction(0)
raises the error
RcppFunction(0, 0)
does not
i Did it, just follow this tutorial. helps a lot
Is a copy from javadb (because is down)
http://informatictips.blogspot.pt/2013/09/using-message-handler-to-alter-soap.html
or
http://www.javadb.com/using-a-message-handler-to-alter-the-soap-header-in-a-web-service-client
In case of detached HEAD, commits work like normal, except no named branch gets updated. To get master branch updated with your committed changes, make a temporary branch where you are (this way the temporary branch will have all the committed changes you have made in the detached HEAD) , then switch to the master branch and merge the temporary branch with the master.
git branch temp
git checkout master
git merge temp
This approach will work on all API level device.
Use Base Activity for attachBaseContext to set the locale language and extend this activity for all activities
open class BaseAppCompactActivity() : AppCompatActivity() {
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(LocaleHelper.onAttach(newBase))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
}
Use Application attachBaseContext and onConfigurationChanged
to set the locale language
public class MyApplication extends Application {
private static MyApplication application;
@Override
public void onCreate() {
super.onCreate();
}
public static MyApplication getApplication() {
return application;
}
/**
* overide to change local sothat language can be chnaged from android device nogaut and above
*/
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.INSTANCE.onAttach(base));
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
setLanguageFromNewConfig(newConfig);
super.onConfigurationChanged(newConfig);
}
/*** also handle chnage language if device language chnaged **/
private void setLanguageFromNewConfig(Configuration newConfig){
Prefs.putSaveLocaleLanguage(this, selectedLocaleLanguage );
LocaleHelper.INSTANCE.onAttach(this);
}
Use Locale Helper for handling language changes, this approach work on all device
object LocaleHelper {
private var defaultLanguage :String = KycUtility.KYC_LANGUAGE.ENGLISH.languageCode
fun onAttach(context: Context, defaultLanguage: String): Context {
return setLocale(context, defaultLanguage)
}
fun setLocale(context: Context, language: String): Context {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
updateResources(context, language)
} else updateResourcesLegacy(context, language)
}
@TargetApi(Build.VERSION_CODES.N)
private fun updateResources(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val configuration = context.getResources().getConfiguration()
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)
return context.createConfigurationContext(configuration)
}
private fun updateResourcesLegacy(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.getResources()
val configuration = resources.getConfiguration()
configuration.locale = locale
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLayoutDirection(locale)
}
resources.updateConfiguration(configuration, resources.getDisplayMetrics())
return context
}
}
Since you already have sent some data,
System.out.println("going to demo.jsp");
you won't be able to send a redirect.
Who says a file name needs an extension?? take a look on a *nix machine sometime...
I agree with your friend, no trailing slash.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}
On my machine:
C:\Program Files\PostgreSQL\8.4\data\postgresql.conf
Either use LINQ:
var value = MyList.First(item => item.name == "foo").value;
(This will just find the first match, of course. There are lots of options around this.)
Or use Find
instead of FindIndex
:
var value = MyList.Find(item => item.name == "foo").value;
I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.
(I'd also suggest following the .NET naming conventions.)
The actual issue should be with the OS architecture, the JDK (32bit or 64 bit) installed and the eclipse type u installed.
Bring them in sync, things would work completely fine.
Just have a check at the Eventlog as mentioned by @Viji Ideally u should encounter error like RADAR_PRE_LEAK_64
XML is not a format for storing images, neither binary data. I think it all depends on how you want to use those images. If you are in a web application and would want to read them from there and display them, I would store the URLs. If you need to send them to another web endpoint, I would serialize them, rather than persisting manually in XML. Please explain what is the scenario.
Use related name to count votes for a specific contest
class Item(models.Model):
name = models.CharField()
class Contest(models.Model);
name = models.CharField()
class Votes(models.Model):
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
contest = models.ForeignKey(Contest, related_name="contest_votes")
comment = models.TextField()
>>> comments = Contest.objects.get(id=contest_id).contest_votes.count()
There is no simple way to do this in a correct AND generic way.
First of all it must be understood that the offset depends on the date in question, the Time Zone AND DST.
GetDate()-GetUTCDate
only gives you the offset today at the server's TZ, which is not relevant.
I have seen only two working solution and I have search a lot.
1) A custom SQL function with a a couple of tables of base data such as Time Zones and DST rules per TZ. Working but not very elegant. I can't post it since I don't own the code.
EDIT: Here is an example of this method https://gist.github.com/drumsta/16b79cee6bc195cd89c8
2) Add a .net assembly to the db, .Net can do this very easily. This is working very well but the downside is that you need to configure several parameters on server level and the config is easily broken e.g. if you restore the database. I use this method but I cant post it since I don't own the code.
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
You might just want to use the new TUN.Logging PowerShell module, this can also send a log mail. Just use the Start-Log and/or Start-MailLog cmdlets to start logging and then just use Write-HostLog, Write-WarningLog, Write-VerboseLog, Write-ErrorLog etc. to write to console and log file/mail. Then call Send-Log and/or Stop-Log at the end and voila, you got your logging. Just install it from the PowerShell Gallery via
Install-Module -Name TUN.Logging
Or just follow the link: https://www.powershellgallery.com/packages/TUN.Logging
Documentation of the module can be found here: https://github.com/echalone/TUN/blob/master/PowerShell/Modules/TUN.Logging/TUN.Logging.md
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html
DATABASE
MongoDB states a nice example:
To select a database to use, in the mongo shell, issue the use <db> statement, as in the following example:
use myDB
use myNewDB
Content from: https://docs.mongodb.com/manual/core/databases-and-collections/#databases
COLLECTIONS
Lowercase names: avoids case sensitivity issues, MongoDB collection names are case sensitive.
Plural: more obvious to label a collection of something as the plural, e.g. "files" rather than "file"
>No word separators: Avoids issues where different people (incorrectly) separate words (username <-> user_name, first_name <->
firstname). This one is up for debate according to a few people
around here but provided the argument is isolated to collection names I don't think it should be ;) If you find yourself improving the
readability of your collection name by adding underscores or
camelCasing your collection name is probably too long or should use
periods as appropriate which is the standard for collection
categorization.Dot notation for higher detail collections: Gives some indication to how collections are related. For example you can be reasonably sure you could delete "users.pagevisits" if you deleted "users", provided the people that designed the schema did a good job.
Content from: http://www.tutespace.com/2016/03/schema-design-and-naming-conventions-in.html
For collections I'm following these suggested patterns until I find official MongoDB documentation.
NDepend was already mentioned by Jesse (if you analyze .NET code) but let's explain exactly how it can help.
Is there a program/script that can scan an executable for DLL dependencies or execute the program in a "clean" DLL-free environment for testing to prevent these oops situations?
In the NDepend Project Properties panel, you can define what application assemblies to analyze (in green) and NDepend will infer Third-Party assemblies used by application ones (in blue). A list of directories where to search application and third-party assemblies is provided.
If a third-party assembly is not found in these directories, it will be in error mode. For example, if I remove the .NET Fx directory C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319
, I can see that .NET Fx third-party assemblies are not resolved:
Disclaimer: I work for NDepend
This may work:
jdialog.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.out.println("jdialog window closed event received");
}
public void windowClosing(WindowEvent e) {
System.out.println("jdialog window closing event received");
}
});
Source: https://alvinalexander.com/java/jdialog-close-closing-event
function normalexport() {
try {
var i;
var j;
var mycell;
var tableID = "tblInnerHTML";
var drop = document.getElementById('<%= ddl_sections.ClientID %>');
var objXL = new ActiveXObject("Excel.Application");
var objWB = objXL.Workbooks.Add();
var objWS = objWB.ActiveSheet;
var str = filterNum(drop.options[drop.selectedIndex].text);
objWB.worksheets("Sheet1").activate; //activate dirst worksheet
var XlSheet = objWB.activeSheet; //activate sheet
XlSheet.Name = str; //rename
for (i = 0; i < document.getElementById("ctl00_ContentPlaceHolder1_1").rows.length - 1; i++) {
for (j = 0; j < document.getElementById("ctl00_ContentPlaceHolder1_1").rows(i).cells.length; j++) {
mycell = document.getElementById("ctl00_ContentPlaceHolder1_1").rows(i).cells(j);
objWS.Cells(i + 1, j + 1).Value = mycell.innerText;
// objWS.Cells(i + 1, j + 1).style.backgroundColor = mycell.style.backgroundColor;
}
}
objWS.Range("A1", "L1").Font.Bold = true;
// objWS.Range("A1", "L1").Font.ColorIndex = 2;
// objWS.Range("A1", "Z1").Interior.ColorIndex = 47;
objWS.Range("A1", "Z1").EntireColumn.AutoFit();
//objWS.Range("C1", "C1").ColumnWidth = 50;
objXL.Visible = true;
} catch (err) {
alert("Error. Scripting for ActiveX might be disabled")
return
}
idTmr = window.setInterval("Cleanup();", 1);
}
function filterNum(str) {
return str.replace(/[ / ]/g, '');
}
I came here looking for a possible explanation before taking a closer look at the lines preceding the linker error. It turned out to have been an additional executable for which the global declaration was missing!
Swift 3.0 Version of Jake's Answer
// Create the alert controller
let alertController = UIAlertController(title: "Alert!", message: "There is no items for the current user", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
The first error message is telling you more about the problem:
verify error:num=20:unable to get local issuer certificate
The issuing certificate authority of the end entity server certificate is
VeriSign Class 3 Secure Server CA - G3
Look closely in your CA file - you will not find this certificate since it is an intermediary CA - what you found was a similar-named G3 Public Primary CA of VeriSign.
But why does the other connection succeed, but this one doesn't? The problem is a misconfiguration of the servers (see for yourself using the -debug
option). The "good" server sends the entire certificate chain during the handshake, therefore providing you with the necessary intermediate certificates.
But the server that is failing sends you only the end entity certificate, and OpenSSL is not capable of downloading the missing intermediate certificate "on the fly" (which would be possible by interpreting the Authority Information Access extension). Therefore your attempt fails using s_client
but it would succeed nevertheless if you browse to the same URL using e.g. FireFox (which does support the "certificate discovery" feature).
Your options to solve the problem are either fixing this on the server side by making the server send the entire chain, too, or by passing the missing intermediate certificate to OpenSSL as a client-side parameter.
Not sure if this has changed in Laravel 5, but the accepted answer using count($data->$relation)
didn't work for me, as the very act of accessing the relation property caused it to be loaded.
In the end, a straightforward isset($data->$relation)
did the trick for me.
I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload
instruction was immediately evaluated, and then the $
usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).
So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.
var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
console.log("script loaded :)");
onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
For my needs, it works fine now. Hope this can help others :)
For data up to 8000 characters use:
CONVERT(VARCHAR(32), HashBytes('MD5', '[email protected]'), 2)
For binary data (without the limit of 8000 bytes) use:
CONVERT(VARCHAR(32), master.sys.fn_repl_hash_binary(@binary_data), 2)
As the other people in this post answer the question in details the difference between ==
and is
for comparing Objects or variables, I would emphasize mainly the comparison between is
and ==
for strings which can give different results and I would urge programmers to carefully use them.
For string comparison, make sure to use ==
instead of is
:
str = 'hello'
if (str is 'hello'):
print ('str is hello')
if (str == 'hello'):
print ('str == hello')
Out:
str is hello
str == hello
But in the below example ==
and is
will get different results:
str2 = 'hello sam'
if (str2 is 'hello sam'):
print ('str2 is hello sam')
if (str2 == 'hello sam'):
print ('str2 == hello sam')
Out:
str2 == hello sam
Conclusion and Analysis:
Use is
carefully to compare between strings.
Since is
for comparing objects and since in Python 3+ every variable such as string interpret as an object, let's see what happened in above paragraphs.
In python there is id
function that shows a unique constant of an object during its lifetime. This id is using in back-end of Python interpreter to compare two objects using is
keyword.
str = 'hello'
id('hello')
> 140039832615152
id(str)
> 140039832615152
But
str2 = 'hello sam'
id('hello sam')
> 140039832615536
id(str2)
> 140039832615792
Already answered but still. Change your code to:
metrics.sort {|a1,a2| a2[1].to_i <=> a1[1].to_i }
Converted to strings along the way or not, this will do the job.
Here's a simple solution to recursively overwrite a destination with a source, creating any necessary directories as it goes. This does not handle symlinks, but it would be a simple extension (see answer by @Michael above).
def recursive_overwrite(src, dest, ignore=None):
if os.path.isdir(src):
if not os.path.isdir(dest):
os.makedirs(dest)
files = os.listdir(src)
if ignore is not None:
ignored = ignore(src, files)
else:
ignored = set()
for f in files:
if f not in ignored:
recursive_overwrite(os.path.join(src, f),
os.path.join(dest, f),
ignore)
else:
shutil.copyfile(src, dest)
In Acrobat, click on the "Advanced" tab, then click on "Enable Features in Adobe Reader." This should do the trick.
I've also thought of this. Finally, my solution is to use github gist. Don't forget it also has highlight functionality. Just copy it. :)
The JavaScript Date
object can help here.
The first step is to convert those strings to Date
instances. That's easily done:
var str = "06/07/2012"; // E.g., "mm/dd/yyyy";
var dt = new Date(parseInt(str.substring(6), 10), // Year
parseInt(str.substring(0, 2), 10) - 1, // Month (0-11)
parseInt(str.substring(3, 5), 10)); // Day
Then you can do all sorts of useful calculations. JavaScript dates understand leap years and such. They use an idealized concept of "day" which is exactly 86,400 seconds long. Their underlying value is the number of milliseconds since The Epoch (midnight, Jan 1st, 1970); it can be a negative number for dates prior to The Epoch.
More on the MDN page on Date
.
You might also consider using a library like MomentJS, which will help with parsing, doing date math, formatting...
While other answers have noted the differences correctly, note that if you are in fact returning a ViewResult only it is better to return the more specific type rather than the base ActionResult type. An obvious exception to this principle is when your method returns multiple types deriving from ActionResult.
For a full discussion of the reasons behind this principle please see the related discussion here: Must ASP.NET MVC Controller Methods Return ActionResult?
Gradle caches artifacts in USER_HOME/.gradle
folder. The compiled scripts are usually in the .gradle
folder in your project folder.
If you can't find the cache, maybe it's because you have not cached any artifacts yet. You can always see where Gradle has cached artifacts with a simple script:
apply plugin: 'java'
repositories{
mavenCentral()
}
dependencies{
compile 'com.google.guava:guava:12.0'
}
task showMeCache << {
configurations.compile.each { println it }
}
Now if you run gradle showMeCache
it should download the deps into cache and print the full path.
Just for sake of completeness, you can also use the same technique above with excel tables.
In the example below, I'm looking of a text in any cell of a Excel Table named "tblConfig", place in the sheet named Config that normally is set to be hidden. I'm accepting the defaults of the Find method.
Dim list As ListObject
Dim config As Worksheet
Dim cell as Range
Set config = Sheets("Config")
Set list = config.ListObjects("tblConfig")
'search in any cell of the data range of excel table
Set cell = list.DataBodyRange.Find(searchTerm)
If cell Is Nothing Then
'when information is not found
Else
'when information is found
End If
1) Go to "Window".
2) Then click on "Open Perspective",
3) Then click on "Other",
4) Select "Java(Default)" and click "OK"
Then again go to "Window" and click on "Reset Perspective"
You can try the following method(python3.6.2):
case one:
@app.route('/hello')
def hello():
headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow'}
response = make_response('<h1>hello world</h1>',301)
response.headers = headers
return response
case two:
@app.route('/hello')
def hello():
headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow.com'}
return '<h1>hello world</h1>',301,headers
I am using Flask .And if you want to return json,you can write this:
import json #
@app.route('/search/<keyword>')
def search(keyword):
result = Book.search_by_keyword(keyword)
return json.dumps(result),200,{'content-type':'application/json'}
from flask import jsonify
@app.route('/search/<keyword>')
def search(keyword):
result = Book.search_by_keyword(keyword)
return jsonify(result)