As Abhishek Bedi points out in a comment, For iOS7 forward the best way to do this is:
//from API docs:
//- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);
[self.mapView showAnnotations:self.mapView.annotations animated:YES];
For my personal project (prior to iOS7) I simply added a category on the MKMapView class to encapsulate the "visible area" functionality for a very common operation: setting it to be able to see all the currently-loaded annotations on the MKMapView instance (this includes as many pins as you might have placed, as well as the user's location). the result was this:
.h file
#import <MapKit/MapKit.h>
@interface MKMapView (Extensions)
-(void)ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:(BOOL)animated;
-(void)ij_setVisibleRectToFitAnnotations:(NSArray *)annotations animated:(BOOL)animated;
@end
.m file
#import "MKMapView+Extensions.h"
@implementation MKMapView (Extensions)
/**
* Changes the currently visible portion of the map to a region that best fits all the currently loadded annotations on the map, and it optionally animates the change.
*
* @param animated is the change should be perfomed with an animation.
*/
-(void)ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:(BOOL)animated
{
MKMapView * mapView = self;
NSArray * annotations = mapView.annotations;
[self ij_setVisibleRectToFitAnnotations:annotations animated:animated];
}
/**
* Changes the currently visible portion of the map to a region that best fits the provided annotations array, and it optionally animates the change.
All elements from the array must conform to the <MKAnnotation> protocol in order to fetch the coordinates to compute the visible region of the map.
*
* @param annotations an array of elements conforming to the <MKAnnotation> protocol, holding the locations for which the visible portion of the map will be set.
* @param animated wether or not the change should be perfomed with an animation.
*/
-(void)ij_setVisibleRectToFitAnnotations:(NSArray *)annotations animated:(BOOL)animated
{
MKMapView * mapView = self;
MKMapRect r = MKMapRectNull;
for (id<MKAnnotation> a in annotations) {
ZAssert([a conformsToProtocol:@protocol(MKAnnotation)], @"ERROR: All elements of the array MUST conform to the MKAnnotation protocol. Element (%@) did not fulfill this requirement", a);
MKMapPoint p = MKMapPointForCoordinate(a.coordinate);
//MKMapRectUnion performs the union between 2 rects, returning a bigger rect containing both (or just one if the other is null). here we do it for rects without a size (points)
r = MKMapRectUnion(r, MKMapRectMake(p.x, p.y, 0, 0));
}
[mapView setVisibleMapRect:r animated:animated];
}
@end
As you can see, I've added 2 methods so far: one for setting the visible region of the map to the one that fits all currently-loaded annotations on the MKMapView instance, and another method to set it to any array of objects. So to set the mapView's visible region the code would then be as simple as:
//the mapView instance
[self.mapView ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:animated];
I hope it helps =)
You can also simply use the Rotate animation feature. That runs a specific animation, for a pre-determined amount of time, on an ImageView.
Animation rotate = AnimationUtils.loadAnimation([context], R.anim.rotate_picture);
splash.startAnimation(rotate);
Then create an animation XML file in your res/anim called rotate_picture with the content:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%">
</rotate>
</set>
Now unfortunately, this will only run it once. You'll need a loop somewhere to make it repeat the animation while it's waiting. I experimented a little bit and got my program stuck in infinite loops, so I'm not sure of the best way to that. EDIT: Christopher's answer provides the info on how to make it loop properly, so removing my bad suggestion about separate threads!
As I tussled with this, TryParse in 3.5 does have NumberStyles: The following code should also do the trick without Regex to ignore thousands seperator.
double.TryParse(length, NumberStyles.AllowDecimalPoint,CultureInfo.CurrentUICulture, out lengthD))
Not relevant to the original question asked but confirming that TryParse() indeed is a good option.
It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.
Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.
It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."
Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.
There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.
more example
I have configus.yml with flows files
"pattern":
- _(\d{14})_
"datetime_string":
- "%m%d%Y%H%M%f"
in python code I use
data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)
Depending on the location of your config file System.Reflection.Assembly.GetExecutingAssembly().Location
might do what you need.
Instead of returning POSITION_NONE
from getItemPosition()
and causing full view recreation, do this:
//call this method to update fragments in ViewPager dynamically
public void update(UpdateData xyzData) {
this.updateData = xyzData;
notifyDataSetChanged();
}
@Override
public int getItemPosition(Object object) {
if (object instanceof UpdateableFragment) {
((UpdateableFragment) object).update(updateData);
}
//don't return POSITION_NONE, avoid fragment recreation.
return super.getItemPosition(object);
}
Your fragments should implement UpdateableFragment
interface:
public class SomeFragment extends Fragment implements
UpdateableFragment{
@Override
public void update(UpdateData xyzData) {
// this method will be called for every fragment in viewpager
// so check if update is for this fragment
if(forMe(xyzData)) {
// do whatever you want to update your UI
}
}
}
and the interface:
public interface UpdateableFragment {
public void update(UpdateData xyzData);
}
Your data class:
public class UpdateData {
//whatever you want here
}
I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)
<meta name="304workaround" content="2013-10-24 21:17:23">
Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...
Now, 2017, you can do it easier with the new MSTest V2 Framework:
Assert.ThrowsException<Exception>(() => myClass.MyMethodWithError());
//async version
await Assert.ThrowsExceptionAsync<SomeException>(
() => myObject.SomeMethodAsync()
);
You can directly create your own style in this way:
input[type=button]
{
//Change the style as you like
}
You can use plt.subplots_adjust to change the spacing between the subplots Link
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
What's the usual way of actually running the tests
I use Python 3.6.2
cd new_project
pytest test/test_antigravity.py
To install pytest: sudo pip install pytest
I didn't set any path variable and my imports are not failing with the same "test" project structure.
I commented out this stuff: if __name__ == '__main__'
like this:
test_antigravity.py
import antigravity
class TestAntigravity(unittest.TestCase):
def test_something(self):
# ... test stuff here
# if __name__ == '__main__':
#
# if __package__ is None:
#
# import something
# sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
# from .. import antigravity
#
# else:
#
# from .. import antigravity
#
# unittest.main()
You can do that by storing cookies on client side.
If there will be no content after the row (whole screen height is taken), the trick with using position: fixed; height: 100%
for .col:before
element may work well:
header {_x000D_
background: green;_x000D_
height: 50px;_x000D_
}_x000D_
.col-xs-3 {_x000D_
background: pink;_x000D_
}_x000D_
.col-xs-3:before {_x000D_
background: pink;_x000D_
content: ' ';_x000D_
height: 100%;_x000D_
margin-left: -15px; /* compensates column's padding */_x000D_
position: fixed;_x000D_
width: inherit; /* bootstrap column's width */_x000D_
z-index: -1; /* puts behind content */_x000D_
}_x000D_
.col-xs-9 {_x000D_
background: yellow;_x000D_
}_x000D_
.col-xs-9:before {_x000D_
background: yellow;_x000D_
content: ' ';_x000D_
height: 100%;_x000D_
margin-left: -15px; /* compensates column's padding */_x000D_
position: fixed;_x000D_
width: inherit; /* bootstrap column's width */_x000D_
z-index: -1; /* puts behind content */_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<header>Header</header>_x000D_
<div class="container-fluid">_x000D_
<div class="row">_x000D_
<div class="col-xs-3">Navigation</div>_x000D_
<div class="col-xs-9">Content</div>_x000D_
</div>_x000D_
</div>
_x000D_
You can also use the sqldf package in R.
Z <- sqldf('SELECT DISTINCT tablename.columnname FROM tablename ')
$(document).ready(function(){_x000D_
$('.cliked').click(function() {_x000D_
$(".cliked").removeClass("liactive");_x000D_
$(this).addClass("liactive");_x000D_
});_x000D_
});
_x000D_
.liactive {_x000D_
background: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul_x000D_
className="sidebar-nav position-fixed "_x000D_
style="height:450px;overflow:scroll"_x000D_
>_x000D_
<li>_x000D_
<a className="cliked liactive" href="#">_x000D_
check Kyc Status_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My Investments_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My SIP_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My Tax Savers Fund_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Transaction History_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Invest Now_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My Profile_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
FAQ`s_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Suggestion Portfolio_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Bluk Lumpsum / Bulk SIP_x000D_
</a>_x000D_
</li>_x000D_
</ul>;
_x000D_
You're trying to access a 3 dimensional array with 4 de-references
You only need 3 loops instead of 4, or int myArray[10][10][10][10];
One recommendation I've gotten is Hex Fiend.
To simplify this actions from accepted answer, you can also create Category for UIView
(since this works for all subclasses of UIView, not only for textfields:
UIView+Additions.h:
#import <Foundation/Foundation.h>
@interface UIView (Additions)
- (void)setBorderForColor:(UIColor *)color
width:(float)width
radius:(float)radius;
@end
UIView+Additions.m:
#import "UIView+Additions.h"
@implementation UIView (Additions)
- (void)setBorderForColor:(UIColor *)color
width:(float)width
radius:(float)radius
{
self.layer.cornerRadius = radius;
self.layer.masksToBounds = YES;
self.layer.borderColor = [color CGColor];
self.layer.borderWidth = width;
}
@end
Usage:
#import "UIView+Additions.h"
//...
[textField setBorderForColor:[UIColor redColor]
width:1.0f
radius:8.0f];
It is a unicode char \u003C = <
If you know the text in the combo box that you want to select, just use the setCurrentText() method to select that item.
ui->comboBox->setCurrentText("choice 2");
From the Qt 5.7 documentation
The setter setCurrentText() simply calls setEditText() if the combo box is editable. Otherwise, if there is a matching text in the list, currentIndex is set to the corresponding index.
So as long as the combo box is not editable, the text specified in the function call will be selected in the combo box.
Reference: http://doc.qt.io/qt-5/qcombobox.html#currentText-prop
with this method, using SYSTEM_UI_FLAG_IMMERSIVE_STICKY the full screen come back with one tap without any implementation. Just copy past this method below and call it where you want in your activity. More details here
private void hideSystemUI() {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_IMMERSIVE
// Set the content to appear under the system bars so that the
// content doesn't resize when the system bars hide and show.
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// Hide the nav bar and status bar
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN);
}
BitConverter
class can be used to convert a byte[]
to string
.
var convertedString = BitConverter.ToString(byteAttay);
Documentation of BitConverter
class can be fount on MSDN
console.log(typeof json_data !== 'undefined'
? json_data.length : 'There is no spoon.');
...or more simply...
console.log(json_data ? json_data.length : 'json_data is null or undefined');
If you have setter and getter as private it will come up in PMD checks.
The fundamental issue with your code is that you mix two APIs. Unfortunately online resources are not great at pointing this out, but there are two semaphore APIs on UNIX-like systems:
Looking at the code above you used semget() from the System V API and tried to post through sem_post() which comes from the POSIX API. It is not possible to mix them.
To decide which semaphore API you want you don't have so many great resources. The simple best is the "Unix Network Programming" by Stevens. The section that you probably interested in is in Vol #2.
These two APIs are surprisingly different. Both support the textbook style semaphores but there are a few good and bad points in the System V API worth mentioning:
To answer one of the questions, it is necessary to have both a global and local install for the tools to work.
If you try to run ng serve
on an application without the local install of the CLI (global install only), you will get the following error.
You have to be inside an Angular CLI project in order to use the serve command.
It will also print this message:
Please take the following steps to avoid issues:
"npm install --save-dev @angular/cli@latest"
Run that npm
command to update the CLI locally, and avoid the warning that you are getting.
Other question: It looks like they do not have to be in sync, but it's probably best that they are in order to avoid any unusual behavior with the tool, or any inconsistencies with the code the tool generates.
Why do we need both the global install, and a local install?
The global install is needed to start a new application. The ng new <app-name>
command is run using the global installation of the CLI. In fact, if you try to run ng new
while inside the folder structure of an existing CLI application, you get this lovely error:
You cannot use the
new
command inside an Angular CLI project.
Other commands that can be run from the global install are ng help
, ng get/set
with the --global
option, ng version
, ng doc
, and ng completion
.
The local install of the CLI is used after an application has been built. This way, when new versions of the CLI are available, you can update your global install, and not affect the local install. This is good for the stability of a project. Most ng
commands only make sense with the local version, like lint
, build
and serve
, etc.
According to the CLI GitHub readme, to update the CLI you must update the global and local package. However, I have used the CLI where the global and local version vary without any trouble so far. If I ever run across an error related to having the global and local CLI versions out of sync, I will post that here.
You can do the following:
Load the data:
test <- read.csv(
"http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
header=FALSE)
Note that the default value of the header
argument for read.csv
is TRUE
so in order to get all lines you need to set it to FALSE
.
Add names to the different columns in the data.frame
names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")
or alternative and faster as I understand (not reloading the entire dataset):
colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")
can we do this using data annotations as I am using MVC4 razor ?
No, as I understand your question, unobtrusive validation will only show erorrs. The simplest way is use jquery plugin:
grep
will print any lines matching the pattern you provide. If you only want to print the part of the line that matches the pattern, you can pass the -o option:
-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
Like this:
echo 'Here is a line mentioning 99% somewhere' | grep -o '[0-9]+'
for (Map.Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
System.out.println( entry.getKey());
System.out.println( entry.getValue());//Returns the list of values
}
You can use .is(':visible')
Selects all elements that are visible.
For example:
if($('#selectDiv').is(':visible')){
Also, you can get the div which is visible by:
$('div:visible').callYourFunction();
Live example:
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
display: none; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
You need to return your promise to the calling function.
islogged:function(){
var cUid=sessionService.get('uid');
alert("in loginServce, cuid is "+cUid);
var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
$checkSessionServer.then(function(){
alert("session check returned!");
console.log("checkSessionServer is "+$checkSessionServer);
});
return $checkSessionServer; // <-- return your promise to the calling function
}
The MySQL function describe table should get you where you want to go (put your table name in for "table"). You'll have to parse the output some, but it's pretty easy. As I recall, if you execute that query, the PHP query result accessing functions that would normally give you a key-value pair will have the column names as the keys. But it's been a while since I used PHP so don't hold me to that. :)
function removeParam(parameter)
{
var url=document.location.href;
var urlparts= url.split('?');
if (urlparts.length>=2)
{
var urlBase=urlparts.shift();
var queryString=urlparts.join("?");
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;)
if (pars[i].lastIndexOf(prefix, 0)!==-1)
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .
}
return url;
}
This will resolve your problem
'\r'
is the carriage return character. The main times it would be useful are:
When reading text in binary mode, or which may come from a foreign OS, you'll find (and probably want to discard) it due to CR/LF line-endings from Windows-format text files.
When writing to an interactive terminal on stdout
or stderr
, '\r'
can be used to move the cursor back to the beginning of the line, to overwrite it with new contents. This makes a nice primitive progress indicator.
The example code in your post is definitely a wrong way to use '\r'
. It assumes a carriage return will precede the newline character at the end of a line entered, which is non-portable and only true on Windows. Instead the code should look for '\n'
(newline), and discard any carriage return it finds before the newline. Or, it could use text mode and have the C library handle the translation (but text mode is ugly and probably should not be used).
I've been searching for an IMAP solution for a while now, and after trying quite a few, I'm going with AE.Net.Mail.
You can download the code by going to the Code tab and click the small 'Download' icon. As the author does not provide any pre-built downloads, you must compile it yourself. (I believe you can get it through NuGet though). There is no longer a .dll in the bin/ folder.
There is no documentation, which I consider a downside, but I was able to whip this up by looking at the source code (yay for open source!) and using Intellisense. The below code connects specifically to Gmail's IMAP server:
// Connect to the IMAP server. The 'true' parameter specifies to use SSL
// which is important (for Gmail at least)
ImapClient ic = new ImapClient("imap.gmail.com", "[email protected]", "pass",
ImapClient.AuthMethods.Login, 993, true);
// Select a mailbox. Case-insensitive
ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());
// Get the first *11* messages. 0 is the first message;
// and it also includes the 10th message, which is really the eleventh ;)
// MailMessage represents, well, a message in your mailbox
MailMessage[] mm = ic.GetMessages(0, 10);
foreach (MailMessage m in mm)
{
Console.WriteLine(m.Subject);
}
// Probably wiser to use a using statement
ic.Dispose();
Make sure you checkout the Github page for the newest version and some better code examples.
You can use the IGNORE
keyword too, example:
update IGNORE table set primary_field = 'value'...............
I would use the SYLK file format if performing diffs is important. It is a text-based format, which should make the comparisons easier and more compact than a binary format. It is compatible with Excel, Gnumeric, and OpenOffice.org as well, so all three tools should be able to work well together. SYLK Wikipedia Article
to use unverified ssl you can add this to your code:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
Just use: (easy as pie)
double number = 651.5176515121351;
number = Math.round(number * 100);
number = number/100;
The output will be 651.52
The best solution we found was to team up with one of those intermediaries. Otherwise you will have to deal with a bunch of other requirements like PCI compliance. We use Verifone's IPCharge and it works quite well.
Mongodb and Mongoose are two completely different things!
Mongodb is the database itself, while Mongoose is an object modeling tool for Mongodb
EDIT: As pointed out MongoDB is the npm package, thanks!
Never mind, I found it in the docs:
-g/--globoff
This option switches off the "URL globbing parser". When you set this option, you can
specify URLs that contain the letters {}[] without having them being interpreted by curl
itself. Note that these letters are not normal legal URL contents but they should be
encoded according to the URI standard.
Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)
The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.
@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start the other program in the same Window
start "" /B cmd
%SendKeys% "echo off{ENTER}"
set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"
set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"
set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"
%SendKeys% "exit{ENTER}"
goto :EOF
@end
// JScript section
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx
For example:
LEFT ARROW {LEFT}
RIGHT ARROW {RIGHT}
For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs
I am python novice so this may not be the most efficient method but, if I understand the intent of the question correctly, steps listed below worked for me.
>>> import numpy as np
>>> Data = np.random.random((100, 100, 1000, 2))
>>> result = np.empty(Data.shape[:-1], dtype=complex)
>>> result.real = Data[...,0]; result.imag = Data[...,1]
>>> print Data[0,0,0,0], Data[0,0,0,1], result[0,0,0]
0.0782889873474 0.156087854837 (0.0782889873474+0.156087854837j)
in build.gradle:
compile 'com.google.maps.android:android-maps-utils:0.4'
and then:
public static Double distanceBetween(LatLng point1, LatLng point2) {
if (point1 == null || point2 == null) {
return null;
}
return SphericalUtil.computeDistanceBetween(point1, point2);
}
This has been discussed into spark mailing list, and please refer this mail.
You should use hadoop fs -put <localsrc> ... <dst>
copy the file into hdfs
:
${HADOOP_COMMON_HOME}/bin/hadoop fs -put /path/to/README.md README.md
If it's an array of strings you can use Aggregate
var array = new string[] { "A", "B", "C", "D"};
Console.WriteLine(array.Aggregate((result, next) => $"{result}, {next}")); // A, B, C, D
that way you can reverses the order by changing the order of the parameters like so
Console.WriteLine(array.Aggregate((result, next) => $"{next}, {result}")); // D, C, B, A
case when field1>0 then field2/field1 else 0 end as field3
<div class="scrollingDiv">foo</div>
div.scrollingDiv
{
overflow:scroll;
}
Very informative answer from @stej, but here is a short answer: Among other options, you have 3 simple options to format [System.DateTime] stored in a variable:
Pass the variable to the Get-Date cmdlet:
Get-Date -Format "HH:mm" $date
Use toString() method:
$date.ToString("HH:mm")
Use Composite formatting:
"{0:HH:mm}" -f $date
A couple of additional points re use of vector
here.
Unlike ArrayList
and Array
in Java, you don't need to do anything special to treat a vector
as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.
Unlike ArrayList
, a vector
can efficiently hold primitive types without encapsulation as a full-fledged object.
When removing items from a vector
, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.
Make sure if you store complex objects in the vector
that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.
Advice about reserve()
ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.
I'd avoid eval.
To solve this problem, you should know these things about JavaScript.
.
rather than square brackets []
, or vice versa.Your problem is a result of considering the dot manner of reference rather than the square bracket manner.
So, why not something like,
window["functionName"]();
That's assuming your function lives in the global space. If you've namespaced, then:
myNameSpace["functionName"]();
Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.
The data containing the date column can be read by using the below code:
data = pd.csv(file_path,parse_dates=[date_column])
Once the data is read by using the above line of code, the column containing the information about the date can be accessed using pd.date_time()
like:
pd.date_time(data[date_column], format = '%d/%m/%y')
to change the format of date as per the requirement.
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
Although this question is rather old, I'd like to share my solution for angular 1 developers. The point is to just reuse the original angular filter, but transparently passing any objects as an array.
app.filter('objectFilter', function ($filter) {
return function (items, searchToken) {
// use the original input
var subject = items;
if (typeof(items) == 'object' && !Array.isArray(items)) {
// or use a wrapper array, if we have an object
subject = [];
for (var i in items) {
subject.push(items[i]);
}
}
// finally, apply the original angular filter
return $filter('filter')(subject, searchToken);
}
});
use it like this:
<div>
<input ng-model="search" />
</div>
<div ng-repeat="item in test | objectFilter : search">
{{item | json}}
</div>
here is a plunker
clipboard
There is a special register for storing this selection, it is the "* register. Nothing is put in here unless the information about what text is selected is about to change (e.g. with a left mouse click somewhere), or when another application wants to paste the selected text. Then the text is put in the "* register. For example, to cut a line and make it the current selection/put it on the CLIPBOARD:
"*dd
Similarly, when you want to paste a selection from another application, e.g., by clicking the middle mouse button, the selection is put in the "* register first, and then 'put' like any other register. For example, to put the selection (contents of the CLIPBOARD):
"*p
registers E354
> There are nine types of registers:
> 1. The unnamed register ""
> 2. 10 numbered registers "0 to "9
> 3. The small delete register "-
> 4. 26 named registers "a to "z or "A to "Z
> 5. four read-only registers ":, "., "% and "#
> 6. the expression register "=
> 7. The selection and drop registers "*, "+ and "~
> 8. The black hole register "_
> 9. Last search pattern register "/
Paste from clipboard
1. Clipboard: Copy
2. Vim insertmode, middle mouse key
Check for X11-clipboard support in terminal
When you like to run Vim in a terminal you need to look for a version of Vim that was compiled with clipboard support. Check for X11-clipboard support, from the console, type:
% vim --version
If you see "+xterm_clipboard", you are good to go.
http://vim.wikia.com/wiki/Accessing_the_system_clipboard
The X server maintains three selections, called:
PRIMARY, SECONDARY and CLIPBOARD
The PRIMARY selection is conventionally used to implement copying and pasting via the middle mouse button. The SECONDARY and CLIPBOARD selections are less frequently used by application programs.
In order to assign these to variables, be sure not to add spaces in front or after the equals sign:
set filepath=%~dp1
set filename=%~nx1
Then you should have no issues.
You have it almost done. Just explicitly say where to create the file
@echo off
echo.>"d:\testing\dblank.txt"
This creates a file containing a blank line (CR + LF = 2 bytes).
If you want the file empty (0 bytes)
@echo off
break>"d:\testing\dblank.txt"
I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").
I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:
public class SeleccionListener implements ActionListener, FocusListener {}
So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
System.out.println("Aceptar pressed");
}
In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).
public void focusGained(FocusEvent focusEvent) {
if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
System.out.println("Data radio button");
}
In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)
You can assign this yourself very easily, here goes a step by step explaination.
1.) In you xCode .m file type the following, it does not matter where you type as long as it's an empty area.
/*
*/
2.)Highlight that two lines of code then drag and drop onto 'code snippet library panel' area (it's at the bottom part of Utilities panel). A light blue plus sign will show up if you do it right.
3.) After you let go of your mouse button, a new window will pop up and will ask you to add name, short cut etc; as shown. As you can see I added my shortcut to //. So every time I want a block comment I will type //. Hope this helps
As a complete new at javascript, I just had the same problem on my side here. The mistake I did, was that I used:
<script type="text.javascript">
console.log("bla bla bla");
</script>
instead of:
<script>
console.log("bla bla bla");
</script>
using the
type="text.javascript"
had the result of not producing the log in the console.
Some time we need to set PATH variable for WINDOWS
%USERPROFILE%\AppData\Roaming\npm
After that test with where grunt
Note: Do not forget to close the command prompt window and reopen it.
Using ES6 solution
For those still reading this answer, if you are using ES6 the find
method was added in arrays. So assuming the same collection, the solution'd be:
const foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
foo.results.find(item => item.id === 2)
I'd totally go for this solution now, as is less tied to angular or any other framework. Pure Javascript.
Angular solution (old solution)
I aimed to solve this problem by doing the following:
$filter('filter')(foo.results, {id: 1})[0];
A use case example:
app.controller('FooCtrl', ['$filter', function($filter) {
var foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
// We filter the array by id, the result is an array
// so we select the element 0
single_object = $filter('filter')(foo.results, function (d) {return d.id === 2;})[0];
// If you want to see the result, just check the log
console.log(single_object);
}]);
Plunker: http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview
type in Terminal:
$ mvn --version
then get following result:
Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 16:51:28+0300)
Maven home: /opt/local/share/java/maven3
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: ru_RU, platform encoding: MacCyrillic
OS name: "mac os x", version: "10.9.4", arch: "x86_64", family: "mac"
here in second line we have:
Maven home: /opt/local/share/java/maven3
type this path into field on configuration dialog. That's all to fix!
Code will be As below.
[textarea id:message 0x0 class:custom-class "Insert text here"]<!-- No Rows No columns -->
[textarea id:message x2 class:custom-class "Insert text here"]<!-- Only Rows -->
[textarea id:message 12x class:custom-class "Insert text here"]<!-- Only Columns -->
[textarea id:message 10x2 class:custom-class "Insert text here"]<!-- Both Rows and Columns -->
For Details: https://contactform7.com/text-fields/
I made a javascript function to create dots with an svg. You can adjust dot spacing and size in the javascript code.
var make_dotted_borders = function() {_x000D_
// EDIT THESE SETTINGS:_x000D_
_x000D_
var spacing = 8;_x000D_
var dot_width = 2;_x000D_
var dot_height = 2;_x000D_
_x000D_
//---------------------_x000D_
_x000D_
var dotteds = document.getElementsByClassName("dotted");_x000D_
for (var i = 0; i < dotteds.length; i++) {_x000D_
var width = dotteds[i].clientWidth + 1.5;_x000D_
var height = dotteds[i].clientHeight;_x000D_
_x000D_
var horizontal_count = Math.floor(width / spacing);_x000D_
var h_spacing_percent = 100 / horizontal_count;_x000D_
var h_subtraction_percent = ((dot_width / 2) / width) * 100;_x000D_
_x000D_
var vertical_count = Math.floor(height / spacing);_x000D_
var v_spacing_percent = 100 / vertical_count;_x000D_
var v_subtraction_percent = ((dot_height / 2) / height) * 100;_x000D_
_x000D_
var dot_container = document.createElement("div");_x000D_
dot_container.classList.add("dot_container");_x000D_
dot_container.style.display = getComputedStyle(dotteds[i], null).display;_x000D_
_x000D_
var clone = dotteds[i].cloneNode(true);_x000D_
_x000D_
dotteds[i].parentElement.replaceChild(dot_container, dotteds[i]);_x000D_
dot_container.appendChild(clone);_x000D_
_x000D_
for (var x = 0; x < horizontal_count; x++) {_x000D_
// The Top Dots_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
var left_percent = (h_spacing_percent * x) - h_subtraction_percent;_x000D_
dot.style.left = left_percent + "%";_x000D_
dot.style.top = (-dot_height / 2) + "px";_x000D_
dot_container.appendChild(dot);_x000D_
_x000D_
// The Bottom Dots_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
dot.style.left = (h_spacing_percent * x) - h_subtraction_percent + "%";_x000D_
dot.style.top = height - (dot_height / 2) + "px";_x000D_
dot_container.appendChild(dot);_x000D_
}_x000D_
_x000D_
for (var y = 1; y < vertical_count; y++) {_x000D_
// The Left Dots:_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
dot.style.left = (-dot_width / 2) + "px";_x000D_
dot.style.top = (v_spacing_percent * y) - v_subtraction_percent + "%";_x000D_
dot_container.appendChild(dot);_x000D_
}_x000D_
for (var y = 0; y < vertical_count + 1; y++) {_x000D_
// The Right Dots:_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
dot.style.left = width - (dot_width / 2) + "px";_x000D_
if (y < vertical_count) {_x000D_
dot.style.top = (v_spacing_percent * y) - v_subtraction_percent + "%";_x000D_
}_x000D_
else {_x000D_
dot.style.top = height - (dot_height / 2) + "px";_x000D_
}_x000D_
_x000D_
dot_container.appendChild(dot);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
make_dotted_borders();
_x000D_
div.dotted {_x000D_
display: inline-block;_x000D_
padding: 0.5em;_x000D_
}_x000D_
_x000D_
div.dot_container {_x000D_
position: relative;_x000D_
margin-left: 0.25em;_x000D_
margin-right: 0.25em;_x000D_
}_x000D_
_x000D_
div.dot {_x000D_
position: absolute;_x000D_
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100"><circle cx="50" cy="50" r="50" fill="black" /></svg>');_x000D_
}
_x000D_
<div class="dotted">Lorem Ipsum</div>
_x000D_
As of Jquery 3.0 and above .bind has been deprecated and they prefer using .on instead. As @Blazemonger answered earlier that it may be removed and its for sure that it will be removed. For the older versions .bind would also call .on internally and there is no difference between them. Please also see the api for more detail.
you can use range
with cells
to get the effect you want (but it would be better not to use select if you don't have to)
For n = 1 to 5
range(cells(1,n).entirecolumn,cells(1,n+4).entirecolumn).Select
do sth
next n
Listen to @milkplusvellocet, I'd recommend you to implement the Comparable interface to your class as well.
Just contributing to the answers of others:
String.compareTo()
will tell you how different a string is from another.
e.g. System.out.println( "Test".compareTo("Tesu") );
will print -1
and System.out.println( "Test".compareTo("Tesa") );
will print 19
and nerdy and geeky one-line solution to this task would be:
return this.lastName.equals(s.getLastName()) ? this.lastName.compareTo(s.getLastName()) : this.firstName.compareTo(s.getFirstName());
Explanation:
this.lastName.equals(s.getLastName())
checks whether lastnames are the same or not
this.lastName.compareTo(s.getLastName())
if yes, then returns comparison of last name.
this.firstName.compareTo(s.getFirstName())
if not, returns the comparison of first name.
Just use the array of options, to see, which option is currently selected.
$options = array( 'one', 'two', 'three' );
$output = '';
for( $i=0; $i<count($options); $i++ ) {
$output .= '<option '
. ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '>'
. $options[$i]
. '</option>';
}
Sidenote: I would define a value to be some kind of id for each element, else you may run into problems, when two options have the same string representation.
For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:
USE master
go
DENY VIEW ANY DATABASE TO [user]
go
This will address exactly the requirement outlined above..
Please use this code for selecting date from Two Jquery calendar like Flight Booking site.
Hashtable h=new Hashtable();
h.put("January",0 );
h.put("February",1);
h.put("March",2);
h.put("April",3);
h.put("May",4);
h.put("June",5);
h.put("July",6);
h.put("August",7);
h.put("September",8);
h.put("October",9);
h.put("November",10);
h.put("December",11);
int expMonth;
int expYear;
// Calendar Month and Year
String calMonth = null;
String calYear = null;
boolean dateNotFound;
dateNotFound = true;
expMonth= 5;
expYear = 2014;
while(dateNotFound)
{
calMonth = driver.findElement(By.className("ui-datepicker-month")).getText(); // get the text of month
calYear = driver.findElement(By.className("ui-datepicker-year")).getText();
if(((Integer)h.get(calMonth))+1 == expMonth && (expYear == Integer.parseInt(calYear)))
{
String block="//div[@class='monthBlock first']/table/tbody/tr/td"; // THIS IS FIRST CALENDAR
selectDate(expDate,block);
dateNotFound = false;
}
// parseInt - Converts String to integer and indexof( It will return the index position of String)
else if(((Integer)h.get(calMonth))+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear))
{
String block="//div[@class='monthBlock last']/table/tbody/tr/td"; // THIS IS SECOND CALENDAR
selectDate(expDate,block); // PASSING DATE AND CALENDAR
dateNotFound = false; // Otherwise it will rotate continuously
}
else if((Integer)h.get(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear))
{
System.out.println(" Please enter the date greater than Current date");
dateNotFound = false;
}
}
}
//Thread.sleep(3000);
public static void selectDate(String date,String block) throws IOException
{
String monthblock=block;
List<WebElement> dateWidget = driver.findElements(By.xpath(monthblock));
for (WebElement cell: dateWidget)
{
//Selects Date
if (cell.getText().equals(date))
{
cell.findElement(By.linkText(date)).click();
break;
}
}
//Doubt : How to verify the expected results and how to sort the program
driver.findElement(By.id("SearchBtn")).submit();
//driver.quit();
}
I couldn't get Facebook to pick the right image from a specific post, so I did what's outlined on this page:
https://webapps.stackexchange.com/questions/18468/adding-meta-tags-to-individual-blogger-posts
In other words, something like this:
<b:if cond='data:blog.url == "http://urlofyourpost.com"'>
<meta content='http://urlofyourimage.png' property='og:image'/>
</b:if>
Basically, you're going to hard code an if statement into your site's HTML to get it to change the meta content for whatever you've changed for that one post. It's a messy solution, but it works.
Here is a very handy and helpful information about Git Push: Git Push: Just the Tip
The most common use of git push is to push your local changes to your public upstream repository. Assuming that the upstream is a remote named "origin" (the default remote name if your repository is a clone) and the branch to be updated to/from is named "master" (the default branch name), this is done with: git push origin master
git push origin
will push changes from all local branches to matching branches the origin remote.
git push origin master
will push changes from the local master branch to the remote master branch.
git push origin master:staging
will push changes from the local master branch to the remote staging branch if it exists.
All C++ compilers have one serious performance problem to deal with. Compiling C++ code is a long, slow process.
Compiling headers included on top of C++ files is a very long, slow process. Compiling the huge header structures that form part of Windows API and other large API libraries is a very, very long, slow process. To have to do it over, and over, and over for every single Cpp source file is a death knell.
This is not unique to Windows but an old problem faced by all compilers that have to compile against a large API like Windows.
The Microsoft compiler can ameliorate this problem with a simple trick called precompiled headers. The trick is pretty slick: although every CPP file can potentially and legally give a sligthly different meaning to the chain of header files included on top of each Cpp file (by things like having different macros #define'd in advance of the includes, or by including the headers in different order), that is most often not the case. Most of the time, we have dozens or hundreds of included files, but they all are intended to have the same meaning for all the Cpp files being compiled in your application.
The compiler can make huge time savings if it doesn't have to start to compile every Cpp file plus its dozens of includes literally from scratch every time.
The trick consists of designating a special header file as the starting point of all compilation chains, the so called 'precompiled header' file, which is commonly a file named stdafx.h simply for historical reasons.
Simply list all your big huge headers for your APIs in your stdafx.h file, in the appropriate order, and then start each of your CPP files at the very top with an #include "stdafx.h"
, before any meaningful content (just about the only thing allowed before is comments).
Under those conditions, instead of starting from scratch, the compiler starts compiling from the already saved results of compiling everything in stdafx.h
.
I don't believe that this trick is unique to Microsoft compilers, nor do I think it was an original development.
For Microsoft compilers, the setting that controls the use of precompiled headers is controlled by a command line argument to the compiler: /Yu "stdafx.h"
. As you can imagine, the use of the stdafx.h
file name is simply a convention; you can change the name if you so wish.
In Visual Studio 2010, this setting is controlled from the GUI via Right-clicking on a CPP Project, selecting 'Properties' and navigating to "Configuration Properties\C/C++\Precompiled Headers". For other versions of Visual Studio, the location in the GUI will be different.
Note that if you disable precompiled headers (or run your project through a tool that doesn't support them), it doesn't make your program illegal; it simply means that your tool will compile everything from scratch every time.
If you are creating a library with no Windows dependencies, you can easily comment out or remove #include
s from the stdafx.h
file. There is no need to remove the file per se, but clearly you may do so as well, by disabling the precompile header setting above.
@mani's response is now slightly outdated as using catch-all '*'
routes is no longer supported when using Vue 3 onward. If this is no longer working for you, try replacing the old catch-all path with
{ path: '/:pathMatch(.*)*', component: PathNotFound },
Essentially, you should be able to replace the '*'
path with '/:pathMatch(.*)*'
and be good to go!
Reason: Vue Router doesn't use path-to-regexp
anymore, instead it implements its own parsing system that allows route ranking and enables dynamic routing. Since we usually add one single catch-all route per project, there is no big benefit in supporting a special syntax for *.
(from https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes)
If removing \0 from the end of string is impossible, you can add your own character for each string you encode, and remove it on decode.
I'm disappointed at how long it took to work this out.
I want to see which values in my range are outside standard deviation.
=STDEV(L3:L32)*2
=$L$32
(whatever cell your stdev is in)I couldn't work out how to put the STDEv inline. I tried many things with unexpected results.
I would recommend EditArea for live editing of a syntax hightlighted textarea.
I had the same issue when getting my software running on another machine. On my developer pc (Windows 7), I had Visual Studio 2015 installed, the target pc was a clean installation of Windows 10 (.Net installed). I also tested it on another clean Windows 7 pc including .Net Framework. However, on both target pc's I needed to install the Visual C++ Redistributable for Visual Studio 2015 package for x86 or x64 (depends on what your application is build for). That was already installed on my developer pc.
My application was using a C library, which has been compiled to a C++ application using /clr and /TP options in visual studio. Also the application was providing functions to C# by using dllexport method signatures. Not sure if the C# integration leaded to give me that error or if a C++ application would have given me the same.
Hope it helps anybody.
You could right click on those cells, go to format, select custom, then type mm yyyy.
UPDATE
In Android Studio AVD:
Applying the BoxCox transformation to data, without the need of any underlying model, can be done currently using the package geoR. Specifically, you can use the function boxcoxfit() for finding the best parameter and then predict the transformed variables using the function BCtransform().
By experiment I was able to observe this:
When SQL Profiler 2005 or SQL Profiler 2000 is used with database residing in SQLServer 2000 - problem mentioned problem persists, but when SQL Profiler 2005 is used with SQLServer 2005 database, it works perfect!
In Summary, the issue seems to be prevalent in SQLServer 2000 & rectified in SQLServer 2005.
The solution for the issue when dealing with SQLServer 2000 is (as explained by wearejimbo)
Identify the DatabaseID of the database you want to filter by querying the sysdatabases table as below
SELECT *
FROM master..sysdatabases
WHERE name like '%your_db_name%' -- Remove this line to see all databases
ORDER BY dbid
Use the DatabaseID Filter (instead of DatabaseName) in the New Trace window of SQL Profiler 2000
Swift 3: Easiest way to dismiss keyboard:
//Dismiss keyboard method
func keyboardDismiss() {
textField.resignFirstResponder()
}
//ADD Gesture Recignizer to Dismiss keyboard then view tapped
@IBAction func viewTapped(_ sender: AnyObject) {
keyboardDismiss()
}
//Dismiss keyboard using Return Key (Done) Button
//Do not forgot to add protocol UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
keyboardDismiss()
return true
}
Sounds like you should just use PostGIS, SpatialLite, SQLServer2008, or Oracle Spatial. They can all answer this question for you with spatial SQL.
In bash
you can get the script file name using $0
. Generally $1
, $2
etc are to access CLI arguments. Similarly $0
is to access the name which triggers the script(script file name).
#!/bin/bash
echo "You are running $0"
...
...
If you invoke the script with path like /path/to/script.sh
then $0
also will give the filename with path. In that case need to use $(basename $0)
to get only script file name.
Communication between controllers is done though $emit
+ $on
/ $broadcast
+ $on
methods.
So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:
app.controller('One', ['$scope', '$rootScope'
function($scope) {
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod();
});
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);
While $rootScope.$emit
is called, you can send any data as second parameter.
I noticed that the other answers involved cutting some of the top from the view. If you want to simply resize the view without cutting any content, just try this method :)
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.view.setTranslatesAutoresizingMaskIntoConstraints(true)
self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.height - keyboardSize.height)
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.collectionView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.height + keyboardSize.height)
}
}
Can't upvote so I'll repost @jfs comment cause I think it should be more visible.
@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02
JPA defines the following entity states:
A newly created object that hasn’t ever been associated with a Hibernate Session
(a.k.a Persistence Context
) and is not mapped to any database table row is considered to be in the New (Transient) state.
To become persisted we need to either explicitly call the EntityManager#persist
method or make use of the transitive persistence mechanism.
A persistent entity has been associated with a database table row and it’s being managed by the currently running Persistence Context. Any change made to such an entity is going to be detected and propagated to the database (during the Session flush-time).
With Hibernate, we no longer have to execute INSERT/UPDATE/DELETE statements. Hibernate employs a transactional write-behind working style and changes are synchronized at the very last responsible moment, during the current Session
flush-time.
Once the currently running Persistence Context is closed all the previously managed entities become detached. Successive changes will no longer be tracked and no automatic database synchronization is going to happen.
You can change the entity state using various methods defined by the EntityManager
interface.
To understand the JPA entity state transitions better, consider the following diagram:
When using JPA, to reassociate a detached entity to an active EntityManager
, you can use the merge operation.
When using the native Hibernate API, apart from merge
, you can reattach a detached entity to an active Hibernate Sessionusing the update methods, as demonstrated by the following diagram:
The merge is going to copy the detached entity state (source) to a managed entity instance (destination).
Consider we have persisted the following Book
entity, and now the entity is detached as the EntityManager
that was used to persist the entity got closed:
Book _book = doInJPA(entityManager -> {
Book book = new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setAuthor("Vlad Mihalcea");
entityManager.persist(book);
return book;
});
While the entity is in the detached state, we modify it as follows:
_book.setTitle(
"High-Performance Java Persistence, 2nd edition"
);
Now, we want to propagate the changes to the database, so we can call the merge
method:
doInJPA(entityManager -> {
Book book = entityManager.merge(_book);
LOGGER.info("Merging the Book entity");
assertFalse(book == _book);
});
And Hibernate is going to execute the following SQL statements:
SELECT
b.id,
b.author AS author2_0_,
b.isbn AS isbn3_0_,
b.title AS title4_0_
FROM
book b
WHERE
b.id = 1
-- Merging the Book entity
UPDATE
book
SET
author = 'Vlad Mihalcea',
isbn = '978-9730228236',
title = 'High-Performance Java Persistence, 2nd edition'
WHERE
id = 1
If the merging entity has no equivalent in the current EntityManager
, a fresh entity snapshot will be fetched from the database.
Once there is a managed entity, JPA copies the state of the detached entity onto the one that is currently managed, and during the Persistence Context flush
, an UPDATE will be generated if the dirty checking mechanism finds that the managed entity has changed.
So, when using
merge
, the detached object instance will continue to remain detached even after the merge operation.
Hibernate, but not JPA supports reattaching through the update
method.
A Hibernate Session
can only associate one entity object for a given database row. This is because the Persistence Context acts as an in-memory cache (first level cache) and only one value (entity) is associated with a given key (entity type and database identifier).
An entity can be reattached only if there is no other JVM object (matching the same database row) already associated with the current Hibernate Session
.
Considering we have persisted the Book
entity and that we modified it when the Book
entity was in the detached state:
Book _book = doInJPA(entityManager -> {
Book book = new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setAuthor("Vlad Mihalcea");
entityManager.persist(book);
return book;
});
_book.setTitle(
"High-Performance Java Persistence, 2nd edition"
);
We can reattach the detached entity like this:
doInJPA(entityManager -> {
Session session = entityManager.unwrap(Session.class);
session.update(_book);
LOGGER.info("Updating the Book entity");
});
And Hibernate will execute the following SQL statement:
-- Updating the Book entity
UPDATE
book
SET
author = 'Vlad Mihalcea',
isbn = '978-9730228236',
title = 'High-Performance Java Persistence, 2nd edition'
WHERE
id = 1
The
update
method requires you tounwrap
theEntityManager
to a HibernateSession
.
Unlike merge
, the provided detached entity is going to be reassociated with the current Persistence Context and an UPDATE is scheduled during flush whether the entity has modified or not.
To prevent this, you can use the @SelectBeforeUpdate
Hibernate annotation which will trigger a SELECT statement that fetched loaded state which is then used by the dirty checking mechanism.
@Entity(name = "Book")
@Table(name = "book")
@SelectBeforeUpdate
public class Book {
//Code omitted for brevity
}
One problem that can occur with update
is if the Persistence Context already contains an entity reference with the same id and of the same type as in the following example:
Book _book = doInJPA(entityManager -> {
Book book = new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setAuthor("Vlad Mihalcea");
Session session = entityManager.unwrap(Session.class);
session.saveOrUpdate(book);
return book;
});
_book.setTitle(
"High-Performance Java Persistence, 2nd edition"
);
try {
doInJPA(entityManager -> {
Book book = entityManager.find(
Book.class,
_book.getId()
);
Session session = entityManager.unwrap(Session.class);
session.saveOrUpdate(_book);
});
} catch (NonUniqueObjectException e) {
LOGGER.error(
"The Persistence Context cannot hold " +
"two representations of the same entity",
e
);
}
Now, when executing the test case above, Hibernate is going to throw a NonUniqueObjectException
because the second EntityManager
already contains a Book
entity with the same identifier as the one we pass to update
, and the Persistence Context cannot hold two representations of the same entity.
org.hibernate.NonUniqueObjectException:
A different object with the same identifier value was already associated with the session : [com.vladmihalcea.book.hpjp.hibernate.pc.Book#1]
at org.hibernate.engine.internal.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:651)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:284)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:227)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:92)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:682)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:674)
The merge
method is to be preferred if you are using optimistic locking as it allows you to prevent lost updates.
The update
is good for batch updates as it can prevent the additional SELECT statement generated by the merge
operation, therefore reducing the batch update execution time.
Firstly, follow Energya's instruction:
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user
Second is the key: After opening jupiter notebook, click the Nbextension tab. Now Search "colla" from the searching tool provided by Nbextension(not by the web browser), then you will find something called "Collapsible Headings"
This is what you want!
The I
attribute only exists on matrix
objects, not ndarray
s. You can use numpy.linalg.inv
to invert arrays:
inverse = numpy.linalg.inv(x)
Note that the way you're generating matrices, not all of them will be invertible. You will either need to change the way you're generating matrices, or skip the ones that aren't invertible.
try:
inverse = numpy.linalg.inv(x)
except numpy.linalg.LinAlgError:
# Not invertible. Skip this one.
pass
else:
# continue with what you were doing
Also, if you want to go through all 3x3 matrices with elements drawn from [0, 10), you want the following:
for comb in itertools.product(range(10), repeat=9):
rather than combinations_with_replacement
, or you'll skip matrices like
numpy.array([[0, 1, 0],
[0, 0, 0],
[0, 0, 0]])
It's a bad idea to change the behavior of the home key. This is why Google doesn't allow you to override the home key. I wouldn't mess with the home key generally speaking. You need to give the user a way to get out of your app if it goes off into the weeds for whatever reason.
I'd image any work around will have unwanted side effects.
& is bitwise AND operator comparing bits of each operand.
For example,
int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.
The other answers so far are all correct; I just wanted to add one more that's slightly cleaner:
v2 = v1 ?? default(int);
Any Nullable<T>
is implicitly convertible to its T
, PROVIDED that the entire expression being evaluated can never result in a null assignment to a ValueType. So, the null-coalescing operator ??
is just syntax sugar for the ternary operator:
v2 = v1 == null ? default(int) : v1;
...which is in turn syntax sugar for an if/else:
if(v1==null)
v2 = default(int);
else
v2 = v1;
Also, as of .NET 4.0, Nullable<T>
has a "GetValueOrDefault()" method, which is a null-safe getter that basically performs the null-coalescing shown above, so this works too:
v2 = v1.GetValueOrDefault();
I realize that this is an old thread, but I thought I'd update it with my results.
Alex, it sounds like you installed MySQL server via the meta-package 'mysql-server'. This installs the latest package by reference (in my case, mysql-server-5.5). I, like you, was not prompted for a MySQL password upon setup as I had expected. I suppose there are two answers:
Solution #1: install MySQL by it's full name:
$ sudo apt-get install mysql-server-5.5
Or
Solution #2: reconfigure the package...
$ sudo dpkg-reconfigure mysql-server-5.5
You must specific the full package name. Using the meta-package 'mysql-server' did not have the desired result for me. I hope this helps someone :)
Reference: https://help.ubuntu.com/12.04/serverguide/mysql.html
If you want to change the color of your toolbar all throughout your app, leverage the styles.xml. In general, I avoid altering ui components in my java code unless I am trying to do something programatically. If this is a one time set, then you should be doing it in xml to make your code cleaner. Here is what your styles.xml will look like:
<!-- Base application theme. -->
<style name="YourAppName.AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Color Primary will be your toolbar color -->
<item name="colorPrimary">@color/colorPrimary</item>
<!-- Color Primary Dark will be your default status bar color -->
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>
Make sure you use the above style in your AndroidManifext.xml as such:
<application
android:theme="@style/YourAppName.AppTheme">
</application>
I wanted different toolbar colors for different activities. So I leveraged styles again like this:
<style name="YourAppName.AppTheme.Activity1">
<item name="colorPrimary">@color/activity1_primary</item>
<item name="colorPrimaryDark">@color/activity1_primaryDark</item>
</style>
<style name="YourAppName.AppTheme.Activity2">
<item name="colorPrimary">@color/activity2_primary</item>
<item name="colorPrimaryDark">@color/activity2_primaryDark</item>
</style>
again, apply the styles to each activity in your AndroidManifest.xml as such:
<activity
android:name=".Activity2"
android:theme="@style/YourAppName.AppTheme.Activity2"
</activity>
<activity
android:name=".Activity1"
android:theme="@style/YourAppName.AppTheme.Activity1"
</activity>
When you perform an DOM query through jQuery like $('class-name')
it actively searched the DOM for that element and returns that element with all the jQuery prototype methods attached.
When you're within the jQuery chain or event you don't have to rerun the DOM query you can use the context $(this)
. Like so:
$('.class-name').on('click', (evt) => {
$(this).hide(); // does not run a DOM query
$('.class-name').hide() // runs a DOM query
});
$(this)
will hold the element that you originally requested. It will attach all the jQuery prototype methods again, but will not have to search the DOM again.
Some more information:
Web Performance with jQuery selectors
Quote from a web blog that doesn't exist anymore but I'll leave it in here for history sake:
In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery. That is, find a balance between using jQuery and plain ol’ JavaScript, and a good place to start is with ‘this‘. Many developers use $(this) exclusively as their hammer inside callbacks and forget about this, but the difference is distinct:
When inside a jQuery method’s anonymous callback function, this is a reference to the current DOM element. $(this) turns this into a jQuery object and exposes jQuery’s methods. A jQuery object is nothing more than a beefed-up array of DOM elements.
A RESTful resource controller sets up some default routes for you and even names them.
Route::resource('users', 'UsersController');
Gives you these named routes:
Verb Path Action Route Name
GET /users index users.index
GET /users/create create users.create
POST /users store users.store
GET /users/{user} show users.show
GET /users/{user}/edit edit users.edit
PUT|PATCH /users/{user} update users.update
DELETE /users/{user} destroy users.destroy
And you would set up your controller something like this (actions = methods)
class UsersController extends BaseController {
public function index() {}
public function show($id) {}
public function store() {}
}
You can also choose what actions are included or excluded like this:
Route::resource('users', 'UsersController', [
'only' => ['index', 'show']
]);
Route::resource('monkeys', 'MonkeysController', [
'except' => ['edit', 'create']
]);
Laravel 5.5 added another method for dealing with routes for resource controllers. API Resource Controller acts exactly like shown above, but does not register create
and edit
routes. It is meant to be used for ease of mapping routes used in RESTful APIs - where you typically do not have any kind of data located in create
nor edit
methods.
Route::apiResource('users', 'UsersController');
RESTful Resource Controller documentation
An Implicit controller is more flexible. You get routed to your controller methods based on the HTTP request type and name. However, you don't have route names defined for you and it will catch all subfolders for the same route.
Route::controller('users', 'UserController');
Would lead you to set up the controller with a sort of RESTful naming scheme:
class UserController extends BaseController {
public function getIndex()
{
// GET request to index
}
public function getShow($id)
{
// get request to 'users/show/{id}'
}
public function postStore()
{
// POST request to 'users/store'
}
}
Implicit Controller documentation
It is good practice to use what you need, as per your preference. I personally don't like the Implicit controllers, because they can be messy, don't provide names and can be confusing when using php artisan routes
. I typically use RESTful Resource controllers in combination with explicit routes.
If you are really interested in a good, in-depth explanation of move semantics, I'd highly recommend reading the original paper on them, "A Proposal to Add Move Semantics Support to the C++ Language."
It's very accessible and easy to read and it makes an excellent case for the benefits that they offer. There are other more recent and up to date papers about move semantics available on the WG21 website, but this one is probably the most straightforward since it approaches things from a top-level view and doesn't get very much into the gritty language details.
The easiest way to calculate the duration of an operation:
import time
start_time = time.monotonic()
print(time.ctime())
<operations, programs>
print('minutes: ',(time.monotonic() - start_time)/60)
This is how you would drop the constraint
ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO
With a script
-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)
set @database = 'dotnetnuke'
set @table = 'tabs'
DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
select @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = @database and
table_name = @table
exec sp_executesql @sql
END
Credits go to Jon Galloway http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx
Another pre-5.14 solution: http://www.perlmonks.org/?node_id=346719 (see japhy's post)
As his approach uses map
, it also works well for arrays, but requires cascading map
to produce a temporary array (otherwise the original would be modified):
my @orig = ('this', 'this sucks', 'what is this?');
my @list = map { s/this/that/; $_ } map { $_ } @orig;
# @orig unmodified
HTML Form Element Validation
Run Function
<script>
$("#validationForm").validation({
button: "#btnGonder",
onSubmit: function () {
alert("Submit Process");
},
onCompleted: function () {
alert("onCompleted");
},
onError: function () {
alert("Error Process");
}
});
</script>
Go to example and download https://github.com/naimserin/Validation.
Just to improve YCR's answer:
1) I added black lines on x and y axis. Otherwise they are made transparent too.
2) I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.
Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.
MyTheme_transparent <- theme(
panel.background = element_rect(fill = "transparent"), # bg of the panel
plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
panel.grid.major = element_blank(), # get rid of major grid
panel.grid.minor = element_blank(), # get rid of minor grid
legend.background = element_rect(fill = "transparent"), # get rid of legend bg
legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
axis.line = element_line(colour = "black") # adding a black line for x and y axis
)
Not sure if you can open them invisibly in the current excel instance
You can open a new instance of excel though, hide it and then open the workbooks
Dim app as New Excel.Application
app.Visible = False 'Visible is False by default, so this isn't necessary
Dim book As Excel.Workbook
Set book = app.Workbooks.Add(fileName)
'
' Do what you have to do
'
book.Close SaveChanges:=False
app.Quit
Set app = Nothing
As others have posted, make sure you clean up after you are finished with any opened workbooks
This works for me and is reusable.
function isThisDayAWeekend($date) {
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
if ($weekday =="Saturday" OR $weekday =="Sunday") { return true; }
else {return false; }
}
Use second process. Declare at AndroidManifest
new Service
with
android:process=":second"
Exchange between first and second process over BroadcastReceiver
The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable
.
So for that, here is what I did, when I came across the same problem.
string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };
foreach (string ColName in ColumnsToBeDeleted)
{
if (dt.Columns.Contains(ColName))
dt.Columns.Remove(ColName);
}
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
I have created FolderLayout
which may help you.
This link helped me
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/path" android:text="Path"
android:layout_width="match_parent" android:layout_height="wrap_content"></TextView>
<ListView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/list"></ListView>
</LinearLayout>
package com.testsample.activity;
public class FolderLayout extends LinearLayout implements OnItemClickListener {
Context context;
IFolderItemListener folderListener;
private List<String> item = null;
private List<String> path = null;
private String root = "/";
private TextView myPath;
private ListView lstView;
public FolderLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.context = context;
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.folderview, this);
myPath = (TextView) findViewById(R.id.path);
lstView = (ListView) findViewById(R.id.list);
Log.i("FolderView", "Constructed");
getDir(root, lstView);
}
public void setIFolderItemListener(IFolderItemListener folderItemListener) {
this.folderListener = folderItemListener;
}
//Set Directory for view at anytime
public void setDir(String dirPath){
getDir(dirPath, lstView);
}
private void getDir(String dirPath, ListView v) {
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if (!dirPath.equals(root)) {
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
path.add(file.getPath());
if (file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
Log.i("Folders", files.length + "");
setItemList(item);
}
//can manually set Item to display, if u want
public void setItemList(List<String> item){
ArrayAdapter<String> fileList = new ArrayAdapter<String>(context,
R.layout.row, item);
lstView.setAdapter(fileList);
lstView.setOnItemClickListener(this);
}
public void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory()) {
if (file.canRead())
getDir(path.get(position), l);
else {
//what to do when folder is unreadable
if (folderListener != null) {
folderListener.OnCannotFileRead(file);
}
}
} else {
//what to do when file is clicked
//You can add more,like checking extension,and performing separate actions
if (folderListener != null) {
folderListener.OnFileClicked(file);
}
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
onListItemClick((ListView) arg0, arg0, arg2, arg3);
}
}
And an Interface IFolderItemListener
to add what to do when a fileItem
is clicked
public interface IFolderItemListener {
void OnCannotFileRead(File file);//implement what to do folder is Unreadable
void OnFileClicked(File file);//What to do When a file is clicked
}
Also an xml to define the row
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowtext" android:layout_width="fill_parent"
android:textSize="23sp" android:layout_height="match_parent"/>
In your xml,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="horizontal" android:weightSum="1">
<com.testsample.activity.FolderLayout android:layout_height="match_parent" layout="@layout/folderview"
android:layout_weight="0.35"
android:layout_width="200dp" android:id="@+id/localfolders"></com.testsample.activity.FolderLayout></LinearLayout>
In Your Activity,
public class SampleFolderActivity extends Activity implements IFolderItemListener {
FolderLayout localFolders;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
localFolders = (FolderLayout)findViewById(R.id.localfolders);
localFolders.setIFolderItemListener(this);
localFolders.setDir("./sys");//change directory if u want,default is root
}
//Your stuff here for Cannot open Folder
public void OnCannotFileRead(File file) {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(
"[" + file.getName()
+ "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
//Your stuff here for file Click
public void OnFileClicked(File file) {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
Import the libraries needed. Hope these help you...
SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'
Please see the below code:
if(dataset.select_dtypes(include=[np.number]).shape[1] > 0):
display(dataset.select_dtypes(include=[np.number]).describe())
if(dataset.select_dtypes(include=[np.object]).shape[1] > 0):
display(dataset.select_dtypes(include=[np.object]).describe())
This way you can check whether the value are numeric such as float and int or the srting values. the second if statement is used for checking the string values which is referred by the object.
It seems that this is the correct way window.location.assign("http://www.mozilla.org");
Just copy-paste the .jar under the "libs" folder (or whole "libs" folder), right click on it and select 'Add as library' option from the list. It will do the rest...
A solution where the logo is truly centered and the links are justified.
The max recommended number of links for the nav is 6, depending on the length of the words in eache link.
If you have 5 links, insert an empty link and style it with:
class="hidden-xs" style="visibility: hidden;"
in this way the number of links is always even.
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<style>_x000D_
.navbar-nav > li {_x000D_
float: none;_x000D_
vertical-align: bottom;_x000D_
}_x000D_
#site-logo {_x000D_
position: relative;_x000D_
vertical-align: bottom;_x000D_
bottom: -35px;_x000D_
}_x000D_
#site-logo a {_x000D_
margin-top: -53px;_x000D_
}_x000D_
</style>_x000D_
<nav class="navbar navbar-default navbar-fixed-top">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
<span class="sr-only">Nav</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
</div>_x000D_
<div id="navbar" class="collapse navbar-collapse">_x000D_
<ul class="nav nav-justified navbar-nav center-block">_x000D_
<li class="active"><a href="#">First Link</a></li>_x000D_
<li><a href="#">Second Link</a></li>_x000D_
<li><a href="#">Third Link</a></li>_x000D_
<li id="site-logo" class="hidden-xs"><a href="#"><img id="logo-navbar-middle" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/32877/logo-thing.png" width="200" alt="Logo Thing main logo"></a></li>_x000D_
<li><a href="#">Fourth Link</a></li>_x000D_
<li><a href="#">Fifth Link</a></li>_x000D_
<li class="hidden-xs" style="visibility: hidden;"><a href="#">Sixth Link</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>_x000D_
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
_x000D_
To see result click on run snippet and then full page
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));
I guess your code relates to Windows Forms.
You call BeginInvoke
if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)
If BeginInvoke
is called for Delegate
type the delegate is just invoked asynchronously.
(Invoke
for the sync version.)
If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task
with the according context. (TaskScheduler.FromCurrentSynchronizationContext()
)
And to add a little to already said by others:
Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var
with lambdas: compiler needs a hint.
UPDATE:
this requires .Net v4.0 and higher
// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);
// also can be called anywhere. Task will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked)
task.Start(scheduler);
If you started the task from other thread and need to wait for its completition task.Wait()
will block calling thread till the end of the task.
Read more about tasks here.
If you are talking about syncing a forked repo then you can follow these steps.
How to sync a fork repository from git
check your current git branch
git branch
checkout to master if you are not on master
git checkout master
Fetch the upstream repository if you have correct access rights
git fetch upstream
If you are getting below error then run
git remote add upstream [email protected]:upstream_clone_repo_url/xyz.git
fatal: 'upstream/master' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.
Now run the below command.
git fetch upstream
Now if you are on master then merge the upstream/master into master branch
git merge upstream/master
That's it!!
Crosscheck via git remote
command, more specific git remote -v
If I also have commit rights to the upstream repo, I can create a local upstream branch and do work that will go upstream there.
If I am just run the node app from console (not using forever etc) I use control + C, not sure if OSX has the same key combination to terminate but much faster than finding the process id and killing it, you could also add the following code to the chat app you are using and then type 'exit' in the console whenever you want to close down the app.
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(data) {
if (data == 'exit\n') process.exit();
});
first_key, *rest_keys = mydict
Use height()
:
var result = $("#myDiv").height();
alert(result);
This will give you the unit-less computed height in pixels. "px" will be stripped from the result. I.e. if the height is 400px, the result will be 400, but the result will be in pixels.
If you want to do it without jQuery, you can use plain JavaScript:
var result = document.getElementById("myDiv").offsetHeight;
gradlew
is a wrapper(w - character) that uses gradle
.
Under the hood gradlew
performs three main things:
gradle
versiongradle
taskUsing Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.
To create a wrapper run:
gradle wrapper
This command generate:
gradle-wrapper.properties
will contain the information about the Gradle distribution
*./
Is used on Unix to specify the current directory
I was looking a lot to find a solution for sticy menue with old school JS (without JQuery). So I build small test to play with it. I think it can be helpfull to those looking for solution in js. It needs improvments of unsticking the menue back, and making it more smooth. Also I find a nice solution with JQuery that clones the original div instead of position fixed, its better since the rest of page element dont need to be replaced after fixing. Anyone know how to that with JS ? Please remark, correct and improve.
<!DOCTYPE html>
<html>
<head>
<script>
// addEvent function by John Resig:
// http://ejohn.org/projects/flexible-javascript-events/
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );};
obj.attachEvent( 'on'+type, obj[type+fn] );
} else {
obj.addEventListener( type, fn, false );
}
}
function getScrollY() {
var scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
} else if( document.body && document.body.scrollTop ) {
//DOM compliant
scrOfY = document.body.scrollTop;
}
return scrOfY;
}
</script>
<style>
#mydiv {
height:100px;
width:100%;
}
#fdiv {
height:100px;
width:100%;
}
</style>
</head>
<body>
<!-- HTML for example event goes here -->
<div id="fdiv" style="background-color:red;position:fix">
</div>
<div id="mydiv" style="background-color:yellow">
</div>
<div id="fdiv" style="background-color:green">
</div>
<script>
// Script for example event goes here
addEvent(window, 'scroll', function(event) {
var x = document.getElementById("mydiv");
var y = getScrollY();
if (y >= 100) {
x.style.position = "fixed";
x.style.top= "0";
}
});
</script>
</body>
</html>
You can use
go build *.go
go run *.go
both will work also you may use
go build .
go run .
I suggest to use autotools
:
//##
Place generated object files (.o) into the same directory as their source files, in order to avoid collisions when non-recursive make is used.
AUTOMAKE_OPTIONS = subdir-objects
just including it in Makefile.am
with the other quite simple stuff.
Here is the tutorial.
You need to deserialize your form data before passing it as the second parameter to .post (). You can achieve this using jQuery's $.param (data) method. Then you will be able to on server side to reference it like $.POST ['email'];
gfxmonk's answer has a very tight data race between the callback and the file.close()
completing. file.close()
actually takes a callback that is called when the close has completed. Otherwise, immediate uses of the file may fail (very rarely!).
A complete solution is:
var http = require('http');
var fs = require('fs');
var download = function(url, dest, cb) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb); // close() is async, call cb after close completes.
});
});
}
Without waiting for the finish event, naive scripts may end up with an incomplete file. Without scheduling the cb
callback via close, you may get a race between accessing the file and the file actually being ready.
In reference to #7 in this MSDN POST , adding a registry entry worked for me. I had Vs2010, et oracle 11.0 installed.
Check for the registry key “TNS_ADMIN” at HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE. If it exists then make sure it has the right value as “Dir:\app\product\11.1.0\client_1\network\admin”. If you don’t see the key then create the key and set appropriate value as below. Regedit->HKEY_LOCAL_MACHINE->Software->Oracle->RightClick NEW->StringValue and name it TNS_ADMIN and give the value “X:\app\product\11.1.0\client_1\network\admin”
I'm implementing it in Play Framework and for me it worked like this:
1) Notice that I used data-rule-equalTo in input tag for the id inputPassword1. The code section of userform in my Modal:
<div class="form-group">
<label for="pass1">@Messages("authentication.password")</label>
<input class="form-control required" id="inputPassword1" placeholder="@Messages("authentication.password")" type="password" name="password" maxlength=10 minlength=5>
</div>
<div class="form-group">
<label for="pass2">@Messages("authentication.password2")</label>
<input class="form-control required" data-rule-equalTo="#inputPassword1" id="inputPassword2" placeholder="@Messages("authentication.password")" type="password" name="password2">
</div>
2)Since I used validator within a Modal
$(document).on("click", ".createUserModal", function () {
$(this).find('#userform').validate({
rules: {
firstName: "required",
lastName: "required",
nationalId: {
required: true,
digits:true
},
email: {
required: true,
email: true
},
optradio: "required",
password :{
required: true,
minlength: 5
},
password2: {
required: true
}
},
highlight: function (element) {
$(element).parent().addClass('error')
},
unhighlight: function (element) {
$(element).parent().removeClass('error')
},
onsubmit: true
});
});
Hope it helps someone :).
Just running through a Visual Studio Code tutorial and came across a similiar issue.
Replace #include "stdafx.h"
with #include "pch.h"
which is the updated name for the precompiled headers.
Apache shows php code instead of executing Issue fixed
1. Opened php5.6 conf or php7.x conf
# following command:
$ sudo vi /etc/apache2/mods-enabled/php5.6.conf
2. Commented following lines
3. Restarted the server
$ sudo service apache2 restart
4 Enjoy :)
Get image size with jQuery
function getMeta(url){
$("<img/>",{
load : function(){
alert(this.width+' '+this.height);
},
src : url
});
}
Get image size with JavaScript
function getMeta(url){
var img = new Image();
img.onload = function(){
alert( this.width+' '+ this.height );
};
img.src = url;
}
Get image size with JavaScript (modern browsers, IE9+ )
function getMeta(url){
var img = new Image();
img.addEventListener("load", function(){
alert( this.naturalWidth +' '+ this.naturalHeight );
});
img.src = url;
}
Use the above simply as: getMeta( "http://example.com/img.jpg" );
https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
If you want to do something x times, you can do this:
Example (x = 200):
FOR /L %%A IN (1,1,200) DO (
ECHO %%A
)
1,1,200
means:
As mentioned by @no?????z??? and @phoenix - You can indeed use it in stub files. e.g.
class Foo:
bar: Any = ...
def __init__(self, name: str=...) -> None: ...
More information and examples of how to use this ellipsis can be discovered here https://www.python.org/dev/peps/pep-0484/#stub-files
You need to isntall pdo_pgsql package
We can also focus webelement using below code:
public focusElement(WebElement element){
String javaScript = "var evObj = document.createEvent('MouseEvents');"
+ "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
+ "arguments[0].dispatchEvent(evObj);";
((JavascriptExecutor) getDriver()).executeScript(javaScript, element);
}
Hope it helps :)
This is a common question. In base, the option you're looking for is aggregate
. Assuming your data.frame
is called "mydf", you can use the following.
> aggregate(B ~ A, mydf, sum)
A B
1 1 5
2 2 3
3 3 11
I would also recommend looking into the "data.table" package.
> library(data.table)
> DT <- data.table(mydf)
> DT[, sum(B), by = A]
A V1
1: 1 5
2: 2 3
3: 3 11
Had this issue, but it wasn't related to the bitcode setting. I had somehow ended up with duplicate framework files in the Frameworks folder of my XCode project. I deleted all frameworks files that were red (and duplicates). This solved the "Apple Mach O, Linker Command failed with exit code 1" error.
Here is my version using the BuildConfig
class:
Intent marketIntent = new Intent(Intent.ACTION_VIEW, uri);
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
}
try {
startActivity(marketIntent);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID)));
}
What about: (unique condition)
if (bool(a) + bool(b) + bool(c) == 1):
Notice, if you allow two conditions too you could do that
if (bool(a) + bool(b) + bool(c) in [1,2]):
For anyone needs to change the options of the menu dynamically:
private Menu menu;
// ...
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.menu = menu;
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
// ...
private void hideOption(int id)
{
MenuItem item = menu.findItem(id);
item.setVisible(false);
}
private void showOption(int id)
{
MenuItem item = menu.findItem(id);
item.setVisible(true);
}
private void setOptionTitle(int id, String title)
{
MenuItem item = menu.findItem(id);
item.setTitle(title);
}
private void setOptionIcon(int id, int iconRes)
{
MenuItem item = menu.findItem(id);
item.setIcon(iconRes);
}
ng-if on ng-include and on ng-controller will have a big impact matter on ng-include it will not load the required partial and does not process unless flag is true on ng-controller it will not load the controller unless flag is true but the problem is when a flag gets false in ng-if it will remove from DOM when flag gets true back it will reload the DOM in this case ng-show is better, for one time show ng-if is better
Maybe because I have an older version of pandas but on Jupyter notebook this work for me
import pandas as pd
from IPython.core.display import HTML
df=pd.read_pickle('Data1')
display(HTML(df.to_html()))
EDIT In hind-sight, I think the potential confusion with changing sys.stderr and not seeing the behaviour updated makes this answer not as good as just using a simple function as others have pointed out.
Using partial only saves you 1 line of code. The potential confusion is not worth saving 1 line of code.
original
To make it even easier, here's a version that uses 'partial', which is a big help in wrapping functions.
from __future__ import print_function
import sys
from functools import partial
error = partial(print, file=sys.stderr)
You then use it like so
error('An error occured!')
You can check that it's printing to stderr and not stdout by doing the following (over-riding code from http://coreygoldberg.blogspot.com.au/2009/05/python-redirect-or-turn-off-stdout-and.html):
# over-ride stderr to prove that this function works.
class NullDevice():
def write(self, s):
pass
sys.stderr = NullDevice()
# we must import print error AFTER we've removed the null device because
# it has been assigned and will not be re-evaluated.
# assume error function is in print_error.py
from print_error import error
# no message should be printed
error("You won't see this error!")
The downside to this is partial assigns the value of sys.stderr to the wrapped function at the time of creation. Which means, if you redirect stderr later it won't affect this function. If you plan to redirect stderr, then use the **kwargs method mentioned by aaguirre on this page.
For my point of view, First thing is to install soap into Centos
yum install php-soap
Second, see if the soap package exist or not
yum search php-soap
third, thus you must see some result of soap package you installed, now type a command in your terminal in the root folder for searching the location of soap for specific path
find -name soap.so
fourth, you will see the exact path where its installed/located, simply copy the path and find the php.ini to add the extension path,
usually the path of php.ini file in centos 6 is in
/etc/php.ini
fifth, add a line of code from below into php.ini file
extension='/usr/lib/php/modules/soap.so'
and then save the file and exit.
sixth run apache restart command in Centos. I think there is two command that can restart your apache ( whichever is easier for you )
service httpd restart
OR
apachectl restart
Lastly, check phpinfo() output in browser, you should see SOAP section where SOAP CLIENT, SOAP SERVER etc are listed and shown Enabled.
Try something like this - it works for the cases you have mentioned.
select * from tbl
where answer like '%[0-9]%'
and answer not like '%[:]%'
and answer not like '%[A-Z]%'
You can use groupingBy
collector:
persons.collect(Collectors.groupingBy(p -> p.getName())).values().forEach(t -> System.out.println(t.get(0).getId()));
If you want to have another stream you can use this:
persons.collect(Collectors.groupingBy(p -> p.getName())).values().stream().map(l -> (l.get(0)));
You can't declare a variable as Decimal
- you have to use Variant
(you can use CDec
to populate it with a Decimal
type though).
If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning
. Your example:
df = df.assign(B=df1['E'])
The following query will find the documents with required string insensitively and with global occurrence also
db.collection.find({name:{
$regex: new RegExp(thename, "ig")
}
},function(err, doc) {
//Your code here...
});
As per this question's answer
You will want something like this:
<bindings> <basicHttpBinding> <binding name="basicHttp" allowCookies="true" maxReceivedMessageSize="20000000" maxBufferSize="20000000" maxBufferPoolSize="20000000"> <readerQuotas maxDepth="32" maxArrayLength="200000000" maxStringContentLength="200000000"/> </binding> </basicHttpBinding> </bindings>
Please also read comments to the accepted answer there, those contain valuable input.
Take a look at this thread: http://code.google.com/p/chromium/issues/detail?id=4158
The problem is caused by javascript method "window.open(URL, windowName[, windowFeatures])". If the 3rd parameter windowFeatures is specified, then alert box doesn't work in the popup constrained window in Chrome, here is a simplified reduction:
http://go/reductions/4158/test-home-constrained.html
If the 3rd parameter windowFeatures is ignored, then alert box works in the popup in Chrome(the popup is actually opened as a new tab in Chrome), like this:
http://go/reductions/4158/test-home-newtab.html
it doesn't happen in IE7, Firefox3 or Safari3, it's a chrome specific issue.
See also attachments for simplified reductions
Swift 4
func writeImage(image: UIImage) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.finishWriteImage), nil)
}
@objc private func finishWriteImage(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if (error != nil) {
// Something wrong happened.
print("error occurred: \(String(describing: error))")
} else {
// Everything is alright.
print("saved success!")
}
}
This is the simple answer I can give.
I try to explain the Bayes rule with an example.
What is the chance that a random person selected from the society is a smoker?
You may reply 10%, and let's assume that's right.
Now, what if I say that the random person is a man and is 15 years old?
You may say 15 or 20%, but why?.
In fact, we try to update our initial guess with new pieces of evidence ( P(smoker) vs. P(smoker | evidence)
). The Bayes rule is a way to relate these two probabilities.
P(smoker | evidence) = P(smoker)* p(evidence | smoker)/P(evidence)
Each evidence may increase or decrease this chance. For example, this fact that he is a man may increase the chance provided that this percentage (being a man) among non-smokers is lower.
In the other words, being a man must be an indicator of being a smoker rather than a non-smoker. Therefore, if an evidence is an indicator of something, it increases the chance.
But how do we know that this is an indicator?
For each feature, you can compare the commonness (probability) of that feature under the given conditions with its commonness alone. (P(f | x) vs. P(f))
.
P(smoker | evidence) / P(smoker) = P(evidence | smoker)/P(evidence)
For example, if we know that 90% of smokers are men, it's not still enough to say whether being a man is an indicator of being smoker or not. For example if the probability of being a man in the society is also 90%, then knowing that someone is a man doesn't help us ((90% / 90%) = 1
. But if men contribute to 40% of the society, but 90% of the smokers, then knowing that someone is a man increases the chance of being a smoker (90% / 40%) = 2.25
, so it increases the initial guess (10%) by 2.25 resulting 22.5%.
However, if the probability of being a man was 95% in the society, then regardless of the fact that the percentage of men among smokers is high (90%)! the evidence that someone is a man decreases the chance of him being a smoker! (90% / 95%) = 0.95)
.
So we have:
P(smoker | f1, f2, f3,... ) = P(smoker) * contribution of f1* contribution of f2 *...
=
P(smoker)*
(P(being a man | smoker)/P(being a man))*
(P(under 20 | smoker)/ P(under 20))
Note that in this formula we assumed that being a man and being under 20 are independent features so we multiplied them, it means that knowing that someone is under 20 has no effect on guessing that he is man or woman. But it may not be true, for example maybe most adolescence in a society are men...
To use this formula in a classifier
The classifier is given with some features (being a man and being under 20) and it must decide if he is an smoker or not (these are two classes). It uses the above formula to calculate the probability of each class under the evidence (features), and it assigns the class with the highest probability to the input. To provide the required probabilities (90%, 10%, 80%...) it uses the training set. For example, it counts the people in the training set that are smokers and find they contribute 10% of the sample. Then for smokers checks how many of them are men or women .... how many are above 20 or under 20....In the other words, it tries to build the probability distribution of the features for each class based on the training data.
You can try this:
Select To_date ('15/2/2007 00:00:00', 'DD/MM/YYYY HH24:MI:SS'),
To_date ('28/2/2007 10:12', 'DD/MM/YYYY HH24:MI:SS')
From DUAL;
Source: http://notsyncing.org/2008/02/manipulando-fechas-con-horas-en-plsql-y-sql/
I think you want .text()
:
var monthname = $(this).text();
The calculated column trick is widely known as a "nullbuster"; my notes credit Steve Kass:
CREATE TABLE dupNulls (
pk int identity(1,1) primary key,
X int NULL,
nullbuster as (case when X is null then pk else 0 end),
CONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)
)
You need to use cell.Text = "#N/A" instead of cell.Value = "#N/A". The error in the cell is actually just text stored in the cell.
we can also calculate the binary for positive or negative numbers as below:
function toBinary(n){
let binary = "";
if (n < 0) {
n = n >>> 0;
}
while(Math.ceil(n/2) > 0){
binary = n%2 + binary;
n = Math.floor(n/2);
}
return binary;
}
console.log(toBinary(7));
console.log(toBinary(-7));
_x000D_
If you absolutely have to add the property to the object, I believe you could cast it as an array, add your property (as a new array key), then cast it back as an object. The only time you run into stdClass
objects (I believe) is when you cast an array as an object or when you create a new stdClass
object from scratch (and of course when you json_decode()
something - silly me for forgetting!).
Instead of:
$foo = new StdClass();
$foo->bar = '1234';
You'd do:
$foo = array('bar' => '1234');
$foo = (object)$foo;
Or if you already had an existing stdClass object:
$foo = (array)$foo;
$foo['bar'] = '1234';
$foo = (object)$foo;
Also as a 1 liner:
$foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) );
I had the same problem as you. I had a long list of arguments, most of which were irrelevant. I didn't want to hard code them in. This is what I came up with
library(magrittr)
do_func_ignore_things <- function(data, what){
acceptable_args <- data[names(data) %in% (formals(what) %>% names)]
do.call(what, acceptable_args %>% as.list)
}
do_func_ignore_things(c(n = 3, hello = 12, mean = -10), "rnorm")
# -9.230675 -10.503509 -10.927077
Some long answers here. The principle is very simple though. I submit the opening statement from wikipedia:
"Loose coupling describes a resilient relationship between two or more systems or organizations with some kind of exchange relationship.
Each end of the transaction makes its requirements explicit and makes few assumptions about the other end."
Something like this?
And the code I used:
.box{
position: relative;
overflow: hidden;
}
.box:hover .hidden{
left: 0px;
}
.box .hidden {
background: yellow;
height: 300px;
position: absolute;
top: 0;
left: -500px;
width: 500px;
opacity: 1;
-webkit-transition: all 0.7s ease-out;
-moz-transition: all 0.7s ease-out;
-ms-transition: all 0.7s ease-out;
-o-transition: all 0.7s ease-out;
transition: all 0.7s ease-out;
}
I may also add that it's possible to move an elment using transform: translate();
, which in this case could work something like this - DEMO nr2
jCarousel is a Jquery Plugin , it have same functionality already implemented , which might want to archive. it's nice and easy. here is the link
and complete documentation can be found here
It depends on what is in test.py
. The following is an appropriate structure:
# suppose this is your 'test.py' file
def main():
"""This function runs the core of your program"""
print("running main")
if __name__ == "__main__":
# if you call this script from the command line (the shell) it will
# run the 'main' function
main()
If you keep this structure, you can run it like this in the command line (assume that $
is your command-line prompt):
$ python test.py
$ # it will print "running main"
If you want to run it from the Python shell, then you simply do the following:
>>> import test
>>> test.main() # this calls the main part of your program
There is no necessity to use the subprocess
module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.
There's a function std::reverse
in the algorithm
header for this purpose.
#include <vector>
#include <algorithm>
int main() {
std::vector<int> a;
std::reverse(a.begin(), a.end());
return 0;
}
Use the following regex
^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$
This will support the following formats:
While you haven't provided enough information to actually indicate WHERE you should be pulling data from, you do need to pull it from somewhere. You can specify the URL in load, as well as define data parameters or a callback function.
$("#getCameraSerialNumbers").click(function () {
$("#step1Content").load('YourUrl');
});
string [] lines = {"text1", "text2", "etc"};
bool bFound = lines.Any(x => x == "Your string to be searched");
bFound sets to true if searched string is matched with any element of array 'lines'.
You can verify your SSH key passphrase by attempting to load it into your SSH agent. With OpenSSH this is done via ssh-add
.
Once you're done, remember to unload your SSH passphrase from the terminal by running ssh-add -d
.
It seems to me to be a bug in PHP. The error
'Fatal error: Uncaught Error: Using $this when not in object context in'
appears in the function using $this
, but the error is that the calling function is using non-static function as a static. I.e:
Class_Name
{
function foo()
{
$this->do_something(); // The error appears there.
}
function do_something()
{
///
}
}
While the error is here:
Class_Name::foo();
ActiveRecord stores validation errors in an array called errors
. If you have a User
model then you would access the validation errors in a given instance like so:
@user = User.create[params[:user]] # create will automatically call validators
if @user.errors.any? # If there are errors, do something
# You can iterate through all messages by attribute type and validation message
# This will be something like:
# attribute = 'name'
# message = 'cannot be left blank'
@user.errors.each do |attribute, message|
# do stuff for each error
end
# Or if you prefer, you can get the full message in single string, like so:
# message = 'Name cannot be left blank'
@users.errors.full_messages.each do |message|
# do stuff for each error
end
# To get all errors associated with a single attribute, do the following:
if @user.errors.include?(:name)
name_errors = @user.errors[:name]
if name_errors.kind_of?(Array)
name_errors.each do |error|
# do stuff for each error on the name attribute
end
else
error = name_errors
# do stuff for the one error on the name attribute.
end
end
end
Of course you can also do any of this in the views instead of the controller, should you want to just display the first error to the user or something.
You could do the following:
def Lists():
my_list1 = [30,34,56]
my_list2 = [29,500,43]
for element in my_list1:
print(element >= 30)
for element in my_list2:
print(element >= 30)
Lists()
This will return the values that are greater than 30 as True, and the values that are smaller as false.
Notice that there is a difference between
set encoding
and
set fileencoding
In the first case, you'll change the output encoding that is shown in the terminal. In the second case, you'll change the output encoding of the file that is written.
Basically the height auto is only available for you after the element is rendered. If you set a fixed height, or if your element is not displayed you can't access it without any tricks.
Luckily there are some tricks you may use.
Clone the element, display it outside of the view give it height auto and you can take it from the clone and use it later for the main element. I use this function and seems to work well.
jQuery.fn.animateAuto = function(prop, speed, callback){
var elem, height, width;
return this.each(function(i, el){
el = jQuery(el), elem = el.clone().css({"height":"auto","width":"auto"}).appendTo("body");
height = elem.css("height"),
width = elem.css("width"),
elem.remove();
if(prop === "height")
el.animate({"height":height}, speed, callback);
else if(prop === "width")
el.animate({"width":width}, speed, callback);
else if(prop === "both")
el.animate({"width":width,"height":height}, speed, callback);
});
}
USAGE:
$(".animateHeight").bind("click", function(e){
$(".test").animateAuto("height", 1000);
});
$(".animateWidth").bind("click", function(e){
$(".test").animateAuto("width", 1000);
});
$(".animateBoth").bind("click", function(e){
$(".test").animateAuto("both", 1000);
});
The main functionality of attr_accessor over the other ones is the capability of accessing data from other files.
So you usually would have attr_reader or attr_writer but the good news is that Ruby lets you combine these two together with attr_accessor. I think of it as my to go method because it is more well rounded or versatile.
Also, peep in mind that in Rails, this is eliminated because it does it for you in the back end. So in other words: you are better off using attr_acessor over the other two because you don't have to worry about being to specific, the accessor covers it all. I know this is more of a general explanation but it helped me as a beginner.
Hope this helped!
When you change an ASP.NET website's configuration file, it restarts the application to reflect the changes...
When you do an IIS reset, that restarts all applications running on that IIS instance.
This is the only one that worked for me in .cshtml file:
@Html.ActionLink(
"Name",
"Action",
"Controller",
routeValues: null,
htmlAttributes:new Dictionary<string, object> {{ "onclick", "alert('Test');" }})
I hope this helps.
There is one more solution to set column Full text to true.
These solution for example didn't work for me
ALTER TABLE news ADD FULLTEXT(headline, story);
My solution.
NEXT STEPS
Refresh
Version of mssql 2014
I think this error can happen for various reasons, but it can be specific to the module you're using. For example I saw this using the uwsgi module, so had to set "uwsgi_read_timeout".
Because i want the solution to work on all machines and all browsers (within reason) I am trying to create a solution using javascript.
Isn't that a really good reason not to use javascript?
As others have said - cookies are probably your best option - just be aware of the limitations.
I have writen a single file AJAX tester. Enjoy it!!! Just because I have had problems with my hosting provider
<?php /*
Author: Luis Siquot
Purpose: Check ajax performance and errors
License: GPL
site5: Please don't drop json requests (nor delay)!!!!
*/
$r = (int)$_GET['r'];
$w = (int)$_GET['w'];
if($r) {
sleep($w);
echo json_encode($_GET);
die ();
} //else
?><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var _settimer;
var _timer;
var _waiting;
$(function(){
clearTable();
$('#boton').bind('click', donow);
})
function donow(){
var w;
var estim = 0;
_waiting = $('#total')[0].value * 1;
clearTable();
for(var r=1;r<=_waiting;r++){
w = Math.floor(Math.random()*6)+2;
estim += w;
dodebug({r:r, w:w});
$.ajax({url: '<?php echo $_SERVER['SCRIPT_NAME']; ?>',
data: {r:r, w:w},
dataType: 'json', // 'html',
type: 'GET',
success: function(CBdata, status) {
CBdebug(CBdata);
}
});
}
doStat(estim);
timer(estim+10);
}
function doStat(what){
$('#stat').replaceWith(
'<table border="0" id="stat"><tr><td>Request Time Sum=<th>'+what+
'<td> /2=<th>'+Math.ceil(what/2)+
'<td> /3=<th>'+Math.ceil(what/3)+
'<td> /4=<th>'+Math.ceil(what/4)+
'<td> /6=<th>'+Math.ceil(what/6)+
'<td> /8=<th>'+Math.ceil(what/8)+
'<td> (seconds)</table>'
);
}
function timer(what){
if(what) {_timer = 0; _settimer = what;}
if(_waiting==0) {
$('#showTimer')[0].innerHTML = 'completed in <b>' + _timer + ' seconds</b> (aprox)';
return ;
}
if(_timer<_settimer){
$('#showTimer')[0].innerHTML = _timer;
setTimeout("timer()",1000);
_timer++;
return;
}
$('#showTimer')[0].innerHTML = '<b>don\'t wait any more!!!</b>';
}
function CBdebug(what){
_waiting--;
$('#req'+what.r)[0].innerHTML = 'x';
}
function dodebug(what){
var tt = '<tr><td>' + what.r + '<td>' + what.w + '<td id=req' + what.r + '> '
$('#debug').append(tt);
}
function clearTable(){
$('#debug').replaceWith('<table border="1" id="debug"><tr><td>Request #<td>Wait Time<td>Done</table>');
}
</script>
</head>
<body>
<center>
<input type="button" value="start" id="boton">
<input type="text" value="80" id="total" size="2"> concurrent json requests
<table id="stat"><tr><td> </table>
Elapsed Time: <span id="showTimer"></span>
<table id="debug"></table>
</center>
</body>
Edit:
r means row and w waiting time.
When you initially press start button 80 (or any other number) of concurrent ajax request are launched by javascript, but as is known they are spooled by the browser. Also they are requested to the server in parallel (limited to certain number, this is the fact of this question). Here the requests are solved server side with a random delay (established by w). At start time all the time needed to solve all ajax calls is calculated. When test is finished, you can see if it took half, took third, took a quarter, etc of the total time, deducting which was the parallelism on the calls to the server. This is not strict, nor precise, but is nice to see in real time how ajaxs calls are completed (seeing the incoming cross). And is a very simple self contained script to show ajax basics.
Of course, this assumes, that server side is not introducing any extra limit.
Preferably use in conjunction with firebug net panel (or your browser's equivalent)
In (unusual) cases where you want to be able to dynamically change styles often -- e.g. a theme builder app -- adding <style> tags or calling CSSStyleSheet.insertRule() will result in a growing stylesheet, which can have performance and design debugging implications.
My approach only allows a single rule per selector/property combo, clearing any existing on setting any rule. The API is simple and flexible:
function addStyle(selector, rulename, value) {
var stylesheet = getAppStylesheet();
var cssRules = stylesheet.cssRules || stylesheet.rules;
var rule = stylesheet.insertRule(selector + ' { ' + rulename + ':' + value + ';}', cssRules.length);
}
function clearStyle(selector, rulename) {
var stylesheet = getAppStylesheet();
var cssRules = stylesheet.cssRules || stylesheet.rules;
for (var i=0; i<cssRules.length; i++) {
var rule = cssRules[i];
if (rule.selectorText == selector && rule.style[0] == rulename) {
stylesheet.deleteRule(i);
break;
}
}
}
function addStyles(selector, rules) {
var stylesheet = getAppStylesheet();
var cssRules = stylesheet.cssRules || stylesheet.rules;
for (var prop in rules) {
addStyle(selector, prop, rules[prop]);
}
}
function getAppStylesheet() {
var stylesheet = document.getElementById('my-styles');
if (!stylesheet) {
stylesheet = $('<style id="my-styles">').appendTo('head')[0];
}
stylesheet = stylesheet.sheet;
return stylesheet;
}
Usage:
addStyles('body', {
'background-color': 'black',
color: 'green',
margin: 'auto'
});
clearStyle('body', 'background-color');
addStyle('body', 'color', '#333')
Make sure that your code is returning a value of given return-type irrespective of conditional statements
This code snippet was showing the same error
int search(char arr[], int start, int end, char value)
{
int i;
for(i=start; i<=end; i++)
{
if(arr[i] == value)
return i;
}
}
This is the working code after little changes
int search(char arr[], int start, int end, char value)
{
int i;
int index=-1;
for(i=start; i<=end; i++)
{
if(arr[i] == value)
index=i;
}
return index;
}
See the abc module. Basically, you define __metaclass__ = abc.ABCMeta
on the class, then decorate each abstract method with @abc.abstractmethod
. Classes derived from this class cannot then be instantiated unless all abstract methods have been overridden.
If your class is already using a metaclass, derive it from ABCMeta
rather than type
and you can continue to use your own metaclass.
A cheap alternative (and the best practice before the abc
module was introduced) would be to have all your abstract methods just raise an exception (NotImplementedError
is a good one) so that classes derived from it would have to override that method to be useful.
However, the abc
solution is better because it keeps such classes from being instantiated at all (i.e., it "fails faster"), and also because you can provide a default or base implementation of each method that can be reached using the super()
function in derived classes.
Use Sequelize.or
:
var condition = {
where: Sequelize.and(
{ name: 'a project' },
Sequelize.or(
{ id: [1,2,3] },
{ id: { lt: 10 } }
)
)
};
Reference (search for Sequelize.or
)
Edit: Also, this has been modified and for the latest method see Morio's answer,
Jaap van Hengstum's answer works great however I think it is expensive and if we apply this method on a Button for example, the touch effect is lost since the view is rendered as a bitmap.
For me the best method and the simplest one consists in applying a mask on the view, like that:
@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
super.onSizeChanged(width, height, oldWidth, oldHeight);
float cornerRadius = <whatever_you_want>;
this.path = new Path();
this.path.addRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, Path.Direction.CW);
}
@Override
protected void dispatchDraw(Canvas canvas) {
if (this.path != null) {
canvas.clipPath(this.path);
}
super.dispatchDraw(canvas);
}
You can use browser default prompt window.
Instead of basic <input type="submit" (...) >
try:
<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>
The most simplist thing you can try is:
df=df[[ 'Mid', 'Upper', 'Lower', 'Net' , 'Zsore']]
So if I wanted to return a first name and last name like: Hello Fred Gerbig I would use the code below, this code works but is it actually the most correct way to do it?
import sys
def main():
if len(sys.argv) >= 2:
fname = sys.argv[1]
lname = sys.argv[2]
else:
name = 'World'
print 'Hello', fname, lname
if __name__ == '__main__':
main()
Edit: Found that the above code works with 2 arguments but crashes with 1. Tried to set len to 3 but that did nothing, still crashes (re-read the other answers and now understand why the 3 did nothing). How do I bypass the arguments if only one is entered? Or how would error checking look that returned "You must enter 2 arguments"?
Edit 2: Got it figured out:
import sys
def main():
if len(sys.argv) >= 2:
name = sys.argv[1] + " " + sys.argv[2]
else:
name = 'World'
print 'Hello', name
if __name__ == '__main__':
main()
If you don't want to use a function constructor like in Brian's answer you can use Object.create() instead:-
var myVar = {
count: 0
}
myVar.init = function(n) {
this.count = n
this.newDiv()
}
myVar.newDiv = function() {
var newDiv = document.createElement("div")
var contents = document.createTextNode("Click me!")
var func = myVar.func(this)
newDiv.addEventListener ?
newDiv.addEventListener('click', func, false) :
newDiv.attachEvent('onclick', func)
newDiv.appendChild(contents)
document.getElementsByTagName("body")[0].appendChild(newDiv)
}
myVar.func = function (thys) {
return function() {
thys.clickme()
}
}
myVar.clickme = function () {
this.count += 1
alert(this.count)
}
myVar.init(2)
var myVar1 = Object.create(myVar)
myVar1.init(55)
var myVar2 = Object.create(myVar)
myVar2.init(150)
// etc
Strangely, I couldn't get the above to work using newDiv.onClick, but it works with newDiv.addEventListener / newDiv.attachEvent.
Since Object.create is newish, include the following code from Douglas Crockford for older browsers, including IE8.
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o
return new F()
}
}
in standart Vi editor in this situation you should