Faced similar issue. In my case the repository and the type being managed where not in same package.
You should also be able to do:
apt install sudo
sudo -i -u tomcat
Then you should be the tomcat user. It's not clear which Linux distribution you're using, but this works with Ubuntu 18.04 LTS, for example.
Similarly using Bash regexp. Shall be able to snatch any key/value pair.
key="Body"
re="\"($key)\": \"([^\"]*)\""
while read -r l; do
if [[ $l =~ $re ]]; then
name="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
echo "$name=$value"
else
echo "No match"
fi
done
Regular expression can be tuned to match multiple spaces/tabs or newline(s). Wouldn't work if value has embedded "
. This is an illustration. Better to use some "industrial" parser :)
I too struggled with something similar. My guess is your actual problem is connecting to a SQL Express instance running on a different machine. The steps to do this can be summarized as follows:
At this point you should be able to connect remotely, using SQL Authentication, user "sqlUser" password "sql" to the SQL Express instance configured as above. A final tip and easy way to check this out is to create an empty text file with the .UDL extension, say "Test.UDL" on your desktop. Double-clicking to edit this file invokes the Microsoft Data Link Properties dialog with which you can quickly test your remote SQL connection
it has been a while but my answer may help someone:
if you already defined the relation properly you can use this:
var res = query.Products.Select(m => new
{
productID = product.Id,
categoryID = m.ProductCategory.Select(s => s.Category.ID).ToList(),
}).ToList();
Instead of using <hr>, you can one of the border of the enclosing block and display it as a horizontal line.
Here is a sample code:
The HTML:
<div class="title_block">
<h3>This is a header.</h3>
</div>
<p>Here is some sample paragraph text.<br>
This demonstrates that a horizontal line goes between the title and the paragraph.</p>
The CSS:
.title_block {
border-bottom: 1px solid #ddd;
padding-bottom: 5px;
margin-bottom: 5px;
}
when you start in cygwin, you are in your $HOME, like in unix generally, which maps to c:/cygwin/home/$YOURNAME by default. So you could put everything there.
You can also access the c: drive from cygwin through /cygdrive/c/ (e.g. /cygdrive/c/Documents anb Settings/yourname/Desktop).
According to Google Developers article, you can:
<script src="..." async>
or element.appendChild()
,You can prevent from this error by using hooks inside a function
I use
Response.Redirect(Page.Request.Path);
If you have to check for the Request.Params when the page is refresh use below. This will not rewrite the Request.Params to the URL.
Response.Redirect(Page.Request.Path + "?Remove=1");
git pull
is really just a shorthand for git pull <remote> <branchname>
, in most cases it's equivalent to git pull origin master
. You will need to add another remote and pull explicitly from it. This page describes it in detail:
Put your floating div(s)
in a div
and in CSS give it overflow:hidden;
it will work fine.
Based on Vikas answer but with a slight modification: The Uri is received by parameter:
private void showPhoto(Uri photoUri){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(photoUri, "image/*");
startActivity(intent);
}
Taking a tip from the Java code base, try using .CompareTo
and test for the zero comparison. This assumes the .CompareTo
function takes in to account floating point equality in an accurate manner. For instance,
System.Math.PI.CompareTo(System.Math.PI) == 0
This predicate should return true
.
In case you cannot use different stylesheet by dynamically loading it, you can use this function to modify CSS class. Hope it helps you...
function changeCss(className, classValue) {
// we need invisible container to store additional css definitions
var cssMainContainer = $('#css-modifier-container');
if (cssMainContainer.length == 0) {
var cssMainContainer = $('<div id="css-modifier-container"></div>');
cssMainContainer.hide();
cssMainContainer.appendTo($('body'));
}
// and we need one div for each class
classContainer = cssMainContainer.find('div[data-class="' + className + '"]');
if (classContainer.length == 0) {
classContainer = $('<div data-class="' + className + '"></div>');
classContainer.appendTo(cssMainContainer);
}
// append additional style
classContainer.html('<style>' + className + ' {' + classValue + '}</style>');
}
This function will take any class name and replace any previously set values with the new value. Note, you can add multiple values by passing the following into classValue: "background: blue; color:yellow"
.
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
You can also do this - Since you want one function to be used everywhere, you can do so by directly calling JqueryObject.function(). For example if you want to create your own function to manipulate any CSS on an element:
jQuery.fn.doSomething = function () {
this.css("position","absolute");
return this;
}
And the way to call it:
$("#someRandomDiv").doSomething();
Did you try this?
new File("<PATH OF YOUR FILE>").toURI().toString();
@Ali Shakiba your code needs some modification. Error part:
for (int i = 0; i < myArray.length; i++) {
myStatement.setString(i, myArray[i][1]);
myStatement.setString(i, myArray[i][2]);
}
Updated code:
String myArray[][] = {
{"1-1", "1-2"},
{"2-1", "2-2"},
{"3-1", "3-2"}
};
StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");
for (int i = 0; i < myArray.length - 1; i++) {
mySql.append(", (?, ?)");
}
mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());
for (int i = 0; i < myArray.length; i++) {
myStatement.setString((2 * i) + 1, myArray[i][1]);
myStatement.setString((2 * i) + 2, myArray[i][2]);
}
myStatement.executeUpdate();
function function_one() {
function_two();
}
function function_two() {
//enter code here
}
Before resetting the emulator first go to your projects "project navigator" screen and under the general -> depoyment info screen check that the main interface property is properly setup!
Easiest way is actually a script.
Run this on production:
USE MASTER;
BACKUP DATABASE [MyDatabase]
TO DISK = 'C:\temp\MyDatabase1.bak' -- some writeable folder.
WITH COPY_ONLY
This one command makes a complete backup copy of the database onto a single file, without interfering with production availability or backup schedule, etc.
To restore, just run this on your dev or test SQL Server:
USE MASTER;
RESTORE DATABASE [MyDatabase]
FROM DISK = 'C:\temp\MyDatabase1.bak'
WITH
MOVE 'MyDatabase' TO 'C:\Sql\MyDatabase.mdf', -- or wherever these live on target
MOVE 'MyDatabase_log' TO 'C:\Sql\MyDatabase_log.ldf',
REPLACE, RECOVERY
Then save these scripts on each server. One-click convenience.
Edit:
if you get an error when restoring that the logical names don't match, you can get them like this:
RESTORE FILELISTONLY
FROM disk = 'C:\temp\MyDatabaseName1.bak'
If you use SQL Server logins (not windows authentication) you can run this after restoring each time (on the dev/test machine):
use MyDatabaseName;
sp_change_users_login 'Auto_Fix', 'userloginname', null, 'userpassword';
If you specify @GET("foobar?a=5")
, then any @Query("b")
must be appended using &
, producing something like foobar?a=5&b=7
.
If you specify @GET("foobar")
, then the first @Query
must be appended using ?
, producing something like foobar?b=7
.
That's how Retrofit works.
When you specify @GET("foobar?")
, Retrofit thinks you already gave some query parameter, and appends more query parameters using &
.
Remove the ?
, and you will get the desired result.
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
You have a couple of questions here, so I'll address them separately:
My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).
You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:
Base table (what you have now):
| id primary_key sequence
| -- other columns here.
Items table:
| id primary_key sequence
| descript VARCHAR(30) UNIQUE
Map table:
| base_id bigint
| items_id bigint
Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.
And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.
If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.
Personally, I would use TEXT
. It does not sound like you'd gain much by making this a BLOB
, and TEXT
, in my experience, is easier to read if you're using some form of IDE.
Use <a>
with href instead of a <button>
solves my problem.
<ion-nav-buttons side="secondary">
<a class="button icon-right ion-plus-round" href="#/app/gosomewhere"></a>
</ion-nav-buttons>
You can use readlink
on /proc/self/fd/NNN
where NNN is the file descriptor. This will give you the name of the file as it was when it was opened — however, if the file was moved or deleted since then, it may no longer be accurate (although Linux can track renames in some cases). To verify, stat
the filename given and fstat
the fd you have, and make sure st_dev
and st_ino
are the same.
Of course, not all file descriptors refer to files, and for those you'll see some odd text strings, such as pipe:[1538488]
. Since all of the real filenames will be absolute paths, you can determine which these are easily enough. Further, as others have noted, files can have multiple hardlinks pointing to them - this will only report the one it was opened with. If you want to find all names for a given file, you'll just have to traverse the entire filesystem.
Martin's solution is very similar to mine, however how would you handle a default descriptions when the desired translation isn't found ?
Would that require an IFNULL() and another SELECT statement for each field ?
The default translation would be stored in the same table, where a flag like "isDefault" indicates wether that description is the default description in case none has been found for the current language.
Solution1 - set global config, by running this command:
git config --system core.longpaths true
Solution2 - or you can edit directly your specific git config file like below:
YourRepoFolder -> .git -> config:
[core]
repositoryformatversion = 0
filemode = false
...
longpaths = true <-- (add this line under core section)
Solution3 - when cloning a new repository: here.
A more naive version, at least you're sure that it'll work on all devices, without conversion and ES6 :
const children = parent.children;
for (var i = 0; i < children.length; i++){
console.log(children[i]);
}
This error raised up because you trying to update dict
object by using a wrong sequence (list
or tuple
) structure.
cash_id.create(cr, uid, lines,context=None)
trying to convert lines
into dict object:
(0, 0, {
'name': l.name,
'date': l.date,
'amount': l.amount,
'type': l.type,
'statement_id': exp.statement_id.id,
'account_id': l.account_id.id,
'account_analytic_id': l.analytic_account_id.id,
'ref': l.ref,
'note': l.note,
'company_id': l.company_id.id
})
Remove the second zero from this tuple to properly convert it into a dict object.
To test it your self, try this into python shell:
>>> l=[(0,0,{'h':88})]
>>> a={}
>>> a.update(l)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
a.update(l)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
>>> l=[(0,{'h':88})]
>>> a.update(l)
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
I hope this helps others with this error.
Run the httpd.exe from the command line to get an accurate description of the problem.
I had the same error message and it turned out to be a miss configured ServerRoot path. Even after running setup_xampp.bat the httpd.conf had the wrong path.
My error.log was empty and starting the service does not give an informative error message.
Use:
+ scale_y_continuous(labels = scales::percent)
Or, to specify formatting parameters for the percent:
+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))
(the command labels = percent
is obsolete since version 2.2.1 of ggplot2)
Here's code that I've verified to work. I use it for spawning MSBuild and listening to its output:
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data);
process.Start();
process.BeginOutputReadLine();
Docker sets the hostname to the container ID by default, but users can override this with --hostname
. Instead, inspect /proc
:
$ more /proc/self/cgroup
14:name=systemd:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
13:pids:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
12:hugetlb:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
11:net_prio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
10:perf_event:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
9:net_cls:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
8:freezer:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
7:devices:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
6:memory:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
5:blkio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
4:cpuacct:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
3:cpu:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
2:cpuset:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
1:name=openrc:/docker
Here's a handy one-liner to extract the container ID:
$ grep "memory:/" < /proc/self/cgroup | sed 's|.*/||'
7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
In my case using latest versions of following dependencies
solved my issue:
'com.google.android.gms:play-services-analytics:16.0.1'
'com.google.android.gms:play-services-tagmanager:16.0.1'
SELECT Lname, Cods, CASE WHEN Lname LIKE '% HN%' THEN SUBSTRING(Lname,
CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE
Lname END AS LnameTrue FROM dbo.____Fname_Lname
$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');
Your code has two problems:
.IsBestAnswe
does not match what you thoughtaddClass()
, not addclass()
.Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer')
part to add only:
$('.IsBestAnswer').addClass('bestanswer');
You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer
vs. bestanswer
).
Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:
x <- 1:10
y <- x + c(-0.5,0.5)
plot(x,y, xlim=c(0,11), ylim=c(-1,12))
fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )
fit7 <- lm( y ~ x + cos(x*pi) )
xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')
Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).
Basend on the example of Gary Kerr and as proposed here one may create empty circles related to specified values with following code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.markers import MarkerStyle
x = np.random.randn(60)
y = np.random.randn(60)
z = np.random.randn(60)
g=plt.scatter(x, y, s=80, c=z)
g.set_facecolor('none')
plt.colorbar()
plt.show()
You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.
Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt
) such as /mnt/c/Users/yourusername/files
within WSL. These files stay synced between WSL and Windows.
For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/
I tried moving away the object files with 0 bytes and fetching them again from the remote, and it worked:
find . -type f -size 0 -exec mv {} /tmp \;
git fetch
It fetched the missing objects from the remote and allowed me to continue working without reinitializing the whole repo.
Your error
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
appears because you must call setRequestHeader
after calling open
. Simply move your setRequestHeader
line below your open
line (but before send
):
xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);
While running Visual Studio 2012 behind a proxy, I received the following error message when checking for extension updates in the Visual Studio Gallery:
The remote server returned an unexpected response: (417) Expectation failed
A look around Google finally revealed a solution here:
Visual Studio 2012 Proxy Settings
http://www.jlpaonline.com/?p=176
Basically, he's saying the fix is to edit your devenv.exe.config file and change this:
<settings>
<ipv6 enabled="true"/>
</settings>
to this:
<settings>
<ipv6 enabled="true"/>
<servicePointManager expect100Continue="false"/>
</settings>
why don't you do it like this:
in the pages:
<html>
<head></head>
<body>
<?php $page = 'one'; include('navigation.php'); ?>
</body>
</html>
in the navigation.php
<div id="nav">
<ul>
<li>
<a <?php echo ($page == 'one') ? "class='active'" : ""; ?>
href="index1.php">Tab1</a>/</li>
<li>
<a <?php echo ($page == 'two') ? "class='active'" : ""; ?>
href="index2.php">Tab2</a>/</li>
<li>
<a <?php echo ($page == 'three') ? "class='active'" : ""; ?>
href="index3.php">Tab3</a>/</li>
</ul>
</div>
You will actually be able to control where in the page you are putting the navigation and what parameters you are passing to it.
Later edit: fixed syntax error.
The best way to do this is to use view port styles. It just does the work and no other techniques needed.
Code:
div{_x000D_
height:100vh;_x000D_
}
_x000D_
<div></div>
_x000D_
Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:
CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm
.PHONY: all
all: client
.PHONY: clean
clean:
$(RM) *~ *.o client
OBJECTS=client.o
client: $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)
In the line defining the client target change the order of $(LDFLAGS) as needed.
Press Ctrl+C
When you start the server it mentions this in the startup text.
Here is my version, adapted from others. I spent 30 minutes just now trying to remember how I came up with this, and @Jeremy 's answer seems to be the core inspiration. I didn't want to update Jeremy's answer, just in case I introduced bugs, so I am posting my version of it here.
I suggest pairing the full script with some inspiration taken from Kenneth Fisher's T-SQL Tuesday: What Permissions Does a Specific User Have?: This will allow you to answer compliance/audit questions bottom-up, as opposed to top-down.
EXECUTE AS LOGIN = '<loginname>'
SELECT token.name AS GroupNames
FROM sys.login_token token
JOIN sys.server_principals grp
ON token.sid = grp.sid
WHERE token.[type] = 'WINDOWS GROUP'
AND grp.[type] = 'G'
REVERT
To understand what this covers, consider Contoso\DB_AdventureWorks_Accounting
Windows AD Group with member Contoso\John.Doe
. John.Doe authenticates to AdventureWorks via server_principal Contoso\DB_AdventureWorks_Logins
Windows AD Group. If someone asks you, "What permissions does John.Doe have?", you cannot answer that question with just the below script. You need to then iterate through each row returned by the below script and join it to the above script. (You may also need to normalize for stale name
values via looking up the SID in your Active Directory provider.)
Here is the script, without incorporating such reverse look-up logic.
/*
--Script source found at : http://stackoverflow.com/a/7059579/1387418
Security Audit Report
1) List all access provisioned to a sql user or windows user/group directly
2) List all access provisioned to a sql user or windows user/group through a database or application role
3) List all access provisioned to the public role
Columns Returned:
UserName : SQL or Windows/Active Directory user account. This could also be an Active Directory group.
UserType : Value will be either 'SQL User' or 'Windows User'. This reflects the type of user defined for the
SQL Server user account.
PrinciaplUserName: if UserName is not blank, then UserName else DatabaseUserName
PrincipalType : Possible values are 'SQL User', 'Windows User', 'Database Role', 'Windows Group'
DatabaseUserName : Name of the associated user as defined in the database user account. The database user may not be the
same as the server user.
Role : The role name. This will be null if the associated permissions to the object are defined at directly
on the user account, otherwise this will be the name of the role that the user is a member of.
PermissionType : Type of permissions the user/role has on an object. Examples could include CONNECT, EXECUTE, SELECT
DELETE, INSERT, ALTER, CONTROL, TAKE OWNERSHIP, VIEW DEFINITION, etc.
This value may not be populated for all roles. Some built in roles have implicit permission
definitions.
PermissionState : Reflects the state of the permission type, examples could include GRANT, DENY, etc.
This value may not be populated for all roles. Some built in roles have implicit permission
definitions.
ObjectType : Type of object the user/role is assigned permissions on. Examples could include USER_TABLE,
SQL_SCALAR_FUNCTION, SQL_INLINE_TABLE_VALUED_FUNCTION, SQL_STORED_PROCEDURE, VIEW, etc.
This value may not be populated for all roles. Some built in roles have implicit permission
definitions.
ObjectName : Name of the object that the user/role is assigned permissions on.
This value may not be populated for all roles. Some built in roles have implicit permission
definitions.
ColumnName : Name of the column of the object that the user/role is assigned permissions on. This value
is only populated if the object is a table, view or a table value function.
*/
DECLARE @HideDatabaseDiagrams BIT = 1;
--List all access provisioned to a sql user or windows user/group directly
SELECT
[UserName] = CASE dbprinc.[type]
WHEN 'S' THEN dbprinc.[name] -- SQL User
WHEN 'U' THEN sprinc.[name] -- Windows User
WHEN 'R' THEN NULL -- Database Role
WHEN 'G' THEN NULL -- Windows Group
ELSE NULL
END,
[UserType] = CASE dbprinc.[type]
WHEN 'S' THEN 'SQL User'
WHEN 'U' THEN 'Windows User'
WHEN 'R' THEN NULL -- Database Role
WHEN 'G' THEN NULL -- Windows Group
ELSE dbprinc.[type]
END,
[PrincipalUserName] = COALESCE(
CASE dbprinc.[type]
WHEN 'S' THEN dbprinc.[name] -- SQL User
WHEN 'U' THEN sprinc.[name] -- Windows User
WHEN 'R' THEN NULL -- Database Role
WHEN 'G' THEN NULL -- Windows Group
ELSE NULL
END,
dbprinc.[name]
),
[PrincipalType] = CASE dbprinc.[type]
WHEN 'S' THEN 'SQL User'
WHEN 'U' THEN 'Windows User'
WHEN 'R' THEN 'Database Role'
WHEN 'G' THEN 'Windows Group'
END,
[DatabaseUserName] = dbprinc.[name],
[Role] = null,
[PermissionType] = perm.[permission_name],
[PermissionState] = perm.[state_desc],
[ObjectType] = obj.[type_desc],--perm.[class_desc],
[ObjectSchema] = OBJECT_SCHEMA_NAME(perm.major_id),
[ObjectName] = OBJECT_NAME(perm.major_id),
[ColumnName] = col.[name]
FROM
--database user
sys.database_principals dbprinc
LEFT JOIN
--Login accounts
sys.server_principals sprinc on dbprinc.[sid] = sprinc.[sid]
LEFT JOIN
--Permissions
sys.database_permissions perm ON perm.[grantee_principal_id] = dbprinc.[principal_id]
LEFT JOIN
--Table columns
sys.columns col ON col.[object_id] = perm.major_id
AND col.[column_id] = perm.[minor_id]
LEFT JOIN
sys.objects obj ON perm.[major_id] = obj.[object_id]
WHERE
dbprinc.[type] in ('S','U')
AND CASE
WHEN @HideDatabaseDiagrams = 1 AND
dbprinc.[name] = 'guest'
AND (
(
obj.type_desc = 'SQL_SCALAR_FUNCTION'
AND OBJECT_NAME(perm.major_id) = 'fn_diagramobjects'
)
OR (
obj.type_desc = 'SQL_STORED_PROCEDURE'
AND OBJECT_NAME(perm.major_id) IN
(
N'sp_alterdiagram',
N'sp_creatediagram',
N'sp_dropdiagram',
N'sp_helpdiagramdefinition',
N'sp_helpdiagrams',
N'sp_renamediagram'
)
)
)
THEN 0
ELSE 1
END = 1
UNION
--List all access provisioned to a sql user or windows user/group through a database or application role
SELECT
[UserName] = CASE memberprinc.[type]
WHEN 'S' THEN memberprinc.[name]
WHEN 'U' THEN sprinc.[name]
WHEN 'R' THEN NULL -- Database Role
WHEN 'G' THEN NULL -- Windows Group
ELSE NULL
END,
[UserType] = CASE memberprinc.[type]
WHEN 'S' THEN 'SQL User'
WHEN 'U' THEN 'Windows User'
WHEN 'R' THEN NULL -- Database Role
WHEN 'G' THEN NULL -- Windows Group
END,
[PrincipalUserName] = COALESCE(
CASE memberprinc.[type]
WHEN 'S' THEN memberprinc.[name]
WHEN 'U' THEN sprinc.[name]
WHEN 'R' THEN NULL -- Database Role
WHEN 'G' THEN NULL -- Windows Group
ELSE NULL
END,
memberprinc.[name]
),
[PrincipalType] = CASE memberprinc.[type]
WHEN 'S' THEN 'SQL User'
WHEN 'U' THEN 'Windows User'
WHEN 'R' THEN 'Database Role'
WHEN 'G' THEN 'Windows Group'
END,
[DatabaseUserName] = memberprinc.[name],
[Role] = roleprinc.[name],
[PermissionType] = perm.[permission_name],
[PermissionState] = perm.[state_desc],
[ObjectType] = obj.type_desc,--perm.[class_desc],
[ObjectSchema] = OBJECT_SCHEMA_NAME(perm.major_id),
[ObjectName] = OBJECT_NAME(perm.major_id),
[ColumnName] = col.[name]
FROM
--Role/member associations
sys.database_role_members members
JOIN
--Roles
sys.database_principals roleprinc ON roleprinc.[principal_id] = members.[role_principal_id]
JOIN
--Role members (database users)
sys.database_principals memberprinc ON memberprinc.[principal_id] = members.[member_principal_id]
LEFT JOIN
--Login accounts
sys.server_principals sprinc on memberprinc.[sid] = sprinc.[sid]
LEFT JOIN
--Permissions
sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN
--Table columns
sys.columns col on col.[object_id] = perm.major_id
AND col.[column_id] = perm.[minor_id]
LEFT JOIN
sys.objects obj ON perm.[major_id] = obj.[object_id]
WHERE
CASE
WHEN @HideDatabaseDiagrams = 1 AND
memberprinc.[name] = 'guest'
AND (
(
obj.type_desc = 'SQL_SCALAR_FUNCTION'
AND OBJECT_NAME(perm.major_id) = 'fn_diagramobjects'
)
OR (
obj.type_desc = 'SQL_STORED_PROCEDURE'
AND OBJECT_NAME(perm.major_id) IN
(
N'sp_alterdiagram',
N'sp_creatediagram',
N'sp_dropdiagram',
N'sp_helpdiagramdefinition',
N'sp_helpdiagrams',
N'sp_renamediagram'
)
)
)
THEN 0
ELSE 1
END = 1
UNION
--List all access provisioned to the public role, which everyone gets by default
SELECT
[UserName] = '{All Users}',
[UserType] = '{All Users}',
[PrincipalUserName] = '{All Users}',
[PrincipalType] = '{All Users}',
[DatabaseUserName] = '{All Users}',
[Role] = roleprinc.[name],
[PermissionType] = perm.[permission_name],
[PermissionState] = perm.[state_desc],
[ObjectType] = obj.type_desc,--perm.[class_desc],
[ObjectSchema] = OBJECT_SCHEMA_NAME(perm.major_id),
[ObjectName] = OBJECT_NAME(perm.major_id),
[ColumnName] = col.[name]
FROM
--Roles
sys.database_principals roleprinc
LEFT JOIN
--Role permissions
sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN
--Table columns
sys.columns col on col.[object_id] = perm.major_id
AND col.[column_id] = perm.[minor_id]
JOIN
--All objects
sys.objects obj ON obj.[object_id] = perm.[major_id]
WHERE
--Only roles
roleprinc.[type] = 'R' AND
--Only public role
roleprinc.[name] = 'public' AND
--Only objects of ours, not the MS objects
obj.is_ms_shipped = 0
AND CASE
WHEN @HideDatabaseDiagrams = 1 AND
roleprinc.[name] = 'public'
AND (
(
obj.type_desc = 'SQL_SCALAR_FUNCTION'
AND OBJECT_NAME(perm.major_id) = 'fn_diagramobjects'
)
OR (
obj.type_desc = 'SQL_STORED_PROCEDURE'
AND OBJECT_NAME(perm.major_id) IN
(
N'sp_alterdiagram',
N'sp_creatediagram',
N'sp_dropdiagram',
N'sp_helpdiagramdefinition',
N'sp_helpdiagrams',
N'sp_renamediagram'
)
)
)
THEN 0
ELSE 1
END = 1
ORDER BY
dbprinc.[Name],
OBJECT_NAME(perm.major_id),
col.[name],
perm.[permission_name],
perm.[state_desc],
obj.type_desc--perm.[class_desc]
You need to initialize whatever members you have in your struct, e.g.:
struct MyStruct {
private:
int someInt_;
float someFloat_;
public:
MyStruct(): someInt_(0), someFloat_(1.0) {} // Initializer list will set appropriate values
};
For a horizontal ProgressBar, you can use a ColorFilter
, too, like this:
progressBar.getProgressDrawable().setColorFilter(
Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
Note: This modifies the appearance of all progress bars in your app. To only modify one specific progress bar, do this:
Drawable progressDrawable = progressBar.getProgressDrawable().mutate();
progressDrawable.setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
progressBar.setProgressDrawable(progressDrawable);
If progressBar is indeterminate then use getIndeterminateDrawable()
instead of getProgressDrawable()
.
Since Lollipop (API 21) you can set a progress tint:
progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
WPF only
don't have the exact code to hand, but in a recent project I think I used MouseDown event and simply put this:
frmBorderless.DragMove();
Try this :
<style type="text/css">
.myTableStyle
{
position:absolute;
top:50%;
left:50%;
/*Alternatively you could use: */
/*
position: fixed;
bottom: 50%;
right: 50%;
*/
}
</style>
If you want to count specific words
function countWholeWords(text, keyword) {
const times = text.match(new RegExp(`\\b${keyword}\\b`, 'gi'));
if (times) {
console.log(`${keyword} occurs ${times.length} times`);
} else {
console.log(keyword + " does not occurs")
}
}
const text = `
In a professional context it often happens that private or corporate clients corder a publication to be
made and presented with the actual content still not being ready. Think of a news blog that's
filled with content hourly on the day of going live. However, reviewers tend to be distracted
by comprehensible content, say, a random text copied from a newspaper or the internet.
`
const wordsYouAreLookingFor = ["random", "cat", "content", "reviewers", "dog", "with"]
wordsYouAreLookingFor.forEach((keyword) => countWholeWords(text, keyword));
// random occurs 1 times
// cat does not occurs
// content occurs 3 times
// reviewers occurs 1 times
// dog does not occurs
// with occurs 2 times
.. the array I get is very little randomized. It generates a lot of blocks of successive numbers...
Sequences of random items often contain blocks of successive numbers, see the Gambler's Fallacy. For example:
.. we have just tossed four heads in a row .. Since the probability of a run of five successive heads is only 1/32 .. a person subject to the gambler's fallacy might believe that this next flip was less likely to be heads than to be tails. http://en.wikipedia.org/wiki/Gamblers_fallacy
find . \( -path '.**/.git' -o -path '.**/.hg' \) -prune -o -name '*.js' -print
The example above finds all *.js
files under the current directory, excluding folders .git
and .hg
, does not matter how deep these .git
and .hg
folders are.
Note: this also works:
find . \( -path '.*/.git' -o -path '.*/.hg' \) -prune -o -name '*.js' -print
but I prefer the **
notation for consistency with some other tools which would be off topic here.
The gear icon is no longer part of developer tools. Since Chome 30.0 it is not even possible to bring it back (In Google Chrome Developer Tools, the toolbar icons disappeared. What gives?)
For anyone needing just top or left position, slight modifications to @Nickf's readable code does the trick.
function getTopPos(el) {
for (var topPos = 0;
el != null;
topPos += el.offsetTop, el = el.offsetParent);
return topPos;
}
and
function getLeftPos(el) {
for (var leftPos = 0;
el != null;
leftPos += el.offsetLeft, el = el.offsetParent);
return leftPos;
}
my "keep it simple stupid" way ...it waste some resources , i know , but i dont care as my code keep simple so... First, add a footer with visibility GONE to your item_layout
<LinearLayout
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="80dp"
android:orientation="vertical"
android:visibility="gone">
</LinearLayout>
Then, set it visible on the last item
public void onBindViewHolder(ChannelAdapter.MyViewHolder holder, int position) {
boolean last = position==data.size()-1;
//....
holder.footer.setVisibility(View.GONE);
if (last && showFooter){
holder.footer.setVisibility(View.VISIBLE);
}
}
do the opposite for header
This one shows SQL that is currently "ACTIVE":-
select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/
This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:
select
object_name,
object_type,
session_id,
type, -- Type or system/user lock
lmode, -- lock mode in which session holds lock
request,
block,
ctime -- Time since current mode was granted
from
v$locked_object, all_objects, v$lock
where
v$locked_object.object_id = all_objects.object_id AND
v$lock.id1 = all_objects.object_id AND
v$lock.sid = v$locked_object.session_id
order by
session_id, ctime desc, object_name
/
This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.
COLUMN percent FORMAT 999.99
SELECT sid, to_char(start_time,'hh24:mi:ss') stime,
message,( sofar/totalwork)* 100 percent
FROM v$session_longops
WHERE sofar/totalwork < 1
/
public mySentences:Array<Object> = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
Or rather,
export interface type{
id:number;
text:string;
}
public mySentences:type[] = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
Scenario
In a college there are many students doing different courses, and after an examination we have to prepare a marks card showing grade. I can calculate grade two ways
1. I can write some code like this
if(totalMark <= 100 && totalMark > 90) { grade = "A+"; }
else if(totalMark <= 90 && totalMark > 80) { grade = "A"; }
else if(totalMark <= 80 && totalMark > 70) { grade = "B"; }
else if(totalMark <= 70 && totalMark > 60) { grade = "C"; }
2. You can ask user to enter grade definition some where and save that data
Something like storing into a database table
In the first case the grade is common for all the courses and if the rule changes the code needs to be changed. But for second case we are giving user the provision to enter grade based on their requirement. So the code will be not be changed when the grade rules changes.
That's the important thing when you give more provision for users to define business logic. The first case is nothing but Hard Coding.
So in your question if you ask the user to enter the path of the file at the start, then you can remove the hard coded path in your code.
I like Andrew's suggestion, and in fact the CSS rule only needs to be:
:checked + label {
font-weight: bold;
}
I like to rely on implicit association of the label
and the input
element, so I'd do something like this:
<label>
<input type="checkbox"/>
<span>Bah</span>
</label>
with CSS:
:checked + span {
font-weight: bold;
}
Example: http://jsfiddle.net/wrumsby/vyP7c/
So I run a functionally equivalent form of your code in an IPython notebook:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
fig, ax = plt.subplots()
ax.plot(xf, 2.0/N * np.abs(yf[:N//2]))
plt.show()
I get what I believe to be very reasonable output.
It's been longer than I care to admit since I was in engineering school thinking about signal processing, but spikes at 50 and 80 are exactly what I would expect. So what's the issue?
The problem here is that you don't have periodic data. You should always inspect the data that you feed into any algorithm to make sure that it's appropriate.
import pandas
import matplotlib.pyplot as plt
#import seaborn
%matplotlib inline
# the OP's data
x = pandas.read_csv('http://pastebin.com/raw.php?i=ksM4FvZS', skiprows=2, header=None).values
y = pandas.read_csv('http://pastebin.com/raw.php?i=0WhjjMkb', skiprows=2, header=None).values
fig, ax = plt.subplots()
ax.plot(x, y)
Unfortunately .mov files are not supported with html5 video playback. You can see what filetypes are supported here:
https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats
If you need to be able to play these formats with your html5 video player, you'll need to first convert your videofile--perhaps with something like this:
You need to select that column:
In [41]:
df.loc[df['First Season'] > 1990, 'First Season'] = 1
df
Out[41]:
Team First Season Total Games
0 Dallas Cowboys 1960 894
1 Chicago Bears 1920 1357
2 Green Bay Packers 1921 1339
3 Miami Dolphins 1966 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 1950 1003
So the syntax here is:
df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]
You can check the docs and also the 10 minutes to pandas which shows the semantics
EDIT
If you want to generate a boolean indicator then you can just use the boolean condition to generate a boolean Series and cast the dtype to int
this will convert True
and False
to 1
and 0
respectively:
In [43]:
df['First Season'] = (df['First Season'] > 1990).astype(int)
df
Out[43]:
Team First Season Total Games
0 Dallas Cowboys 0 894
1 Chicago Bears 0 1357
2 Green Bay Packers 0 1339
3 Miami Dolphins 0 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 0 1003
you can do it with Procedure also so i have a procedure for this
DELIMITER $$
CREATE PROCEDURE copyTo()
BEGIN
DECLARE x INT;
DECLARE str varchar(45);
SET x = 1;
set str = '';
WHILE x < 5 DO
set str = (select source_col from emp where id=x);
update emp set target_col =str where id=x;
SET x = x + 1;
END WHILE;
END$$
DELIMITER ;
Here's a solution with flexbox
for images with variable width and height:
.container {
display: flex;
flex-wrap: no-wrap;
overflow-x: auto;
margin: 20px;
}
img {
flex: 0 0 auto;
width: auto;
height: 100px;
max-width: 100%;
margin-right: 10px;
}
Example: JsFiddle
My problem was that I tried to import a Django model before calling django.setup()
This worked for me:
import django
django.setup()
from myapp.models import MyModel
The above script is in the project root folder.
By publishing your whole node_modules
folder you are deploying far more files than you will actually need in production.
Instead, use a task runner as part of your build process to package up those files you require, and deploy them to your wwwroot
folder. This will also allow you to concat and minify your assets at the same time, rather than having to serve each individual library separately.
You can then also completely remove the FileServer
configuration and rely on UseStaticFiles
instead.
Currently, gulp is the VS task runner of choice. Add a gulpfile.js
to the root of your project, and configure it to process your static files on publish.
For example, you can add the following scripts
section to your project.json
:
"scripts": {
"prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
},
Which would work with the following gulpfile (the default when scaffolding with yo
):
/// <binding Clean='clean'/>
"use strict";
var gulp = require("gulp"),
rimraf = require("rimraf"),
concat = require("gulp-concat"),
cssmin = require("gulp-cssmin"),
uglify = require("gulp-uglify");
var webroot = "./wwwroot/";
var paths = {
js: webroot + "js/**/*.js",
minJs: webroot + "js/**/*.min.js",
css: webroot + "css/**/*.css",
minCss: webroot + "css/**/*.min.css",
concatJsDest: webroot + "js/site.min.js",
concatCssDest: webroot + "css/site.min.css"
};
gulp.task("clean:js", function (cb) {
rimraf(paths.concatJsDest, cb);
});
gulp.task("clean:css", function (cb) {
rimraf(paths.concatCssDest, cb);
});
gulp.task("clean", ["clean:js", "clean:css"]);
gulp.task("min:js", function () {
return gulp.src([paths.js, "!" + paths.minJs], { base: "." })
.pipe(concat(paths.concatJsDest))
.pipe(uglify())
.pipe(gulp.dest("."));
});
gulp.task("min:css", function () {
return gulp.src([paths.css, "!" + paths.minCss])
.pipe(concat(paths.concatCssDest))
.pipe(cssmin())
.pipe(gulp.dest("."));
});
gulp.task("min", ["min:js", "min:css"]);
To open the terminal:
Please find more about integrated terminal here https://code.visualstudio.com/docs/editor/integrated-terminal
@Howard Hinnant's answer is both correct and comprehensive. But it might be misunderstood if it's read too quickly, because std::terminate()
(whole process) happens to have the same name as the "terminating" that @Alexander V had in mind (1 thread).
Summary: "terminate 1 thread + forcefully (target thread doesn't cooperate) + pure C++11 = No way."
Execute:
rails generate migration add_column_to_table column:boolean
It will generate this migration:
class AddColumnToTable < ActiveRecord::Migration
def change
add_column :table, :column, :boolean
end
end
Set the default value adding :default => 1
add_column :table, :column, :boolean, :default => 1
Run:
rake db:migrate
For all that you add xmlbeans-2.3.0.jar and it is not working,you must use HSSFWorkbook instead of XSSFWorkbook after add jar.For instance;
Workbook workbook = new HSSFWorkbook();
Sheet listSheet = workbook.createSheet("Kisi Listesi");
int rowIndex = 0;
for (KayitParam kp : kayitList) {
Row row = listSheet.createRow(rowIndex++);
int cellIndex = 0;
row.createCell(cellIndex++).setCellValue(kp.getAd());
row.createCell(cellIndex++).setCellValue(kp.getSoyad());
row.createCell(cellIndex++).setCellValue(kp.getEposta());
row.createCell(cellIndex++).setCellValue(kp.getCinsiyet());
row.createCell(cellIndex++).setCellValue(kp.getDogumtarihi());
row.createCell(cellIndex++).setCellValue(kp.getTahsil());
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
AMedia amedia = new AMedia("Kisiler.xls", "xls",
"application/file", baos.toByteArray());
Filedownload.save(amedia);
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
Cell spacing and margin is the space between cells.
Cell padding is space inside cells, between the cell border (even if invisible) and the cell content, such as text.
You can use either of the following ways listed below:
Manage Jenkins -> Configure System -> Global Properties -> Environment Variables -> Add
As Seth stated thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occuring.
Consider the following method:
private int myInt = 0;
public int AddOne()
{
int tmp = myInt;
tmp = tmp + 1;
myInt = tmp;
return tmp;
}
Now thread A
and thread B
both would like to execute AddOne()
. but A
starts first and reads the value of myInt (0)
into tmp
. Now for some reason the scheduler decides to halt thread A
and defer execution to thread B
. Thread B
now also reads the value of myInt
(still 0
) into it's own variable tmp
. Thread B
finishes the entire method, so in the end myInt = 1
. And 1
is returned. Now it's Thread A
's turn again. Thread A
continues. And adds 1
to tmp
(tmp
was 0
for thread A
). And then saves this value in myInt
. myInt
is again 1
.
So in this case the method AddOne()
was called two times, but because the method was not implemented in a thread safe way the value of myInt
is not 2
, as expected, but 1
because the second thread read the variable myInt
before the first thread finished updating it.
Creating thread safe methods is very hard in non trivial cases. And there are quite a few techniques. In Java you can mark a method as synchronized, this means that only one thread can execute that method at a given time. The other threads wait in line. This makes a method thread safe, but if there is a lot of work to be done in a method, then this wastes a lot of time. Another technique is to 'mark only a small part of a method as synchronized' by creating a lock or semaphore, and locking this small part (usually called the critical section). There are even some methods that are implemented as lockless thread safe, which means that they are built in such a way that multiple threads can race through them at the same time without ever causing problems, this can be the case when a method only executes one atomic call. Atomic calls are calls that can't be interrupted and can only be done by one thread at a time.
the method modify()
that you called in the last is called in global context
if you want to override modify()
you first have to inherit A
or B
.
Maybe you're trying to do this:
In this case C
inherits A
function A() {
this.modify = function() {
alert("in A");
}
}
function B() {
this.modify = function() {
alert("in B");
}
}
C = function() {
this.modify = function() {
alert("in C");
};
C.prototype.modify(); // you can call this method where you need to call modify of the parent class
}
C.prototype = new A();
I don't know why my web service has the same structure with you but it doesn't need Class for parameter, just is array.
For example: - My WSDL:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns="http://www.kiala.com/schemas/psws/1.0">
<soapenv:Header/>
<soapenv:Body>
<ns:createOrder reference="260778">
<identification>
<sender>5390a7006cee11e0ae3e0800200c9a66</sender>
<hash>831f8c1ad25e1dc89cf2d8f23d2af...fa85155f5c67627</hash>
<originator>VITS-STAELENS</originator>
</identification>
<delivery>
<from country="ES" node=””/>
<to country="ES" node="0299"/>
</delivery>
<parcel>
<description>Zoethout thee</description>
<weight>0.100</weight>
<orderNumber>10K24</orderNumber>
<orderDate>2012-12-31</orderDate>
</parcel>
<receiver>
<firstName>Gladys</firstName>
<surname>Roldan de Moras</surname>
<address>
<line1>Calle General Oraá 26</line1>
<line2>(4º izda)</line2>
<postalCode>28006</postalCode>
<city>Madrid</city>
<country>ES</country>
</address>
<email>[email protected]</email>
<language>es</language>
</receiver>
</ns:createOrder>
</soapenv:Body>
</soapenv:Envelope>
I var_dump:
var_dump($client->getFunctions());
var_dump($client->getTypes());
Here is result:
array
0 => string 'OrderConfirmation createOrder(OrderRequest $createOrder)' (length=56)
array
0 => string 'struct OrderRequest {
Identification identification;
Delivery delivery;
Parcel parcel;
Receiver receiver;
string reference;
}' (length=130)
1 => string 'struct Identification {
string sender;
string hash;
string originator;
}' (length=75)
2 => string 'struct Delivery {
Node from;
Node to;
}' (length=41)
3 => string 'struct Node {
string country;
string node;
}' (length=46)
4 => string 'struct Parcel {
string description;
decimal weight;
string orderNumber;
date orderDate;
}' (length=93)
5 => string 'struct Receiver {
string firstName;
string surname;
Address address;
string email;
string language;
}' (length=106)
6 => string 'struct Address {
string line1;
string line2;
string postalCode;
string city;
string country;
}' (length=99)
7 => string 'struct OrderConfirmation {
string trackingNumber;
string reference;
}' (length=71)
8 => string 'struct OrderServiceException {
string code;
OrderServiceException faultInfo;
string message;
}' (length=97)
So in my code:
$client = new SoapClient('http://packandship-ws.kiala.com/psws/order?wsdl');
$params = array(
'reference' => $orderId,
'identification' => array(
'sender' => param('kiala', 'sender_id'),
'hash' => hash('sha512', $orderId . param('kiala', 'sender_id') . param('kiala', 'password')),
'originator' => null,
),
'delivery' => array(
'from' => array(
'country' => 'es',
'node' => '',
),
'to' => array(
'country' => 'es',
'node' => '0299'
),
),
'parcel' => array(
'description' => 'Description',
'weight' => 0.200,
'orderNumber' => $orderId,
'orderDate' => date('Y-m-d')
),
'receiver' => array(
'firstName' => 'Customer First Name',
'surname' => 'Customer Sur Name',
'address' => array(
'line1' => 'Line 1 Adress',
'line2' => 'Line 2 Adress',
'postalCode' => 28006,
'city' => 'Madrid',
'country' => 'es',
),
'email' => '[email protected]',
'language' => 'es'
)
);
$result = $client->createOrder($params);
var_dump($result);
but it successfully!
There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR
// iOS Simulator
#elif TARGET_OS_IPHONE
// iOS device
#elif TARGET_OS_MAC
// Other kinds of Mac OS
#else
# error "Unknown Apple platform"
#endif
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif
The defined macros depend on the compiler that you are going to use.
The _WIN64
#ifdef
can be nested into the _WIN32
#ifdef
because _WIN32
is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both
(also WIN32
without underscore allows IDE to highlight the right partition of code).
create trigger doct_trigger
after delete on doctor
for each row
delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;
Like sgibb said it was an if problem, it had nothing to do with | or ||.
Here is another way to solve your problem:
for (i in 1:nrow(trip)) {
if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='A') {
trip[i, 'mutType'] <- "G:C to T:A"
}
else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='G') {
trip[i, 'mutType'] <- "G:C to C:G"
}
else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='A'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='T') {
trip[i, 'mutType'] <- "G:C to A:T"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='A') {
trip[i, 'mutType'] <- "A:T to T:A"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='G'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='C') {
trip[i, 'mutType'] <- "A:T to G:C"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='G') {
trip[i, 'mutType'] <- "A:T to C:G"
}
}
Add an interface in your adapter.
public interface SelectedUser{
void selectedUser(UserModel userModel);
}
implement the interface in your mainactivity and override the method. @Override public void selectedUser(UserModel userModel) {
startActivity(new Intent(MainActivity.this, SelectedUserActivity.class).putExtra("data",userModel));
}
Full tutorial and source code: Recyclerview with searchview and onclicklistener
Try to make your javascript unobtrusive :
The trouble with parsing HTML is that it isn't an exact science. If it was XHTML that you were parsing, then things would be a lot easier (as you mention you could use a general XML parser). Because HTML isn't necessarily well-formed XML you will come into lots of problems trying to parse it. It almost needs to be done on a site-by-site basis.
Mint 18.2 (Cinnamon)
Menu > Keyboard Preferences > Layouts > Options > Switching to another layout:
Try this
After selecting a block of text, press Shift+i or capital I.
Lowercase i will not work.
Then type the things you want and finally to apply it to all lines, press Esc twice.
If this doesn't work...
Check if you have +visualextra
enabled in your version of Vim.
You can do this by typing in :ver
and scrolling through the list of features. (You might want to copy and paste it into a buffer and do incremental search because the format is odd.)
Enabling it is outside the scope of this question but I'm sure you can find it somewhere.
In a simple way:
$('#yourTableId').append('<tr><td>your data1</td><td>your data2</td><td>your data3</td></tr>');
Below is one of the way by which you can achieve that, may not be an ideal way to do.
Have one method accepting both types of request, then check what type of request you received, is it of type "GET" or "POST", once you come to know that, do respective actions and the call one method which does common task for both request Methods ie GET and POST.
@RequestMapping(value = "/books")
public ModelAndView listBooks(HttpServletRequest request){
//handle both get and post request here
// first check request type and do respective actions needed for get and post.
if(GET REQUEST){
//WORK RELATED TO GET
}else if(POST REQUEST){
//WORK RELATED TO POST
}
commonMethod(param1, param2....);
}
I use Enthought Canopy for my python, at first I used "pip install --upgrade pip", it showed a syntax error like yours, then I added a "!" in front of the pip, then it finally worked.
I would MD5/SHA1 the password if you don't need to be able to reverse the hash. When users login, you can just encrypt the password given and compare it to the hash. Hash collisions are nearly impossible in this case, unless someone gains access to the database and sees a hash they already have a collision for.
Your main problem is you create new figures in your loop, so each vector gets drawn on a different figure. Here's what I came up with, let me know if it's still not what you expect:
CODE:
import numpy as np
import matplotlib.pyplot as plt
M = np.array([[1,1],[-2,2],[4,-7]])
rows,cols = M.T.shape
#Get absolute maxes for axis ranges to center origin
#This is optional
maxes = 1.1*np.amax(abs(M), axis = 0)
for i,l in enumerate(range(0,cols)):
xs = [0,M[i,0]]
ys = [0,M[i,1]]
plt.plot(xs,ys)
plt.plot(0,0,'ok') #<-- plot a black point at the origin
plt.axis('equal') #<-- set the axes to the same scale
plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits
plt.legend(['V'+str(i+1) for i in range(cols)]) #<-- give a legend
plt.grid(b=True, which='major') #<-- plot grid lines
plt.show()
OUTPUT:
EDIT CODE:
import numpy as np
import matplotlib.pyplot as plt
M = np.array([[1,1],[-2,2],[4,-7]])
rows,cols = M.T.shape
#Get absolute maxes for axis ranges to center origin
#This is optional
maxes = 1.1*np.amax(abs(M), axis = 0)
colors = ['b','r','k']
for i,l in enumerate(range(0,cols)):
plt.axes().arrow(0,0,M[i,0],M[i,1],head_width=0.05,head_length=0.1,color = colors[i])
plt.plot(0,0,'ok') #<-- plot a black point at the origin
plt.axis('equal') #<-- set the axes to the same scale
plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits
plt.grid(b=True, which='major') #<-- plot grid lines
plt.show()
Sounds like you don't want to resolve dns yourself (this might be the wrong nomenclature) dnspython appears to be a standalone dns client that will understandably ignore your operating system because its bypassing the operating system's utillities.
We can look at a shell utility named getent
to understand how the (debian 11 alike) operating system resolves dns for programs, this is likely the standard for all *nix like systems that use a socket implementation.
see man getent
's "hosts" section, which mentions the use of getaddrinfo
, which we can see as man getaddrinfo
and to use it in python, we have to extract some info from the data structures
.
import socket
def get_ipv4_by_hostname(hostname):
# see `man getent` `/ hosts `
# see `man getaddrinfo`
return list(
i # raw socket structure
[4] # internet protocol info
[0] # address
for i in
socket.getaddrinfo(
hostname,
0 # port, required
)
if i[0] is socket.AddressFamily.AF_INET # ipv4
# ignore duplicate addresses with other socket types
and i[1] is socket.SocketKind.SOCK_RAW
)
print(get_ipv4_by_hostname('localhost'))
print(get_ipv4_by_hostname('google.com'))
What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.
// new answer
function justTesting() {
return new Promise((resolve, reject) => {
if (true) {
return resolve("testing");
} else {
return reject("promise failed");
}
});
}
justTesting()
.then(res => {
let test = res;
// do something with the output :)
})
.catch(err => {
console.log(err);
});
Hope this helps!
// old answer
function justTesting() {
return promise.then(function(output) {
return output + 1;
});
}
justTesting().then((res) => {
var test = res;
// do something with the output :)
}
Find element with id in row using jquery
$(document).ready(function () {
$("button").click(function() {
//find content of different elements inside a row.
var nameTxt = $(this).closest('tr').find('.name').text();
var emailTxt = $(this).closest('tr').find('.email').text();
//assign above variables text1,text2 values to other elements.
$("#name").val( nameTxt );
$("#email").val( emailTxt );
});
});
For those using debian, the guide for setting up a device under Ubuntu to create the file "/etc/udev/rules.d/51-android.rules" does not work. I followed instructions from here. Putting down the same here for reference.
Edit this file as superuser
sudo nano /lib/udev/rules.d/91-permissions.rules
Find the text similar to this
# usbfs-like devices
SUBSYSTEM==”usb”, ENV{DEVTYPE}==”usb_device”, \ MODE=”0664"
Then change the mode to 0666 like below
# usbfs-like devices
SUBSYSTEM==”usb”, ENV{DEVTYPE}==”usb_device”, \ MODE=”0666"
This allows adb to work, however we still need to set up the device so it can be recognized. We need to create this file as superuser,
sudo nano /lib/udev/rules.d/99-android.rules
and enter
SUBSYSTEM==”usb”, ENV{DEVTYPE}==”usb_device”, ATTRS{idVendor}==”0bb4", MODE=”0666"
the above line is for HTC, follow @grebulon's post for complete list.
Save the file and then restart udev as super user
sudo /etc/init.d/udev restart
Connect the phone via USB and it should be detected when you compile and run a project.
I'm not sure what you're trying to do: If you added the file via
svn add myfile
you only told svn to put this file into your repository when you do your next commit. There's no change to the repository before you type an
svn commit
If you delete the file before the commit, svn
has it in its records (because you added it) but cannot send it to the repository because the file no longer exist.
So either you want to save the file in the repository and then delete it from your working copy: In this case try to get your file back (from the trash?), do the commit and delete the file afterwards via
svn delete myfile
svn commit
If you want to undo the add
and just throw the file away, you can to an
svn revert myfile
which tells svn
(in this case) to undo the add-Operation.
EDIT
Sorry, I wasn't aware that you're using the "Versions" GUI client for Max OSX. So either try a revert on the containing directory using the GUI or jump into the cold water and fire up your hidden Mac command shell :-) (it's called "Terminal" in the german OSX, no idea how to bring it up in the english version...)
This is working fine for me:
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, "Vikas Patidar") // Name of the person
.build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, "9999999999") // Number of the person
.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); // Type of mobile number
try
{
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
catch (RemoteException e)
{
// error
}
catch (OperationApplicationException e)
{
// error
}
Here's mine:
set statusline=
set statusline +=%1*\ %n\ %* "buffer number
set statusline +=%5*%{&ff}%* "file format
set statusline +=%3*%y%* "file type
set statusline +=%4*\ %<%F%* "full path
set statusline +=%2*%m%* "modified flag
set statusline +=%1*%=%5l%* "current line
set statusline +=%2*/%L%* "total lines
set statusline +=%1*%4v\ %* "virtual column number
set statusline +=%2*0x%04B\ %* "character under cursor
And here's the colors I used:
hi User1 guifg=#eea040 guibg=#222222
hi User2 guifg=#dd3333 guibg=#222222
hi User3 guifg=#ff66ff guibg=#222222
hi User4 guifg=#a0ee40 guibg=#222222
hi User5 guifg=#eeee40 guibg=#222222
I had to change this rows:
$cfg['Servers'][$i]['pma__bookmarktable'] = 'pma__bookmark';
$cfg['Servers'][$i]['pma__relation'] = 'pma__relation';
$cfg['Servers'][$i]['pma__table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['pma__table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pma__pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['pma__column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['pma__history'] = 'pma__history';
$cfg['Servers'][$i]['pma__table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['pma__designer_coords'] = 'pma__designer_coords';
$cfg['Servers'][$i]['pma__tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['pma__userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['pma__recent'] = 'pma__recent';
$cfg['Servers'][$i]['pma__table_uiprefs'] = 'pma__table_uiprefs';
add: "pma__" to ['bookmarktable'] and "_" to 'pma_bookmark'
Using this function you can require a whole dir.
const GetAllModules = ( dirname ) => {
if ( dirname ) {
let dirItems = require( "fs" ).readdirSync( dirname );
return dirItems.reduce( ( acc, value, index ) => {
if ( PATH.extname( value ) == ".js" && value.toLowerCase() != "index.js" ) {
let moduleName = value.replace( /.js/g, '' );
acc[ moduleName ] = require( `${dirname}/${moduleName}` );
}
return acc;
}, {} );
}
}
// calling this function.
let dirModules = GetAllModules(__dirname);
window.open('https://support.wwf.org.uk', '_blank');
The second parameter is what makes it open in a new window. Don't forget to read Jakob Nielsen's informative article :)
--force-reinstall
doesn't appear to force reinstall using python2.7 with pip-1.5
I've had to use
--no-deps --ignore-installed
Apply the reverse function to the range to iterate backwards:
For Swift 1.2 and earlier:
// Print 10 through 1
for i in reverse(1...10) {
println(i)
}
It also works with half-open ranges:
// Print 9 through 1
for i in reverse(1..<10) {
println(i)
}
Note: reverse(1...10)
creates an array of type [Int]
, so while this might be fine for small ranges, it would be wise to use lazy
as shown below or consider the accepted stride
answer if your range is large.
To avoid creating a large array, use lazy
along with reverse()
. The following test runs efficiently in a Playground showing it is not creating an array with one trillion Int
s!
Test:
var count = 0
for i in lazy(1...1_000_000_000_000).reverse() {
if ++count > 5 {
break
}
println(i)
}
For Swift 2.0 in Xcode 7:
for i in (1...10).reverse() {
print(i)
}
Note that in Swift 2.0, (1...1_000_000_000_000).reverse()
is of type ReverseRandomAccessCollection<(Range<Int>)>
, so this works fine:
var count = 0
for i in (1...1_000_000_000_000).reverse() {
count += 1
if count > 5 {
break
}
print(i)
}
For Swift 3.0 reverse()
has been renamed to reversed()
:
for i in (1...10).reversed() {
print(i) // prints 10 through 1
}
I believe that the best idea is just to capture in a group whatever you want to replace, and then replace it by using the start and end properties of the captured group.
regards
Adrián
#the pattern will contain the expression we want to replace as the first group
pat = "word1\s(.*)\sword2"
test = "word1 will never be a word2"
repl = "replace"
import re
m = re.search(pat,test)
if m and m.groups() > 0:
line = test[:m.start(1)] + repl + test[m.end(1):]
print line
else:
print "the pattern didn't capture any text"
This will print: 'word1 will never be a word2'
The group to be replaced could be located in any position of the string.
I have found that the 65536 limit still applies to pivot tables, even in Excel 2007.
In case of Windows(in my case XP):-
Here is a sample project for a soft keyboard.
https://developer.android.com/guide/topics/text/creating-input-method.html
Your's should be in the same lines with a different layout.
Edit: If you need the keyboard only in your application, its very simple! Create a linear layout with vertical orientation, and create 3 linear layouts inside it with horizontal orientation. Then place the buttons of each row in each of those horizontal linear layouts, and assign the weight property to the buttons. Use android:layout_weight=1 for all of them, so they get equally spaced.
This will solve. If you didn't get what was expected, please post the code here, and we are here to help you!
I think it is worthwhile to recap/summarize the choices here for clarity... then offer a new variation that I believe provides the best utility.
write-host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
cmd /c Pause | Out-Null
Read-Host -Prompt "Press Enter to continue"
This is a composite of <1> above with the ISE workaround/kludge extracted from the proposal on Adam's Tech Blog (courtesy of Nick from earlier comments on this page). I made two slight improvements to the latter: added Test-Path to avoid an error if you use Set-StrictMode (you do, don't you?!) and the final Write-Host to add a newline after your keystroke to put the prompt in the right place.
Function Pause ($Message = "Press any key to continue . . . ") {
if ((Test-Path variable:psISE) -and $psISE) {
$Shell = New-Object -ComObject "WScript.Shell"
$Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0)
}
else {
Write-Host -NoNewline $Message
[void][System.Console]::ReadKey($true)
Write-Host
}
}
Use Collections.list(iterator).stream()...
The problem is that you haven't got any element with the id u
so that you are calling something that doesn't exist.
To fix that you have to add an id to the element.
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
And I've seen too you have added a value for the input, so it means the input is not empty and it will contain text. As result placeholder
won't be displayed.
Finally there is a warning that W3Validator will say because of the "/" in the end. :
For the current document, the validator interprets strings like according to legacy rules that break the expectations of most authors and thus cause confusing warnings and error messages from the validator. This interpretation is triggered by HTML 4 documents or other SGML-based HTML documents. To avoid the messages, simply remove the "/" character in such contexts. NB: If you expect <FOO /> to be interpreted as an XML-compatible "self-closing" tag, then you need to use XHTML or HTML5.
In conclusion it says you have to remove the slash. Simply write this:
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item...">
If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
When you want to show an URL of remote branches, try:
git remote -v
Based on Daniel Krom's solution. This is version in swift 3.0. Works great with AutoLayout, and moves whole view when keyboard appears.
extension UIView {
func bindToKeyboard(){
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
func unbindFromKeyboard(){
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
@objc
func keyboardWillChange(notification: NSNotification) {
guard let userInfo = notification.userInfo else { return }
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
let curFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let targetFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = targetFrame.origin.y - curFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
self.frame.origin.y += deltaY
})
}
}
How to use it:
Add bindToKeyboard
function in viewDidLoad
like:
override func viewDidLoad() {
super.viewDidLoad()
view.bindToKeyboard()
}
And add unbindFromKeyboard
function in deinit:
deinit {
view.unbindFromKeyboard()
}
If I recall correctly, there are some issues with adding SharePoint web services as a VS2K8 "Service Reference". You need to add it as an old-style "Web Reference" to work properly.
To replace na values in pandas
df['column_name'].fillna(value_to_be_replaced,inplace=True)
if inplace = False
, instead of updating the df (dataframe) it will return the modified values.
This exception only happens if you are parsing an empty String/empty byte array.
below is a snippet on how to reproduce it:
String xml = ""; // <-- deliberately an empty string.
ByteArrayInputStream xmlStream = new java.io.ByteArrayInputStream(xml.getBytes());
Unmarshaller u = JAXBContext.newInstance(...)
u.setSchema(...);
u.unmarshal( xmlStream ); // <-- here it will fail
If you're installing using --user
(e.g. pip3.6 install --user tmuxp
), it is possible to get the platform-specific user install directory from Python itself using the site
module. For example, on macOS:
$ python2.7 -m site --user-base
/Users/alexp/Library/Python/2.7
By appending /bin
to this, we now have the path where package executables will be installed. We can dynamically populate the PATH in your shell's rc file based on the output; I'm using bash, but with any luck this is portable:
# Add Python bin directories to path
python3.6 -m site &> /dev/null && PATH="$PATH:`python3.6 -m site --user-base`/bin"
python2.7 -m site &> /dev/null && PATH="$PATH:`python2.7 -m site --user-base`/bin"
I use the precise Python versions to reduce the chance of the executables just "disappearing" when Python upgrades a minor version, e.g. from 3.5 to 3.6. They'll disappear because, as can be seen above, the user installation path may include the Python version. So while python3
could point to 3.5 or 3.6, python3.6
will always point to 3.6. This needs to be kept in mind when installing further packages, e.g. use pip3.6
over pip3
.
If you don't mind the idea of packages disappearing, you can use python2
and python3
instead:
# Add Python bin directories to path
# Note: When Python is upgraded, packages may need to be re-installed
# or Python versions managed.
python3 -m site &> /dev/null && PATH="$PATH:`python3 -m site --user-base`/bin"
python2 -m site &> /dev/null && PATH="$PATH:`python2 -m site --user-base`/bin"
This is due to the mismatch of the data type of your java Entity and the database table column. Please review if all the column is exact same data type as your entity. This mismatch happens when we update our model attribute's data-type.
I prefer to exclude things on an as-needed basis. You don't want to shotgun exclude everything with the string "bin" or "obj" in the name. At least be sure to follow those with a slash.
Here's what I start with on a VS2010 project:
bin/
obj/
*.suo
*.user
And only because I use ReSharper, also this:
_ReSharper*
I'd say:
<a href="#"id="buttonOne">
<div id="linkedinB">
<img src="img/linkedinB.png" width="40" height="40">
</div>
</div>
However, it will still be a link. If you want to change your link into a button, you should rename the #buttonone to #buttonone a { your css here }.
The idea ...To create a File object (api) in javaScript for images already present in the DOM :
<img src="../img/Products/fijRKjhudDjiokDhg1524164151.jpg">
var file = new File(['fijRKjhudDjiokDhg1524164151'],
'../img/Products/fijRKjhudDjiokDhg1524164151.jpg',
{type:'image/jpg'});
// created object file
console.log(file);
Don't do that ! ... (but I did it anyway)
-> the console give a result similar as an Object File :
File(0) {name: "fijRKjokDhgfsKtG1527053050.jpg", lastModified: 1527053530715, lastModifiedDate: Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)), webkitRelativePath: "", size: 0, …}
lastModified:1527053530715
lastModifiedDate:Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)) {}
name:"fijRKjokDhgfsKtG1527053050.jpg"
size:0
type:"image/jpg"
webkitRelativePath:""__proto__:File
But the size of the object is wrong ...
Why i need to do that ?
For example to retransmit an image form already uploaded, during a product update, along with additional images added during the update
Here is an example. (I am using CompareToBuilder
class from Apache for convenience, although this can be done without using it.)
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.builder.CompareToBuilder;
public class Tester {
boolean ascending = true;
public static void main(String args[]) {
Tester tester = new Tester();
tester.printValues();
}
public void printValues() {
List<HashMap<String, Object>> list =
new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map =
new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(21) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(7) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(456) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(1) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(20) );
map.put( "fromDate", getDate(4) );
map.put( "toDate", getDate(16) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(22) );
map.put( "fromDate", getDate(8) );
map.put( "toDate", getDate(11) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(10) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(4) );
map.put( "toDate", getDate(15) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(567) );
map.put( "eventId", new Integer(12) );
map.put( "fromDate", getDate(-1) );
map.put( "toDate", getDate(1) );
list.add(map);
System.out.println("\n Before Sorting \n ");
for( int j = 0; j < list.size(); j++ )
System.out.println(list.get(j));
Collections.sort( list, new HashMapComparator2() );
System.out.println("\n After Sorting \n ");
for( int j = 0; j < list.size(); j++ )
System.out.println(list.get(j));
}
public static Date getDate(int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, days);
return cal.getTime();
}
public class HashMapComparator2 implements Comparator {
public int compare(Object object1, Object object2) {
if( ascending ) {
return new CompareToBuilder()
.append(
((HashMap)object1).get("actionId"),
((HashMap)object2).get("actionId")
)
.append(
((HashMap)object2).get("eventId"),
((HashMap)object1).get("eventId")
)
.toComparison();
} else {
return new CompareToBuilder()
.append(
((HashMap)object2).get("actionId"),
((HashMap)object1).get("actionId")
)
.append(
((HashMap)object2).get("eventId"),
((HashMap)object1).get("eventId")
)
.toComparison();
}
}
}
}
If you have a specific code that you are working on and are having issues, you can post your pseudo code and we can try to help you out!
It's for declaring class member variables in PHP4, and is no longer needed. It will work in PHP5, but will raise an E_STRICT
warning in PHP from version 5.0.0 up to version 5.1.2, as of when it was deprecated. Since PHP 5.3, var has been un-deprecated and is a synonym for 'public'.
Example usage:
class foo {
var $x = 'y'; // or you can use public like...
public $x = 'y'; //this is also a class member variables.
function bar() {
}
}
Iterating through elements of two lists simultaneously is known as zipping, and python provides a built in function for it, which is documented here.
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True
[Example is taken from pydocs]
In your case, it will be simply:
for (lat, lon) in zip(latitudes, longitudes):
... process lat and lon
ps aux | grep -ie amarok | awk '{print $2}' | xargs kill -9
xargs(1): xargs -- construct argument list(s) and execute utility. Helpful when you want to pipe in arguments to something like kill
or ls
or so on.
I had the same problem. So I got remembere. Yesterday I had commented this code in htttp-xampp.conf
Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
# AllowOverride AuthConfig
# Require local
# ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
SO I can access my localhost using other system on same network(LAN/WIFI) as it make localhost require local.
So I just make it like
Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
AllowOverride AuthConfig
# Require local
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
and now its working on my local machine and also localhost is accessible using other systems on same LAN/WIFI.
function replaceAll(str, find, replace) {
var i = str.indexOf(find);
if (i > -1){
str = str.replace(find, replace);
i = i + replace.length;
var st2 = str.substring(i);
if(st2.indexOf(find) > -1){
str = str.substring(0,i) + replaceAll(st2, find, replace);
}
}
return str;
}
You can't represent most decimal fractions exactly with binary floating point types (which is what ECMAScript uses to represent floating point values). So there isn't an elegant solution unless you use arbitrary precision arithmetic types or a decimal based floating point type. For example, the Calculator app that ships with Windows now uses arbitrary precision arithmetic to solve this problem.
Use https://prestodb.io/docs/current/connector/kafka-tutorial.html
A super SQL engine, provided by Facebook, that connects on several data sources (Cassandra, Kafka, JMX, Redis ...).
PrestoDB is running as a server with optional workers (there is a standalone mode without extra workers), then you use a small executable JAR (called presto CLI) to make queries.
Once you have configured well the Presto server , you can use traditionnal SQL:
SELECT count(*) FROM TOPIC_NAME;
which <cmd>
also see options which
supports for aliases if applicable to your case.
Example
$ which foobar
which: no foobar in (/usr/local/bin:/usr/bin:/cygdrive/c/Program Files (x86)/PC Connectivity Solution:/cygdrive/c/Windows/system32/System32/WindowsPowerShell/v1.0:/cygdrive/d/Program Files (x86)/Graphviz 2.28/bin:/cygdrive/d/Program Files (x86)/GNU/GnuPG
$ if [ $? -eq 0 ]; then echo "foobar is found in PATH"; else echo "foobar is NOT found in PATH, of course it does not mean it is not installed."; fi
foobar is NOT found in PATH, of course it does not mean it is not installed.
$
PS: Note that not everything that's installed may be in PATH. Usually to check whether something is "installed" or not one would use installation related commands relevant to the OS. E.g. rpm -qa | grep -i "foobar"
for RHEL.
I needed some more context, so I made an example to show how this is done. The most helpful thing I read while preparing was this:
activity_main.xml
Add a FrameLayout
to your activity to hold the parent fragment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity"/>
<FrameLayout
android:id="@+id/parent_fragment_container"
android:layout_width="match_parent"
android:layout_height="200dp"/>
</LinearLayout>
MainActivity.java
Load the parent fragment and implement the fragment listeners. (See fragment communication.)
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements ParentFragment.OnFragmentInteractionListener, ChildFragment.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Begin the transaction
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.parent_fragment_container, new ParentFragment());
ft.commit();
}
@Override
public void messageFromParentFragment(Uri uri) {
Log.i("TAG", "received communication from parent fragment");
}
@Override
public void messageFromChildFragment(Uri uri) {
Log.i("TAG", "received communication from child fragment");
}
}
fragment_parent.xml
Add another FrameLayout
container for the child fragment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:background="#91d0c2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Parent fragment"/>
<FrameLayout
android:id="@+id/child_fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
ParentFragment.java
Use getChildFragmentManager
in onViewCreated
to set up the child fragment.
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
public class ParentFragment extends Fragment {
private OnFragmentInteractionListener mListener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_parent, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Fragment childFragment = new ChildFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.child_fragment_container, childFragment).commit();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void messageFromParentFragment(Uri uri);
}
}
fragment_child.xml
There is nothing special here.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:background="#f1ff91">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Child fragment"/>
</LinearLayout>
ChildFragment.java
There is nothing too special here, either.
import android.support.v4.app.Fragment;
public class ChildFragment extends Fragment {
private OnFragmentInteractionListener mListener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_child, container, false);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void messageFromChildFragment(Uri uri);
}
}
If you dont want to use any module for age calculation
var age = Math.floor((new Date() - new Date(date_of_birth)) / 1000 / 60 / 60 / 24 / 365.25)
I'm going to add to the existing answers because modern C++ is now a thing and official Core Guidelines have been created to help with questions such as these.
Here's a relevant section from the guidelines:
C.2: Use class if the class has an invariant; use struct if the data members can vary independently
An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume. After the invariant is established (typically by a constructor) every member function can be called for the object. An invariant can be stated informally (e.g., in a comment) or more formally using Expects.
If all data members can vary independently of each other, no invariant is possible.
If a class has any private data, a user cannot completely initialize an object without the use of a constructor. Hence, the class definer will provide a constructor and must specify its meaning. This effectively means the definer need to define an invariant.
Enforcement
Look for structs with all data private and classes with public members.
The code examples given:
struct Pair { // the members can vary independently
string name;
int volume;
};
// but
class Date {
public:
// validate that {yy, mm, dd} is a valid date and initialize
Date(int yy, Month mm, char dd);
// ...
private:
int y;
Month m;
char d; // day
};
Class
es work well for members that are, for example, derived from each other or interrelated. They can also help with sanity checking upon instantiation. Struct
s work well for having "bags of data", where nothing special is really going on but the members logically make sense being grouped together.
From this, it makes sense that class
es exist to support encapsulation and other related coding concepts, that struct
s are simply not very useful for.
I use largely the same patterns as Aaronaught, but if you have a lot of properties it could be nice to use a little generic method magic to make your code a little more DRY
public class TheClass : INotifyPropertyChanged {
private int _property1;
private string _property2;
private double _property3;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null) {
handler(this, e);
}
}
protected void SetPropertyField<T>(string propertyName, ref T field, T newValue) {
if(!EqualityComparer<T>.Default.Equals(field, newValue)) {
field = newValue;
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
}
public int Property1 {
get { return _property1; }
set { SetPropertyField("Property1", ref _property1, value); }
}
public string Property2 {
get { return _property2; }
set { SetPropertyField("Property2", ref _property2, value); }
}
public double Property3 {
get { return _property3; }
set { SetPropertyField("Property3", ref _property3, value); }
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
Usually I also make the OnPropertyChanged method virtual to allow sub-classes to override it to catch property changes.
If what you want is a way to turn your class into kind of a list without subclassing list
, then just make a method that returns a list:
def MyClass():
def __init__(self):
self.value1 = 1
self.value2 = 2
def get_list(self):
return [self.value1, self.value2...]
>>>print MyClass().get_list()
[1, 2...]
If you meant that print MyClass()
will print a list, just override __repr__
:
class MyClass():
def __init__(self):
self.value1 = 1
self.value2 = 2
def __repr__(self):
return repr([self.value1, self.value2])
EDIT:
I see you meant how to make objects compare. For that, you override the __cmp__
method.
class MyClass():
def __cmp__(self, other):
return cmp(self.get_list(), other.get_list())
Just a note of a peculiarity I faced:
Consider:
db server: 192.168.0.101
web server: 192.168.0.102
If you have a user defined in mysql.user as 'user'@'192.168.0.102'
with password1 and another 'user'@'192.168.0.%'
with password2,
then,
if you try to connect to the db server from the web server as 'user' with password2,
it will result in an 'Access denied' error because the single IP 'user'@'192.168.0.102'
authentication is used over the wildcard 'user'@'192.168.0.%'
authentication.
Seems to work fine.
If you have an empty BEGIN ... END block you might see
Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'END'.
you can use instead of click :
$('#whatever').on('touchstart click', function(){ /* do something... */ });
openssl rsa -in f.pem -inform PEM -out f.der -outform DER
You should try this syntax - assuming you want to have @OrderID
as a parameter for your stored procedure:
CREATE PROCEDURE dbo.YourStoredProcNameHere
@OrderID INT
AS
BEGIN
DECLARE @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SELECT @OrderItemID = OrderItemID
FROM [OrderItem]
WHERE OrderID = @OrderID
SELECT @AppointmentID = AppoinmentID
FROM [Appointment]
WHERE OrderID = @OrderID
SELECT @PurchaseOrderID = PurchaseOrderID
FROM [PurchaseOrder]
WHERE OrderID = @OrderID
END
OF course, that only works if you're returning exactly one value (not multiple values!)
If you simply want to create a new branch without immediately changing to it, you could do the following:
git branch newbranch v1.0
Seems like the accepted answer does not work anymore. I found the correct method from another post: https://stackoverflow.com/a/46811403/6368026
Now you should use:
http://www.youtube.com/embed/videoseries?list=USERID And the USERID is your youtube user id with 'UU' appended.
For example, if your user id is TlQ5niAIDsLdEHpQKQsupg then you should put UUTlQ5niAIDsLdEHpQKQsupg. If you only have the channel id (which you can find in your channel URL) then just replace the first two characters (UC) with UU.
So in the end you would have an URL like this:
http://www.youtube.com/embed/videoseries?list=UUTlQ5niAIDsLdEHpQKQsupg
Python uses "Duck typing", i.e. if a variable kwaks like a duck, it must be a duck. In your case, you probably want it to be iterable, or you want to access the item at a certain index. You should just do this: i.e. use the object in for var:
or var[idx]
inside a try
block, and if you get an exception it wasn't a duck...
Here is updated working version for me which will get City/Town, It looks like some fields are modified in the json response. Referring previous answers for this questions. ( Thanks to Michal & one more reference : Link
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
// Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng);
}
function errorFunction() {
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
console.log(results);
$.each(arrAddress, function(i, address_component) {
if (address_component.types[0] == "locality") {
console.log("City: " + address_component.address_components[0].long_name);
itemLocality = address_component.address_components[0].long_name;
}
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
I just made a pure Javascript function based on that code. Javascript only version demo: http://jsbin.com/copidifiji
That is the independent code from jQuery
if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;}
function wheel(event) {
var delta = 0;
if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
else if (event.detail) delta = -(event.detail)/3;
handle(delta);
if (event.preventDefault) event.preventDefault();
event.returnValue = false;
}
function handle(sentido) {
var inicial = document.body.scrollTop;
var time = 1000;
var distance = 200;
animate({
delay: 0,
duration: time,
delta: function(p) {return p;},
step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);
}});}
function animate(opts) {
var start = new Date();
var id = setInterval(function() {
var timePassed = new Date() - start;
var progress = (timePassed / opts.duration);
if (progress > 1) {progress = 1;}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}
socket.send
is implemented for compatibility with vanilla WebSocket interface. socket.emit
is feature of Socket.IO only. They both do the same, but socket.emit
is a bit more convenient in handling messages.
Light red fill with dark red text.
{'bg_color': '#FFC7CE', 'font_color': '#9C0006'})
Light yellow fill with dark yellow text.
{'bg_color': '#FFEB9C', 'font_color': '#9C6500'})
Green fill with dark green text.
{'bg_color': '#C6EFCE', 'font_color': '#006100'})
Here is the answer:
Download the "Windows Mobile Device Center" for your machine type, likely 64bit.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3182
Before you run the install, change the compatibility settings to 'Windows 7'. Then install it... Then run it: You'll find it under 'WMDC'.. Your device should now recognize, when plugged in, mine did!
Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.
An alternative option is to set it in the machine level web.config, so its not even in the web site folder.
To generate it do it just like the linked article in David's answer.
This is the behavior of ln
if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx
to be the symlink, you should remove that directory first and run that same command.
Yes, Use jspdf To create a pdf file.
You can then turn it into a data URI and inject a download link into the DOM
You will however need to write the HTML to pdf conversion yourself.
Just use printer friendly versions of your page and let the user choose how he wants to print the page.
Edit: Apparently it has minimal support
So the answer is write your own PDF writer or get a existing PDF writer to do it for you (on the server).
I guess what you need is np.set_printoptions(suppress=True)
, for details see here:
http://pythonquirks.blogspot.fr/2009/10/controlling-printing-in-numpy.html
For SciPy.org numpy documentation, which includes all function parameters (suppress isn't detailed in the above link), see here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html
If all the keys are strings and all of them have the underscore prefix, then you can patch up the hash in place with this:
h.keys.each { |k| h[k[1, k.length - 1]] = h[k]; h.delete(k) }
The k[1, k.length - 1]
bit grabs all of k
except the first character. If you want a copy, then:
new_h = Hash[h.map { |k, v| [k[1, k.length - 1], v] }]
Or
new_h = h.inject({ }) { |x, (k,v)| x[k[1, k.length - 1]] = v; x }
You could also use sub
if you don't like the k[]
notation for extracting a substring:
h.keys.each { |k| h[k.sub(/\A_/, '')] = h[k]; h.delete(k) }
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
And, if only some of the keys have the underscore prefix:
h.keys.each do |k|
if(k[0,1] == '_')
h[k[1, k.length - 1]] = h[k]
h.delete(k)
end
end
Similar modifications can be done to all the other variants above but these two:
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
should be okay with keys that don't have underscore prefixes without extra modifications.
You can submit any form automatically on page load simply by adding a snippet of javascript code to your body tag referencing the form name like this....
<body onload="document.form1.submit()">
@Test(expected = Exception.class)
Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.
For
@Test
Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.
The code helped me change the title.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name);
ActivityName.this.setTitle("Your Activity Title");}
Thanks for the help. I've managed to get it working now so thought I would post so that the others can use to help them.
Server:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
Socket socket = null;
InputStream in = null;
OutputStream out = null;
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
out = new FileOutputStream("M:\\test2.xml");
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[16*1024];
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
socket.close();
serverSocket.close();
}
}
and the Client:
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
String host = "127.0.0.1";
socket = new Socket(host, 4444);
File file = new File("M:\\test.xml");
// Get the size of the file
long length = file.length();
byte[] bytes = new byte[16 * 1024];
InputStream in = new FileInputStream(file);
OutputStream out = socket.getOutputStream();
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
socket.close();
}
}
Swift 5 answer based on @ZpaceZombor's excellent answer
If you have a UIImage, just use
var image: UIImage = ....
image.draw(in: CGRect)
If you have a CGImage use my category below
Note: Unlike some other answers, this one takes into account that the rect you want to draw in might have y != 0. Those answers that don't take that into account are incorrect and won't work in the general case.
extension CGContext {
final func drawImage(image: CGImage, inRect rect: CGRect) {
//flip coords
let ty: CGFloat = (rect.origin.y + rect.size.height)
translateBy(x: 0, y: ty)
scaleBy(x: 1.0, y: -1.0)
//draw image
let rect__y_zero = CGRect(x: rect.origin.x, y: 0, width: rect.width, height: rect.height)
draw(image, in: rect__y_zero)
//flip back
scaleBy(x: 1.0, y: -1.0)
translateBy(x: 0, y: -ty)
}
}
Use like this:
let imageFrame: CGRect = ...
let context: CGContext = ....
let img: CGImage = .....
context.drawImage(image: img, inRect: imageFrame)
Please try this.
private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
boolean ismove = false;
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File(sourcefolder + filename);
File bfile = new File(destinationfolder + filename);
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024 * 4];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
// delete the original file
afile.delete();
ismove = true;
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}finally{
inStream.close();
outStream.close();
}
return ismove;
}
In views with {{}}
and/or ng-model, Angular is setting up $watch()
es for you behind the scenes.
By default $watch
compares by reference. If you set the third parameter to $watch
to true
, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:
$scope.$watch('myModel', function() { ... }, true);
Update: Angular v1.2 added a new method for this, `$watchCollection():
$scope.$watchCollection('myModel', function() { ... });
Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.
Since guava 21, you can use
Streams.mapWithIndex()
Example (from official doc):
Streams.mapWithIndex(
Stream.of("a", "b", "c"),
(str, index) -> str + ":" + index)
) // will return Stream.of("a:0", "b:1", "c:2")
You're not looping over the items. Try this instead:
$.getJSON(url, function(data){
$.each(data.response.venue.tips.groups.items, function (index, value) {
console.log(this.text);
});
});
The server-side processing language in use (eg PHP, .net, etc) isn't specified, but if it's PHP, grab the required number (or all the records) and instead of randomising in the query use PHP's shuffle function. I don't know if .net has an equivalent function but if it does then use that if you're using .net
ORDER BY RAND() can have quite a performance penalty, depending on how many records are involved.
preg_replace('/(?!\n)[\p{Cc}]/', '', $response);
This will remove all the control characters (http://uk.php.net/manual/en/regexp.reference.unicode.php) leaving the \n
newline characters. From my experience, the control characters are the ones that most often cause the printing issues.
How to use a clock and do assertions
This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.
The key idea is that the process
blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.
library ieee;
use ieee.std_logic_1164.all;
entity counter_tb is
end counter_tb;
architecture behav of counter_tb is
constant width : natural := 2;
constant clk_period : time := 1 ns;
signal clk : std_logic := '0';
signal data : std_logic_vector(width-1 downto 0);
signal count : std_logic_vector(width-1 downto 0);
type io_t is record
load : std_logic;
data : std_logic_vector(width-1 downto 0);
count : std_logic_vector(width-1 downto 0);
end record;
type ios_t is array (natural range <>) of io_t;
constant ios : ios_t := (
('1', "00", "00"),
('0', "UU", "01"),
('0', "UU", "10"),
('0', "UU", "11"),
('1', "10", "10"),
('0', "UU", "11"),
('0', "UU", "00"),
('0', "UU", "01")
);
begin
counter_0: entity work.counter port map (clk, load, data, count);
process
begin
for i in ios'range loop
load <= ios(i).load;
data <= ios(i).data;
wait until falling_edge(clk);
assert count = ios(i).count;
end loop;
wait;
end process;
process
begin
for i in 1 to 2 * ios'length loop
wait for clk_period / 2;
clk <= not clk;
end loop;
wait;
end process;
end behav;
The counter would look like this:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned
entity counter is
generic (
width : in natural := 2
);
port (
clk, load : in std_logic;
data : in std_logic_vector(width-1 downto 0);
count : out std_logic_vector(width-1 downto 0)
);
end entity counter;
architecture rtl of counter is
signal cnt : unsigned(width-1 downto 0);
begin
process(clk) is
begin
if rising_edge(clk) then
if load = '1' then
cnt <= unsigned(data);
else
cnt <= cnt + 1;
end if;
end if;
end process;
count <= std_logic_vector(cnt);
end architecture rtl;
Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
I implemeneted this algorithm in typescript and ES6
export type Coordinate = {
lat: number;
lon: number;
};
get the distance between two points:
function getDistanceBetweenTwoPoints(cord1: Coordinate, cord2: Coordinate) {
if (cord1.lat == cord2.lat && cord1.lon == cord2.lon) {
return 0;
}
const radlat1 = (Math.PI * cord1.lat) / 180;
const radlat2 = (Math.PI * cord2.lat) / 180;
const theta = cord1.lon - cord2.lon;
const radtheta = (Math.PI * theta) / 180;
let dist =
Math.sin(radlat1) * Math.sin(radlat2) +
Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = (dist * 180) / Math.PI;
dist = dist * 60 * 1.1515;
dist = dist * 1.609344; //convert miles to km
return dist;
}
get the distance between an array of coordinates
export function getTotalDistance(coordinates: Coordinate[]) {
coordinates = coordinates.filter((cord) => {
if (cord.lat && cord.lon) {
return true;
}
});
let totalDistance = 0;
if (!coordinates) {
return 0;
}
if (coordinates.length < 2) {
return 0;
}
for (let i = 0; i < coordinates.length - 2; i++) {
if (
!coordinates[i].lon ||
!coordinates[i].lat ||
!coordinates[i + 1].lon ||
!coordinates[i + 1].lat
) {
totalDistance = totalDistance;
}
totalDistance =
totalDistance +
getDistanceBetweenTwoPoints(coordinates[i], coordinates[i + 1]);
}
return totalDistance.toFixed(2);
}
Switch the order of the code: You're calling the click event before it is attached.
$(document).ready(function() {
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
Process p = Runtime.getRuntime().exec("ping google.com");
p.getInputStream().transferTo(System.out);
p.getErrorStream().transferTo(System.out);
The encoding in your XML and XSD (or DTD) are different.
XML file header: <?xml version='1.0' encoding='utf-8'?>
XSD file header: <?xml version='1.0' encoding='utf-16'?>
Another possible scenario that causes this is when anything comes before the XML document type declaration. i.e you might have something like this in the buffer:
helloworld<?xml version="1.0" encoding="utf-8"?>
or even a space or special character.
There are some special characters called byte order markers that could be in the buffer. Before passing the buffer to the Parser do this...
String xml = "<?xml ...";
xml = xml.trim().replaceFirst("^([\\W]+)<","<");
android studio 4.1.1
applicationVariants.all { variant ->
variant.outputs.all { output ->
def reversion = "118"
def date = new java.text.SimpleDateFormat("yyyyMMdd").format(new Date())
def versionName = defaultConfig.versionName
outputFileName = "MyApp_${versionName}_${date}_${reversion}.apk"
}
}
This is a WMI query to get the user name:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
You will need to add System.Management
under References manually.
You can install other builds but not Appstore build.
From Xcode 8.2,drag and drop the build to simulator for the installation.
Look for this on your Manifest.xml android:icon="@drawable/ic_launcher"
then change the ic_launcher
to the name of your icon which is on your @drawable
folder.
You can also do it like this:
var tt="88,9827";
tt=tt.replace(",", ".");
alert(tt);
private static long getFolderSize(Path folder) {
try {
return Files.walk(folder)
.filter(p -> p.toFile().isFile())
.mapToLong(p -> p.toFile().length())
.sum();
} catch (IOException e) {
e.printStackTrace();
return 0L;
}
If you only need the indices, you could try numpy.ndindex
:
>>> a = numpy.arange(9).reshape(3, 3)
>>> [(x, y) for x, y in numpy.ndindex(a.shape)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
I've got this code working in a windows form,
Public Class Form1
Private dataStuff As List(Of String)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DataGridView1.DataSource = Nothing
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dataStuff = New List(Of String)
dataStuff.Add("qwerty")
dataStuff.Add("another")
dataStuff.Add("...and another")
DataGridView1.DataSource = dataStuff
End Sub
End Class
Use try with resources. this will automatically close the resources.
try (BufferedReader br = new BufferedReader(new FileReader("C:/test.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
}
With fluent 4.5.2 i had to make the following modification to make it work.
try {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSslcontext(sc).build();
String output = Executor.newInstance(httpClient).execute(Request.Get("https://127.0.0.1:3000/something")
.connectTimeout(1000)
.socketTimeout(1000)).returnContent().asString();
} catch (Exception e) {
}
I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:
@{
var htmlAttr = new Dictionary<string, object>();
htmlAttr.Add("id", strElementId);
if (!CSSClass.IsEmpty())
{
htmlAttr.Add("class", strCSSClass);
}
}
@* ... *@
@Html.TextBox("somename", "", htmlAttr)
If this way will be useful for you i recommend to define dictionary htmlAttr
in your model so your view doesn't need any @{ }
logic blocks (be more clear).
You can use include=FALSE
to exclude everything in a chunk.
```{r include=FALSE}
source("C:/Rscripts/source.R")
```
If you only want to suppress messages, use message=FALSE
instead:
```{r message=FALSE}
source("C:/Rscripts/source.R")
```
Be aware
try{
// ...
} catch (...) {
// ...
}
catches only language-level exceptions, other low-level exceptions/errors like Access Violation
and Segmentation Fault
wont be caught.
In code level also, you could add your lib to the project using the compiler directives #pragma.
example:
#pragma comment( lib, "yourLibrary.lib" )
There is a way simpler way. You put the href in a paragraph just created for that href. For example:
HREF name
Awhile ago, I put together a package for doing what you want, and more. (I needed it for a utility I was writing). It uses the ASM library. You can use reflection, but ASM turned out to perform better.
I put my package in an open source library I have on my web site. The library is here: http://software.clapper.org/javautil/. You want to start with the with ClassFinder class.
The utility I wrote it for is an RSS reader that I still use every day, so the code does tend to get exercised. I use ClassFinder to support a plug-in API in the RSS reader; on startup, it looks in a couple directory trees for jars and class files containing classes that implement a certain interface. It's a lot faster than you might expect.
The library is BSD-licensed, so you can safely bundle it with your code. Source is available.
If that's useful to you, help yourself.
Update: If you're using Scala, you might find this library to be more Scala-friendly.
...
WHERE
x_field IN ('f', 'p', 'i', 'a') ...
ORDER BY
CASE x_field
WHEN 'f' THEN 1
WHEN 'p' THEN 2
WHEN 'i' THEN 3
WHEN 'a' THEN 4
ELSE 5 --needed only is no IN clause above. eg when = 'b'
END, id
Using ClipRRect
you need to hardcode BorderRadius
, so if you need complete circular stuff, use ClipOval
instead.
ClipOval(
child: Image.network(
"image_url",
height: 100,
width: 100,
fit: BoxFit.cover,
),
),
Another solution could be via pandas Series:
import pandas as pd
a = pd.Series([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
c = a[b]
You can then convert c back to a list if you want:
c = list(c)
Rather simple:
Key = i.ToString("D2");
D
stands for "decimal number", 2
for the number of digits to print.
/*
If your delimiters are slash-based, escape it:
\/*
*
means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.
The correct way to do it would be:
adb -s 123abc12 shell getprop
Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop
to access its value directly, like this:
adb -s 123abc12 shell getprop ro.product.model
The details in adb devices -l
consist of the following three properties: ro.product.name
, ro.product.model
and ro.product.device
.
Note that ADB shell ends lines with \r\n
, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7
you might get Nexus 7\r
).
This answer is outdated. For Android 3.1 Studio go to this answer
One thing you can do is deactivate the external build. To do so click on "compiler settings icon" in the "Messages Make" panel that appears when you have an error. You can also open the compiler settings by going to File -> Settings -> Compiler. (Thanx to @maxgalbu for this tip).
Uncheck "Use External build"
And you will see the errors in the console
EDIT: After returning to "internal build" again you may get some errors, you can solve them this way: Android Studio: disabling "External build" to display error output create duplicate class errors
Use
System.Drawing.Color.FromArgb(myHashCode);
Step To Use AutoMapper with ASP.NET Core.
Step 1. Installing AutoMapper.Extensions.Microsoft.DependencyInjection from NuGet Package.
Step 2. Create a Folder in Solution to keep Mappings with Name "Mappings".
Step 3. After adding Mapping folder we have added a class with Name "MappingProfile" this name can anything unique and good to understand.
In this class, we are going to Maintain all Mappings.
Step 4. Initializing Mapper in Startup "ConfigureServices"
In Startup Class, we Need to Initialize Profile which we have created and also Register AutoMapper Service.
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
Code Snippet to show ConfigureServices Method where we need to Initialize and Register AutoMapper.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// Start Registering and Initializing AutoMapper
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
// End Registering and Initializing AutoMapper
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}}
Step 5. Get Output.
To Get Mapped result we need to call AutoMapper.Mapper.Map and pass Proper Destination and Source.
AutoMapper.Mapper.Map<Destination>(source);
CodeSnippet
[HttpPost]
public void Post([FromBody] SchemeMasterViewModel schemeMaster)
{
if (ModelState.IsValid)
{
var mappedresult = AutoMapper.Mapper.Map<SchemeMaster>(schemeMaster);
}
}
Easy solution. Here's how I'd fix the issue:
platforms/ios
pod install
That's it. This should install the missing library.
Subclass UILabel, and override -drawInRect:
Using Python's built in range function:
Python 2
input = 8
output = range(input + 1)
print output
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Python 3
input = 8
output = list(range(input + 1))
print(output)
[0, 1, 2, 3, 4, 5, 6, 7, 8]