It may happens because fake png files. You can use this command to check out fake pngs.
cd <YOUR_PROJECT/res/> && find . -name *.png | xargs pngcheck
And then,use ImageEditor(Ex, Pinta) to open fake pngs and re-save them to png.
Good luck.
I faced a similar problem but in my case I was trying to install Visual C++ Redistributable for Visual Studio 2015 Update 1 on Windows Server 2012 R2. However the root cause should be the same.
In short, you need to install the prerequisites of KB2999226.
In more details, the installation log I got stated that the installation for Windows Update KB2999226 failed. According to the Microsoft website here:
Prerequisites To install this update, you must have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) installed in Windows 8.1 or Windows Server 2012 R2. Or, install Service Pack 1 for Windows 7 or Windows Server 2008 R2. Or, install Service Pack 2 for Windows Vista and for Windows Server 2008.
After I have installed April 2014 on my Windows Server 2012 R2, I am able to install the Visual C++ Redistributable correctly.
aforementioned solutions did not help me, I could solve it by re-installing the Tomcat server which took few seconds.
The std::mbstowcs
function is what you are looking for:
char text[] = "something";
wchar_t wtext[20];
mbstowcs(wtext, text, strlen(text)+1);//Plus null
LPWSTR ptr = wtext;
for string
s,
string text = "something";
wchar_t wtext[20];
mbstowcs(wtext, text.c_str(), text.length());//includes null
LPWSTR ptr = wtext;
--> ED: The "L" prefix only works on string literals, not variables. <--
Remember before you merge you need to update the tag, it's quite different from branches (git pull origin tag_name
won't update your local tags). Thus, you need the following command:
git fetch --tags origin
Then you can perform git merge tag_name
to merge the tag onto a branch.
The number is held in an int[]
- the maximum size of an array is Integer.MAX_VALUE
. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE
.
Admittedly, this is implementation dependent, not part of the specification.
In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:
BigInteger
must support values in the range-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive) and may support values outside of that range.Implementation note:
BigInteger
constructors and operations throwArithmeticException
when the result is out of the supported range of-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive).
Notes:
This answer is old. This is just a proof of concept on how the desired outcome can be achieved. However, it may not be the best solution as per some comments below. I don't have any documentation to support or reject the following approach. Please refer to some of the comments below for further discussion on this topic.
Original Answer:
I answered this to
Yes you absolutely can do so using ng-init
and a simple init function.
Here is the example of it on plunker
HTML
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl" ng-init="init('James Bond','007')">
<h1>I am {{name}} {{id}}</h1>
</body>
</html>
JavaScript
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.init = function(name, id)
{
//This function is sort of private constructor for controller
$scope.id = id;
$scope.name = name;
//Based on passed argument you can make a call to resource
//and initialize more objects
//$resource.getMeBond(007)
};
});
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
It’s because you tried to update a table without a WHERE that uses a KEY column.
The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :
SET SQL_SAFE_UPDATES=0;
Or
close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .
BTW you can use TRUNCATE TABLE tablename;
to delete all the records .
Try this, it will work for sure.
When writing Rails migrations to convert a string column to an integer you'd usually say:
change_column :table_name, :column_name, :integer
However, PostgreSQL will complain:
PG::DatatypeMismatch: ERROR: column "column_name" cannot be cast automatically to type integer
HINT: Specify a USING expression to perform the conversion.
The "hint" basically tells you that you need to confirm you want this to happen, and how data shall be converted. Just say this in your migration:
change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'
The above will mimic what you know from other database adapters. If you have non-numeric data, results may be unexpected (but you're converting to an integer, after all).
You can use addBatch and executeBatch for batch insert in java See the Example : Batch Insert In Java
I had a similar issue not long time ago and this was how I solved it
.rotated-half-circle {_x000D_
/* Create the circle */_x000D_
width: 40px;_x000D_
height: 40px;_x000D_
border: 10px solid black;_x000D_
border-radius: 50%;_x000D_
/* Halve the circle */_x000D_
border-bottom-color: transparent;_x000D_
border-left-color: transparent;_x000D_
/* Rotate the circle */_x000D_
transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="rotated-half-circle"></div>
_x000D_
EDIT : It is not bleeding edge anymore : http://blog.docker.com/2016/02/docker-1-10/
Original Answer
I battled with it the whole night.
If you're not afraid of bleeding edge, the latest version of Docker engine and Docker compose both implement libnetwork.
With the right config file (that need to be put in version 2), you will create services that will all see each other. And, bonus, you can scale them with docker-compose as well (you can scale any service you want that doesn't bind port on the host)
Here is an example file
version: "2"
services:
router:
build: services/router/
ports:
- "8080:8080"
auth:
build: services/auth/
todo:
build: services/todo/
data:
build: services/data/
And the reference for this new version of compose file: https://github.com/docker/compose/blob/1.6.0-rc1/docs/networking.md
It also works without jQuery if you do the following changes:
Add type="button"
to the edit button in order not to trigger submission of the form.
Change the name of your function from change()
to anything else.
Don't use hidden="hidden"
, use CSS instead: style="display: none;"
.
The following code works for me:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">
<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
<img src="dba_images/textfield_key.png" alt=""/>
Edit
</button>
<button type="submit" class="positive" name="save" id="save" style="display:none;">
<img src="dba_images/apply2.png" alt=""/>
Save
</button>
<button class="regular" name="change" id="change" style="display:none;">
<img src="dba_images/textfield_key.png" alt=""/>
change
</button>
<button class="negative" name="cancel" id="cancel" style="display:none;">
<img src="dba_images/cross.png" alt=""/>
Cancel
</button>
</div>
</form>
</body>
</html>
Add by
Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_SECURE_NO_WARNINGS
1)Goto Server tab 2)Right on server -> general -> click on switch location. 3)Double click on the server -> under server location -> select tomcat installation. 4) restart the server.
This worked for me, but I used it as start. powershell outputs, waiting for service to finshing starting a few times then finishes and then a get-service on the remote server shows the service started.
**start**-service -inputobject $(get-service -ComputerName remotePC -Name Spooler)
Git GUI has a PUSH button - pardon the pun, and the dialog box it opens has a checkbox for tags.
I pushed a branch from the command line, without tags, and then tried again pushing the branch using the --follow-tags
option descibed above. The option is described as following annotated tags. My tags were simple tags.
I'd fixed something, tagged the commit with the fix in, (so colleagues can cherry pick the fix,) then changed the software version number and tagged the release I created (so colleagues can clone that release).
Git returned saying everything was up-to-date. It did not send the tags! Perhaps because the tags weren't annotated. Perhaps because there was nothing new on the branch.
When I did a similar push with Git GUI, the tags were sent.
For the time being, I am going to be pushing my changes to my remotes with Git GUI and not with the command line and --follow-tags
.
Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:
InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );
Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.
If you don't specify any path and put just the file (Just like you did), the default directory is always the one of your project (It's not inside the "src" folder. It's just inside the folder of your project).
Showing it graphically.
Centering on parent is done by constraining both sides to the parent. You can the constrain additional objects off of the centered object.
Note. Each arrow represents a "app:layout_constraintXXX_toYYY=" attribute. (6 in the picture)
onCreate()
method gets called when activity gets created, and its called only once in whole Activity life cycle.
where as onStart()
is called when activity is stopped... I mean it has gone to background and its onStop()
method is called by the os. onStart()
may be called multiple times in Activity life cycle.More details here
Adding the link as an Answer to draw more attention to Aaron Lavers' comment below the first answer.
This works like a charm - http://clipboardjs.com. Just add the clipboard.js or min file. While initiating, use the class which has the html component to be clicked and just pass the id of the component with the content to be copied, to the click element.
Change
$array=array_map('intval', explode(',', $string));
To:
$array= implode(',', array_map('intval', explode(',', $string)));
array_map returns an array, not a string. You need to convert the array to a comma separated string in order to use in the WHERE clause.
Option 1
: Declare a struct with an int and string and return a struct variable.
struct foo {
int bar1;
char bar2[MAX];
};
struct foo fun() {
struct foo fooObj;
...
return fooObj;
}
Option 2
: You can pass one of the two via pointer and make changes to the actual parameter through the pointer and return the other as usual:
int fun(char **param) {
int bar;
...
strcpy(*param,"....");
return bar;
}
or
char* fun(int *param) {
char *str = /* malloc suitably.*/
...
strcpy(str,"....");
*param = /* some value */
return str;
}
Option 3
: Similar to the option 2. You can pass both via pointer and return nothing from the function:
void fun(char **param1,int *param2) {
strcpy(*param1,"....");
*param2 = /* some calculated value */
}
The flowchart below can be of help when choosing one of the various semantic HTML5 elements:
PermGen space is replaced by MetaSpace in Java 8. The PermSize and MaxPermSize JVM arguments are ignored and a warning is issued if present at start-up.
Most allocations for the class metadata are now allocated out of native memory. * The classes that were used to describe class metadata have been removed.
Main difference between old PermGen and new MetaSpace is, you don't have to mandatory define upper limit of memory usage. You can keep MetaSpace space limit unbounded. Thus when memory usage increases you will not get OutOfMemoryError error. Instead the reserved native memory is increased to full-fill the increase memory usage.
You can define the max limit of space for MetaSpace, and then it will throw OutOfMemoryError : Metadata space. Thus it is important to define this limit cautiously, so that we can avoid memory waste.
This should be understood in the context of GitHub forks (where you fork a GitHub repo on GitHub before cloning that fork locally).
upstream
generally refers to the original repo that you have forkeddownstream
” and “upstream
”" for more on upstream
term) origin
is your fork: your own repo on GitHub, clone of the original repo of GitHubFrom the GitHub page:
When a repo is cloned, it has a default remote called
origin
that points to your fork on GitHub, not the original repo it was forked from.
To keep track of the original repo, you need to add another remote namedupstream
git remote add upstream git://github.com/<aUser>/<aRepo.git>
(with aUser/aRepo
the reference for the original creator and repository, that you have forked)
You will use upstream
to fetch from the original repo (in order to keep your local copy in sync with the project you want to contribute to).
git fetch upstream
(git fetch
alone would fetch from origin
by default, which is not what is needed here)
You will use origin
to pull and push since you can contribute to your own repository.
git pull
git push
(again, without parameters, 'origin' is used by default)
You will contribute back to the upstream
repo by making a pull request.
Use getch()
:
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
Windows alternative should be _getch().
If you're using Windows, this should be the full example:
#include <conio.h>
#include <ctype.h>
int main( void )
{
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
_getch();
}
P.S. as @Rörd noted, if you're on POSIX system, you need to make sure that curses library is setup right.
There are in fact 3 questions in your question :
What JB King has described is correct, but it is a particular, simple version, where in fact he mapped front, middle and bacn to an MVC layer. He mapped M to the back, V to the front, and C to the middle.
For many people, it is just fine, since they come from the ugly world where even MVC was not applied, and you could have direct DB calls in a view.
However in real, complex web applications, you indeed have two or three different layers, called front, middle and back. Each of them may have an associated database and a controller.
The front-end will be visible by the end-user. It should not be confused with the front-office, which is the UI for parameters and administration of the front. The front-end will usually be some kind of CMS or e-commerce Platform (Magento, etc.)
The middle-end is not compulsory and is where the business logics is. It will be based on a PIM, a MDM tool, or some kind of custom database where you enrich your produts or your articles (for CMS). It'll also be the place where you code business functions that need to be shared between differents frontends (for instance between the PC frontend and the API-based mobile application). Sometimes, an ESB or tool like ActiveMQ will be your middle-end
The back-end will be a 3rd layer, surrouding your source database or your ERP. It may be jsut the API wrting to and reading from your ERP. It may be your supplier DB, if you are doing e-commerce. In fact, it really depends on web projects, but it is always a central repository. It'll be accessed either through a DB call, through an API, or an Hibernate layer, or a full-featured back-end application
This description means that answering the other 2 questions is not possible in this thread, as bottlenecks really depend on what your 3 ends contain : what JB King wrote remains true for simple MVC architectures
at the time the question was asked (5 years ago), maybe the MVC pattern was not yet so widely adopted. Now, there is absolutely no reason why the MVC pattern would not be followed and a view would be tied to DB calls. If you read the question "Are there cases where they MUST overlap, and frontend/backend cannot be separated?" in a broader sense, with 3 different components, then there times when the 3 layers architecture is useless of course. Think of a simple personal blog, you'll not need to pull external data or poll RabbitMQ queues.
Another solution would be as below where the list is placed under a drop-down button.
<button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
>Markets<span class="caret"></span></button>
<ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
{{ form.markets }}
</ul>
A SOAP message is a XML document which is used to transmit your data. WSDL is an XML document which describes how to connect and make requests to your web service.
Basically SOAP messages are the data you transmit, WSDL tells you what you can do and how to make the calls.
A quick search in Google will yield many sources for additional reading (previous book link now dead, to combat this will put any new recommendations in comments)
Just noting your specific questions:
Are all SOAP messages WSDL's? No, they are not the same thing at all.
Is SOAP a protocol that accepts its own 'SOAP messages' or 'WSDL's? No - reading required as this is far off.
If they are different, then when should I use SOAP messages and when should I use WSDL's? Soap is structure you apply to your message/data for transfer. WSDLs are used only to determine how to make calls to the service in the first place. Often this is a one time thing when you first add code to make a call to a particular webservice.
I found the right answer to this one. Try TCPView from Sysinternals, now owned by Microsoft. You can find it at http://technet.microsoft.com/en-us/sysinternals/bb897437
The problem seems to be that you have misunderstood how async/await work with Entity Framework.
So, let's look at this code:
public IQueryable<URL> GetAllUrls()
{
return context.Urls.AsQueryable();
}
and example of it usage:
repo.GetAllUrls().Where(u => <condition>).Take(10).ToList()
What happens there?
IQueryable
object (not accessing database yet) using repo.GetAllUrls()
IQueryable
object with specified condition using .Where(u => <condition>
IQueryable
object with specified paging limit using .Take(10)
.ToList()
. Our IQueryable
object is compiled to sql (like select top 10 * from Urls where <condition>
). And database can use indexes, sql server send you only 10 objects from your database (not all billion urls stored in database)Okay, let's look at first code:
public async Task<IQueryable<URL>> GetAllUrlsAsync()
{
var urls = await context.Urls.ToListAsync();
return urls.AsQueryable();
}
With the same example of usage we got:
await context.Urls.ToListAsync();
.Why async/await is preferred to use? Let's look at this code:
var stuff1 = repo.GetStuff1ForUser(userId);
var stuff2 = repo.GetStuff2ForUser(userId);
return View(new Model(stuff1, stuff2));
What happens here?
var stuff1 = ...
userId
var stuff2 = ...
userId
So let's look to an async version of it:
var stuff1Task = repo.GetStuff1ForUserAsync(userId);
var stuff2Task = repo.GetStuff2ForUserAsync(userId);
await Task.WhenAll(stuff1Task, stuff2Task);
return View(new Model(stuff1Task.Result, stuff2Task.Result));
What happens here?
So good code here:
using System.Data.Entity;
public IQueryable<URL> GetAllUrls()
{
return context.Urls.AsQueryable();
}
public async Task<List<URL>> GetAllUrlsByUser(int userId) {
return await GetAllUrls().Where(u => u.User.Id == userId).ToListAsync();
}
Note, than you must add using System.Data.Entity
in order to use method ToListAsync()
for IQueryable.
Note, that if you don't need filtering and paging and stuff, you don't need to work with IQueryable
. You can just use await context.Urls.ToListAsync()
and work with materialized List<Url>
.
You may, redefine the a
tag using angular directive:
angular.module('myApp').directive('a', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
if ('disabled' in attrs) {
elem.on('click', function(e) {
e.preventDefault(); // prevent link click
});
}
}
};
});
In html:
<a href="nextPage" disabled>Next</a>
You can only type them manually, but the content assist helps you there, so it is pretty easy.
Add this line
<uses-permission android:name="android.permission."/>
and hit ctrl + space after the dot (or cmd + space on Mac). If you need an explanation for the permission, you can hit ctrl + q.
There is a version of string.Split
that takes an array of strings and a StringSplitOptions
parameter:
route -f causes damage. So we need to either disconnect the correct parts of the routing table or find out how to rebuild it.
maybe not as stylish, but easier:
#!/bin/bash
log="/var/log/yourlog"
/path/to/your/script.py 2>&1 | (while read; do echo "$REPLY" >> $log; done)
You can simply simply achieve it with any python module that gives you an interaction with command line(cmd
) like subprocess
, os
, etc.
but here I came up with examples on only two modules.
Here is syntax (command) cmd /c start browser_name "URL"
import os
# or open with iexplore
os.system('cmd /c start iexplore "http://your_url"')
# or open with chrome
os.system('cmd /c start chrome "http://your_url"')
__import__('subprocess').getoutput('cmd /c start iexplore "http://your_url"')
You can also run the command in the cmd it will work to or use other module call
click
which mainly used for writing command line utilities.
import click
click.launch('http://your_url')
try this it worked for me in ie 7 and ie 8
$(this).click(function (j) {
var href = ($(this).attr('href'));
window.location = href;
return true;
Try this using list comprehension:
import pandas as pd
df = pd.DataFrame(
[p, p.team, p.passing_att, p.passer_rating()] for p in game.players.passing()
)
I'm using PreviewKeyDown
private void _calendar_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e){
switch (e.KeyCode){
case Keys.Down:
case Keys.Right:
//action
break;
case Keys.Up:
case Keys.Left:
//action
break;
}
}
I know this may be too late for a better answer but a desired perfect solution must be a system like positioner. I mean, when system makes a positioning for an Editor field it places the field just up to the keyboard, so as UI/UX rules it is perfect.
What below code makes is the Android way positioning smoothly. First of all we keep the current scroll point as a reference point. Second thing is to find the best positioning scroll point for an editor, to do this we scroll to top, and then request the editor fields to make the ScrollView component to do the best positioning. Gatcha! We've learned the best position. Now, what we'll do is scroll smoothly from the previous point to the point we've found newly. If you want you may omit smooth scrolling by using scrollTo instead of smoothScrollTo only.
NOTE: The main container ScrollView is a member field named scrollViewSignup, because my example was a signup screen, as you may figure out a lot.
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(final View view, boolean b) {
if (b) {
scrollViewSignup.post(new Runnable() {
@Override
public void run() {
int scrollY = scrollViewSignup.getScrollY();
scrollViewSignup.scrollTo(0, 0);
final Rect rect = new Rect(0, 0, view.getWidth(), view.getHeight());
view.requestRectangleOnScreen(rect, true);
int new_scrollY = scrollViewSignup.getScrollY();
scrollViewSignup.scrollTo(0, scrollY);
scrollViewSignup.smoothScrollTo(0, new_scrollY);
}
});
}
}
});
If you want to use this block for all EditText instances, and quickly integrate it with your screen code. You can simply make a traverser like below. To do this, I've made the main OnFocusChangeListener a member field named focusChangeListenerToScrollEditor, and call it during onCreate as below.
traverseEditTextChildren(scrollViewSignup, focusChangeListenerToScrollEditor);
And the method implementation is as below.
private void traverseEditTextChildren(ViewGroup viewGroup, View.OnFocusChangeListener focusChangeListenerToScrollEditor) {
int childCount = viewGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = viewGroup.getChildAt(i);
if (view instanceof EditText)
{
((EditText) view).setOnFocusChangeListener(focusChangeListenerToScrollEditor);
}
else if (view instanceof ViewGroup)
{
traverseEditTextChildren((ViewGroup) view, focusChangeListenerToScrollEditor);
}
}
}
So, what we've done here is making all EditText instance children to call the listener at focus.
To reach this solution, I've checked it out all the solutions here, and generated a new solution for better UI/UX result.
Many thanks to all other answers inspiring me much.
Uri myUri = Uri.parse("http://www.google.com");
Here's the doc http://developer.android.com/reference/android/net/Uri.html#parse%28java.lang.String%29
In almost every case (that is: all cases except the very first ones), instance
won't be null. Acquiring a lock is more costly than a simple check, so checking once the value of instance
before locking is a nice and free optimization.
This pattern is called double-checked locking: http://en.wikipedia.org/wiki/Double-checked_locking
I suppose you want to get the content generated by PHP, if so use:
$Vdata = file_get_contents('http://YOUR_HOST/YOUR/FILE.php');
Otherwise if you want to get the source code of the PHP file, it's the same as a .txt file:
$Vdata = file_get_contents('path/to/YOUR/FILE.php');
With the tspan solution, let's say you don't know in advance where to put your line breaks: you can use this nice function, that I found here: http://bl.ocks.org/mbostock/7555321
That automatically does line breaks for long text svg for a given width in pixel.
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):
aptitude install debian-archive-keyring
In case it is some other keyring you need, check out
apt-cache search keyring | grep debian
My squeeze system shows all these:
debian-archive-keyring - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring - GnuPG archive keys of the Debian Edu archive
debian-keyring - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring - GnuPG archive keys for the emdebian repository
If you have special logic required for the first route only you can do the following:
loaded = false;
constructor(private router: Router....) {
router.events.pipe(filter(e => e instanceof NavigationEnd), take(1))
.subscribe((e) => {
this.loaded = true;
alert('loaded - this fires only once');
});
I had a need for this to hide my page footer, which was otherwise appearing at the top of the page. Also if you only want a loader for the first page you can use this.
Here's a shell script that does it without calling other programs:
#! /bin/env bash
#bash script to find the relative path between two directories
mydir=${0%/}
mydir=${0%/*}
creadlink="$mydir/creadlink"
shopt -s extglob
relpath_ () {
path1=$("$creadlink" "$1")
path2=$("$creadlink" "$2")
orig1=$path1
path1=${path1%/}/
path2=${path2%/}/
while :; do
if test ! "$path1"; then
break
fi
part1=${path2#$path1}
if test "${part1#/}" = "$part1"; then
path1=${path1%/*}
continue
fi
if test "${path2#$path1}" = "$path2"; then
path1=${path1%/*}
continue
fi
break
done
part1=$path1
path1=${orig1#$part1}
depth=${path1//+([^\/])/..}
path1=${path2#$path1}
path1=${depth}${path2#$part1}
path1=${path1##+(\/)}
path1=${path1%/}
if test ! "$path1"; then
path1=.
fi
printf "$path1"
}
relpath_test () {
res=$(relpath_ /path1/to/dir1 /path1/to/dir2 )
expected='../dir2'
test_results "$res" "$expected"
res=$(relpath_ / /path1/to/dir2 )
expected='path1/to/dir2'
test_results "$res" "$expected"
res=$(relpath_ /path1/to/dir2 / )
expected='../../..'
test_results "$res" "$expected"
res=$(relpath_ / / )
expected='.'
test_results "$res" "$expected"
res=$(relpath_ /path/to/dir2/dir3 /path/to/dir1/dir4/dir4a )
expected='../../dir1/dir4/dir4a'
test_results "$res" "$expected"
res=$(relpath_ /path/to/dir1/dir4/dir4a /path/to/dir2/dir3 )
expected='../../../dir2/dir3'
test_results "$res" "$expected"
#res=$(relpath_ . /path/to/dir2/dir3 )
#expected='../../../dir2/dir3'
#test_results "$res" "$expected"
}
test_results () {
if test ! "$1" = "$2"; then
printf 'failed!\nresult:\nX%sX\nexpected:\nX%sX\n\n' "$@"
fi
}
#relpath_test
I still had the issue above after installing postgresql using homebrew - I resolved it by putting /usr/local/bin in my path before /usr/bin
By default, it uses YAFFS - Yet Another Flash File System.
I use the solution posted by Umberto Raimondi extending type Double:
extension Double {
func roundTo(places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.
You can try using: netstat -a
to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp
On mac you will start your activemq using:
$ACTMQ_HOME/bin/activemq start
Or if your config file (activemq.xml ) if located in another location you can use:
$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}
In your case the executable is under: bin/macosx/activemq
so you need to use: $ACTMQ_HOME/bin/macosx/activemq start
For me this worked after I downloaded AJAX Unobtrusive library via NuGet :
Search and install via NuGet Packages: Microsoft.jQuery.Unobtrusive.Ajax
Than add in the view the references to jquery and AJAX Unobtrusive:
@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"> </script>
Yes you are right, your example doesn't do any harm (at least not on most modern operating systems). All the memory allocated by your process will be recovered by the operating system once the process exits.
Source: Allocation and GC Myths (PostScript alert!)
Allocation Myth 4: Non-garbage-collected programs should always deallocate all memory they allocate.
The Truth: Omitted deallocations in frequently executed code cause growing leaks. They are rarely acceptable. but Programs that retain most allocated memory until program exit often perform better without any intervening deallocation. Malloc is much easier to implement if there is no free.
In most cases, deallocating memory just before program exit is pointless. The OS will reclaim it anyway. Free will touch and page in the dead objects; the OS won't.
Consequence: Be careful with "leak detectors" that count allocations. Some "leaks" are good!
That said, you should really try to avoid all memory leaks!
Second question: your design is ok. If you need to store something until your application exits then its ok to do this with dynamic memory allocation. If you don't know the required size upfront, you can't use statically allocated memory.
// sample code for addition using JOptionPane
import javax.swing.JOptionPane;
public class Addition {
public static void main(String[] args) {
String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");
String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");
int num1 = Integer.parseInt(firstNumber);
int num2 = Integer.parseInt(secondNumber);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sum of two Integers", JOptionPane.PLAIN_MESSAGE);
}
}
You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.
Pick an encoding and stick with it:
f.write(printinfo.encode('utf8') + '\n')
or use io.open()
to create a file object that'll encode for you as you write to the file:
import io
f = io.open(filename, 'w', encoding='utf8')
You may want to read:
Pragmatic Unicode by Ned Batchelder
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky
before continuing.
Most of the time, when you try to assing value into object, and if the value is null, then this kind of exception occur. Please check this link.
for the sake of self learning, you can put some check condition. like
if (myObj== null)
Console.Write("myObj is NULL");
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.
Replace
onclick="changeLink();"
by
onclick="changeLink(); return false;"
to cancel its default action
In controller.
Exception closes the Entity Manager. This makes troubles for bulk insert. To continue, need to redefine it.
/**
* @var \Doctrine\ORM\EntityManager
*/
$em = $this->getDoctrine()->getManager();
foreach($to_insert AS $data)
{
if(!$em->isOpen())
{
$this->getDoctrine()->resetManager();
$em = $this->getDoctrine()->getManager();
}
$entity = new \Entity();
$entity->setUniqueNumber($data['number']);
$em->persist($entity);
try
{
$em->flush();
$counter++;
}
catch(\Doctrine\DBAL\DBALException $e)
{
if($e->getPrevious()->getCode() != '23000')
{
/**
* if its not the error code for a duplicate key
* value then rethrow the exception
*/
throw $e;
}
else
{
$duplication++;
}
}
}
You should probably use SQL_Latin1_General_Cp1_CI_AS_KI_WI
as your collation. The one you specify in your question is explictly case sensitive.
You can see a list of collations here.
A small modification to answer from Alex is turning on and off of auto calculation.
Surprisingly the unmodified code was working fine with VLOOKUP but failed with OFFSET. Also turning auto calculation off speeds up the save drastically.
Public Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven
' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
' Save the file in current director
OutputPath = ThisWorkbook.Path
If OutputPath <> "" Then
Application.Calculation = xlCalculationManual
' save for each sheet
For Each Sheet In Sheets
OutputFile = OutputPath & Application.PathSeparator & Sheet.Name & ".csv"
' make a copy to create a new book with this sheet
' otherwise you will always only get the first sheet
Sheet.Copy
' this copy will now become active
ActiveWorkbook.SaveAs Filename:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close
Next
Application.Calculation = xlCalculationAutomatic
End If
Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
Exit Sub
Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
"Source: " & Err.Source & " " & vbCrLf & _
"Number: " & Err.Number & " " & vbCrLf & _
"Description: " & Err.Description & " " & vbCrLf
GoTo Finally
End Sub
=>
is used in associative array key value assignment. Take a look at:
http://php.net/manual/en/language.types.array.php.
->
is used to access an object method or property. Example: $obj->method()
.
The stdlib.h file contains the header information or prototype of the malloc, calloc, realloc and free functions.
So to avoid this warning in ANSI C, you should include the stdlib header file.
Source: CodePath - UI Testing With Espresso
- Finally, we need to pull in the Espresso dependencies and set the test runner in our app build.gradle:
// build.gradle
...
android {
...
defaultConfig {
...
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
dependencies {
...
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
// Necessary if your app targets Marshmallow (since Espresso
// hasn't moved to Marshmallow yet)
exclude group: 'com.android.support', module: 'support-annotations'
}
androidTestCompile('com.android.support.test:runner:0.5') {
// Necessary if your app targets Marshmallow (since the test runner
// hasn't moved to Marshmallow yet)
exclude group: 'com.android.support', module: 'support-annotations'
}
}
I've added that to my gradle file and the warning disappeared.
Also, if you get any other dependency listed as conflicting, such as support-annotations, try excluding it too from the androidTestCompile dependencies.
You can try the trim() method.
String newString = oldString.trim();
Take a look at javadocs
Try something like this
jQuery
$('#toggle_icon').toggle(function() {
$('#toggle_icon').text('-');
$('#toggle_text').slideToggle();
}, function() {
$('#toggle_icon').text('+');
$('#toggle_text').slideToggle();
});
HTML
<a href="#" id="toggle_icon">+</a>
<div id="toggle_text" style="display: none">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
</div>
Moving element with respect to each other is something I needed a lot in a project of mine. So I wrote a small util class that moves an element in an list to a position relative to another element. Feel free to use (and improve upon ;))
import java.util.List;
public class ListMoveUtil
{
enum Position
{
BEFORE, AFTER
};
/**
* Moves element `elementToMove` to be just before or just after `targetElement`.
*
* @param list
* @param elementToMove
* @param targetElement
* @param pos
*/
public static <T> void moveElementTo( List<T> list, T elementToMove, T targetElement, Position pos )
{
if ( elementToMove.equals( targetElement ) )
{
return;
}
int srcIndex = list.indexOf( elementToMove );
int targetIndex = list.indexOf( targetElement );
if ( srcIndex < 0 )
{
throw new IllegalArgumentException( "Element: " + elementToMove + " not in the list!" );
}
if ( targetIndex < 0 )
{
throw new IllegalArgumentException( "Element: " + targetElement + " not in the list!" );
}
list.remove( elementToMove );
// if the element to move is after the targetelement in the list, just remove it
// else the element to move is before the targetelement. When we removed it, the targetindex should be decreased by one
if ( srcIndex < targetIndex )
{
targetIndex -= 1;
}
switch ( pos )
{
case AFTER:
list.add( targetIndex + 1, elementToMove );
break;
case BEFORE:
list.add( targetIndex, elementToMove );
break;
}
}
two of the best options are
$(this).parent("div:first")
$(this).parent().closest('div')
and of course you can find the class attr by
$(this).parent("div:first").attr("class")
$(this).parent().closest('div').attr("class")
I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:
div.hardware-accelarate {
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
I've made a plunkr setup for ya'll to test and tweak...
You can use jQuery’s show()
and hide()
methods. Like below:
JQuery:
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var val = $(this).attr("value");
var target = $("." + val);
$(".msg").not(target).hide();
$(target).show();
});
});
HTML:
<input type="radio" name="color" value="yellow"> Yellow
<input type="radio" name="color" value="red"> Red
<input type="radio" name="color" value="green"> Green
<div class="yellow msg">You have selected Yellow</div>
<div class="red msg">You have selected Red</div>
<div class="green msg">You have selected Green</div>
Here is an example: Show/hide DIV based on Radio Button click
I have an use case I don't believe any of your examples cover.
boxes = [b1, b2, b3]
items = [i1, i2, i3, i4, i5]
for j in range(len(boxes)):
boxes[j].putitemin(items[j])
I'm relatively new to python though so happy to learn a more elegant approach.
You can use:
db.foo.update({}, {$rename:{"name.additional":"name.last"}}, false, true);
Or to just update the docs which contain the property:
db.foo.update({"name.additional": {$exists: true}}, {$rename:{"name.additional":"name.last"}}, false, true);
The false, true
in the method above are: { upsert:false, multi:true }
. You need the multi:true
to update all your records.
Or you can use the former way:
remap = function (x) {
if (x.additional){
db.foo.update({_id:x._id}, {$set:{"name.last":x.name.additional}, $unset:{"name.additional":1}});
}
}
db.foo.find().forEach(remap);
In MongoDB 3.2 you can also use
db.students.updateMany( {}, { $rename: { "oldname": "newname" } } )
The general syntax of this is
db.collection.updateMany(filter, update, options)
https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/
A function pointer is like any other pointer, but it points to the address of a function instead of the address of data (on heap or stack). Like any pointer, it needs to be typed correctly. Functions are defined by their return value and the types of parameters they accept. So in order to fully describe a function, you must include its return value and the type of each parameter is accepts. When you typedef such a definition, you give it a 'friendly name' which makes it easier to create and reference pointers using that definition.
So for example assume you have a function:
float doMultiplication (float num1, float num2 ) {
return num1 * num2; }
then the following typedef:
typedef float(*pt2Func)(float, float);
can be used to point to this doMulitplication
function. It is simply defining a pointer to a function which returns a float and takes two parameters, each of type float. This definition has the friendly name pt2Func
. Note that pt2Func
can point to ANY function which returns a float and takes in 2 floats.
So you can create a pointer which points to the doMultiplication function as follows:
pt2Func *myFnPtr = &doMultiplication;
and you can invoke the function using this pointer as follows:
float result = (*myFnPtr)(2.0, 5.1);
This makes good reading: http://www.newty.de/fpt/index.html
Matheus de Oliveira created handy functions for JSON CRUD operations in postgresql. They can be imported using the \i directive. Notice the jsonb fork of the functions if jsonb if your data type.
9.3 json https://gist.github.com/matheusoliveira/9488951
9.4 jsonb https://gist.github.com/inindev/2219dff96851928c2282
Best way is to use import Random function
import random
print(random.sample(range(10), 10))
or without any library import:
n={}
for i in range(10):
n[i]=i
for p in range(10):
print(n.popitem()[1])
here the popitems removes and returns an arbitrary value from the dictionary n
.
$('.mybtn').on('click',_x000D_
function(){_x000D_
$('#myinput').attr('value', '');_x000D_
}_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<button class="mybtn">CLEAR</button>_x000D_
<input type="text" id="myinput" name="myinput" value="?????????">
_x000D_
This is how to loop through a javascript object and put the data into a table, code modified from @Vanuan's answer.
<body>_x000D_
<script>_x000D_
function createTable(objectArray, fields, fieldTitles) {_x000D_
let body = document.getElementsByTagName('body')[0];_x000D_
let tbl = document.createElement('table');_x000D_
let thead = document.createElement('thead');_x000D_
let thr = document.createElement('tr');_x000D_
_x000D_
for (p in objectArray[0]){_x000D_
let th = document.createElement('th');_x000D_
th.appendChild(document.createTextNode(p));_x000D_
thr.appendChild(th);_x000D_
_x000D_
}_x000D_
_x000D_
thead.appendChild(thr);_x000D_
tbl.appendChild(thead);_x000D_
_x000D_
let tbdy = document.createElement('tbody');_x000D_
let tr = document.createElement('tr');_x000D_
objectArray.forEach((object) => {_x000D_
let n = 0;_x000D_
let tr = document.createElement('tr');_x000D_
for (p in objectArray[0]){_x000D_
var td = document.createElement('td');_x000D_
td.setAttribute("style","border: 1px solid green");_x000D_
td.appendChild(document.createTextNode(object[p]));_x000D_
tr.appendChild(td);_x000D_
n++;_x000D_
};_x000D_
tbdy.appendChild(tr); _x000D_
});_x000D_
tbl.appendChild(tbdy);_x000D_
body.appendChild(tbl)_x000D_
return tbl;_x000D_
}_x000D_
_x000D_
createTable([_x000D_
{name: 'Banana', price: '3.04'}, // k[0]_x000D_
{name: 'Orange', price: '2.56'}, // k[1]_x000D_
{name: 'Apple', price: '1.45'}_x000D_
])_x000D_
</script>
_x000D_
One of the easiest solutions is using the following protocol:
protocol ScrollViewKeyboardDelegate: class {
var scrollView: UIScrollView? { get set }
func registerKeyboardNotifications()
func unregisterKeyboardNotifications()
}
extension ScrollViewKeyboardDelegate where Self: UIViewController {
func registerKeyboardNotifications() {
NotificationCenter.default.addObserver(
forName: UIResponder.keyboardWillChangeFrameNotification,
object: nil,
queue: nil) { [weak self] notification in
self?.keyboardWillBeShown(notification)
}
NotificationCenter.default.addObserver(
forName: UIResponder.keyboardWillHideNotification,
object: nil,
queue: nil) { [weak self] notification in
self?.keyboardWillBeHidden(notification)
}
}
func unregisterKeyboardNotifications() {
NotificationCenter.default.removeObserver(
self,
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil
)
NotificationCenter.default.removeObserver(
self,
name: UIResponder.keyboardWillHideNotification,
object: nil
)
}
func keyboardWillBeShown(_ notification: Notification) {
let info = notification.userInfo
let key = (info?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)
let aKeyboardSize = key?.cgRectValue
guard let keyboardSize = aKeyboardSize,
let scrollView = self.scrollView else {
return
}
let bottomInset = keyboardSize.height
scrollView.contentInset.bottom = bottomInset
scrollView.scrollIndicatorInsets.bottom = bottomInset
if let activeField = self.view.firstResponder {
let yPosition = activeField.frame.origin.y - bottomInset
if yPosition > 0 {
let scrollPoint = CGPoint(x: 0, y: yPosition)
scrollView.setContentOffset(scrollPoint, animated: true)
}
}
}
func keyboardWillBeHidden(_ notification: Notification) {
self.scrollView?.contentInset = .zero
self.scrollView?.scrollIndicatorInsets = .zero
}
}
extension UIView {
var firstResponder: UIView? {
guard !isFirstResponder else { return self }
return subviews.first(where: {$0.firstResponder != nil })
}
}
When you want to use this protocol, you only need to conform to it and assign your scroll view in your controller as follows:
class MyViewController: UIViewController {
@IBOutlet var scrollViewOutlet: UIScrollView?
var scrollView: UIScrollView?
public override func viewDidLoad() {
super.viewDidLoad()
self.scrollView = self.scrollViewOutlet
self.scrollView?.isScrollEnabled = true
self.registerKeyboardNotifications()
}
extension MyViewController: ScrollViewKeyboardDelegate {}
deinit {
self.unregisterKeyboardNotifications()
}
}
UPDATE:
onActivityCreated()
is deprecated from API Level 28.
onCreate():
The onCreate()
method in a Fragment
is called after the Activity
's onAttachFragment()
but before that Fragment
's onCreateView()
.
In this method, you can assign variables, get Intent
extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity
's onCreate()
is not finished, and so trying to access the View hierarchy here may result in a crash.
onCreateView():
After the onCreate()
is called (in the Fragment
), the Fragment
's onCreateView()
is called. You can assign your View
variables and do any graphical initialisations. You are expected to return a View
from this method, and this is the main UI view, but if your Fragment
does not use any layouts or graphics, you can return null
(happens by default if you don't override).
onActivityCreated():
As the name states, this is called after the Activity
's onCreate()
has completed. It is called after onCreateView()
, and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.
To sum up...
... they are all called in the Fragment
but are called at different times.
The onCreate()
is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View
variables you want to use in onCreateView()
. Afterwards, use onActivityCreated()
to do any final initialisations you want to do once everything has completed.
If you want to view the official Android documentation, it can be found here:
There are also some slightly different, but less developed questions/answers here on Stack Overflow:
jQuery.val() and .text() will never return 'undefined' for an empty selection. It always returns an empty string (i.e. ""). .html() will return null if the element doesn't exist though.You need to do:
if(page_name != '')
For other variables that don't come from something like jQuery.val() you would do this though:
if(typeof page_name != 'undefined')
You just have to use the typeof
operator.
VBScript doesn't have Try/Catch. (VBScript language reference. If it had Try, it would be listed in the Statements section.)
On Error Resume Next
is the only error handling in VBScript. Sorry. If you want try/catch, JScript is an option. It's supported everywhere that VBScript is and has the same capabilities.
You say
The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything).
In fact, it does do something (it causes your code to throw a FormatException
:"Invalid character in a Base-64 string") because the Convert.FromBase64String
does not consider "\0" to be a valid Base64 character.
byte[] data1 = Convert.FromBase64String("AAAA\0"); // Throws exception
byte[] data2 = Convert.FromBase64String("AAAA"); // Works
Solution: Get rid of the zero termination. (Maybe call .Trim("\0")
)
Notes:
The MSDN docs for Convert.FromBase64String
say it will throw a FormatException
when
The length of s, ignoring white space characters, is not zero or a multiple of 4.
-or-
The format of s is invalid. s contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
and that
The base 64 digits in ascending order from zero are the uppercase characters 'A' to 'Z', lowercase characters 'a' to 'z', numerals '0' to '9', and the symbols '+' and '/'.
I think there's a simpler solution: Just use the DialogInterface
argument that is passed to the onClick
method.
AlertDialog.Builder db = new AlertDialog.Builder(context);
db.setNegativeButton("cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface d, int arg1) {
db.cancel();
//here db.cancel will dismiss the builder
};
});
See, for example, http://www.mkyong.com/android/android-alert-dialog-example.
Intellisense is not auto refreshed and you should not fully rely on that
var objectList = objects.ToList();
objectList[0].SimpleInt=5;
This will update the original object as well. The new list will contain references to the objects contained within it, just like the original list. You can change the elements either and the update will be reflected in the other.
Now if you update a list (adding or deleting an item) that will not be reflected in the other list.
Fast canvas resample with good quality: http://jsfiddle.net/9g9Nv/442/
Update: version 2.0 (faster, web workers + transferable objects) - https://github.com/viliusle/Hermite-resize
/**
* Hermite resize - fast image resize/resample using Hermite filter. 1 cpu version!
*
* @param {HtmlElement} canvas
* @param {int} width
* @param {int} height
* @param {boolean} resize_canvas if true, canvas will be resized. Optional.
*/
function resample_single(canvas, width, height, resize_canvas) {
var width_source = canvas.width;
var height_source = canvas.height;
width = Math.round(width);
height = Math.round(height);
var ratio_w = width_source / width;
var ratio_h = height_source / height;
var ratio_w_half = Math.ceil(ratio_w / 2);
var ratio_h_half = Math.ceil(ratio_h / 2);
var ctx = canvas.getContext("2d");
var img = ctx.getImageData(0, 0, width_source, height_source);
var img2 = ctx.createImageData(width, height);
var data = img.data;
var data2 = img2.data;
for (var j = 0; j < height; j++) {
for (var i = 0; i < width; i++) {
var x2 = (i + j * width) * 4;
var weight = 0;
var weights = 0;
var weights_alpha = 0;
var gx_r = 0;
var gx_g = 0;
var gx_b = 0;
var gx_a = 0;
var center_y = (j + 0.5) * ratio_h;
var yy_start = Math.floor(j * ratio_h);
var yy_stop = Math.ceil((j + 1) * ratio_h);
for (var yy = yy_start; yy < yy_stop; yy++) {
var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;
var center_x = (i + 0.5) * ratio_w;
var w0 = dy * dy; //pre-calc part of w
var xx_start = Math.floor(i * ratio_w);
var xx_stop = Math.ceil((i + 1) * ratio_w);
for (var xx = xx_start; xx < xx_stop; xx++) {
var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;
var w = Math.sqrt(w0 + dx * dx);
if (w >= 1) {
//pixel too far
continue;
}
//hermite filter
weight = 2 * w * w * w - 3 * w * w + 1;
var pos_x = 4 * (xx + yy * width_source);
//alpha
gx_a += weight * data[pos_x + 3];
weights_alpha += weight;
//colors
if (data[pos_x + 3] < 255)
weight = weight * data[pos_x + 3] / 250;
gx_r += weight * data[pos_x];
gx_g += weight * data[pos_x + 1];
gx_b += weight * data[pos_x + 2];
weights += weight;
}
}
data2[x2] = gx_r / weights;
data2[x2 + 1] = gx_g / weights;
data2[x2 + 2] = gx_b / weights;
data2[x2 + 3] = gx_a / weights_alpha;
}
}
//clear and resize canvas
if (resize_canvas === true) {
canvas.width = width;
canvas.height = height;
} else {
ctx.clearRect(0, 0, width_source, height_source);
}
//draw
ctx.putImageData(img2, 0, 0);
}
I had the following property working for me in IntelliJ 2017
<properties>
<java.version>1.8</java.version>
</properties>
I use this trick for equal data bucketing. Instead of text result you get the number. Here is example for four buckets. Suppose you have data in A1:A100
range. Put this formula in B1:
=MAX(ROUNDUP(PERCENTRANK($A$1:$A$100,A1) *4,0),1)
Fill down the formula all across B column and you are done. The formula divides the range into 4 equal buckets and it returns the bucket number which the cell A1 falls into. The first bucket contains the lowest 25% of values.
Adjust the number of buckets according to thy wish:
=MAX(ROUNDUP(PERCENTRANK([Range],[OneCellOfTheRangeToTest]) *[NumberOfBuckets],0),1)
The number of observation in each bucket will be equal or almost equal. For example if you have a 100 observations and you want to split it into 3 buckets (like in your example) then the buckets will contain 33, 33, 34 observations. So almost equal. You do not have to worry about that - the formula works that out for you.
I got the errors to go away by installing the Windows Universal CRT SDK
component, which adds support for legacy Windows SDKs. You can install this using the Visual Studio Installer:
If the problem still persists, you should change the Target SDK in the Visual Studio Project : check whether the Windows SDK version is 10.0.15063.0.
In : Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0.
Then errno.h and other standard files will be found and it will compile.
For those looking to debug gradle dependencies in react-native
projects, the command is (executed from projectname/android
)
./gradlew app:dependencies --configuration compile
you can do that by xml
:
<TextView
android:id="@+id/textview"
android:maxLines="1" // or any number of lines you want
android:ellipsize="end"
/>
Here's my hack... =D
# Make sure no one can connect to this database except you!
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "UPDATE pg_database SET datallowconn=false WHERE datname='<DATABASE_NAME>';"
# Drop all existing connections except for yours!
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '<DATABASE_NAME>' AND pid <> pg_backend_pid();"
# Drop database! =D
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "DROP DATABASE <DATABASE_NAME>;"
I put this answer because include a command (above) to block new connections and because any attempt with the command...
REVOKE CONNECT ON DATABASE <DATABASE_NAME> FROM PUBLIC, <USERS_ETC>;
... do not works to block new connections!
Thanks to @araqnid @GoatWalker ! =D
You are mixing mysql and mysqli
Change these lines:
$sql = mysql_query("SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysql_num_rows($sql);
to
$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);
@vimal answer did not provide solution for me. It seems the orientation is not the current orientation, but from previous orientation. To fix it, I use [[UIDevice currentDevice] orientation]
- (void)orientationChanged:(NSNotification *)notification{
[self adjustViewsForOrientation:[[UIDevice currentDevice] orientation]];
}
Then
- (void) adjustViewsForOrientation:(UIDeviceOrientation) orientation { ... }
With this code I get the current orientation position.
NSDate *today = [NSDate date]; // it will give you current date
NSDate *newDate = [NSDate dateWithString:@"xxxxxx"]; // your date
NSComparisonResult result;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
result = [today compare:newDate]; // comparing two dates
if(result==NSOrderedAscending)
NSLog(@"today is less");
else if(result==NSOrderedDescending)
NSLog(@"newDate is less");
else
NSLog(@"Both dates are same");
There are other ways that you may use to compare an NSDate objects. Each of the methods will be more efficient at certain tasks. I have chosen the compare method because it will handle most of your basic date comparison needs.
Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:
Visual Studio 2008 for Python 2.7. See: https://docs.python.org/2.7/using/windows.html#compiling-python-on-windows
Visual Studio 2010 for Python 3.4. See: https://docs.python.org/3.4/using/windows.html#compiling-python-on-windows
Alternatively, you can use MinGw to compile extensions in a way that won't depend on others.
See: https://docs.python.org/2/install/#gnu-c-cygwin-MinGW or https://docs.python.org/3.4/install/#gnu-c-cygwin-mingw
This allows you to have one compiler to build your extensions for both versions of Python, Python 2.x and Python 3.x.
This it what you are looking for:
<input type="checkbox" [(ngModel)]="isChecked" (change)="checkValue(isChecked?'A':'B')" />
Inside your class:
checkValue(event: any){
console.log(event);
}
Also include FormsModule in app.module.ts
to make ngModel work !
Hope it Helps!
Both handlers get called.
You may be thinking of inline event binding (eg "onclick=..."
), where a big drawback is only one handler may be set for an event.
jQuery conforms to the DOM Level 2 event registration model:
The DOM Event Model allows registration of multiple event listeners on a single EventTarget. To achieve this, event listeners are no longer stored as attribute values
You're missing FIELDS TERMINATED BY ','
and it's assuming you're delimiting by tabs by default.
If you want many inserts
from rope.base.codeanalyze import ChangeCollector
c = ChangeCollector(code)
c.add_change(5, 5, '<span style="background-color:#339999;">')
c.add_change(10, 10, '</span>')
rend_code = c.get_changed()
If you have a plist of devices (eg maintained by @Tib above in https://stackoverflow.com/a/17655825/849616) to handle it if Swift 3 you'd use:
extension UIDevice {
/// Fetches the information about the name of the device.
///
/// - Returns: Should return meaningful device name, if not found will return device system code.
public static func modelName() -> String {
let physicalName = deviceSystemCode()
if let deviceTypes = deviceTypes(), let modelName = deviceTypes[physicalName] as? String {
return modelName
}
return physicalName
}
}
private extension UIDevice {
/// Fetches from system the code of the device
static func deviceSystemCode() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
/// Fetches the plist entries from plist maintained in https://stackoverflow.com/a/17655825/849616
///
/// - Returns: A dictionary with pairs of deviceSystemCode <-> meaningfulDeviceName.
static func deviceTypes() -> NSDictionary? {
if let fileUrl = Bundle.main.url(forResource: "your plist name", withExtension: "plist"),
let configurationDictionary = NSDictionary(contentsOf: fileUrl) {
return configurationDictionary
}
return nil
}
}
Later you can call it using UIDevice.modelName()
.
Additional credits go to @Tib (for plist), @Aniruddh Joshi (for deviceSystemCode()
function).
If anyone else is having a nullptr on the searchview variable, I found out that the item setup is a tiny bit different:
old:
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView"
new:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
pre-android x:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
For more information, it's updated documentation is located here.
UPDATE TX_Master_PCBA
SET TIMESTAMP2 = '2013-12-12 15:40:31.593',
G_FIELD='0000'
WHERE TIMESTAMP2 IN
(
SELECT TOP 1 TIMESTAMP2
FROM TX_Master_PCBA WHERE SERIAL_NO='0500030309'
ORDER BY TIMESTAMP2 DESC -- You need to decide what column you want to sort on
)
There is a probably a better “command line” way to do this, and I know this is a hack, but I’ve never been able to find a good solution.
Using TortoiseGIT: If you have a GIT commit where some file move operations are showing up as load of adds/deletes rather than renames, even though the files only have small changes, then do this:
The new commit will now properly show the file renames… which will help maintain proper file history.
//auth required or redirect
app.use('/account', function(req, res, next) {
console.log(req.path);
if ( !req.session.user ) {
res.redirect('/login?ref='+req.path);
} else {
next();
}
});
req.path is / when it should be /account ??
The reason for this is that Express subtracts the path your handler function is mounted on, which is '/account'
in this case.
Why do they do this?
Because it makes it easier to reuse the handler function. You can make a handler function that does different things for req.path === '/'
and req.path === '/goodbye'
for example:
function sendGreeting(req, res, next) {
res.send(req.path == '/goodbye' ? 'Farewell!' : 'Hello there!')
}
Then you can mount it to multiple endpoints:
app.use('/world', sendGreeting)
app.use('/aliens', sendGreeting)
Giving:
/world ==> Hello there!
/world/goodbye ==> Farewell!
/aliens ==> Hello there!
/aliens/goodbye ==> Farewell!
I met the same problem, the situation is I need to download flash game by embed tag and H5 game by iframe, I need a loading box there, when the flash or H5 download done, let the loading box display none. well, the flash one work well but when things go to iframe, I cannot find the property 'style' of null , so I add a clock to it , and it works
let clock = setInterval(() => {
clearInterval(clock)
clock = null
document.getElementById('loading-box').style.display = 'none'
}, 200)
You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:
textBox1.Text = s ?? "Is null";
The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.
More info here: https://msdn.microsoft.com/en-us/library/ms173224.aspx
And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015
textBox1.Text = customer?.orders?[0].description ?? "n/a";
This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.
More info here: https://msdn.microsoft.com/en-us/library/dn986595.aspx
<script>
function seetext(x){
x.type = "text";
}
function seeasterisk(x){
x.type = "password";
}
</script>
<body>
<img onmouseover="seetext(a)" onmouseout="seeasterisk(a)" border="0" src="smiley.gif" alt="Smiley" width="32" height="32">
<input id = "a" type = "password"/>
</body>
Try this see if it works
Question states 'I want to drop all the columns whose name contains the word "Test".'
test_columns = [col for col in df if 'Test' in col]
df.drop(columns=test_columns, inplace=True)
You should always check for the type too, since JavaScript is a duck typed language, so you may not know when and how the data changed in the middle of the process. So, here's the better solution:
let undefinedStr;
if (!undefinedStr) {
console.log("String is undefined");
}
let emptyStr = "";
if (!emptyStr) {
console.log("String is empty");
}
let nullStr = null;
if (!nullStr) {
console.log("String is null");
}
_x000D_
Attach your variable to the req
object, not res
.
Instead of
res.somevariable = variable1;
Have:
req.somevariable = variable1;
As others have pointed out, res.locals
is the recommended way of passing data through middleware.
I'm using Eclipse Europa, which also has the Favorite preference section:
Window > Preferences > Java > Editor > Content Assist > Favorites
In mine, I have the following entries (when adding, use "New Type" and omit the .*
):
org.hamcrest.Matchers.*
org.hamcrest.CoreMatchers.*
org.junit.*
org.junit.Assert.*
org.junit.Assume.*
org.junit.matchers.JUnitMatchers.*
All but the third of those are static imports. By having those as favorites, if I type "assertT
" and hit Ctrl+Space, Eclipse offers up assertThat
as a suggestion, and if I pick it, it will add the proper static import to the file.
From the documentation on expandtab
:
To insert a real tab when
expandtab
is on, useCTRL-V
<Tab>
. See also:retab
and ins-expandtab.
This option is reset when thepaste
option is set and restored when thepaste
option is reset.
So if you have a mapping for toggling the paste
option, e.g.
set pastetoggle=<F2>
you could also do <F2>Tab<F2>
.
Changing the log level is simple; modifying other portions of the configuration will pose a more in depth approach.
LogManager.getRootLogger().setLevel(Level.DEBUG);
The changes are permanent through the life cyle of the Logger
. On reinitialization the configuration will be read and used as setting the level at runtime does not persist the level change.
UPDATE: If you are using Log4j 2 you should remove the calls to setLevel
per the documentation as this can be achieved via implementation classes.
Calls to logger.setLevel() or similar methods are not supported in the API. Applications should remove these. Equivalent functionality is provided in the Log4j 2 implementation classes but may leave the application susceptible to changes in Log4j 2 internals.
You can list the tags on remote repository with ls-remote
, and then check if it's there. Supposing the remote reference name is origin
in the following.
git ls-remote --tags origin
And you can list tags local with tag
.
git tag
You can compare the results manually or in script.
You want java.text.DecimalFormat
input.name()
needs to be inside a function; classes contain declarations, not random code.
This is usually caused by a program that writes into the event log and is then uninstalled or moved.
Simply use substr for string
ex.
var str = "Hello world!";
var res = str.substr(1, str.length);
Result = ello world!
I have tried all of the methods and none of them works. The easiest way is to reinstall node from https://nodejs.org/en/download/
Simply download the pkg
and install it.
Now I have a working npm
and node
again.
Place the following after the setContentView() method.
final EditText edit = (EditText) findViewById(R.id.Your_Edit_ID);
String emailString = (String) edit.getText().toString();
Log.d("email",emailString);
Thanks, Achim Koellner, will expand your answer a bit:
var t0 = process.hrtime();
//Start of code to measure
//End of code
var timeInMilliseconds = process.hrtime(t0)[1]/1000000; // dividing by 1000000 gives milliseconds from nanoseconds
Please, note, that you shouldn't do anything apart from what you want to measure (for example, console.log
will also take time to execute and will affect performance tests).
Note, that in order by measure asynchronous functions execution time, you should insert var timeInMilliseconds = process.hrtime(t0)[1]/1000000;
inside the callback. For example,
var t0 = process.hrtime();
someAsyncFunction(function(err, results) {
var timeInMilliseconds = process.hrtime(t0)[1]/1000000;
});
Looks like you are doing a Python implementation of the Coursera Machine Learning Neural Network exercise. Here's what I did for randInitializeWeights(L_in, L_out)
#get a random array of floats between 0 and 1 as Pavel mentioned
W = numpy.random.random((L_out, L_in +1))
#normalize so that it spans a range of twice epsilon
W = W * 2 * epsilon
#shift so that mean is at zero
W = W - epsilon
In my case here, I just had to resurrect a server that was 9 years old, and Oracle was giving me this error.
For some reason, the server had been renamed, but the app/oracle/product/10.2.0/server/network/admin/listener.ora
file was still declaring a LISTENER with the old HOST.
I had to put the same name that I had in /etc/hostname
in the /etc/hosts
, and also fix the name used in the listener.ora
.
Sorry but all the answers I see here are either hacky or fail if you sneeze a little harder.
If you use a table you can (if you wish) add a space between the divs, set borders, padding...
<table width="100%" cellspacing="0">
<tr>
<td style="width:50%;">A</td>
<td style="width:50%;">B</td>
</tr>
</table>
Check a more complete example here: http://jsfiddle.net/qPduw/5/
Follow these two simple steps and get increase height of your UItextField
.
Step 1: right click on XIB file and open it as in "Source Code".
Step 2: Find the same UITextfield
source and set the frame as you want.
You can use these steps to change frame of any apple controls.
First use git remote update
, to bring your remote refs up to date. Then you can do one of several things, such as:
git status -uno
will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same.
git show-branch *master
will show you the commits in all of the branches whose names end in 'master' (eg master and origin/master).
If you use -v
with git remote update
(git remote -v update
) you can see which branches got updated, so you don't really need any further commands.
However, it looks like you want to do this in a script or program and end up with a true/false value. If so, there are ways to check the relationship between your current HEAD commit and the head of the branch you're tracking, although since there are four possible outcomes you can't reduce it to a yes/no answer. However, if you're prepared to do a pull --rebase
then you can treat "local is behind" and "local has diverged" as "need to pull", and the other two as "don't need to pull".
You can get the commit id of any ref using git rev-parse <ref>
, so you can do this for master and origin/master and compare them. If they're equal, the branches are the same. If they're unequal, you want to know which is ahead of the other. Using git merge-base master origin/master
will tell you the common ancestor of both branches, and if they haven't diverged this will be the same as one or the other. If you get three different ids, the branches have diverged.
To do this properly, eg in a script, you need to be able to refer to the current branch, and the remote branch it's tracking. The bash prompt-setting function in /etc/bash_completion.d
has some useful code for getting branch names. However, you probably don't actually need to get the names. Git has some neat shorthands for referring to branches and commits (as documented in git rev-parse --help
). In particular, you can use @
for the current branch (assuming you're not in a detached-head state) and @{u}
for its upstream branch (eg origin/master
). So git merge-base @ @{u}
will return the (hash of the) commit at which the current branch and its upstream diverge and git rev-parse @
and git rev-parse @{u}
will give you the hashes of the two tips. This can be summarized in the following script:
#!/bin/sh
UPSTREAM=${1:-'@{u}'}
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse "$UPSTREAM")
BASE=$(git merge-base @ "$UPSTREAM")
if [ $LOCAL = $REMOTE ]; then
echo "Up-to-date"
elif [ $LOCAL = $BASE ]; then
echo "Need to pull"
elif [ $REMOTE = $BASE ]; then
echo "Need to push"
else
echo "Diverged"
fi
Note: older versions of git didn't allow @
on its own, so you may have to use @{0}
instead.
The line UPSTREAM=${1:-'@{u}'}
allows you optionally to pass an upstream branch explicitly, in case you want to check against a different remote branch than the one configured for the current branch. This would typically be of the form remotename/branchname. If no parameter is given, the value defaults to @{u}
.
The script assumes that you've done a git fetch
or git remote update
first, to bring the tracking branches up to date. I didn't build this into the script because it's more flexible to be able to do the fetching and the comparing as separate operations, for example if you want to compare without fetching because you already fetched recently.
If navigating to another page . Navigator.pushReplacement()
can be used. It can be used If you're navigating from login to home screen. Or you can use .
AppBar(automaticallyImplyLeading: false)
One thing want to add is that if a property is declared as @dynamic it will not occupy memory (I confirmed with allocation instrument). A consequence is that you can declare property in class category.
I've noticed a lot of people are using this answer so I decided to update it a little bit. If you want to see the original answer, check below. The new answer demonstrates how you can add some style to your list.
ul > li {_x000D_
display: inline-block;_x000D_
/* You can also add some margins here to make it look prettier */_x000D_
zoom:1;_x000D_
*display:inline;_x000D_
/* this fix is needed for IE7- */_x000D_
}
_x000D_
<ul>_x000D_
<li> <a href="#">some item</a>_x000D_
_x000D_
</li>_x000D_
<li> <a href="#">another item</a>_x000D_
_x000D_
</li>_x000D_
</ul>
_x000D_
the only purpose of interfaces is to make sure that the class which implements an interface has got the correct methods in it as described by an interface? Or is there any other use of interfaces?
I am updating the answer with new features of interface, which have introduced with java 8 version.
From oracle documentation page on summary of interface :
An interface declaration can contain
The only methods that have implementations are default and static methods.
Uses of interface:
Serializable
interface may or may not have any relation between them except implementing that interfaceSome related SE questions with respect to difference between abstract class and interface and use cases with working examples:
What is the difference between an interface and abstract class?
How should I have explained the difference between an Interface and an Abstract class?
Have a look at documentation page to understand new features added in java 8 : default methods and static methods.
The thing is that you are using the option -t
when running your container.
Could you check if enabling the tty
option (see reference) in your docker-compose.yml file the container keeps running?
version: '2'
services:
ubuntu:
build: .
container_name: ubuntu
volumes:
- ~/sph/laravel52:/www/laravel
ports:
- "80:80"
tty: true
You installed PHP IntelliSense
extension, and this error because of it.
So if you want to fix this problem go to this menu:
File -> Preferences -> Settings
Now you can see 2 window. In the right window add below codes:
{
"php.validate.executablePath": "C:\\wamp64\\bin\\php\\php7.0.4\\php.exe",
"php.executablePath": "C:\\wamp64\\bin\\php\\php7.0.4\\php.exe"
}
Just like below image.
NOTICE: This address C:\\wamp64\\bin\\php\\php7.0.4\\php.exe
is my php7.exe
file address. Replace this address with own php7.exe
.
Working plunk here.
To add the new input just once, use the following code:
$(document).ready(function()
{
$("#insertAfterBtn").one("click", function(e)
{
var r = $('<input/>', { type: "button", id: "field", value: "I'm a button" });
$("body").append(r);
});
});
[... source stripped here ...]
<body>
<button id="insertAfterBtn">Insert after</button>
</body>
[... source stripped here ...]
To make it work in w3 editor, copy/paste the code below into 'source code' section inside w3 editor and then hit 'Submit Code':
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<button id="insertAfterBtn">Insert only one button after</button>
<div class="myClass"></div>
<div id="myId"></div>
</body>
<script type="text/javascript">
$(document).ready(function()
{
// when dom is ready, call this method to add an input to 'body' tag.
addInputTo($("body"));
// when dom is ready, call this method to add an input to a div with class=myClass
addInputTo($(".myClass"));
// when dom is ready, call this method to add an input to a div with id=myId
addInputTo($("#myId"));
$("#insertAfterBtn").one("click", function(e)
{
var r = $('<input/>', { type: "button", id: "field", value: "I'm a button" });
$("body").append(r);
});
});
function addInputTo(container)
{
var inputToAdd = $("<input/>", { type: "button", id: "field", value: "I was added on page load" });
container.append(inputToAdd);
}
</script>
</html>
You will need to repeat your call to strtol
inside your loops where you are asking the user to try again. In fact, if you make the loop a do { ... } while(...);
instead of while, you don't get a the same sort of repeat things twice behaviour.
You should also format your code so that it's possible to see where the code is inside a loop and not.
If you download the latest version of Adobe Acrobat Reader, it will tell you if your pdf is PDF/A compliant. Just open the PDF file and a big blue marking should appear.
OpenOffice supports PDF/A. For some reason "PDF/A-1" is called
"SelectPdfVersion"internally in OpenOffice. Just add 1 to that value and your output should be PDF/A.
The different values can be
0 = PDFXNONE
1 = PDFX1A2001
2 = PDFX32002
3 = PDFA1A
4 = PDFA1B
You set
FilterDatato be a
HashMap('SelectPdfVersion',1) //1 for PDFX1A2001
For a more detailed explanation, check out this post:
http://www.viget.com/inspire/webkit-transform-kill-the-flash/
I would definitely avoid applying it to the entire body. The key is to make sure whatever specific element you plan on transforming in the future starts out rendered in 3d so the browsers doesn't have to switch in and out of rendering modes. Adding
-webkit-transform: translateZ(0)
(or either of the options already mentioned) to the animated element will accomplish this.
i would assume fastest and simplest way would be have python call the system commands...
example..
import os
cmd = '<command line call>'
os.system(cmd)
Tar and gzip up the directory.... unzip and untar the directory in the desired place.
yah?
This works if you just want the count of unique values in e.g. the following range
=counta(unique(B4:B21))
If you're using Spring Boot, you can simply use @SpringBootTest
to load in your ApplicationContext
(which is what your stacktrace is barking at you about). This allows you to autowire in your spring-data repositories. Be sure to add @RunWith(SpringRunner.class)
so the spring-specific annotations are picked up:
@RunWith(SpringRunner.class)
@SpringBootTest
public class OrphanManagementTest {
@Autowired
private UserRepository userRepository;
@Test
public void saveTest() {
User user = new User("Tom");
userRepository.save(user);
Assert.assertNotNull(userRepository.findOne("Tom"));
}
}
You can read more about testing in spring boot in their docs.
You need a space on either side of the !=
. Change your code to:
str="Hello World"
str2=" "
str3=""
if [ ! -z "$str" -a "$str" != " " ]; then
echo "Str is not null or space"
fi
if [ ! -z "$str2" -a "$str2" != " " ]; then
echo "Str2 is not null or space"
fi
if [ ! -z "$str3" -a "$str3" != " " ]; then
echo "Str3 is not null or space"
fi
select convert(varchar(11), transfer_date, 106)
got me my desired result of date formatted as 07 Mar 2018
My column transfer_date
is a datetime type column and I am using SQL Server 2017 on azure
Just to add one case to unutbu's list.
One of the biggest practical differences for me of numpy ndarrays compared to numpy matrices or matrix languages like matlab, is that the dimension is not preserved in reduce operations. Matrices are always 2d, while the mean of an array, for example, has one dimension less.
For example demean rows of a matrix or array:
with matrix
>>> m = np.mat([[1,2],[2,3]])
>>> m
matrix([[1, 2],
[2, 3]])
>>> mm = m.mean(1)
>>> mm
matrix([[ 1.5],
[ 2.5]])
>>> mm.shape
(2, 1)
>>> m - mm
matrix([[-0.5, 0.5],
[-0.5, 0.5]])
with array
>>> a = np.array([[1,2],[2,3]])
>>> a
array([[1, 2],
[2, 3]])
>>> am = a.mean(1)
>>> am.shape
(2,)
>>> am
array([ 1.5, 2.5])
>>> a - am #wrong
array([[-0.5, -0.5],
[ 0.5, 0.5]])
>>> a - am[:, np.newaxis] #right
array([[-0.5, 0.5],
[-0.5, 0.5]])
I also think that mixing arrays and matrices gives rise to many "happy" debugging hours. However, scipy.sparse matrices are always matrices in terms of operators like multiplication.
I have found that "get-task-allow" needs to be checked for Development builds but unchecked for Distribution builds. The easiest way to accomplish this (AFAIK) is to have two entitlements files in your project: Entitlements.plist and EntitlementsDebug.plist - and to reference the proper one in the build project settings for the various configurations in your project.
Date.parse('01/01/2011 10:20:45') > Date.parse('01/01/2011 5:10:10')
> true
The 1st January is an arbitrary date, doesn't mean anything.
One of the way is Using below sql queries
--Size of All Table Space
--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME
--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)", FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);
This code will remove your whole cache of the application, You can check on app setting and open the app info and check the size of cache. Once you will use this code your cache size will be 0KB . So it and enjoy the clean cache.
if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
((ActivityManager) context.getSystemService(ACTIVITY_SERVICE))
.clearApplicationUserData();
return;
}
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
li = listView1.GetItemAt(e.X, e.Y);
X = e.X;
Y = e.Y;
}
private void listView1_MouseUp(object sender, MouseEventArgs e)
{
int nStart = X;
int spos = 0;
int epos = listView1.Columns[1].Width;
for (int i = 0; i < listView1.Columns.Count; i++)
{
if (nStart > spos && nStart < epos)
{
subItemSelected = i;
break;
}
spos = epos;
epos += listView1.Columns[i].Width;
}
li.SubItems[subItemSelected].Text = "9";
}
Always open in binary mode, in this case
file = open("Fruits.obj",'rb')
I've simply used this javascript code (using jquery but it's not strictly necessary) :
$( "#button" ).on( "click", function(event) {
$(this).attr('href', 'mailto:[email protected]?subject=hello');
});
When users click on the link, we replace the href attribute of the clicked element.
Be careful don't prevent the default comportment (event.preventDefault), we must let do it because we have just replaced the href where to go
I think robots can't see it, the address is protected from spams.
In linux you can use this commande :
for exemple i want to delete "*.py~" so my command should be ==>
find . -name "*.py~" -exec rm -f {} \;
As of Jackson 2.0, @JsonSerialize(include = xxx)
has been deprecated in favour of @JsonInclude
Try Logic Friday 1
It includes tools from the Univerity of California (Espresso and misII) and makes them usable with a GUI. You can enter boolean equations and truth tables as desired. It also features a graphical gate diagram input and output.
The minimization can be carried out two-level or multi-level. The two-level form yields a minimized sum of products. The multi-level form creates a circuit composed out of logical gates. The types of gates can be restricted by the user.
Your expression simplifies to C
.
The problem was that the async
keyword needs to appear before the lambda, not before the body:
db.Groups.ToList().ForEach(async (i) => {
await GetAdminsFromGroup(i.Gid);
});
I wasn't satisfied with other solutions because they either draw several time (using more power than necessary) or have problems with orientation. Here is what I used for a scaled square croppedImage from a UIImage * image.
CGFloat minimumSide = fminf(image.size.width, image.size.height);
CGFloat finalSquareSize = 600.;
//create new drawing context for right size
CGRect rect = CGRectMake(0, 0, finalSquareSize, finalSquareSize);
CGFloat scalingRatio = 640.0/minimumSide;
UIGraphicsBeginImageContext(rect.size);
//draw
[image drawInRect:CGRectMake((minimumSide - photo.size.width)*scalingRatio/2., (minimumSide - photo.size.height)*scalingRatio/2., photo.size.width*scalingRatio, photo.size.height*scalingRatio)];
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I found the solution here:
How to properly -filter multiple strings in a PowerShell copy script
You have to use -Include
flag for Get-ChildItem
My Example:
$Location = "C:\user\files"
$result = (Get-ChildItem $Location\* -Include *.png, *.gif, *.jpg)
Dont forget put "*" after path location.
With pandas it can be done as:
If lakes is your DataFrame:
area_dict = lakes.to_dict('records')
There seem to be a lot of solutions for Windows here but this is the simplest:
Tools -> Build System -> New Build System, type in the above, save as Browser.sublime-build
:
{
"cmd": "explorer $file"
}
Then go back to your HTML file. Tools -> Build System -> Browser. Then press CTRL-B
and the file will be opened in whatever browser is your system default browser.
You cannot simply add a link using CSS. CSS is used for styling.
You can style your using CSS.
If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.
You can accomplish that very easily using jQuery.
I have done a sample for you. You can refer that.
$('#link').attr('href','http://www.google.com');
This single line will do the trick.
You can also use react router dom library useHistory;
`
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
`
I know OP asked about the utils::read.csv
function, but let me provide an answer for these that come here searching how to do it using readr::read_csv
from the tidyverse.
read_csv ("test.csv", col_names=FALSE, col_types = cols (.default = "c", time = "i"))
This should set the default type for all columns as character, while time would be parsed as integer.
Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.
var closedStatusId = @(Model.ClosedStatusId);
Say Parent pom.xml contains 6 modules and you want to run A, B and F.
<modules>
<module>A</module>
<module>B</module>
<module>C</module>
<module>D</module>
<module>E</module>
<module>F</module>
</modules>
1- cd into parent project
mvn --projects A,B,F --also-make clean install
OR
mvn -pl A,B,F -am clean install
OR
mvn -pl A,B,F -amd clean install
Note: When you specify a project with the -am option, Maven will build all of the projects that the specified project depends upon (either directly or indirectly). Maven will examine the list of projects and walk down the dependency tree, finding all of the projects that it needs to build.
While the -am command makes all of the projects required by a particular project in a multi-module build, the -amd or --also-make-dependents option configures Maven to build a project and any project that depends on that project. When using --also-make-dependents, Maven will examine all of the projects in our reactor to find projects that depend on a particular project. It will automatically build those projects and nothing else.
As said above -- use Euclidean distance.
from math import hypot
def in_radius(c_x, c_y, r, x, y):
return math.hypot(c_x-x, c_y-y) <= r
Try using a list comprehension and the ternary operator.
>>> a=[1,2,3,1,3,2,1,1]
>>> [4 if x==1 else x for x in a]
[4, 2, 3, 4, 3, 2, 4, 4]
"Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section."
No one actually answered the above part of the original poster's question.
Here's the answer: http://www.456bereastreet.com/archive/201112/the_difference_between_widthauto_and_width100/
As long as the value of width is auto, the element can have horizontal margin, padding and border without becoming wider than its container...
On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border... This may be what you want, but most likely it isn’t.
To visualise the difference I made an example: http://www.456bereastreet.com/lab/width-auto/
If you want to convert a number to a hexadecimal representation of an RGBA color value, I've found this to be the most useful combination of several tips from here:
function toHexString(n) {
if(n < 0) {
n = 0xFFFFFFFF + n + 1;
}
return "0x" + ("00000000" + n.toString(16).toUpperCase()).substr(-8);
}
In Python 3, they made the /
operator do a floating-point division, and added the //
operator to do integer division (i.e., quotient without remainder); whereas in Python 2, the /
operator was simply integer division, unless one of the operands was already a floating point number.
In Python 2.X:
>>> 10/3
3
>>> # To get a floating point number from integer division:
>>> 10.0/3
3.3333333333333335
>>> float(10)/3
3.3333333333333335
In Python 3:
>>> 10/3
3.3333333333333335
>>> 10//3
3
For further reference, see PEP238.
Update 26/03/2016:
Instead of a link in the bottom right corner of the Settings form, the delete button is moved to the top right corner, saying:
Move To Trash Can
When you click on it, it will ask you for confirmation and move it to Trash Can
.
I didn't find the suggestion to use UIButton
in the answers above. So I will try to prove that this is a good choice.
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
In my situation using UIButton
was the best solution because:
UIView
as a container for UILabel
(i.e. I wanted to simplify math calculations for Autolayout in my cell)NSParagraphStyle
(because tailIndent
works incorrect with Autolayout – width of UILabel
is smaller than expected)UITextView
(because of possible side effects)UILabel
(less code fewer bugs)That's why using the contentEdgeInsets
from UIButton
in my situation became the easiest way to add text margins.
Hope this will help someone.
The padding options padx
and pady
of the grid
and pack
methods can take a 2-tuple that represent the left/right and top/bottom padding.
Here's an example:
import tkinter as tk
class MyApp():
def __init__(self):
self.root = tk.Tk()
l1 = tk.Label(self.root, text="Hello")
l2 = tk.Label(self.root, text="World")
l1.grid(row=0, column=0, padx=(100, 10))
l2.grid(row=1, column=0, padx=(10, 100))
app = MyApp()
app.root.mainloop()
Python might be overkill for this.
for file in *; do mencoder -some options $file; rm -f $file ; done
What @JosephSilber said, or pass the $event object into ng-click
callback and stop the propagation inside of it:
<div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
<img src="http://some_src" ng-click="nextImage($event)"/>
</div>
$scope.nextImage = function($event) {
$event.stopPropagation();
// Some code to find and display the next image
}
That is the release version of RHEL, or at least the release of RHEL from which the package supplying /etc/redhat-release was installed. A file like that is probably the closest you can come; you could also look at /etc/lsb-release.
It is theoretically possible to have packages installed from a mix of versions (e.g. upgrading part of the system to 5.5 while leaving other parts at 5.4), so if you depend on the versions of specific components you will need to check for those individually.
I had similar problem on windows, however sometimes eslint worked (in vscode) sometimes not. Later I realized that it works fine after a while. It was related to this issue: eslint server takes ~3-5 minutes until available
Setting enviroment variable NO_UPDATE_NOTIFIER=1
solved the problem
You would use off() to remove an event like so:
$("#saveBtn").off("click");
but this will remove all click events bound to this element. If the function with SaveQuestion is the only event bound then the above will do it. If not do the following:
$("#saveBtn").off("click").click(function() { saveQuestion(id); });
Problem was solved by simply:
node_modules
folder npm install
to get all packages with correct versionsIn my case, the problem occurred after changing Git branches, where a new branch was using a different set of node modules. The old branch was using TypeScript v1.8, the new one v2.0
jQuery.fn.outerHTML = function() {
return $(this).clone().wrap('<div>').parent().html();
};
$('input#password').replaceWith($('input.password').outerHTML().replace(/text/g,'password'));
Does this work?
display_errors = Off
Also, what version of php are you using?
`pip -v` or `pip --v`
However note, if you are using macos catelina which has the zsh (z shell) it might give you a whole bunch of things, so the best option is to try install the version or start as -- pip3
You can do like this:
SELECT convert(datetime, convert(date, '27-09-2013', 103), 103)
If you are using tcsh, then edit your ~/.cshrc
file to include the lines:
setenv CLICOLOR 1
setenv LSCOLORS dxfxcxdxbxegedabagacad
Where, like Martin says, LSCOLORS specifies the color scheme you want to use.
To generate the LSCOLORS you want to use, checkout this site
Like so:
//New Request
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
final OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
Here is another example which is working
public class EnregistrementVideoStackActivity extends Activity implements SurfaceHolder.Callback {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec = new MediaRecorder();
private Button startRecording = null;
File video;
private Camera mCamera;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_surface);
Log.i(null , "Video starting");
startRecording = (Button)findViewById(R.id.buttonstart);
mCamera = Camera.open();
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(0, 0, 0, "StartRecording");
menu.add(0, 1, 0, "StopRecording");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case 0:
try {
startRecording();
} catch (Exception e) {
String message = e.getMessage();
Log.i(null, "Problem Start"+message);
mrec.release();
}
break;
case 1: //GoToAllNotes
mrec.stop();
mrec.release();
mrec = null;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
protected void startRecording() throws IOException
{
mrec = new MediaRecorder(); // Works well
mCamera.unlock();
mrec.setCamera(mCamera);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setOutputFile("/sdcard/zzzz.3gp");
mrec.prepare();
mrec.start();
}
protected void stopRecording() {
mrec.stop();
mrec.release();
mCamera.release();
}
private void releaseMediaRecorder(){
if (mrec != null) {
mrec.reset(); // clear recorder configuration
mrec.release(); // release the recorder object
mrec = null;
mCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera != null){
Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
}
}
camera_surface.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<SurfaceView
android:id="@+id/surface_camera"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/buttonstart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/record_start" />
</RelativeLayout>
And of course include these permission in manifest:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Use config something like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>user-webservice</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
and then you'll need three files:
The *-servlet.xml
files are used automatically and each creates an application context for that servlet.
From the Spring documentation, 13.2. The DispatcherServlet:
The framework will, on initialization of a
DispatcherServlet
, look for a file named [servlet-name]-servlet.xml in theWEB-INF
directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).
I created the next class for this validation
public class EnumUtils {
public static boolean isPresent(Enum enumArray[], String name) {
for (Enum element: enumArray ) {
if(element.toString().equals(name))
return true;
}
return false;
}
}
example of usage :
public ArrivalEnum findArrivalEnum(String name) {
if (!EnumUtils.isPresent(ArrivalEnum.values(), name))
throw new EnumConstantNotPresentException(ArrivalEnum.class,"Arrival value must be 'FROM_AIRPORT' or 'TO_AIRPORT' ");
return ArrivalEnum.valueOf(name);
}
To complete Eric's answer (who left out popovers, navigation controllers, tabbarcontrollers, view controllers added as subviews to some other view controllers while traversing), here is my version of returning the currently visible view controller:
=====================================================================
- (UIViewController*)topViewController {
return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}
- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)viewController {
if ([viewController isKindOfClass:[UITabBarController class]]) {
UITabBarController* tabBarController = (UITabBarController*)viewController;
return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
} else if ([viewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navContObj = (UINavigationController*)viewController;
return [self topViewControllerWithRootViewController:navContObj.visibleViewController];
} else if (viewController.presentedViewController && !viewController.presentedViewController.isBeingDismissed) {
UIViewController* presentedViewController = viewController.presentedViewController;
return [self topViewControllerWithRootViewController:presentedViewController];
}
else {
for (UIView *view in [viewController.view subviews])
{
id subViewController = [view nextResponder];
if ( subViewController && [subViewController isKindOfClass:[UIViewController class]])
{
if ([(UIViewController *)subViewController presentedViewController] && ![subViewController presentedViewController].isBeingDismissed) {
return [self topViewControllerWithRootViewController:[(UIViewController *)subViewController presentedViewController]];
}
}
}
return viewController;
}
}
=====================================================================
And now all you need to do to get top most view controller is call the above method as follows:
UIViewController *topMostViewControllerObj = [self topViewController];
Maybe
x=> x.Lists.Include(l => l.Title)
.Where(l => l.Title != string.Empty)
.Where(l => l.InternalName != string.Empty)
?
You can probably also put it in the same where clause:
x=> x.Lists.Include(l => l.Title)
.Where(l => l.Title != string.Empty && l.InternalName != string.Empty)
If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.
After a some research i found the way to bypass ssl error Trust anchor for certification path not found. This might be not a good way to do but you can use it for a testing purpose.
private HttpsURLConnection httpsUrlConnection( URL urlDownload) throws Exception {
HttpsURLConnection connection=null;
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@SuppressLint("TrustAllX509TrustManager")
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@SuppressLint("TrustAllX509TrustManager")
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL"); // Add in try catch block if you get error.
sc.init(null, trustAllCerts, new java.security.SecureRandom()); // Add in try catch block if you get error.
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier usnoHostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
connection = (HttpsURLConnection) urlDownload.openConnection();
connection.setHostnameVerifier(usnoHostnameVerifier);
connection.setSSLSocketFactory(sslSocketFactory);
return connection;
}
I'll post this comment as answer, as I'm confident enough that what I asked is not possible.
I) Couple of similar questions trying to do the same, without success:
II) This article: Excel Pivot Table Calculated Field for example lists many restrictions of Calculated Field:
III) There is tiny limited possibility to use AVERAGE()
and similar function for a range of cells, but that applies only if Pivot table doesn't have grouped cells, which allows listing the cells as items in new group (right to "Fileds" listbox in above screenshot) and then user can calculate AVERAGE()
, referencing explicitly every item (cell), from Items listbox, as argument. Maybe it's better explained here: Calculate values in a PivotTable report
For my Pivot table it wasn't applicable because my range wasn't small enough, this option to be sane choice.
Look closely at URI's for ordinary web resources. Those are your template. Think of directory trees; use simple Linux-like file and directory names.
HelloWorld
isn't a really good class of resources. It doesn't appear to be a "thing". It might be, but it isn't very noun-like. A greeting
is a thing.
user-id
might be a noun that you're fetching. It's doubtful, however, that the result of your request is only a user_id. It's much more likely that the result of the request is a User. Therefore, user
is the noun you're fetching
www.example.com/greeting/user/x/
Makes sense to me. Focus on making your REST request a kind of noun phrase -- a path through a hierarchy (or taxonomy, or directory). Use the simplest nouns possible, avoiding noun phrases if possible.
Generally, compound noun phrases usually mean another step in your hierarchy. So you don't have /hello-world/user/
and /hello-universe/user/
. You have /hello/world/user/
and hello/universe/user/
. Or possibly /world/hello/user/
and /universe/hello/user/
.
The point is to provide a navigation path among resources.