Use this:
countries='Paris, France, Europe'
OIFS="$IFS"
IFS=', ' array=($countries)
IFS="$OIFS"
#${array[1]} == Paris
#${array[2]} == France
#${array[3]} == Europe
Spinner don't support Hint, i recommend you to make a custom spinner adapter.
check this link : https://stackoverflow.com/a/13878692/1725748
Using java.time
framework built into Java 8.
import java.time.LocalTime;
import java.time.LocalDateTime;
LocalDateTime now = LocalDateTime.now(); // 2015-11-19T19:42:19.224
// start of a day
now.with(LocalTime.MIN); // 2015-11-19T00:00
now.with(LocalTime.MIDNIGHT); // 2015-11-19T00:00
// end of a day
now.with(LocalTime.MAX); // 2015-11-19T23:59:59.999999999
The line height of the <br>
can be different from the line height of the rest of the text inside a <p>
. You can control the line height of your <br>
tags independently of the rest of the text by enclosing two of them in a <span>
that is styled. Use the line-height
css property, as others have suggested.
<p class="normalLineHeight">
Lots of text here which will display on several lines with normal line height if you put it in a narrow container...
<span class="customLineHeight"><br><br></span>
After a custom break, this text will again display on several lines with normal line height...
</p>
I often use row_number() as a quick way to discard duplicate records from my select statements. Just add a where clause. Something like...
select a,b,rn
from (select a, b, row_number() over (partition by a,b order by a,b) as rn
from table)
where rn=1;
Somewhat similar to your original attempt, but more Pythonic, is to use Python's standard negative-indexing convention to count backwards from the end:
df[df.columns[-1]]
Docx4j is open source and the best API for convert Docx to pdf without any alignment or font issue.
Maven Dependencies:
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-Internal</artifactId>
<version>8.0.0</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
<version>8.0.0</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-MOXy</artifactId>
<version>8.0.0</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-export-fo</artifactId>
<version>8.0.0</version>
</dependency>
Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
public class DocToPDF {
public static void main(String[] args) {
try {
InputStream templateInputStream = new FileInputStream("D:\\\\Workspace\\\\New\\\\Sample.docx");
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
String outputfilepath = "D:\\\\Workspace\\\\New\\\\Sample.pdf";
FileOutputStream os = new FileOutputStream(outputfilepath);
Docx4J.toPDF(wordMLPackage,os);
os.flush();
os.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
1) When the user logs out (Forms signout in Action) I want to redirect to a login page.
public ActionResult Logout() {
//log out the user
return RedirectToAction("Login");
}
2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)
Why would you want to redirect from a controller init?
the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:
public ActionResult Index() {
return RedirectToAction("whateverAction", "whateverController");
}
ArrayList get(int index)
method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.
public Element get(int index)
Example : In below example we are getting few elements of an arraylist by using get method.
package beginnersbook.com;
import java.util.ArrayList;
public class GetMethodExample {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("pen");
al.add("pencil");
al.add("ink");
al.add("notebook");
al.add("book");
al.add("books");
al.add("paper");
al.add("white board");
System.out.println("First element of the ArrayList: "+al.get(0));
System.out.println("Third element of the ArrayList: "+al.get(2));
System.out.println("Sixth element of the ArrayList: "+al.get(5));
System.out.println("Fourth element of the ArrayList: "+al.get(3));
}
}
Output:
First element of the ArrayList: pen
Third element of the ArrayList: ink
Sixth element of the ArrayList: books
Fourth element of the ArrayList: notebook
I had a similar problem, with vertical scrollbars appearing when I set a maxWidth in the Fancybox options.
To get around the problem I had to set
.fancybox-inner {
overflow: hidden !important;
}
and set a fixed width CSS rule on the Fancybox content rather than specifying a maxWidth in the Fancybox options. If I did the latter, Fancybox's calculated height for the content was slightly too small - probably hinting at why it was putting in scrollbars in the first place.
Previous answer does not seems to handle cases where rootController are UITabBarController or UINavigationController.
Here is the function in swift which works for those cases :
func getCurrentView() -> UIViewController?
{
if let window = UIApplication.sharedApplication().keyWindow, var currentView: UIViewController = window.rootViewController
{
while (currentView.presentedViewController != nil)
{
if let presented = currentView.presentedViewController
{
currentView = presented
}
}
if currentView is UITabBarController
{
if let visible = (currentView as! UITabBarController).selectedViewController
{
currentView = visible;
}
}
if currentView is UINavigationController
{
if let visible = (currentView as! UINavigationController).visibleViewController
{
currentView = visible;
}
}
return currentView
}
return nil
}
unset()
and initialization:unset($_POST);
$_POST = array();
Or in a single statement:
unset($_POST) ? $_POST = array() : $_POST = array();
But what is the reason you want to do this?
in case you would like to print all file contents:
find . -type f -exec cat {} +
using sqldf
fits here:
library(sqldf)
sqldf("SELECT Believe, Count(1) as N FROM Santa
GROUP BY Believe")
---- Remove Constraint ----
EXEC sp_MSForEachTable "ALTER TABLE ? NOCHECK CONSTRAINT all"
---- Delete Data ----
EXEC sp_MSForEachTable "DELETE FROM ?"
---- Add Constraint ----
EXEC sp_MSForEachTable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
---- Reset Identity value ----
EXEC sp_MSForEachTable "DBCC CHECKIDENT ( '?', RESEED, 0)"
I would recommend using JSON.stringify
, which converts the set of the variables in the object to a JSON string. Most modern browsers support this method natively, but for those that don't, you can include a JS version:
var obj = {
name: 'myObj'
};
JSON.stringify(obj);
A very simple work-around for this issue is to create a Streamable<T>
interface extending Iterable<T>
that holds a default <T> stream()
method.
interface Streamable<T> extends Iterable<T> {
default Stream<T> stream() {
return StreamSupport.stream(spliterator(), false);
}
}
Now any of your Iterable<T>
s can be trivially made streamable just by declaring them implements Streamable<T>
instead of Iterable<T>
.
I am a bit lazy, so I like simple things:
let users = await Users.find({}, null, {limit: 50});
It's Carriage Return
. Source: http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx
The following repeats the loop until the user has pressed the Return key.
while(ch!='\r')
{
ch=getche();
}
You basically need a helper method to read a stream into memory. This works pretty well:
public static byte[] readFully(InputStream stream) throws IOException
{
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = stream.read(buffer)) != -1)
{
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}
Then you'd call it with:
public static byte[] loadFile(String sourcePath) throws IOException
{
InputStream inputStream = null;
try
{
inputStream = new FileInputStream(sourcePath);
return readFully(inputStream);
}
finally
{
if (inputStream != null)
{
inputStream.close();
}
}
}
Don't mix up text and binary data - it only leads to tears.
Comments were removed from JSON by design.
I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't.
Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.
It is not listed as a function in dplyr (yet): http://cran.rstudio.org/web/packages/dplyr/dplyr.pdf
The function below works (almost) the same if you don't want to load both plyr and dplyr
rename <- function(dat, oldnames, newnames) {
datnames <- colnames(dat)
datnames[which(datnames %in% oldnames)] <- newnames
colnames(dat) <- datnames
dat
}
dat <- rename(mtcars,c("mpg","cyl"), c("mympg","mycyl"))
head(dat)
mympg mycyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
Edit: The comment by Romain produces the following (note that the changes function requires dplyr .1.1)
> dplyr:::changes(mtcars, dat)
Changed variables:
old new
disp 0x108b4b0e0 0x108b4e370
hp 0x108b4b210 0x108b4e4a0
drat 0x108b4b340 0x108b4e5d0
wt 0x108b4b470 0x108b4e700
qsec 0x108b4b5a0 0x108b4e830
vs 0x108b4b6d0 0x108b4e960
am 0x108b4b800 0x108b4ea90
gear 0x108b4b930 0x108b4ebc0
carb 0x108b4ba60 0x108b4ecf0
mpg 0x1033ee7c0
cyl 0x10331d3d0
mympg 0x108b4e110
mycyl 0x108b4e240
Changed attributes:
old new
names 0x10c100558 0x10c2ea3f0
row.names 0x108b4bb90 0x108b4ee20
class 0x103bd8988 0x103bd8f58
You asked why it happens, let's see:
The official language specificaion dictates a call to the internal [[GetValue]]
method. Your .attr
returns undefined and you're trying to access its length.
If Type(V) is not Reference, return V.
This is true, since undefined is not a reference (alongside null, number, string and boolean)
Let base be the result of calling GetBase(V).
This gets the undefined
part of myVar.length
.
If IsUnresolvableReference(V), throw a ReferenceError exception.
This is not true, since it is resolvable and it resolves to undefined.
If IsPropertyReference(V), then
This happens since it's a property reference with the .
syntax.
Now it tries to convert undefined
to a function which results in a TypeError.
In .NET a POCO is a 'Plain old CLR Object'. It is not a 'Plain old C# object'...
Execute this script:
SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;'
FROM v$session
where username='YOUR_USER';
It will printout sqls, which should be executed.
You can Use sender argument
@IBAction func TickToeButtonClick(sender: AnyObject) {
sender.setTitle("my text here", forState: .normal)
}
Uninstalling the IIS UrlScan Extension solved the problem for me.
Here is an example that works on Chrome 5.0.375.125.
The page B (iframe content):
<html>
<head></head>
<body>
<script>
top.postMessage('hello', 'A');
</script>
</body>
</html>
Note the use of top.postMessage
or parent.postMessage
not window.postMessage
here
The page A:
<html>
<head></head>
<body>
<iframe src="B"></iframe>
<script>
window.addEventListener( "message",
function (e) {
if(e.origin !== 'B'){ return; }
alert(e.data);
},
false);
</script>
</body>
</html>
A and B must be something like http://domain.com
EDIT:
From another question, it looks the domains(A and B here) must have a /
for the postMessage
to work properly.
I did this:
// Left, top, right, bottom drawables.
Drawable[] drawables = button.getCompoundDrawables();
// get left drawable.
Drawable leftCompoundDrawable = drawables[0];
// get new drawable.
Drawable img = getContext().getResources().getDrawable(R.drawable.ic_launcher);
// set image size (don't change the size values)
img.setBounds(leftCompoundDrawable.getBounds());
// set new drawable
button.setCompoundDrawables(img, null, null, null);
You can use the extract_html
field of the summary REST endpoint for this: e.g. https://en.wikipedia.org/api/rest_v1/page/summary/Cat.
Note: This aims to simply the content a bit by removing most of the pronunciations, mainly in parentheses in some cases.
"System tray" application is just a regular win forms application, only difference is that it creates a icon in windows system tray area. In order to create sys.tray icon use NotifyIcon component , you can find it in Toolbox(Common controls), and modify it's properties: Icon, tool tip. Also it enables you to handle mouse click and double click messages.
And One more thing , in order to achieve look and feels or standard tray app. add followinf lines on your main form show event:
private void MainForm_Shown(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
Hide();
}
Try using this query:
SELECT * FROM tablename
WHERE visible=1
ORDER BY
CASE WHEN position IS NULL THEN 1 ELSE 0 END ASC,id DESC
I am installing pyfuzzy
but is is not in PyPI; it returns the message: No matching distribution found for pyfuzzy
.
I tried the accepted answer
pip install --no-index --find-links=file:///Users/victor/Downloads/pyfuzzy-0.1.0 pyfuzzy
But it does not work either and returns the following error:
Ignoring indexes: https://pypi.python.org/simple Collecting pyfuzzy Could not find a version that satisfies the requirement pyfuzzy (from versions: ) No matching distribution found for pyfuzzy
At last , I have found a simple good way there: https://pip.pypa.io/en/latest/reference/pip_install.html
Install a particular source archive file.
$ pip install ./downloads/SomePackage-1.0.4.tar.gz
$ pip install http://my.package.repo/SomePackage-1.0.4.zip
So the following command worked for me:
pip install ../pyfuzzy-0.1.0.tar.gz.
Hope it can help you.
I realize this question was asked a long time ago, but I came here looking for answers and wasn't satisfied with anything I could find. I finally found the answer here:
https://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor
To get the results from the form, use the FormCollection and then pull each individual value out by it's model name thus:
yourRecord.FieldName = Request.Form["FieldNameInModel"];
As far as I could tell it makes absolutely no difference what argument name you give to the FormCollection - use Request.Form["NameFromModel"] to retrieve it.
No, I did not dig down to see how th4e magic works under the covers. I just know it works...
I hope this helps somebody avoid the hours I spent trying different approaches before I got it working.
Go to File > Preferences > Settings
(or press Ctrl+,) then click the leftmost icon in the top right corner, "Open Settings (JSON)"
In the JSON settings window, add this (within the curly braces {}
):
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\bash.exe"`
(Here you can put any other custom settings you want as well)
Checkout that path to make sure your bash.exe file is there otherwise find out where it is and point to that path instead.
Now if you open a new terminal window in VS Code, it should open with bash instead of PowerShell.
final ScrollView scrollview = (ScrollView)findViewById(R.id.selected_place_layout_scrollview);
scrollview.post(new Runnable() {
public void run() {
scrollview.scrollTo(0, 0);
}
});
You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):
dataGridView1.Columns[1].Width = 108; // or whatever width works well for abbrev
dataGridView1.Columns[2].Width =
dataGridView1.Width
- dataGridView1.Columns[0].Width
- dataGridView1.Columns[1].Width
- 72; // this is an extra "margin" number of pixels
If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize
event handler of the DataGridView.
I like parseInt for this case:
parseInt(Math.random()*0xFFFFFFFF).toString(16)
First you should learn about loops, in this case most suitable is for
loop. For instance let's initialize whole table with increasing values starting with 0:
final int SIZE = 10;
int[] array = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
array[i] = i;
}
Now you can modify it to initialize your table with values as per your assignment.
But what happen if you replace condition i < SIZE
with i < 11
? Well, you will get IndexOutOfBoundException
, as you try to access (at some point) an object under index 10, but the highest index in 10-element array is 9. So you are trying, in other words, to find friend's home with number 11, but there are only 10 houses in the street.
In case of the code you presented, well, there must be more of it, as you can not get this error (exception) from that code.
Here's a new automated tool, JSNice, to try to deobfuscate/deminify it. The tool even tries to guess the variable names, which is unbelievably cool. (It mines Javascript on github for this purpose.)
The highest (Deepak Goel) answer didn't work well for me. Somehow the tag wasn't added properly.
I ended up just sending the ID of the fragment through the flow (using intents) and retrieving it directly from fragment manager.
There is a "3 of 9"
control on CodeProject: Barcode .NET Control
HTML
<div class='containerBox'>
<div>
<img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails'>
<div>
<h4>Facebook</h4>
<div style="font-size:.6em;float:left; margin-left:5px;color:white;">fine location, GPS, coarse location</div>
<div style="float:right;font-size:.6em; margin-right:5px; color:white;">0 mins ago</div>
</div>
</div>
</div>
CSS
.iconDetails {
margin-left:2%;
float:left;
height:40px;
width:40px;
}
.containerBox {
width:300px;
height:60px;
padding:1px;
background-color:#303030;
}
h4{
margin:0px;
margin-top:3%;
margin-left:50px;
color:white;
}
Short answer: There's no way to do it using CSS only.
Long(er) answer: Why? Because when you do position: absolute;
, that takes your element out of the document's regular flow, so there's no way for the text to have any positional-relationship with it, unfortunately.
One of the possible alternatives is to float: right;
your div
, but if that doesn't achieve what you want, you'll have to use JavaScript/jQuery, or just come up with a better layout.
Updated code:
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.your_color)));
It is worth noting that what you're doing isn't rounding, it's casting. Casting using (int) x
truncates the decimal value of x
. As in your example, if x = 3.9995
, the .9995
gets truncated and x = 3
.
As proposed by many others, one solution is to add 0.5
to x
, and then cast.
concat.js is being included in the concat
task's source files public/js/*.js
. You could have a task that removes concat.js
(if the file exists) before concatenating again, pass an array to explicitly define which files you want to concatenate and their order, or change the structure of your project.
If doing the latter, you could put all your sources under ./src
and your built files under ./dest
src
+-- css
¦ +-- 1.css
¦ +-- 2.css
¦ +-- 3.css
+-- js
+-- 1.js
+-- 2.js
+-- 3.js
Then set up your concat task
concat: {
js: {
src: 'src/js/*.js',
dest: 'dest/js/concat.js'
},
css: {
src: 'src/css/*.css',
dest: 'dest/css/concat.css'
}
},
Your min task
min: {
js: {
src: 'dest/js/concat.js',
dest: 'dest/js/concat.min.js'
}
},
The build-in min task uses UglifyJS, so you need a replacement. I found grunt-css to be pretty good. After installing it, load it into your grunt file
grunt.loadNpmTasks('grunt-css');
And then set it up
cssmin: {
css:{
src: 'dest/css/concat.css',
dest: 'dest/css/concat.min.css'
}
}
Notice that the usage is similar to the built-in min.
Change your default
task to
grunt.registerTask('default', 'concat min cssmin');
Now, running grunt
will produce the results you want.
dest
+-- css
¦ +-- concat.css
¦ +-- concat.min.css
+-- js
+-- concat.js
+-- concat.min.js
if you need the batch file to schedule the backup, the SQL management tools have scheduled tasks built in...
Instead of implementing a "constants interface", in Java 1.5+, you can use static imports to import the constants/static methods from another class/interface:
import static com.kittens.kittenpolisher.KittenConstants.*;
This avoids the ugliness of making your classes implement interfaces that have no functionality.
As for the practice of having a class just to store constants, I think it's sometimes necessary. There are certain constants that just don't have a natural place in a class, so it's better to have them in a "neutral" place.
But instead of using an interface, use a final class with a private constructor. (Making it impossible to instantiate or subclass the class, sending a strong message that it doesn't contain non-static functionality/data.)
Eg:
/** Set of constants needed for Kitten Polisher. */
public final class KittenConstants
{
private KittenConstants() {}
public static final String KITTEN_SOUND = "meow";
public static final double KITTEN_CUTENESS_FACTOR = 1;
}
I know the question is old but I found this very helpful http://www.gnuplot.info/demo_canvas/dashcolor.html . So you can choose linetype and linecolor separately but you have to precede everything by "set termoption dash" (worked for me in gnuplot 4.4).
If you want to get request path (more info):
echo parse_url($_SERVER["REQUEST_URI"])['path']
If you want to remove the query and (and maybe fragment also):
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
$i = strposa($_SERVER["REQUEST_URI"], ['#', '?']);
echo strrpos($_SERVER["REQUEST_URI"], 0, $i);
The problem you are describing sounds like your version of PHP might be missing the readline PHP module, causing the interactive shell to not work. I base this on this PHP bug submission.
Try running
php -m
And see if "readline" appears in the output.
There might be good reasons for omitting readline from the distribution. PHP is typically executed by a web server; so it is not really need for most use cases. I am sure you can execute PHP code in a file from the command prompt, using:
php file.php
There is also the phpsh project which provides a (better) interactive shell for PHP. However, some people have had trouble running it under Windows (I did not try this myself).
Edit:
According to the documentation here, readline
is not supported under Windows:
Note: This extension is not available on Windows platforms.
So, if that is correct, your options are:
I'm not sure if it would be faster, or even accurate, but you could use John Carmack's Magical Square Root, algorithm to solve the square root faster. You could probably easily test this for all possible 32 bit integers, and validate that you actually got correct results, as it's only an appoximation. However, now that I think about it, using doubles is approximating also, so I'm not sure how that would come into play.
I don't know of any way doing this in SQL Developer. You can see all the other schemas and their objects (if you have the correct privileges) when looking in "Other Users" -> "< Schemaname >".
In your case, either use the method described above or create a new connection for the schema in which you want to work or create synonyms for all the tables you wish to access.
If you would work in SQL*Plus, issuing ALTER SESSION SET CURRENT_SCHEMA=MY_NAME
would set your current schema (This is probably what your DBA means).
An alternative solution is to introduce a method to the file instance that would do the explicit conversion.
import types
def _write_str(self, ascii_str):
self.write(ascii_str.encode('ascii'))
source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)
And then you can use it as source_file.write_str("Hello World")
.
I've written a script to get all child process pids of a parent process. Here is the code. Hope it will help.
function getcpid() {
cpids=`pgrep -P $1|xargs`
# echo "cpids=$cpids"
for cpid in $cpids;
do
echo "$cpid"
getcpid $cpid
done
}
getcpid $1
In the position where you want to add text, do:
Shift
+ Alt
+ down arrow
and select the lines you want. Then type. The text you type is inserted on all of the lines you selected.
not nearly as concise as the link you provided: but the following chapter 14 - 24 may help :) hehe
adb shell am start -n '<appPackageName>/.<appActitivityName>
Ex:
adb shell am start -n 'com.android.settings/.wifi.WifiStatusTest'
You can use APK-INFO application to know the list of App Activities with respect to each App Package
If you wish dialog box to be re-activated for the page you set as prevent dialog box to show.
Chrome: select settings, a google page for chrome will open with all your settings for chrome.
At the very bottom, go to advance settings and at the bottom of the advance settings you may click on Resset Browser Settings... this will make dialog box appear as they should.
Servlet - it's java server side layer.
Just to be complete, I'll build build off of Robocide and point out that typeid
can be used alone without using name():
#include <typeinfo>
#include <iostream>
using namespace std;
class A {
public:
virtual ~A() = default; // We're not polymorphic unless we
// have a virtual function.
};
class B : public A { } ;
class C : public A { } ;
int
main(int argc, char* argv[])
{
B b;
A& a = b;
cout << "a is B: " << boolalpha << (typeid(a) == typeid(B)) << endl;
cout << "a is C: " << boolalpha << (typeid(a) == typeid(C)) << endl;
cout << "b is B: " << boolalpha << (typeid(b) == typeid(B)) << endl;
cout << "b is A: " << boolalpha << (typeid(b) == typeid(A)) << endl;
cout << "b is C: " << boolalpha << (typeid(b) == typeid(C)) << endl;
}
Output:
a is B: true
a is C: false
b is B: true
b is A: false
b is C: false
I want columns One and Two to shrink/grow to fit rather than being fixed.
Have you tried: flex-basis: auto
or this:
flex: 1 1 auto
, which is short for:
flex-grow: 1
(grow proportionally)flex-shrink: 1
(shrink proportionally)flex-basis: auto
(initial size based on content size)or this:
main > section:first-child {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:nth-child(2) {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:last-child {
flex: 20 1 auto;
display: flex;
flex-direction: column;
}
Related:
When you add the const
keyword to a method the this
pointer will essentially become a pointer to const
object, and you cannot therefore change any member data. (Unless you use mutable
, more on that later).
The const
keyword is part of the functions signature which means that you can implement two similar methods, one which is called when the object is const
, and one that isn't.
#include <iostream>
class MyClass
{
private:
int counter;
public:
void Foo()
{
std::cout << "Foo" << std::endl;
}
void Foo() const
{
std::cout << "Foo const" << std::endl;
}
};
int main()
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
}
This will output
Foo
Foo const
In the non-const method you can change the instance members, which you cannot do in the const
version. If you change the method declaration in the above example to the code below you will get some errors.
void Foo()
{
counter++; //this works
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter++; //this will not compile
std::cout << "Foo const" << std::endl;
}
This is not completely true, because you can mark a member as mutable
and a const
method can then change it. It's mostly used for internal counters and stuff. The solution for that would be the below code.
#include <iostream>
class MyClass
{
private:
mutable int counter;
public:
MyClass() : counter(0) {}
void Foo()
{
counter++;
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter++; // This works because counter is `mutable`
std::cout << "Foo const" << std::endl;
}
int GetInvocations() const
{
return counter;
}
};
int main(void)
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
std::cout << "Foo has been invoked " << ccc.GetInvocations() << " times" << std::endl;
}
which would output
Foo
Foo const
Foo has been invoked 2 times
You should be able to set the server.session.timeout
in your application.properties file.
ref: http://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html
Check if the data attribute is present, then do the stuff...
$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
if(e.target.getAttribute('data-title')) {
var careerTitle = $(this).attr('data-title');
if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
}
});
Use this method (No need to xml file)
If you want scale to quarter(half x,half y)
view.animate().scaleX(0.5f).scaleY(0.5f)
If you want scale and move to bottom right
view.animate().scaleX(0.5f).scaleY(0.5f)
.translationY((view.height/4).toFloat()).translationX((view.width/4).toFloat())
If you want move to top use (-view.height/4)
and for left (-view.width/4)
If you want do something after animation ends use withEndAction(Runnable runnable)
function.
You can use some other property like alpha and rotation
Full code
view.animate()
.scaleX(0.5f).scaleY(0.5f)//scale to quarter(half x,half y)
.translationY((view.height/4).toFloat()).translationX((view.width/4).toFloat())// move to bottom / right
.alpha(0.5f) // make it less visible
.rotation(360f) // one round turns
.setDuration(1000) // all take 1 seconds
.withEndAction(new Runnable() {
@Override
public void run() {
//animation ended
}
});
It would be more correct to say that stdin
, stdout
, and stderr
are "I/O streams" rather
than files. As you've noticed, these entities do not live in the filesystem. But the
Unix philosophy, as far as I/O is concerned, is "everything is a file". In practice,
that really means that you can use the same library functions and interfaces (printf
,
scanf
, read
, write
, select
, etc.) without worrying about whether the I/O stream
is connected to a keyboard, a disk file, a socket, a pipe, or some other I/O abstraction.
Most programs need to read input, write output, and log errors, so stdin
, stdout
,
and stderr
are predefined for you, as a programming convenience. This is only
a convention, and is not enforced by the operating system.
You can use n-number of recipient below method:
String to[] = {"[email protected]"} //Mail id you want to send;
InternetAddress[] address = new InternetAddress[to.length];
for(int i =0; i< to.length; i++)
{
address[i] = new InternetAddress(to[i]);
}
msg.setRecipients(Message.RecipientType.TO, address);
You could use something like this:
import re
s = #that big string
# the parenthesis create a group with what was matched
# and '\w' matches only alphanumeric charactes
p = re.compile("name +(\w+) +is valid", re.flags)
# use search(), so the match doesn't have to happen
# at the beginning of "big string"
m = p.search(s)
# search() returns a Match object with information about what was matched
if m:
name = m.group(1)
else:
raise Exception('name not found')
<script type="text/javascript">
function clearThis(target){
if(target.value=='[email protected]'){
target.value= "";}
}
</script>
Is this really what your looking for?
The easiest is:
int label = 0;
loop:while(true) {
switch(state) {
case 0:
// Some code
state = 5;
break;
case 2:
// Some code
state = 4;
break;
...
default:
break loop;
}
}
To be absolutely clear... what you describe does not conflict with the spec in any way. The spec talks about the values Hibernate assigns to your entities, not the values actually stored in the database sequence.
However, there is the option to get the behavior you are looking for. First see my reply on Is there a way to dynamically choose a @GeneratedValue strategy using JPA annotations and Hibernate? That will give you the basics. As long as you are set up to use that SequenceStyleGenerator, Hibernate will interpret allocationSize
using the "pooled optimizer" in the SequenceStyleGenerator. The "pooled optimizer" is for use with databases that allow an "increment" option on the creation of sequences (not all databases that support sequences support an increment). Anyway, read up about the various optimizer strategies there.
is a HTML entity. When doing .text()
, all HTML entities are decoded to their character values.
Instead of comparing using the entity, compare using the actual raw character:
var x = td.text();
if (x == '\xa0') { // Non-breakable space is char 0xa0 (160 dec)
x = '';
}
Or you can also create the character from the character code manually it in its Javascript escaped form:
var x = td.text();
if (x == String.fromCharCode(160)) { // Non-breakable space is char 160
x = '';
}
More information about String.fromCharCode
is available here:
More information about character codes for different charsets are available here:
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
Occurs when the text content of an element is changed through the user interface.
It's not quite an alias for keyup
because keyup
will fire even if the key does nothing (for example: pressing and then releasing the Control key will trigger a keyup
event).
A good way to think about it is like this: it's an event that triggers whenever the input changes. This includes -- but is not limited to -- pressing keys which modify the input (so, for example, Ctrl
by itself will not trigger the event, but Ctrl-V
to paste some text will), selecting an auto-completion option, Linux-style middle-click paste, drag-and-drop, and lots of other things.
See this page and the comments on this answer for more details.
This turned out to be a stupid error. My log4j wasn't configured to capture my error output. I was throwing configuration errors in the background and once I fixed those I was good to go and my request mappings worked fine.
You can use Postman a plugin for chrome. It gives the ability to choose the authentication type you need for each of the requests. In that menu you can configure user and password. Postman will automatically translate the config to a authentication header that will be sent with your request.
public int gcd(int num1, int num2) {
int max = Math.abs(num1);
int min = Math.abs(num2);
while (max > 0) {
if (max < min) {
int x = max;
max = min;
min = x;
}
max %= min;
}
return min;
}
This method uses the Euclid’s algorithm to get the "Greatest Common Divisor" of two integers. It receives two integers and returns the gcd of them. just that easy!
Try writing it like this:
div { border: 1px solid #CCC; }
_x000D_
<div style="display: inline">a</div>_x000D_
<div style="display: inline">b</div>_x000D_
<div style="display: inline">c</div>
_x000D_
It simply means that you are not sure about what number of rows or columns you can give and you are asking numpy to suggest number of column or rows to get reshaped in.
numpy provides last example for -1 https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html
check below code and its output to better understand about (-1):
CODE:-
import numpy
a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
print("Without reshaping -> ")
print(a)
b = numpy.reshape(a, -1)
print("HERE We don't know about what number we should give to row/col")
print("Reshaping as (a,-1)")
print(b)
c = numpy.reshape(a, (-1,2))
print("HERE We just know about number of columns")
print("Reshaping as (a,(-1,2))")
print(c)
d = numpy.reshape(a, (2,-1))
print("HERE We just know about number of rows")
print("Reshaping as (a,(2,-1))")
print(d)
OUTPUT :-
Without reshaping ->
[[1 2 3 4]
[5 6 7 8]]
HERE We don't know about what number we should give to row/col
Reshaping as (a,-1)
[[1 2 3 4 5 6 7 8]]
HERE We just know about number of columns
Reshaping as (a,(-1,2))
[[1 2]
[3 4]
[5 6]
[7 8]]
HERE We just know about number of rows
Reshaping as (a,(2,-1))
[[1 2 3 4]
[5 6 7 8]]
I would do it like this:
var form2 = new Form2();
form2.Show();
and to close current form I would use
this.Hide();
instead of
this.close();
check out this Youtube channel link for easy start-up tutorials you might find it helpful if u are a beginner
Following syntax helped me when I have columns in sequence
awards_frame.values[:,1:4].sum(axis =1)
Just make sure put single space before and after "and" Keyword..
objdump -T *.so
may also do the job
Be careful with setup
projects if you're using them; Visual Studio setup projects Primary Output
pulls from the obj
folder rather than the bin
.
I was releasing applications I thought were obfuscated and signed in msi
setups for quite a while before I discovered that the deployed application files were actually neither obfuscated nor signed as I as performing the post-build procedure on the bin
folder assemblies and should have been targeting the obj
folder assemblies instead.
This is far from intuitive imho, but the general setup
approach is to use the Primary Output
of the project and this is the obj
folder. I'd love it if someone could shed some light on this btw.
$('.list-toggle').click(function() {
var $listSort = $('.list-sort');
if ($listSort.attr('colspan')) {
$listSort.removeAttr('colspan');
} else {
$listSort.attr('colspan', 6);
}
});
Here's a working fiddle example.
See the answer by @RienNeVaPlus below for a more elegant solution.
This should work in modern browsers:
input[value]:not([value=""])
It selects all inputs with value attribute and then select inputs with non empty value among them.
The best explanation to me is given here
What is JNDI
It is an API to providing access to a directory service, that is, a service mapping name (strings) with objects, reference to remote objects or simple data. This is called binding. The set of bindings is called the context. Applications use the JNDI interface to access resources.
To put it very simply, it is like a hashmap with a String key and Object values representing resources on the web.
What Issues Does JNDI Solve
Without JNDI, the location or access information of remote resources would have to be hard-coded in applications or made available in a configuration. Maintaining this information is quite tedious and error prone.
If a resources has been relocated on another server, with another IP address, for example, all applications using this resource would have to be updated with this new information. With JNDI, this is not necessary. Only the corresponding resource binding has to be updated. Applications can still access it with its name and the relocation is transparent.
I tweaked it some, but it needs a lot more work to conform to the JavaScript weirding way.
function validateNumber(myEvent,decimal) {
var e = myEvent || window.event;
var key = e.keyCode || e.which;
if (e.shiftKey) {
} else if (e.altKey) {
} else if (e.ctrlKey) {
} else if (key === 48) { // 0
} else if (key === 49) { // 1
} else if (key === 50) { // 2
} else if (key === 51) { // 3
} else if (key === 52) { // 4
} else if (key === 53) { // 5
} else if (key === 54) { // 6
} else if (key === 55) { // 7
} else if (key === 56) { // 8
} else if (key === 57) { // 9
} else if (key === 96) { // Numeric keypad 0
} else if (key === 97) { // Numeric keypad 1
} else if (key === 98) { // Numeric keypad 2
} else if (key === 99) { // Numeric keypad 3
} else if (key === 100) { // Numeric keypad 4
} else if (key === 101) { // Numeric keypad 5
} else if (key === 102) { // Numeric keypad 6
} else if (key === 103) { // Numeric keypad 7
} else if (key === 104) { // Numeric keypad 8
} else if (key === 105) { // Numeric keypad 9
} else if (key === 8) { // Backspace
} else if (key === 9) { // Tab
} else if (key === 13) { // Enter
} else if (key === 35) { // Home
} else if (key === 36) { // End
} else if (key === 37) { // Left Arrow
} else if (key === 39) { // Right Arrow
} else if (key === 190 && decimal) { // decimal
} else if (key === 110 && decimal) { // period on keypad
// } else if (key === 188) { // comma
} else if (key === 109) { // minus
} else if (key === 46) { // Del
} else if (key === 45) { // Ins
} else {
e.returnValue = false;
if (e.preventDefault) e.preventDefault();
}
}
And then it's called via:
$('input[name=Price]').keydown(function(myEvent) {
validateNumber(myEvent,true);
});
Since your content-type is application/x-www-form-urlencoded
you'll need to encode the POST body, especially if it contains characters like &
which have special meaning in a form.
Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.
Here are a couple links for reference.
If everything else fails, it's good to try my option and download a HAXM installer.
It needs to be copied to HAXM installation folder and then started from command line (start CMD as an Administrator). After restarting computer HAXM will be installed. It perfectly worked for me as I was having problems with installing it on my laptop.
After all simply type sc query
intelhaxm in your cmd in order to check whether HAXM is installed properly.
Try using jQuery.parseJSON when you get the data back.
type: "POST",
dataType: "json",
url: url,
data: { get_member: id },
success: function(data) {
response = jQuery.parseJSON(data);
$("input[ name = type ]:eq(" + response.type + " )")
.attr("checked", "checked");
$("input[ name = name ]").val( response.name);
$("input[ name = fname ]").val( response.fname);
$("input[ name = lname ]").val( response.lname);
$("input[ name = email ]").val( response.email);
$("input[ name = phone ]").val( response.phone);
$("input[ name = website ]").val( response.website);
$("#admin_member_img")
.attr("src", "images/member_images/" + response.image);
},
error: function(error) {
alert(error);
}
It is possible to use patterns in a .gitignore
file. See the gitignore man page. The pattern */target/*
should ignore any directory named target and anything under it. Or you may try */target/**
to ignore everything under target.
I had the same issue it was due to that I had the bootstrap class "hidden-lg" on the table which caused it to stupidly become display: block !important;
I wonder how Bootstrap never considered to just instead do this:
@media (min-width: 1200px) {
.hidden-lg {
display: none;
}
}
And then just leave the element whatever display it had before for other screensizes.. Perhaps it is too advanced for them to figure out..
Anyway so:
table {
display: table; /* check so these really applies */
width: 100%;
}
should work
You can do this instead of using -o
option:
curl [url] > [file]
VB6/VBA uses deterministic approach to destoying objects. Each object stores number of references to itself. When the number reaches zero, the object is destroyed.
Object variables are guaranteed to be cleaned (set to Nothing
) when they go out of scope, this decrements the reference counters in their respective objects. No manual action required.
There are only two cases when you want an explicit cleanup:
When you want an object to be destroyed before its variable goes out of scope (e.g., your procedure is going to take long time to execute, and the object holds a resource, so you want to destroy the object as soon as possible to release the resource).
When you have a circular reference between two or more objects.
If objectA
stores a references to objectB
, and objectB
stores a reference to objectA
, the two objects will never get destroyed unless you brake the chain by explicitly setting objectA.ReferenceToB = Nothing
or objectB.ReferenceToA = Nothing
.
The code snippet you show is wrong. No manual cleanup is required. It is even harmful to do a manual cleanup, as it gives you a false sense of more correct code.
If you have a variable at a class level, it will be cleaned/destroyed when the class instance is destructed. You can destroy it earlier if you want (see item 1.
).
If you have a variable at a module level, it will be cleaned/destroyed when your program exits (or, in case of VBA, when the VBA project is reset). You can destroy it earlier if you want (see item 1.
).
Access level of a variable (public vs. private) does not affect its life time.
Small sample test.cmd
<# :
@echo off
powershell /nologo /noprofile /command ^
"&{[ScriptBlock]::Create((cat """%~f0""") -join [Char[]]10).Invoke(@(&{$args}%*))}"
exit /b
#>
Write-Host Hello, $args[0] -fo Green
#You programm...
+new
is equivalent to +alloc/-init
in Apple's NSObject
implementation. It is highly unlikely that this will ever change, but depending on your paranoia level, Apple's documentation for +new
appears to allow for a change of implementation (and breaking the equivalency) in the future. For this reason, because "explicit is better than implicit" and for historical continuity, the Objective-C community generally avoids +new
. You can, however, usually spot the recent Java comers to Objective-C by their dogged use of +new
.
IEnumerable: IEnumerable is best suitable for working with in-memory collection (or local queries). IEnumerable doesn’t move between items, it is forward only collection.
IQueryable: IQueryable best suits for remote data source, like a database or web service (or remote queries). IQueryable is a very powerful feature that enables a variety of interesting deferred execution scenarios (like paging and composition based queries).
So when you have to simply iterate through the in-memory collection, use IEnumerable, if you need to do any manipulation with the collection like Dataset and other data sources, use IQueryable
Moment.subtract
does not support an argument of type Moment - documentation:
moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);
The simplest solution is to specify the time delta as an object:
// Assumes string is hh:mm:ss
var myString = "03:15:00",
myStringParts = myString.split(':'),
hourDelta: +myStringParts[0],
minuteDelta: +myStringParts[1];
date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()
// -> "Sat Jun 07 2014 06:07:06 GMT+0100"
xxdiff is lightweight if that's what you're after.
If you initialize both the parameters as float
, you will sure get actual divided value.
For example:
float RoomWidth, TileWidth, NumTiles;
RoomWidth = 142;
TileWidth = 8;
NumTiles = RoomWidth/TileWidth;
Ans:17.75.
String s = "3.14";
float f = Float.parseFloat(s);
I style the div container - usually the sole child of the body with the following css
.body-container {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
height: 100%;
display: flex;
flex-direction: column;
overflow-y: auto;
}
strong is the default. An object remains “alive” as long as there is a strong pointer to it.
weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.
My answer does not use numpy or python collections.
One trivial way to find elements would be as follows:
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
c = [i for i in a if i in b]
Drawback: This method may not work for larger lists. Using numpy is recommended for larger lists.
I have also used following link as others have suggested you for bluetooth communication.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
The thing is all you need is a class BluetoothChatService.java
this class has following threads:
Now when you call start function of the BluetoothChatService like:
mChatService.start();
It starts accept thread which means it will start looking for connection.
Now when you call
mChatService.connect(<deviceObject>,false/true);
Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.
connect
function will start connecting thread which will look for any device which is running accept thread.
When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:
connected(mmSocket, mmDevice, mSocketType);
this method starts connected thread in both the devices:
Using this socket object connected thread obtains the input and output stream to the other device.
And calls read
function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.
BluetoothChatService also has a write
method which takes byte[]
as input and calls write method on connected thread.
mChatService.write("your message".getByte());
write method in connected thread just write this byte data to outputsream of the other device.
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(
// BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
// buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.
You can overload your method. One method contains one parameter GetFooBar(int a)
and the other contain both parameters, GetFooBar(int a, int b)
Shed Skin is "a (restricted) Python-to-C++ compiler".
To solve this edit /etc/ssh/ssh_config and comment the following line 1
https://www.evilbox.ro/linux/solve-ssh_exchange_identification-connection-closed-by-remote-host/ for reference
Key Points:
ngModel in angular2 is valid only if the FormsModule is available as a part of your AppModule.
ng-model
is syntatically wrong.
So, to fix your error.
Step 1: Importing FormsModule
import {FormsModule} from '@angular/forms'
Step 2: Add it to imports array of your AppModule as
imports :[ ... , FormsModule ]
Step 3: Change ng-model
as ngModel with banana boxes as
<input id="name" type="text" [(ngModel)]="name" />
Note: Also, you can handle the two way databinding separately as well as below
<input id="name" type="text" [ngModel]="name" (ngModelChange)="valueChange($event)"/>
valueChange(value){
}
Maven have a Eclipse plugin and Eclipse have a Maven plugin we are going to discus those things.when we using maven with those command line stuffs and etc when we are going through eclipse we don't want to that command line codes it have very much helpful, Maven and eclipse giving good integration ,they will work very well together thanks for that plugins
Step 1: Go to the maven project. Here my project is FirstApp.(Example my project is FirstApp)
There you can see one pom.xml file, now what we want is to generate an eclipse project using that pom.xml.
Step 2: Use mvn eclipse:eclipse command
Step 3: Verify the project
after execution of this command notice that two new files have been created
Note:- both these files are created for Eclipse. When you open those files you will notice a "M2_REPO" class variable is generate. You want to add that class path in eclipse, otherwise eclipse will show a error.
Step 4: Importing eclipse project
File -> Import -> General -> Existing Projects in Workspace -> Select root directory -> Done
I have checked a variable if it is a boolean or not as below
console.log(isBoolean(this.myVariable));
Similarly we have
isNumber(this.myVariable);
isString(this.myvariable);
and so on.
I'd recommend using a class instead of setting css properties. So instead of this:
$(this).css({"border-color": "#C1E0FF",
"border-width":"1px",
"border-style":"solid"});
Define a css class:
.border
{
border-color: #C1E0FF;
border-width:1px;
border-style:solid;
}
And then change your javascript to:
$(this).addClass("border");
Richard Schneider is right. use code below to fetch data from site which is not utf8 charset will get wrong string.
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
" i can't vote.so wrote this.
In Post API call we are sending data in request body. So if we will send data by adding any extra header to an API call. Then first OPTIONS API call will happen and then post call will happen. Therefore, you have to handle OPTION API call first.
You can handle the issue by writing a filter and inside that you have to check for option call API call and return a 200 OK status. Below is the sample code:
package com.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.connector.Response;
public class CustomFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest httpRequest = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
if (httpRequest.getMethod().equalsIgnoreCase("OPTIONS")) {
response.setStatus(Response.SC_OK);
}
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
// TODO
}
public void destroy() {
// Todo
}
}
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
You can use fprintf/sprintf with familiar C syntax. Maybe something like:
fprintf('x = %d, y = %d \n x+y=%d \n x*y=%d \n x/y=%f\n', x,y,d,e,f)
reading your comment, this is how you use your functions from the main program:
x = 2;
y = 2;
[d e f] = answer(x,y);
fprintf('%d + %d = %d\n', x,y,d)
fprintf('%d * %d = %d\n', x,y,e)
fprintf('%d / %d = %f\n', x,y,f)
Also for the answer() function, you can assign the output values to a vector instead of three distinct variables:
function result=answer(x,y)
result(1)=addxy(x,y);
result(2)=mxy(x,y);
result(3)=dxy(x,y);
and call it simply as:
out = answer(x,y);
In a Groovy script the scoping can be different than expected. That is because a Groovy script in itself is a class with a method that will run the code, but that is all done runtime. We can define a variable to be scoped to the script by either omitting the type definition or in Groovy 1.8 we can add the @Field annotation.
import groovy.transform.Field
var1 = 'var1'
@Field String var2 = 'var2'
def var3 = 'var3'
void printVars() {
println var1
println var2
println var3 // This won't work, because not in script scope.
}
sudo find / -Bmin 60
From the man
page:
-Bmin n
True if the difference between the time of a file's inode creation and the time
find
was started, rounded up to the next full minute, is n minutes.
Obviously, you may want to set up a bit differently, but this primary seems the best solution for searching for any file created in the last N minutes.
The outline
property is what you need. It's shorthand for setting each of the following properties in a single declaration:
outline-style
outline-width
outline-color
You could use outline: none;
, which is suggested in the accepted answer. You could also be more specific if you wanted:
button {
outline-style: none;
}
I'd suggest to override Object.clone(), call super.clone() first and than call ref = ref.clone() on all references that you want to have deep copied. It's more or less Do it yourself approach but needs a bit less coding.
Use select setval('payments_id_seq', 21, true);
setval
contains 3 parameters:
sequence_name
nextval
The use of true or false in 3rd parameter of setval is as follows:
SELECT setval('payments_id_seq', 21); // Next nextval will return 22
SELECT setval('payments_id_seq', 21, true); // Same as above
SELECT setval('payments_id_seq', 21, false); // Next nextval will return 21
The better way to avoid hard-coding of sequence name, next sequence value and to handle empty column table correctly, you can use the below way:
SELECT setval(pg_get_serial_sequence('table_name', 'id'), coalesce(max(id), 0)+1 , false) FROM table_name;
where table_name
is the name of the table, id
is the primary key
of the table
We can animate images in ios 5 using this simple code.
CGRect imageFrame = imageView.frame;
imageFrame.origin.y = self.view.bounds.size.height;
[UIView animateWithDuration:0.5
delay:1.0
options: UIViewAnimationCurveEaseOut
animations:^{
imageView.frame = imageFrame;
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
you can fix the wrapper using absolute positioning. and the give inside div a fixed position.
.wrapper{
position:absolute;
left:10%;// or some valve in px
top:10%; // or some valve in px
}
and div inside that
.wrapper .fixed-element{
position:fixed;
width:100%;
height:100%;
margin-left:auto; // to center this div inside at center give auto margin
margin-right:auto;
}
try this It might work for you
string outString= number.ToString("####0.00");
Everyone is correct...try everything...(in order of a little to a lot of time wasted)
Try sprintf in JS or you could use this gist
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" />
describe
may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once
In [43]:
df.describe()
Out[43]:
shopper_num is_martian number_of_items count_pineapples
count 14.0000 14 14.000000 14
mean 7.5000 0 3.357143 0
std 4.1833 0 6.452276 0
min 1.0000 False 0.000000 0
25% 4.2500 0 0.000000 0
50% 7.5000 0 0.000000 0
75% 10.7500 0 3.500000 0
max 14.0000 False 22.000000 0
[8 rows x 4 columns]
Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data
As you prefer you can transpose the result if you prefer:
In [47]:
df.describe().transpose()
Out[47]:
count mean std min 25% 50% 75% max
shopper_num 14 7.5 4.1833 1 4.25 7.5 10.75 14
is_martian 14 0 0 False 0 0 0 False
number_of_items 14 3.357143 6.452276 0 0 0 3.5 22
count_pineapples 14 0 0 0 0 0 0 0
[4 rows x 8 columns]
Here's A generic VBA Array To Range function that writes an array to the sheet in a single 'hit' to the sheet. This is much faster than writing the data into the sheet one cell at a time in loops for the rows and columns... However, there's some housekeeping to do, as you must specify the size of the target range correctly.
This 'housekeeping' looks like a lot of work and it's probably rather slow: but this is 'last mile' code to write to the sheet, and everything is faster than writing to the worksheet. Or at least, so much faster that it's effectively instantaneous, compared with a read or write to the worksheet, even in VBA, and you should do everything you possibly can in code before you hit the sheet.
A major component of this is error-trapping that I used to see turning up everywhere . I hate repetitive coding: I've coded it all here, and - hopefully - you'll never have to write it again.
A VBA 'Array to Range' function
Public Sub ArrayToRange(rngTarget As Excel.Range, InputArray As Variant)
' Write an array to an Excel range in a single 'hit' to the sheet
' InputArray must be a 2-Dimensional structure of the form Variant(Rows, Columns)
' The target range is resized automatically to the dimensions of the array, with
' the top left cell used as the start point.
' This subroutine saves repetitive coding for a common VBA and Excel task.
' If you think you won't need the code that works around common errors (long strings
' and objects in the array, etc) then feel free to comment them out.
On Error Resume Next
'
' Author: Nigel Heffernan
' HTTP://Excellerando.blogspot.com
'
' This code is in te public domain: take care to mark it clearly, and segregate
' it from proprietary code if you intend to assert intellectual property rights
' or impose commercial confidentiality restrictions on that proprietary code
Dim rngOutput As Excel.Range
Dim iRowCount As Long
Dim iColCount As Long
Dim iRow As Long
Dim iCol As Long
Dim arrTemp As Variant
Dim iDimensions As Integer
Dim iRowOffset As Long
Dim iColOffset As Long
Dim iStart As Long
Application.EnableEvents = False
If rngTarget.Cells.Count > 1 Then
rngTarget.ClearContents
End If
Application.EnableEvents = True
If IsEmpty(InputArray) Then
Exit Sub
End If
If TypeName(InputArray) = "Range" Then
InputArray = InputArray.Value
End If
' Is it actually an array? IsArray is sadly broken so...
If Not InStr(TypeName(InputArray), "(") Then
rngTarget.Cells(1, 1).Value2 = InputArray
Exit Sub
End If
iDimensions = ArrayDimensions(InputArray)
If iDimensions < 1 Then
rngTarget.Value = CStr(InputArray)
ElseIf iDimensions = 1 Then
iRowCount = UBound(InputArray) - LBound(InputArray)
iStart = LBound(InputArray)
iColCount = 1
If iRowCount > (655354 - rngTarget.Row) Then
iRowCount = 655354 + iStart - rngTarget.Row
ReDim Preserve InputArray(iStart To iRowCount)
End If
iRowCount = UBound(InputArray) - LBound(InputArray)
iColCount = 1
' It's a vector. Yes, I asked for a 2-Dimensional array. But I'm feeling generous.
' By convention, a vector is presented in Excel as an arry of 1 to n rows and 1 column.
ReDim arrTemp(LBound(InputArray, 1) To UBound(InputArray, 1), 1 To 1)
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
arrTemp(iRow, 1) = InputArray(iRow)
Next
With rngTarget.Worksheet
Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount))
rngOutput.Value2 = arrTemp
Set rngTarget = rngOutput
End With
Erase arrTemp
ElseIf iDimensions = 2 Then
iRowCount = UBound(InputArray, 1) - LBound(InputArray, 1)
iColCount = UBound(InputArray, 2) - LBound(InputArray, 2)
iStart = LBound(InputArray, 1)
If iRowCount > (65534 - rngTarget.Row) Then
iRowCount = 65534 - rngTarget.Row
InputArray = ArrayTranspose(InputArray)
ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iRowCount)
InputArray = ArrayTranspose(InputArray)
End If
iStart = LBound(InputArray, 2)
If iColCount > (254 - rngTarget.Column) Then
ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iColCount)
End If
With rngTarget.Worksheet
Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount + 1))
Err.Clear
Application.EnableEvents = False
rngOutput.Value2 = InputArray
Application.EnableEvents = True
If Err.Number <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
InputArray(iRow, iCol) = Trim(InputArray(iRow, iCol))
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Formula = InputArray
End If 'err<>0
If Err <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
If Left(InputArray(iRow, iCol), 1) = "=" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
If Left(InputArray(iRow, iCol), 1) = "+" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
If Left(InputArray(iRow, iCol), 1) = "*" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Value2 = InputArray
End If 'err<>0
If Err <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsObject(InputArray(iRow, iCol)) Then
InputArray(iRow, iCol) = "[OBJECT] " & TypeName(InputArray(iRow, iCol))
ElseIf IsArray(InputArray(iRow, iCol)) Then
InputArray(iRow, iCol) = Split(InputArray(iRow, iCol), ",")
ElseIf IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
If Len(InputArray(iRow, iCol)) > 255 Then
' Block-write operations fail on strings exceeding 255 chars. You *have*
' to go back and check, and write this masterpiece one cell at a time...
InputArray(iRow, iCol) = Left(Trim(InputArray(iRow, iCol)), 255)
End If
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Text = InputArray
End If 'err<>0
If Err <> 0 Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
iRowOffset = LBound(InputArray, 1) - 1
iColOffset = LBound(InputArray, 2) - 1
For iRow = 1 To iRowCount
If iRow Mod 100 = 0 Then
Application.StatusBar = "Filling range... " & CInt(100# * iRow / iRowCount) & "%"
End If
For iCol = 1 To iColCount
rngOutput.Cells(iRow, iCol) = InputArray(iRow + iRowOffset, iCol + iColOffset)
Next iCol
Next iRow
Application.StatusBar = False
Application.ScreenUpdating = True
End If 'err<>0
Set rngTarget = rngOutput ' resizes the range This is useful, *most* of the time
End With
End If
End Sub
You will need the source for ArrayDimensions:
This API declaration is required in the module header:
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As Any, _
Source As Any, _
ByVal Length As Long)
...And here's the function itself:
Private Function ArrayDimensions(arr As Variant) As Integer
'-----------------------------------------------------------------
' will return:
' -1 if not an array
' 0 if an un-dimmed array
' 1 or more indicating the number of dimensions of a dimmed array
'-----------------------------------------------------------------
' Retrieved from Chris Rae's VBA Code Archive - http://chrisrae.com/vba
' Code written by Chris Rae, 25/5/00
' Originally published by R. B. Smissaert.
' Additional credits to Bob Phillips, Rick Rothstein, and Thomas Eyde on VB2TheMax
Dim ptr As Long
Dim vType As Integer
Const VT_BYREF = &H4000&
'get the real VarType of the argument
'this is similar to VarType(), but returns also the VT_BYREF bit
CopyMemory vType, arr, 2
'exit if not an array
If (vType And vbArray) = 0 Then
ArrayDimensions = -1
Exit Function
End If
'get the address of the SAFEARRAY descriptor
'this is stored in the second half of the
'Variant parameter that has received the array
CopyMemory ptr, ByVal VarPtr(arr) + 8, 4
'see whether the routine was passed a Variant
'that contains an array, rather than directly an array
'in the former case ptr already points to the SA structure.
'Thanks to Monte Hansen for this fix
If (vType And VT_BYREF) Then
' ptr is a pointer to a pointer
CopyMemory ptr, ByVal ptr, 4
End If
'get the address of the SAFEARRAY structure
'this is stored in the descriptor
'get the first word of the SAFEARRAY structure
'which holds the number of dimensions
'...but first check that saAddr is non-zero, otherwise
'this routine bombs when the array is uninitialized
If ptr Then
CopyMemory ArrayDimensions, ByVal ptr, 2
End If
End Function
Also: I would advise you to keep that declaration private. If you must make it a public Sub in another module, insert the Option Private Module
statement in the module header. You really don't want your users calling any function with CopyMemoryoperations and pointer arithmetic.
a core dump is usually only made when the Windows kernel crashes (aka blue screen). A servicecrash will most of the times only leave some logging behind (in the event viewer probably).
If it is the bluescreen crash dump you are looking for, look in C:\Windows\Minidump or C:\windows\MEMORY.DMP
Creating an sqlite connection to a file on disk is left as an exercise for the reader ... but there is now a two-liner made possible by the pandas library
df = pandas.read_csv(csvfile)
df.to_sql(table_name, conn, if_exists='append', index=False)
My guess is that the webpage is listening to mousedown rather than click (which is bad for accessibility because when a user uses the keyboard, only focus and click are fired, not mousedown). So you should simulate mousedown, click, and mouseup (which, by the way, is what the iPhone, iPod Touch, and iPad do on tap events).
To simulate the mouse events, you can use this snippet for browsers that support DOM 2 Events. For a more foolproof simulation, fill in the mouse position using initMouseEvent
instead.
// DOM 2 Events
var dispatchMouseEvent = function(target, var_args) {
var e = document.createEvent("MouseEvents");
// If you need clientX, clientY, etc., you can call
// initMouseEvent instead of initEvent
e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
dispatchMouseEvent(element, 'mouseover', true, true);
dispatchMouseEvent(element, 'mousedown', true, true);
dispatchMouseEvent(element, 'click', true, true);
dispatchMouseEvent(element, 'mouseup', true, true);
When you fire a simulated click event, the browser will actually fire the default action (e.g. navigate to the link's href, or submit a form).
In IE, the equivalent snippet is this (unverified since I don't have IE). I don't think you can give the event handler mouse positions.
// IE 5.5+
element.fireEvent("onmouseover");
element.fireEvent("onmousedown");
element.fireEvent("onclick"); // or element.click()
element.fireEvent("onmouseup");
You can simulate keydown and keypress events, but unfortunately in Chrome they only fire the event handlers and don't perform any of the default actions. I think this is because the DOM 3 Events working draft describes this funky order of key events:
This means that you have to (while combing the HTML5 and DOM 3 Events drafts) simulate a large amount of what the browser would otherwise do. I hate it when I have to do that. For example, this is roughly how to simulate a key press on an input or textarea.
// DOM 3 Events
var dispatchKeyboardEvent = function(target, initKeyboradEvent_args) {
var e = document.createEvent("KeyboardEvents");
e.initKeyboardEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
var dispatchTextEvent = function(target, initTextEvent_args) {
var e = document.createEvent("TextEvent");
e.initTextEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
var dispatchSimpleEvent = function(target, type, canBubble, cancelable) {
var e = document.createEvent("Event");
e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
var canceled = !dispatchKeyboardEvent(element,
'keydown', true, true, // type, bubbles, cancelable
null, // window
'h', // key
0, // location: 0=standard, 1=left, 2=right, 3=numpad, 4=mobile, 5=joystick
''); // space-sparated Shift, Control, Alt, etc.
dispatchKeyboardEvent(
element, 'keypress', true, true, null, 'h', 0, '');
if (!canceled) {
if (dispatchTextEvent(element, 'textInput', true, true, null, 'h', 0)) {
element.value += 'h';
dispatchSimpleEvent(element, 'input', false, false);
// not supported in Chrome yet
// if (element.form) element.form.dispatchFormInput();
dispatchSimpleEvent(element, 'change', false, false);
// not supported in Chrome yet
// if (element.form) element.form.dispatchFormChange();
}
}
dispatchKeyboardEvent(
element, 'keyup', true, true, null, 'h', 0, '');
I don't think it is possible to simulate key events in IE.
Just recreate the Path variable in users. Go to user variables, highlight path, then new, the type in value. Look on another computer with same version windows. Usually it is in windows 10: Path %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;
You'd have to define alphanumerics exactly, but
/^(\w{3,5})$/
Should match any digit/character/_ combination of length 3-5.
If you also need the dash, make sure to escape it ( add it, like this: :\-
)
/^([\w\-]{3,5})$/
Also: the ^
anchor means that the sequence has to start at the beginning of the line (character string), and the $
that it ends at the end of the line (character string). So your value
string mustn't contain anything else, or it won't match.
You should use the grep
-q
flag for quiet output. See the man pages below:
man grep output :
General Output Control
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immediately with zero status
if any match is found, even if an error was detected. Also see the -s or
--no-messages option. (-q is specified by POSIX.)
This KornShell (ksh) script demos the grep
quiet output and is a solution to your question.
grepUtil.ksh :
#!/bin/ksh
#Initialize Variables
file=poet.txt
var=""
dir=tempDir
dirPath="/"${dir}"/"
searchString="poet"
#Function to initialize variables
initialize(){
echo "Entering initialize"
echo "Exiting initialize"
}
#Function to create File with Input
#Params: 1}Directory 2}File 3}String to write to FileName
createFileWithInput(){
echo "Entering createFileWithInput"
orgDirectory=${PWD}
cd ${1}
> ${2}
print ${3} >> ${2}
cd ${orgDirectory}
echo "Exiting createFileWithInput"
}
#Function to create File with Input
#Params: 1}directoryName
createDir(){
echo "Entering createDir"
mkdir -p ${1}
echo "Exiting createDir"
}
#Params: 1}FileName
readLine(){
echo "Entering readLine"
file=${1}
while read line
do
#assign last line to var
var="$line"
done <"$file"
echo "Exiting readLine"
}
#Check if file exists
#Params: 1}File
doesFileExit(){
echo "Entering doesFileExit"
orgDirectory=${PWD}
cd ${PWD}${dirPath}
#echo ${PWD}
if [[ -e "${1}" ]]; then
echo "${1} exists"
else
echo "${1} does not exist"
fi
cd ${orgDirectory}
echo "Exiting doesFileExit"
}
#Check if file contains a string quietly
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainStringQuiet(){
echo "Entering doesFileContainStringQuiet"
orgDirectory=${PWD}
cd ${PWD}${1}
#echo ${PWD}
grep -q ${3} ${2}
if [ ${?} -eq 0 ];then
echo "${3} found in ${2}"
else
echo "${3} not found in ${2}"
fi
cd ${orgDirectory}
echo "Exiting doesFileContainStringQuiet"
}
#Check if file contains a string with output
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainString(){
echo "Entering doesFileContainString"
orgDirectory=${PWD}
cd ${PWD}${1}
#echo ${PWD}
grep ${3} ${2}
if [ ${?} -eq 0 ];then
echo "${3} found in ${2}"
else
echo "${3} not found in ${2}"
fi
cd ${orgDirectory}
echo "Exiting doesFileContainString"
}
#-----------
#---Main----
#-----------
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
#initialize #function call#
createDir ${dir} #function call#
createFileWithInput ${dir} ${file} ${searchString} #function call#
doesFileExit ${file} #function call#
if [ ${?} -eq 0 ];then
doesFileContainStringQuiet ${dirPath} ${file} ${searchString} #function call#
doesFileContainString ${dirPath} ${file} ${searchString} #function call#
fi
echo "Exiting: ${PWD}/${0}"
grepUtil.ksh Output :
user@foo /tmp
$ ksh grepUtil.ksh
Starting: /tmp/grepUtil.ksh with Input Parameters: {1: {2: {3:
Entering createDir
Exiting createDir
Entering createFileWithInput
Exiting createFileWithInput
Entering doesFileExit
poet.txt exists
Exiting doesFileExit
Entering doesFileContainStringQuiet
poet found in poet.txt
Exiting doesFileContainStringQuiet
Entering doesFileContainString
poet
poet found in poet.txt
Exiting doesFileContainString
Exiting: /tmp/grepUtil.ksh
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
If you know that they are just 0
and 1
:
np.sum(y)
gives you the number of ones. np.sum(1-y)
gives the zeroes.
For slight generality, if you want to count 0
and not zero (but possibly 2 or 3):
np.count_nonzero(y)
gives the number of nonzero.
But if you need something more complicated, I don't think numpy will provide a nice count
option. In that case, go to collections:
import collections
collections.Counter(y)
> Counter({0: 8, 1: 4})
This behaves like a dict
collections.Counter(y)[0]
> 8
I have toyed with this for forever, and finally found something that seems to always work!
textField = new JTextField() {
public void addNotify() {
super.addNotify();
requestFocus();
}
};
Have a look to this wiki: LaTeX/Labels and Cross-referencing:
The hyperref package automatically includes the nameref package, and a similarly named command. It inserts text corresponding to the section name, for example:
\section{MyFirstSection}
\label{marker}
\section{MySecondSection} In section \nameref{marker} we defined...
Let's say we want to apply a function add5 to columns 'a' and 'b' of DataFrame df
def add5(x):
return x+5
df[['a', 'b']].apply(add5)
Assuming you already know lists are of equal size, the following will guarantee True if and only if two vectors are exactly the same (including order)
functools.reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, listA, ListB), True)
Example:
>>> from functools import reduce
>>> def compvecs(a,b):
... return reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, a, b), True)
...
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compvecs(a=[1,2,3,4], b=[1,2,3,4])
True
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compare_vectors(a=[1,2,3,4], b=[1,2,2,4])
False
>>>
A possibility is to have an iframe inside the outer form. The iframe contains the inner form. Make sure to use the <base target="_parent" />
tag inside the head tag of the iframe to make the form behave as part of the main page.
In addition to @Greg Bacon answer, in case binary files were added to the index and were part of the stash using
git stash show -p | git apply --reverse
may result in
error: cannot apply binary patch to '<YOUR_NEW_FILE>' without full index line
error: <YOUR_NEW_FILE>: patch does not apply
Adding --binary
resolves the issue, but unfortunately haven't figured out why yet.
git stash show -p --binary | git apply --reverse
Please find below codes for ios 10 request permission sample for info.plist
.
You can modify for your custom message.
<key>NSCameraUsageDescription</key>
<string>${PRODUCT_NAME} Camera Usage</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>${PRODUCT_NAME} BluetoothPeripheral</string>
<key>NSCalendarsUsageDescription</key>
<string>${PRODUCT_NAME} Calendar Usage</string>
<key>NSContactsUsageDescription</key>
<string>${PRODUCT_NAME} Contact fetch</string>
<key>NSHealthShareUsageDescription</key>
<string>${PRODUCT_NAME} Health Description</string>
<key>NSHealthUpdateUsageDescription</key>
<string>${PRODUCT_NAME} Health Updates</string>
<key>NSHomeKitUsageDescription</key>
<string>${PRODUCT_NAME} HomeKit Usage</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} Use location always</string>
<key>NSLocationUsageDescription</key>
<string>${PRODUCT_NAME} Location Updates</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>${PRODUCT_NAME} WhenInUse Location</string>
<key>NSAppleMusicUsageDescription</key>
<string>${PRODUCT_NAME} Music Usage</string>
<key>NSMicrophoneUsageDescription</key>
<string>${PRODUCT_NAME} Microphone Usage</string>
<key>NSMotionUsageDescription</key>
<string>${PRODUCT_NAME} Motion Usage</string>
<key>kTCCServiceMediaLibrary</key>
<string>${PRODUCT_NAME} MediaLibrary Usage</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>${PRODUCT_NAME} PhotoLibrary Usage</string>
<key>NSRemindersUsageDescription</key>
<string>${PRODUCT_NAME} Reminder Usage</string>
<key>NSSiriUsageDescription</key>
<string>${PRODUCT_NAME} Siri Usage</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>${PRODUCT_NAME} Speech Recognition Usage</string>
<key>NSVideoSubscriberAccountUsageDescription</key>
<string>${PRODUCT_NAME} Video Subscribe Usage</string>
iOS 11 and plus, If you want to add photo/image to your library then you must add this key
<key>NSPhotoLibraryAddUsageDescription</key>
<string>${PRODUCT_NAME} library Usage</string>
Either you need to use a method which uses a predicate indicating whether to keep going (so it has the break instead) or you need to throw an exception - which is a very ugly approach, of course.
So you could write a forEachConditional
method like this:
public static <T> void forEachConditional(Iterable<T> source,
Predicate<T> action) {
for (T item : source) {
if (!action.test(item)) {
break;
}
}
}
Rather than Predicate<T>
, you might want to define your own functional interface with the same general method (something taking a T
and returning a bool
) but with names that indicate the expectation more clearly - Predicate<T>
isn't ideal here.
With iOS 7+, static Launch Images are now deprecated.
You should create a custom view that composes slices of images, which sizes to all screens like a normal UIViewController view.
Capture the onContextMenu
event, and return false in the event handler.
You can also capture the click event and check which mouse button fired the event with event.button
, in some browsers anyway.
do it all in one line without 3rd party libraries or complicated solutions. Here is how
let myVariable = new URLSearchParams(history.location.search).get('business');
the only thing you need to change is the word 'business' with your own param name.
example url.com?business=hello
the result of myVariable will be hello
This is an experiment in necromancy :-)
Most answers compare performance and API differences. They miss the fundamental point that the two operations simply have different semantics.
Your intuition is correct. x.equals(y) is not interchangeable with x.compareTo(y) == 0. The first compares identity, while the other compares the notion of 'size'. It is true that in many cases, especially with primitive types, these two co-align.
The general case is this:
If x and y are identical, they share the same 'size': if x.equals(y) is true => x.compareTo(y) is 0.
However, if x and y share the same size, it does not mean they are identical.
if x.compareTo(y) is 0 does not necessarily mean x.equals(y) is true.
A compelling example where identity differs from size would be complex numbers. Assume that the comparison is done by their absolute value. So given two complex numbers: Z1 = a1 + b1*i and Z2 = a2 + b2*i:
Z1.equals(z2) returns true if and only if a1 = a2 and b1 = b2.
However Z1.compareTo(Z2) returns 0 for and infinite number of (a1,b1) and (a2,b2) pairs as long as they satisfy the condition a1^2 + b1^2 == a2^2 + b2^2.
I'm sorry, I still yet cant comment, so to answer Tom's answer... In javascript (undefined != null) == false In fact that function wont work with "null", you should use "undefined"
you can achieve this by using below in the commandline itself
-e for error_x000D_
-X for debug_x000D_
-q for only error
_x000D_
e.g :
mvn test -X -DsomeProperties='SomeValue' [For Debug level Logs]_x000D_
mvn test -e -DsomeProperties='SomeValue' [For Error level Logs]_x000D_
mvn test -q -DsomeProperties='SomeValue' [For Only Error Logs]
_x000D_
Try to run xcrun simctl delete unavailable
in your terminal.
Original answer: Xcode - free to clear devices folder?
Sub SelectAllCellsInSheet(SheetName As String)
lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub
To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)
There is an example at the end of the csv module documentation that demonstrates how to deal with Unicode. Below is copied directly from that example. Note that the strings read or written will be Unicode strings. Don't pass a byte string to UnicodeWriter.writerows
, for example.
import csv,codecs,cStringIO
class UTF8Recoder:
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader:
def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
'''next() -> unicode
This function reads and returns the next line as a Unicode string.
'''
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
class UnicodeWriter:
def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
'''writerow(unicode) -> None
This function takes a Unicode string and encodes it to the output.
'''
self.writer.writerow([s.encode("utf-8") for s in row])
data = self.queue.getvalue()
data = data.decode("utf-8")
data = self.encoder.encode(data)
self.stream.write(data)
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
with open('xxx.csv','rb') as fin, open('lll.csv','wb') as fout:
reader = UnicodeReader(fin)
writer = UnicodeWriter(fout,quoting=csv.QUOTE_ALL)
for line in reader:
writer.writerow(line)
Input (UTF-8 encoded):
American,???
French,???
German,???
Output:
"American","???"
"French","???"
"German","???"
It sounds like the admin has locked the "authentication" node of the web.config, which one can do in the global web.config pretty easily. Or, in a nutshell, this is working as designed.
When having a column defined with "NOT NULL DEFAULT CURRENT_TIMESTAMP
," inserted records will always get set with UTC/GMT time.
Here's what I did to avoid having to include the time in my INSERT/UPDATE statements:
--Create a table having a CURRENT_TIMESTAMP:
CREATE TABLE FOOBAR (
RECORD_NO INTEGER NOT NULL,
TO_STORE INTEGER,
UPC CHAR(30),
QTY DECIMAL(15,4),
EID CHAR(16),
RECORD_TIME NOT NULL DEFAULT CURRENT_TIMESTAMP)
--Create before update and after insert triggers:
CREATE TRIGGER UPDATE_FOOBAR BEFORE UPDATE ON FOOBAR
BEGIN
UPDATE FOOBAR SET record_time = datetime('now', 'localtime')
WHERE rowid = new.rowid;
END
CREATE TRIGGER INSERT_FOOBAR AFTER INSERT ON FOOBAR
BEGIN
UPDATE FOOBAR SET record_time = datetime('now', 'localtime')
WHERE rowid = new.rowid;
END
Test to see if it works...
--INSERT a couple records into the table:
INSERT INTO foobar (RECORD_NO, TO_STORE, UPC, PRICE, EID)
VALUES (0, 1, 'xyz1', 31, '777')
INSERT INTO foobar (RECORD_NO, TO_STORE, UPC, PRICE, EID)
VALUES (1, 1, 'xyz2', 32, '777')
--UPDATE one of the records:
UPDATE foobar SET price = 29 WHERE upc = 'xyz2'
--Check the results:
SELECT * FROM foobar
Hope that helps.
The simplest way to get tooltips in most browsers is to set some text in the title attribute.
eg.
<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />
produces (hover your mouse over the image):
a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg
Title attributes can be applied to most HTML elements.
After many answers that did not work, I finally found a solution when Anonymous access is Disabled on the IIS server. Our server is using Windows authentication, not Kerberos. This is thanks to this blog posting.
No changes were made to web.config.
On the server side, the .SVC file in the ISAPI folder uses MultipleBaseAddressBasicHttpBindingServiceHostFactory
The class attributes of the service are:
[BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class InvoiceServices : IInvoiceServices
{
...
}
On the client side, the key that made it work was the http binding security attributes:
EndpointAddress endpoint =
new EndpointAddress(new Uri("http://SharePointserver/_vti_bin/InvoiceServices.svc"));
BasicHttpBinding httpBinding = new BasicHttpBinding();
httpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
InvoiceServicesClient myClient = new InvoiceServicesClient(httpBinding, endpoint);
myClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
(call service)
I hope this works for you!
ListView was intended for simple use cases like the same static view for all row items.
Since you have to create ViewHolders and make significant use of getItemViewType()
, and dynamically show different row item layout xml's, you should try doing that using the RecyclerView, which is available in Android API 22. It offers better support and structure for multiple view types.
Check out this tutorial on how to use the RecyclerView to do what you are looking for.
I tried renaming my build configuration Release
to Production
, but apparently cocoa pods doesn't like it. I renamed it again to Release
, and everything builds just fine.
Try this (see ?detach
for more details):
detach("package:vegan", unload=TRUE)
It is possible to have multiple versions of a package loaded at once (for example, if you have a development version and a stable version in different libraries). To guarantee that all copies are detached, use this function.
detach_package <- function(pkg, character.only = FALSE)
{
if(!character.only)
{
pkg <- deparse(substitute(pkg))
}
search_item <- paste("package", pkg, sep = ":")
while(search_item %in% search())
{
detach(search_item, unload = TRUE, character.only = TRUE)
}
}
Usage is, for example
detach_package(vegan)
or
detach_package("vegan", TRUE)
After an hour or two of trying every combination of ui-view autoscroll=true
, $stateChangeStart
, $locationChangeStart
, $uiViewScrollProvider.useAnchorScroll()
, $provide('$uiViewScroll', ...)
, and many others, I couldn't get scroll-to-top-on-new-page to work as expected.
This was ultimately what worked for me. It captures pushState and replaceState and only updates scroll position when new pages are navigated to (back/forward button retain their scroll positions):
.run(function($anchorScroll, $window) {
// hack to scroll to top when navigating to new URLS but not back/forward
var wrap = function(method) {
var orig = $window.window.history[method];
$window.window.history[method] = function() {
var retval = orig.apply(this, Array.prototype.slice.call(arguments));
$anchorScroll();
return retval;
};
};
wrap('pushState');
wrap('replaceState');
})
you can also use DataFrame.head(x)
/ .tail(x)
to display the first / last x rows of the DataFrame.
Add an input id to the element and do something like that:
document.getElementById('inputId').value.split(/[\\$]/).pop()
To gain access for other users to your local machine, i usually use ngrok. Ngrok exposes your localhost to the web, and has an NPM wrapper that is simple to install and start:
$ npm install ngrok -g
$ ngrok http 3000
See this example usage:
In the above example, the locally running instance of sails at: localhost:3000 is now available on the Internet served at: http://69f8f0ee.ngrok.io or https://69f8f0ee.ngrok.io
Use the following:
type file.txt | findstr /v ERROR | findstr /v REFERENCE
This has the advantage of using standard tools in the Windows OS, rather than having to find and install sed/awk/perl and such.
See the following transcript for it in operation:
C:\>type file.txt Good Line of data bad line of C:\Directory\ERROR\myFile.dll Another good line of data bad line: REFERENCE Good line C:\>type file.txt | findstr /v ERROR | findstr /v REFERENCE Good Line of data Another good line of data Good line
It Worked for me: For Current Date
$date = date('Y-m-d', strtotime("+1 day"));
for anydate:
date('Y-m-d', strtotime("+1 day", strtotime($date)));
Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.
' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit
Private Type FourBytes
A As Byte
B As Byte
C As Byte
D As Byte
End Type
Private Type OneLong
L As Long
End Type
Function HexDefaultSHA1(Message() As Byte) As String
Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
DefaultSHA1 Message, H1, H2, H3, H4, H5
HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function
Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function
Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub
Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
'"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
Dim U As Long, P As Long
Dim FB As FourBytes, OL As OneLong
Dim i As Integer
Dim W(80) As Long
Dim A As Long, B As Long, C As Long, D As Long, E As Long
Dim T As Long
H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0
U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)
ReDim Preserve Message(0 To (U + 8 And -64) + 63)
Message(U) = 128
U = UBound(Message)
Message(U - 4) = A
Message(U - 3) = FB.D
Message(U - 2) = FB.C
Message(U - 1) = FB.B
Message(U) = FB.A
While P < U
For i = 0 To 15
FB.D = Message(P)
FB.C = Message(P + 1)
FB.B = Message(P + 2)
FB.A = Message(P + 3)
LSet OL = FB
W(i) = OL.L
P = P + 4
Next i
For i = 16 To 79
W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
Next i
A = H1: B = H2: C = H3: D = H4: E = H5
For i = 0 To 19
T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
Next i
For i = 20 To 39
T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
Next i
For i = 40 To 59
T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
Next i
For i = 60 To 79
T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
Next i
H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
Wend
End Sub
Function U32Add(ByVal A As Long, ByVal B As Long) As Long
If (A Xor B) < 0 Then
U32Add = A + B
Else
U32Add = (A Xor &H80000000) + B Xor &H80000000
End If
End Function
Function U32ShiftLeft3(ByVal A As Long) As Long
U32ShiftLeft3 = (A And &HFFFFFFF) * 8
If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function
Function U32ShiftRight29(ByVal A As Long) As Long
U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function
Function U32RotateLeft1(ByVal A As Long) As Long
U32RotateLeft1 = (A And &H3FFFFFFF) * 2
If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function
Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
Dim H As String, L As Long
DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function
' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog
Public Function SHA1HASH(str)
Dim i As Integer
Dim arr() As Byte
ReDim arr(0 To Len(str) - 1) As Byte
For i = 0 To Len(str) - 1
arr(i) = Asc(Mid(str, i + 1, 1))
Next i
SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function
Here you can find the direct download link for Curl.exe
I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just
unzip it and then go to bin folder there you get exe file
I assume "direction" is "ASC" or "DESC" and dt contains a column named "colName"
public static DataTable resort(DataTable dt, string colName, string direction)
{
DataTable dtOut = null;
dt.DefaultView.Sort = colName + " " + direction;
dtOut = dt.DefaultView.ToTable();
return dtOut;
}
OR without creating dtOut
public static DataTable resort(DataTable dt, string colName, string direction)
{
dt.DefaultView.Sort = colName + " " + direction;
dt = dt.DefaultView.ToTable();
return dt;
}
Create a group object and call methods like below example:
grp = df.groupby(['col1', 'col2', 'col3'])
grp.max()
grp.mean()
grp.describe()
When I click 'save' button, it has this error. Based on the answers in this post and other websites, I just found the solution. My jupyter notebook is installed from pip. So I access it by typing 'jupyter notebook' in the windows command line.
(1) open a new command window, then open a new jupyter notebook. try to save again in the old notebook, this time ,the error is 'fail: forbidden'
(2) Then in the old notebook, click 'download as', it will pop out a new windows ask you the token.
(3) open another command window, then open another jupyter notebook, type 'jupyter notebook list' copy the code after 'token=' and before :: to the box you just saw. You can save this time. If it fails, you can try another token in the list
See A comparison of the C++ casting operators.
However, using the same syntax for a variety of different casting operations can make the intent of the programmer unclear.
Furthermore, it can be difficult to find a specific type of cast in a large codebase.
the generality of the C-style cast can be overkill for situations where all that is needed is a simple conversion. The ability to select between several different casting operators of differing degrees of power can prevent programmers from inadvertently casting to an incorrect type.
style="position:absolute"
Stefan Brinkmann's answer is excellent, but incomplete for beginners (omits the variable assignment). Just to clarify:
// this structure is called a ternary operator
var cbAns = ( $("#ans").is(':checked') ) ? 1 : 0;
It works like this:
var myVar = ( if test goes here ) ? 'ans if yes' : 'ans if no' ;
Example:
var myMath = ( 1 > 2 ) ? 'yes' : 'no' ;
alert( myMath );
Alerts 'no'
If this is helpful, please upvote Stefan Brinkmann's answer.
Fixed with downgrading Node from v12.8.1 to v11.15.0 and everything installed successfully
In plain english a callback is a promise. Joe, Jane, David and Samantha share a carpool to work. Joe is driving today. Jane, David and Samantha have a couple of options:
Option 1: This is more like a polling example where Jane would be stuck in a "loop" checking if Joe is outside. Jane can't do anything else in the mean time.
Option 2: This is the callback example. Jane tells Joe to ring her doorbell when he's outside. She gives him a "function" to ring the door bell. Joe does not need to know how the door bell works or where it is, he just needs to call that function i.e. ring the door bell when he's there.
Callbacks are driven by "events". In this example the "event" is Joe's arrival. In Ajax for example events can be "success" or "failure" of the asynchronous request and each can have the same or different callbacks.
In terms of JavaScript applications and callbacks. We also need to understand "closures" and application context. What "this" refers to can easily confuse JavaScript developers. In this example within each person's "ring_the_door_bell()" method/callback there might be some other methods that each person need to do based on their morning routine ex. "turn_off_the_tv()". We would want "this" to refer to the "Jane" object or the "David" object so that each can setup whatever else they need done before Joe picks them up. This is where setting up the callback with Joe requires parodying the method so that "this" refers to the right object.
Hope that helps!
cat 1.txt | xargs rm -f | bash
Run the command will do the following for files only.
cat 1.txt | xargs rm -rf | bash
Run the command will do the following recursive behaviour.
<table >
<thead >
<tr>
<th>No</th><th>ID</th><th>Name</th><th>Ip</th><th>Save</th>
</tr>
</thead>
<tbody id="table_data">
<tr>
<td>
<form method="POST" autocomplete="off" id="myForm_207" action="save.php">
<input type="hidden" name="pvm" value="207">
<input type="hidden" name="customer_records_id" value="2">
<input type="hidden" name="name_207" id="name_207" value="BURÇIN MERYEM ONUK">
<input type="hidden" name="ip_207" id="ip_207" value="89.19.24.118">
</form>
1
</td>
<td>
207
</td>
<td>
<input type="text" id="nameg_207" value="BURÇIN MERYEM ONUK">
</td>
<td>
<input type="text" id="ipg_207" value="89.19.24.118">
</td>
<td>
<button type="button" name="Kaydet_207" class="searchButton" onclick="postData('myForm_207','207')">SAVE</button>
</td>
</tr>
<tr>
<td>
<form method="POST" autocomplete="off" id="myForm_209" action="save.php">
<input type="hidden" name="pvm" value="209">
<input type="hidden" name="customer_records_id" value="2">
<input type="hidden" name="name_209" id="name_209" value="BALA BASAK KAN">
<input type="hidden" name="ip_209" id="ip_209" value="217.17.159.22">
</form>
2
</td>
<td>
209
</td>
<td>
<input type="text" id="nameg_209" value="BALA BASAK KAN">
</td>
<td>
<input type="text" id="ipg_209" value="217.17.159.22">
</td>
<td>
<button type="button" name="Kaydet_209" class="searchButton" onclick="postData('myForm_209','209')">SAVE</button>
</td>
</tr>
</tbody>
</table>
<script>
function postData(formId,keyy){
//alert(document.getElementById(formId).length);
//alert(document.getElementById('name_'+keyy).value);
document.getElementById('name_'+keyy).value=document.getElementById('nameg_'+keyy).value;
document.getElementById('ip_'+keyy).value=document.getElementById('ipg_'+keyy).value;
//alert(document.getElementById('name_'+keyy).value);
document.getElementById(formId).submit();
}
</script>
The easiest way I've found for a global association is simply to ctrl+k m (or ctrl+shift+p and type "change language mode") with a file of the type you're associating open.
In the first selections will be "Configure File Association for 'x' " (whatever file type - see image attached) Selecting this makes the filetype association permanent
This may have changed (probably did) since the original question and accepted answer (and I don't know when it changed) but it's so much easier than the manual editing steps in the accepted and some of the other answers, and totaly avoids having to muss with IDs that may not be obvious.
Register the EventEmitter
in your child component as the @Output
:
@Output() onDatePicked = new EventEmitter<any>();
Emit value on click:
public pickDate(date: any): void {
this.onDatePicked.emit(date);
}
Listen for the events in your parent component's template:
<div>
<calendar (onDatePicked)="doSomething($event)"></calendar>
</div>
and in the parent component:
public doSomething(date: any):void {
console.log('Picked date: ', date);
}
It's also well explained in the official docs: Component interaction.
Inci framework you can do download like so:
function clubDownload($clubname)
{
$this->load->library("excel");
$object = new PHPExcel();
$object->setActiveSheetIndex(0);
$this->load->model('Members_student_model');
$query = $this->db->query("SELECT * FROM student WHERE $clubname!='' order by id desc");
$resultdatanew=$query->result_array();
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 1;
$object->getActiveSheet()->getStyle("A1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("B1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("C1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("D1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("E1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("F1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("G1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("H1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("I1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$headerStyle = array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb'=>'CCE5FF'),
),
'font' => array(
'bold' => true,
)
);
$object->getActiveSheet()->getStyle('A1:'.'I1')->applyFromArray($headerStyle);
$table_columns = array("id", "studentid", "passport", "lastname", "firstname","university","commencing",$clubname,"added_date");
$column = 0;
foreach($table_columns as $field)
{
$object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
$column++;
}
$excel_row = 2;
foreach($resultdatanew as $row)
{
$id=$row['id'];
$studentid=$row['studentid'];
$passport=$row['passport'];
$lastname=$row['last_name'];
$firstname=$row['first_name'];
$passport=$row['university'];
$commencing=$row['commencing'];
$email_id=$row['email_id'];
$added_date=$row['added_date'];
$object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$id);
$object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $studentid);
$object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $passport);
$object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $lastname);
$object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $firstname);
$object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $passport);
$object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $commencing);
$object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, $email_id);
$object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $added_date);
$excel_row++;
}
$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="club' .$clubname.'-'.date('Y-m-d') . '.xls');
$object_writer->save('php://output');
if you use your website in the same network as the server IE likes to switch to compability mode despite DOCTYPE.
Adding meta http-equiv="X-UA-Compatible" content="IE=Edge"
disables this unwanted behaviour.
For Visual Studio Users, On Package Manager console:
git branch | %{ git fetch upstream; git merge upstream/master}
As a sidenote to @Navaneethan 's answer, Jinja2
is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.
parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]
{% for dict_item in parent_dict %}
This example has {{dict_item['A']}} and {{dict_item['B']}}:
with the content --
{% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}
This example has val1 and val2:
with the content --
1.1 and 2.2.
This example has val3 and val4:
with the content --
3.3 and 4.4.
Really fast, really easy:
srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.
And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random
header to avoid that bias like so:
#include <random>
std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased
int r = gen(rng);
But you can also remove the bias in normal C++ like this:
int rangeRandomAlg2 (int min, int max){
int n = max - min + 1;
int remainder = RAND_MAX % n;
int x;
do{
x = rand();
}while (x >= RAND_MAX - remainder);
return min + x % n;
}
and that was gotten from this post.
Here's how to do this in Xamarin.ios.
public class NotificationUtils
{
public static bool AreNotificationsEnabled ()
{
var settings = UIApplication.SharedApplication.CurrentUserNotificationSettings;
var types = settings.Types;
return types != UIUserNotificationType.None;
}
}
If you are supporting iOS 10+ only go with the UNUserNotificationCenter method.
good review of several approaches:
Article copy -
Coalesce is not the answer to string concatentation in T-SQL I've seen many posts over the years about using the COALESCE function to get string concatenation working in T-SQL. This is one of the examples here (borrowed from Readifarian Marc Ridey).
DECLARE @categories varchar(200)
SET @categories = NULL
SELECT @categories = COALESCE(@categories + ',','') + Name
FROM Production.ProductCategory
SELECT @categories
This query can be quite effective, but care needs to be taken, and the use of COALESCE should be properly understood. COALESCE is the version of ISNULL which can take more than two parameters. It returns the first thing in the list of parameters which is not null. So really it has nothing to do with concatenation, and the following piece of code is exactly the same - without using COALESCE:
DECLARE @categories varchar(200)
SET @categories = ''
SELECT @categories = @categories + ',' + Name
FROM Production.ProductCategory
SELECT @categories
But the unordered nature of databases makes this unreliable. The whole reason why T-SQL doesn't (yet) have a concatenate function is that this is an aggregate for which the order of elements is important. Using this variable-assignment method of string concatenation, you may actually find that the answer that gets returned doesn't have all the values in it, particularly if you want the substrings put in a particular order. Consider the following, which on my machine only returns ',Accessories', when I wanted it to return ',Bikes,Clothing,Components,Accessories':
DECLARE @categories varchar(200)
SET @categories = NULL
SELECT @categories = COALESCE(@categories + ',','') + Name
FROM Production.ProductCategory
ORDER BY LEN(Name)
SELECT @categories
Far better is to use a method which does take order into consideration, and which has been included in SQL2005 specifically for the purpose of string concatenation - FOR XML PATH('')
SELECT ',' + Name
FROM Production.ProductCategory
ORDER BY LEN(Name)
FOR XML PATH('')
In the post I made recently comparing GROUP BY and DISTINCT when using subqueries, I demonstrated the use of FOR XML PATH(''). Have a look at this and you'll see how it works in a subquery. The 'STUFF' function is only there to remove the leading comma.
USE tempdb;
GO
CREATE TABLE t1 (id INT, NAME VARCHAR(MAX));
INSERT t1 values (1,'Jamie');
INSERT t1 values (1,'Joe');
INSERT t1 values (1,'John');
INSERT t1 values (2,'Sai');
INSERT t1 values (2,'Sam');
GO
select
id,
stuff((
select ',' + t.[name]
from t1 t
where t.id = t1.id
order by t.[name]
for xml path('')
),1,1,'') as name_csv
from t1
group by id
;
FOR XML PATH is one of the only situations in which you can use ORDER BY in a subquery. The other is TOP. And when you use an unnamed column and FOR XML PATH(''), you will get a straight concatenation, with no XML tags. This does mean that the strings will be HTML Encoded, so if you're concatenating strings which may have the < character (etc), then you should maybe fix that up afterwards, but either way, this is still the best way of concatenating strings in SQL Server 2005.
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
Google disallows automated access in their TOS, so if you accept their terms you would break them.
That said, I know of no lawsuit from Google against a scraper. Even Microsoft scraped Google, they powered their search engine Bing with it. They got caught in 2011 red handed :)
There are two options to scrape Google results:
1) Use their API
UPDATE 2020: Google has reprecated previous APIs (again) and has new prices and new limits. Now (https://developers.google.com/custom-search/v1/overview) you can query up to 10k results per day at 1,500 USD per month, more than that is not permitted and the results are not what they display in normal searches.
You can issue around 40 requests per hour You are limited to what they give you, it's not really useful if you want to track ranking positions or what a real user would see. That's something you are not allowed to gather.
If you want a higher amount of API requests you need to pay.
60 requests per hour cost 2000 USD per year, more queries require a custom deal.
2) Scrape the normal result pages
3) Alternatively use a scraping service (updated)
Values highlighted that I mean:
This probably really belongs as comments in several of the above posts, but I don't yet have the rep to do that, so here goes.
I think it is interesting that a lot of the pros and cons often cited for SOAP and REST have (IMO) very little to do with the actual values or limits of the two technologies. Probably the most cited pro for REST is that it is "light-weight" or tends to be more "human readable". At one level this is certainly true, REST does have a lower barrier to entry - there is less required structure than SOAP (though I agree with those who have said that good tooling is largely the answer here - too bad much of the SOAP tooling is pretty dreadful).
Beyond that initial entry cost however, I think the REST impression comes from a combination of the form of the request URLs and the complexity of the data exchanged by most REST services. REST tends to encourage simpler, more human readable request URLs and the data tends to be more digestable as well. To what extent however are these inherent to REST and to what extent are they merely accidental. The simpler URL structure is a direct result of the architecture - but it could be equally well applied to SOAP based services. The more digestable data is more likely to be a result of the lack of any defined structure. This means you'd better keep your data formats simple or you are going to be in for a lot of work. So here SOAP's additional structure, which should be a benefit is actually enabling sloppy design and that sloppy design then gets used as a dig against the technology.
So for use in the exchange of structured data between computer systems I'm not sure that REST is inherently better than SOAP (or visa-versa), they are just different. I think the comparison above of REST vs SOAP to dynamic vs. static typing is a good one. Where dyanmic languages tend to run in to trouble is in long term maintenance and upkeep of a system (and by long term I'm not talking a year or 2, I'm talking 5 or 10). It will be interesting to see if REST runs into the same challenges over time. I tend to think it will so if I were building a distributed, information processing system I would gravitate to SOAP as the communication mechanism (also because of the tranmission and application protocol layering and flexibility that it affords as has been mentioned above).
In other places though REST seems more appropriate. AJAX between the client and its server (regardless of payload) is one major example. I don't have much care for the longevity of this type of connection and ease of use and flexibility are at a premimum. Similarly if I needed quick access to some external service and I didn't think I was going to care about the maintainability of the interaction over time (again I'm assuming this is where REST is going to end up costing me more, one way or another), then I might choose REST just so I could get in and out quickly.
Anyway, they are both viable technologies and depending on what tradeoffs you want to make for a given application they can serve you well (or poorly).
Another way to look at it is to consider git rebase master
as:
Rebase the current branch on top of
master
Here , 'master
' is the upstream branch, and that explain why, during a rebase, ours
and theirs
are reversed.
If you want to change a foreign key without dropping it you can do:
ALTER TABLE child_table_name WITH CHECK ADD FOREIGN KEY(child_column_name)
REFERENCES parent_table_name (parent_column_name) ON DELETE CASCADE
use formtarget="_blank"
its working for me
<input type="button" onClick="parent.location='http://www.facebook.com/'" value="facebook" formtarget="_blank">
Browser compatibility: from caniuse.com
IE: 10+
| Edge: 12+
| Firefox: 4+
| Chrome: 15+
| Safari/iOS: 5.1+
| Android: 4+