create external table table_name(
Year int,
Month int,
column_name data_type )
row format delimited fields terminated by ','
location '/user/user_name/example_data' TBLPROPERTIES('serialization.null.format'='', 'skip.header.line.count'='1');
This is what I was getting when tried to install m2e from Eclipse Market place. I am using Eclipse Juno.
Cannot complete the install because one or more required items could not be found. Software being installed: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) Missing requirement: Maven Integration for Eclipse 1.5.0.20140606-0033 (org.eclipse.m2e.core 1.5.0.20140606-0033) requires 'bundle com.google.guava [14.0.1,16.0.0)' but it could not be found Cannot satisfy dependency: From: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) To: org.eclipse.m2e.core [1.5.0.20140606-0033]
However, the below links is perfect, it works for me.
http://marketplace.eclipse.org/content/maven-integration-eclipse-wtp-juno-0
Regards, Bilal
If you want to upload videos programatically, check the YouTube Data API for PHP
So this solution takes a string as its parameter. It finds how many rows are in the sheet. It gets all the values in the column specified. It loops through the values from the end to the beginning until it finds a value that is not an empty string. Finally it retunrs the value.
Script:
function lastValue(column) {
var lastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
var values = SpreadsheetApp.getActiveSheet().getRange(column + "1:" + column + lastRow).getValues();
for (; values[lastRow - 1] == "" && lastRow > 0; lastRow--) {}
return values[lastRow - 1];
}
Usage:
=lastValue("G")
EDIT:
In response to the comment asking for the function to update automatically:
The best way I could find is to use this with the code above:
function onEdit(event) {
SpreadsheetApp.getActiveSheet().getRange("A1").setValue(lastValue("G"));
}
It would no longer be required to use the function in a cell like the Usage section states. Instead you are hard coding the cell you would like to update and the column you would like to track. It is possible that there is a more eloquent way to implement this (hopefully one that is not hard coded), but this is the best I could find for now.
Note that if you use the function in cell like stated earlier, it will update upon reload. Maybe there is a way to hook into onEdit()
and force in cell functions to update. I just can't find it in the documentation.
Reading the remark of Kleopatra (her 2nd time she suggested to have a look at javax.swing.JXTable, and now I Am sorry I didn't have a look the first time :) ) I suggest you follow the link
I had this solution for the same problem: (but I suggest you follow the link above) On resize the table, scale the table column widths to the current table total width. to do this I use a global array of ints for the (relative) column widths):
private int[] columnWidths=null;
I use this function to set the table column widths:
public void setColumnWidths(int[] widths){
int nrCols=table.getModel().getColumnCount();
if(nrCols==0||widths==null){
return;
}
this.columnWidths=widths.clone();
//current width of the table:
int totalWidth=table.getWidth();
int totalWidthRequested=0;
int nrRequestedWidths=columnWidths.length;
int defaultWidth=(int)Math.floor((double)totalWidth/(double)nrCols);
for(int col=0;col<nrCols;col++){
int width = 0;
if(columnWidths.length>col){
width=columnWidths[col];
}
totalWidthRequested+=width;
}
//Note: for the not defined columns: use the defaultWidth
if(nrRequestedWidths<nrCols){
log.fine("Setting column widths: nr of columns do not match column widths requested");
totalWidthRequested+=((nrCols-nrRequestedWidths)*defaultWidth);
}
//calculate the scale for the column width
double factor=(double)totalWidth/(double)totalWidthRequested;
for(int col=0;col<nrCols;col++){
int width = defaultWidth;
if(columnWidths.length>col){
//scale the requested width to the current table width
width=(int)Math.floor(factor*(double)columnWidths[col]);
}
table.getColumnModel().getColumn(col).setPreferredWidth(width);
table.getColumnModel().getColumn(col).setWidth(width);
}
}
When setting the data I call:
setColumnWidths(this.columnWidths);
and on changing I call the ComponentListener set to the parent of the table (in my case the JScrollPane that is the container of my table):
public void componentResized(ComponentEvent componentEvent) {
this.setColumnWidths(this.columnWidths);
}
note that the JTable table is also global:
private JTable table;
And here I set the listener:
scrollPane=new JScrollPane(table);
scrollPane.addComponentListener(this);
As Jim Garrison said in the comment, no obvious reason why you'd make a one-element list out of drug.upper()
(which implies drug is a string).
But that's not your error, as your function medications_minimum3()
doesn't even use the second argument (something you should fix).
TypeError: unhashable type: 'list'
usually means that you are trying to use a list as a hash argument (like for accessing a dictionary). I'd look for the error in counter[row[11]]+=1
-- are you sure that row[11]
is of the right type? Sounds to me it might be a list.
var array = string.split(',')
and good morning, too, since I have to type 30 chars ...
I would put the code in the viewWillAppear delegate on each view being shown:
Like this where you need to hide it:
- (void)viewWillAppear:(BOOL)animated
{
[yourObject hideBar];
}
Like this where you need to show it:
- (void)viewWillAppear:(BOOL)animated
{
[yourObject showBar];
}
If you want d1
to have priority in the conflicts, do:
d3 = d2.copy()
d3.update(d1)
Otherwise, reverse d2
and d1
.
here's an example for bash:
usage="$(basename "$0") [-h] [-s n] -- program to calculate the answer to life, the universe and everything
where:
-h show this help text
-s set the seed value (default: 42)"
seed=42
while getopts ':hs:' option; do
case "$option" in
h) echo "$usage"
exit
;;
s) seed=$OPTARG
;;
:) printf "missing argument for -%s\n" "$OPTARG" >&2
echo "$usage" >&2
exit 1
;;
\?) printf "illegal option: -%s\n" "$OPTARG" >&2
echo "$usage" >&2
exit 1
;;
esac
done
shift $((OPTIND - 1))
To use this inside a function:
"$FUNCNAME"
instead of $(basename "$0")
local OPTIND OPTARG
before calling getopts
Are there situations in which sys.stdout.write() is preferable to print?
I have found that stdout works better than print in a multithreading situation. I use a queue (FIFO) to store the lines to print and I hold all threads before the print line until my print queue is empty. Even so, using print I sometimes lose the final \n on the debug I/O (using the Wing Pro IDE).
When I use std.out with \n in the string, the debug I/O formats correctly and the \n's are accurately displayed.
C:\Users\<_username>\.gradle\wrapper\dists\gradle-<_version>-all\<_number_random_maybe>\gradle-<_version>
\Android studio\gradle didn't worked for me.
And "Default gradle wrapper" wasn't configured while importing (cloning) the project from bitbucket
If it causes problem to figure out the path, here is my path :
C:\Users\prabs\.gradle\wrapper\dists\gradle-5.4.1-all\3221gyojl5jsh0helicew7rwx\gradle-5.4.1
I guess the above methods have changed after the release, check this link out
https://github.com/valor-software/ng2-bootstrap/blob/development/docs/getting-started/ng-cli.md
initiate project
npm i -g angular-cli
ng new my-app
cd my-app
ng serve
npm install --save @ng-bootstrap/ng-bootstrap
install ng-bootstrap and bootstrap
npm install ng2-bootstrap bootstrap --save
open src/app/app.module.ts and add
import { AlertModule } from 'ng2-bootstrap/ng2-bootstrap';
...
@NgModule({
...
imports: [AlertModule, ... ],
...
})
open angular-cli.json and insert a new entry into the styles array
"styles": [
"styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
open src/app/app.component.html and test all works by adding
<alert type="success">hello</alert>
Sybase :
% : Matches any string of zero or more characters.
_ : Matches a single character.
[specifier] : Brackets enclose ranges or sets, such as [a-f]
or [abcdef].Specifier can take two forms:
rangespec1-rangespec2:
rangespec1 indicates the start of a range of characters.
- is a special character, indicating a range.
rangespec2 indicates the end of a range of characters.
set:
can be composed of any discrete set of values, in any
order, such as [a2bR].The range [a-f], and the
sets [abcdef] and [fcbdae] return the same
set of values.
Specifiers are case-sensitive.
[^specifier] : A caret (^) preceding a specifier indicates
non-inclusion. [^a-f] means "not in the range
a-f"; [^a2bR] means "not a, 2, b, or R."
String date="Sat Jun 01 12:53:10 IST 2013";
SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
Date currentdate=sdf.parse(date);
SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");
System.out.println(sdf2.format(currentdate));
Since you used the Windows installer, everything is set up for you to run MySQL 5.7 as a Windows service, which is a great option in most cases.
Instead of running mysqld.exe
from the command line,
Win + R
services.msc
MySQL57
In my case, I was getting this error because I had an input named x
and I was creating (without realizing it) a local variable called x
. I thought I was trying to access an element of the input x
(which was an array), while I was actually trying to access an element of the local variable x
(which was a scalar).
The typical solution to this is to write your own function to clone an object. If you are able to provide copy constructors and copy assignement operators, this may be as far as you need to go.
class Foo
{
public:
Foo();
Foo(const Foo& rhs) { /* copy construction from rhs*/ }
Foo& operator=(const Foo& rhs) {};
};
// ...
Foo orig;
Foo copy = orig; // clones orig if implemented correctly
Sometimes it is beneficial to provide an explicit clone()
method, especially for polymorphic classes.
class Interface
{
public:
virtual Interface* clone() const = 0;
};
class Foo : public Interface
{
public:
Interface* clone() const { return new Foo(*this); }
};
class Bar : public Interface
{
public:
Interface* clone() const { return new Bar(*this); }
};
Interface* my_foo = /* somehow construct either a Foo or a Bar */;
Interface* copy = my_foo->clone();
EDIT: Since Stack
has no member variables, there's nothing to do in the copy constructor or copy assignment operator to initialize Stack
's members from the so-called "right hand side" (rhs
). However, you still need to ensure that any base classes are given the opportunity to initialize their members.
You do this by calling the base class:
Stack(const Stack& rhs)
: List(rhs) // calls copy ctor of List class
{
}
Stack& operator=(const Stack& rhs)
{
List::operator=(rhs);
return * this;
};
add this to your ngnix conf file
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com https://assets.zendesk.com https://connect.facebook.net; img-src 'self' https://ssl.google-analytics.com https://s-static.ak.facebook.com https://assets.zendesk.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://assets.zendesk.com; font-src 'self' https://themes.googleusercontent.com; frame-src https://assets.zendesk.com https://www.facebook.com https://s-static.ak.facebook.com https://tautt.zendesk.com; object-src 'none'";
For static assertions, C++11 introduced decltype
which is quite useful in certain scenarios.
Just add style="table-layout: fixed ; width: 100%;"
inside <table>
tag and also if you do not specify any styles and add just style=" width: 100%;"
inside <table>
You will be able to resolve it.
<span style="color:#ffffff; font-size:18px; line-height:35px; font-family: Calibri;">Our Activities </span>
This works for me well:) As it has been already mentioned above "The font tag has been deprecated, at least in XHTML. It always safe to use span tag. font may not give you desire results, at least in my case it didn't.
I got this after saving the JSON file using Notepad2, so I had to open it with Notepad++ and then say "Convert to UTF-8". Then it worked.
Timer for jQuery - smaller, working, tested.
var sec = 0;_x000D_
function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
setInterval( function(){_x000D_
$("#seconds").html(pad(++sec%60));_x000D_
$("#minutes").html(pad(parseInt(sec/60,10)));_x000D_
}, 1000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
Pure JavaScript:
var sec = 0;_x000D_
function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
setInterval( function(){_x000D_
document.getElementById("seconds").innerHTML=pad(++sec%60);_x000D_
document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));_x000D_
}, 1000);
_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
Update:
This answer shows how to pad.
Stopping setInterval MDN is achieved with clearInterval MDN
var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );
Probably you are trying to access the excel with the index 0, please note that Excel rows/columns start from 1.
The BCP Utility can also be used in the form of a .bat file, but be cautious of escape sequences (ie quotes "" must be used in conjunction with ) and the appropriate tags.
.bat Example:
C:
bcp "\"YOUR_SERVER\".dbo.Proc" queryout C:\FilePath.txt -T -c -q
-- Add PAUSE here if you'd like to see the completed batch
-q MUST be used in the presence of quotations within the query itself.
BCP can also run Stored Procedures if necessary. Again, be cautious: Temporary Tables must be created prior to execution or else you should consider using Table Variables.
Update 2nd table data in 1st table need to Inner join before SET :
`UPDATE `table1` INNER JOIN `table2` ON `table2`.`id`=`table1`.`id` SET `table1`.`name`=`table2`.`name`, `table1`.`template`=`table2`.`template`;
Ok so I spent lots of time debugging this. I found out that the maximum text height as defined by boundingRectWithSize
allowed to display text by my UITextView
was lower than the frame size.
In my case the frame is at most 140pt but the UITextView tolerate texts at most 131pt.
I had to figure that out manually and hardcode the "real" maximum height.
Here is my solution:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
NSString *proposedText = [textView.text stringByReplacingCharactersInRange:range withString:text];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:proposedText];
CGRect boundingRect;
CGFloat maxFontSize = 100;
CGFloat minFontSize = 30;
CGFloat fontSize = maxFontSize + 1;
BOOL fit;
NSLog(@"Trying text: \"%@\"", proposedText);
do {
fontSize -= 1;
//XXX Seems like trailing whitespaces count for 0. find a workaround
[attributedText addAttribute:NSFontAttributeName value:[textView.font fontWithSize:fontSize] range:NSMakeRange(0, attributedText.length)];
CGFloat padding = textView.textContainer.lineFragmentPadding;
CGSize boundingSize = CGSizeMake(textView.frame.size.width - padding * 2, CGFLOAT_MAX);
boundingRect = [attributedText boundingRectWithSize:boundingSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
NSLog(@"bounding rect for font %f is %@; (max is %f %f). Padding: %f", fontSize, NSStringFromCGRect(boundingRect), textView.frame.size.width, 148.0, padding);
fit = boundingRect.size.height <= 131;
} while (!fit && fontSize > minFontSize);
if (fit) {
self.textView.font = [self.textView.font fontWithSize:fontSize];
NSLog(@"Fit!");
} else {
NSLog(@"No fit");
}
return fit;
}
You could use the UPPER keyword:
SELECT *
FROM Customers
WHERE UPPER(LastName) = UPPER('AnGel')
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
I came accross the same problem and solved it by checking my #includes. If you use QKeyEvent you have to make sure that you also include it.
I had a class like this and my error appeared when working with "event"in the .cpp file.
myfile.h
#include <QKeyEvent> // adding this import solved the problem.
class MyClass : public QWidget
{
Q_OBJECT
public:
MyClass(QWidget* parent = 0);
virtual ~QmitkHelpOverlay();
protected:
virtual void keyPressEvent(QKeyEvent* event);
};
For all those recommending using table variables, be cautious in doing so. Table variable cannot be indexed whereas a temp table can be. A table variable is best when working with small amounts of data but if you are working on larger sets of data (e.g. 50k records) a temp table will be much faster than a table variable.
Also keep in mind that you can't rely on a try/catch to force a cleanup within the stored procedure. certain types of failures cannot be caught within a try/catch (e.g. compile failures due to delayed name resolution) if you want to be really certain you may need to create a wrapper stored procedure that can do a try/catch of the worker stored procedure and do the cleanup there.
e.g. create proc worker AS BEGIN -- do something here END
create proc wrapper AS
BEGIN
Create table #...
BEGIN TRY
exec worker
exec worker2 -- using same temp table
-- etc
END TRY
END CATCH
-- handle transaction cleanup here
drop table #...
END CATCH
END
One place where table variables are always useful is they do not get rolled back when a transaction is rolled back. This can be useful for capturing debug data that you want to commit outside the primary transaction.
I come across similar problem while calling stored procedure
CREATE PROCEDURE UserPreference_Search
@UserPreferencesId int,
@SpecialOfferMails char(1),
@NewsLetters char(1),
@UserLoginId int,
@Currency varchar(50)
AS
DECLARE @QueryString nvarchar(4000)
SET @QueryString = 'SELECT UserPreferencesId,SpecialOfferMails,NewsLetters,UserLoginId,Currency FROM UserPreference'
IF(@UserPreferencesId IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE UserPreferencesId = @DummyUserPreferencesId';
END
IF(@SpecialOfferMails IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE SpecialOfferMails = @DummySpecialOfferMails';
END
IF(@NewsLetters IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE NewsLetters = @DummyNewsLetters';
END
IF(@UserLoginId IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE UserLoginId = @DummyUserLoginId';
END
IF(@Currency IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE Currency = @DummyCurrency';
END
EXECUTE SP_EXECUTESQL @QueryString
,N'@DummyUserPreferencesId int, @DummySpecialOfferMails char(1), @DummyNewsLetters char(1), @DummyUserLoginId int, @DummyCurrency varchar(50)'
,@DummyUserPreferencesId=@UserPreferencesId
,@DummySpecialOfferMails=@SpecialOfferMails
,@DummyNewsLetters=@NewsLetters
,@DummyUserLoginId=@UserLoginId
,@DummyCurrency=@Currency;
Which dynamically constructing the query for search I was calling above one by:
public DataSet Search(int? AccessRightId, int? RoleId, int? ModuleId, char? CanAdd, char? CanEdit, char? CanDelete, DateTime? CreatedDatetime, DateTime? LastAccessDatetime, char? Deleted)
{
dbManager.ConnectionString = ConfigurationManager.ConnectionStrings["MSSQL"].ToString();
DataSet ds = new DataSet();
try
{
dbManager.Open();
dbManager.CreateParameters(9);
dbManager.AddParameters(0, "@AccessRightId", AccessRightId, ParameterDirection.Input);
dbManager.AddParameters(1, "@RoleId", RoleId, ParameterDirection.Input);
dbManager.AddParameters(2, "@ModuleId", ModuleId, ParameterDirection.Input);
dbManager.AddParameters(3, "@CanAdd", CanAdd, ParameterDirection.Input);
dbManager.AddParameters(4, "@CanEdit", CanEdit, ParameterDirection.Input);
dbManager.AddParameters(5, "@CanDelete", CanDelete, ParameterDirection.Input);
dbManager.AddParameters(6, "@CreatedDatetime", CreatedDatetime, ParameterDirection.Input);
dbManager.AddParameters(7, "@LastAccessDatetime", LastAccessDatetime, ParameterDirection.Input);
dbManager.AddParameters(8, "@Deleted", Deleted, ParameterDirection.Input);
ds = dbManager.ExecuteDataSet(CommandType.StoredProcedure, "AccessRight_Search");
return ds;
}
catch (Exception ex)
{
}
finally
{
dbManager.Dispose();
}
return ds;
}
Then after lot of head scratching I modified stored procedure to:
ALTER PROCEDURE [dbo].[AccessRight_Search]
@AccessRightId int=null,
@RoleId int=null,
@ModuleId int=null,
@CanAdd char(1)=null,
@CanEdit char(1)=null,
@CanDelete char(1)=null,
@CreatedDatetime datetime=null,
@LastAccessDatetime datetime=null,
@Deleted char(1)=null
AS
DECLARE @QueryString nvarchar(4000)
DECLARE @HasWhere bit
SET @HasWhere=0
SET @QueryString = 'SELECT a.AccessRightId, a.RoleId,a.ModuleId, a.CanAdd, a.CanEdit, a.CanDelete, a.CreatedDatetime, a.LastAccessDatetime, a.Deleted, b.RoleName, c.ModuleName FROM AccessRight a, Role b, Module c WHERE a.RoleId = b.RoleId AND a.ModuleId = c.ModuleId'
SET @HasWhere=1;
IF(@AccessRightId IS NOT NULL)
BEGIN
IF(@HasWhere=0)
BEGIN
SET @QueryString = @QueryString + ' WHERE a.AccessRightId = @DummyAccessRightId';
SET @HasWhere=1;
END
ELSE SET @QueryString = @QueryString + ' AND a.AccessRightId = @DummyAccessRightId';
END
IF(@RoleId IS NOT NULL)
BEGIN
IF(@HasWhere=0)
BEGIN
SET @QueryString = @QueryString + ' WHERE a.RoleId = @DummyRoleId';
SET @HasWhere=1;
END
ELSE SET @QueryString = @QueryString + ' AND a.RoleId = @DummyRoleId';
END
IF(@ModuleId IS NOT NULL)
BEGIN
IF(@HasWhere=0)
BEGIN
SET @QueryString = @QueryString + ' WHERE a.ModuleId = @DummyModuleId';
SET @HasWhere=1;
END
ELSE SET @QueryString = @QueryString + ' AND a.ModuleId = @DummyModuleId';
END
IF(@CanAdd IS NOT NULL)
BEGIN
IF(@HasWhere=0)
BEGIN
SET @QueryString = @QueryString + ' WHERE a.CanAdd = @DummyCanAdd';
SET @HasWhere=1;
END
ELSE SET @QueryString = @QueryString + ' AND a.CanAdd = @DummyCanAdd';
END
IF(@CanEdit IS NOT NULL)
BEGIN
IF(@HasWhere=0)
BEGIN
SET @QueryString = @QueryString + ' WHERE a.CanEdit = @DummyCanEdit';
SET @HasWhere=1;
END
ELSE SET @QueryString = @QueryString + ' AND a.CanEdit = @DummyCanEdit';
END
IF(@CanDelete IS NOT NULL)
BEGIN
IF(@HasWhere=0)
BEGIN
SET @QueryString = @QueryString + ' WHERE a.CanDelete = @DummyCanDelete';
SET @HasWhere=1;
END
ELSE SET @QueryString = @QueryString + ' AND a.CanDelete = @DummyCanDelete';
END
IF(@CreatedDatetime IS NOT NULL)
BEGIN
IF(@HasWhere=0)
BEGIN
SET @QueryString = @QueryString + ' WHERE a.CreatedDatetime = @DummyCreatedDatetime';
SET @HasWhere=1;
END
ELSE SET @QueryString = @QueryString + ' AND a.CreatedDatetime = @DummyCreatedDatetime';
END
IF(@LastAccessDatetime IS NOT NULL)
BEGIN
IF(@HasWhere=0)
BEGIN
SET @QueryString = @QueryString + ' WHERE a.LastAccessDatetime = @DummyLastAccessDatetime';
SET @HasWhere=1;
END
ELSE SET @QueryString = @QueryString + ' AND a.LastAccessDatetime = @DummyLastAccessDatetime';
END
IF(@Deleted IS NOT NULL)
BEGIN
IF(@HasWhere=0)
BEGIN
SET @QueryString = @QueryString + ' WHERE a.Deleted = @DummyDeleted';
SET @HasWhere=1;
END
ELSE SET @QueryString = @QueryString + ' AND a.Deleted = @DummyDeleted';
END
PRINT @QueryString
EXECUTE SP_EXECUTESQL @QueryString
,N'@DummyAccessRightId int, @DummyRoleId int, @DummyModuleId int, @DummyCanAdd char(1), @DummyCanEdit char(1), @DummyCanDelete char(1), @DummyCreatedDatetime datetime, @DummyLastAccessDatetime datetime, @DummyDeleted char(1)'
,@DummyAccessRightId=@AccessRightId
,@DummyRoleId=@RoleId
,@DummyModuleId=@ModuleId
,@DummyCanAdd=@CanAdd
,@DummyCanEdit=@CanEdit
,@DummyCanDelete=@CanDelete
,@DummyCreatedDatetime=@CreatedDatetime
,@DummyLastAccessDatetime=@LastAccessDatetime
,@DummyDeleted=@Deleted;
HERE I am Initializing the Input Params of Stored Procedure to null as Follows
@AccessRightId int=null,
@RoleId int=null,
@ModuleId int=null,
@CanAdd char(1)=null,
@CanEdit char(1)=null,
@CanDelete char(1)=null,
@CreatedDatetime datetime=null,
@LastAccessDatetime datetime=null,
@Deleted char(1)=null
that did the trick for Me.
I hope this will be helpfull to someone who fall in similar trap.
To view any variable in chrome, go to "Sources", and then "Watch" and add it. If you add the "window" variable here then you can expand it and explore.
For those who need the same feature in IE 8, this is how I solved the problem:
var myImage = $('<img/>');
myImage.attr('width', 300);
myImage.attr('height', 300);
myImage.attr('class', "groupMediaPhoto");
myImage.attr('src', photoUrl);
I could not force IE8 to use object in constructor.
You can use the window object to get at it .
window['myVar']
window
has a reference to all global variables and global functions you are using.
select * from table where column_date > now()- INTERVAL '6 hours';
For conversion,you can create ~/.my.cnf
file in host:
[Mysql]
user=root
password=yourpass
host=127.0.0.1
port=3306
Then next time just run mysql
for mysql client to open connection.
You can use the Apache Commons StringUtils.substring(String str, int start, int end)
static method, which is also null safe.
I don't think the existing answers adequately addressed this part of the question:
When should I use them?
If you're writing an API that will be published or reused within your organization, you should write comprehensive Javadoc comments for every public
class, method, and field, as well as protected
methods and fields of non-final
classes. Javadoc should cover everything that cannot be conveyed by the method signature, such as preconditions, postconditions, valid arguments, runtime exceptions, internal calls, etc.
If you're writing an internal API (one that's used by different parts of the same program), Javadoc is arguably less important. But for the benefit of maintenance programmers, you should still write Javadoc for any method or field where the correct usage or meaning is not immediately obvious.
The "killer feature" of Javadoc is that it's closely integrated with Eclipse and other IDEs. A developer only needs to hover their mouse pointer over an identifier to learn everything they need to know about it. Constantly referring to the documentation becomes second nature for experienced Java developers, which improves the quality of their own code. If your API isn't documented with Javadoc, experienced developers will not want to use it.
I assume that you enable developer mode
on your android device and you are connected to your device and you have shell access (adb shell
).
Once this is done you can uninstall application with this command pm uninstall --user 0 <package.name>
. 0 is root id -this way you don't need too root your device.
# gain shell access
$ adb shell
# check who you are
$ whoami
shell
# obtain user id
$ id
uid=2000(shell) gid=2000(shell)
# list packages
$ pm list packages | grep google
package:com.google.android.youtube
package:com.google.android.ext.services
package:com.google.android.googlequicksearchbox
package:com.google.android.onetimeinitializer
package:com.google.android.ext.shared
package:com.google.android.apps.docs.editors.sheets
package:com.google.android.configupdater
package:com.google.android.marvin.talkback
package:com.google.android.apps.tachyon
package:com.google.android.instantapps.supervisor
package:com.google.android.setupwizard
package:com.google.android.music
package:com.google.android.apps.docs
package:com.google.android.apps.maps
package:com.google.android.webview
package:com.google.android.syncadapters.contacts
package:com.google.android.packageinstaller
package:com.google.android.gm
package:com.google.android.gms
package:com.google.android.gsf
package:com.google.android.tts
package:com.google.android.partnersetup
package:com.google.android.videos
package:com.google.android.feedback
package:com.google.android.printservice.recommendation
package:com.google.android.apps.photos
package:com.google.android.syncadapters.calendar
package:com.google.android.gsf.login
package:com.google.android.backuptransport
package:com.google.android.inputmethod.latin
# uninstall gmail app
pm uninstall --user 0 com.google.android.gms
For people with only one IP address and multiple sites on one server, you can configure IIS to listen on a port other than 80
, e.g 8080
by setting the TCP port in the properties of each of its sites (including the default one).
In Apache, enable mod_proxy
and mod_proxy_http
, then add a catch-all VirtualHost (after all others) so that requests Apache isn't explicitly handling get "forwarded" on to IIS.
<VirtualHost *:80>
ServerName foo.bar
ServerAlias *
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:8080/
</VirtualHost>
Now you can have Apache serve some sites and IIS serve others, with no visible difference to the user.
Edit: your IIS sites must not include their port number in any URLs within their responses, including headers.
The size of storage required and how big the numbers can be.
On SQL Server:
tinyint
1 byte, 0 to 255smallint
2 bytes, -215 (-32,768) to 215-1 (32,767)int
4 bytes, -231 (-2,147,483,648) to 231-1 (2,147,483,647)bigint
8 bytes, -263 (-9,223,372,036,854,775,808) to 263-1 (9,223,372,036,854,775,807)You can store the number 1 in all 4, but a bigint
will use 8 bytes, while a tinyint
will use 1 byte.
I face the same issue. I am using docker version:17.09.0-ce
.
I follow below steps:
$ sudo docker build -t ubuntu-test:latest .
It resolved issue and image created successsfully.
Note: build command depend on docker version as well as which build option we are using. :)
The other response shows this, but essentially you just need to create a SqlParameter
, set the Direction
to Output
, and add it to the SqlCommand
's Parameters
collection. Then execute the stored procedure and get the value of the parameter.
Using your code sample:
// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("sproc", conn))
{
// Create parameter with Direction as Output (and correct name and type)
SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
// Some various ways to grab the output depending on how you would like to
// handle a null value returned from the query (shown in comment for each).
// Note: You can use either the SqlParameter variable declared
// above or access it through the Parameters collection by name:
// outputIdParam.Value == cmd.Parameters["@ID"].Value
// Throws FormatException
int idFromString = int.Parse(outputIdParam.Value.ToString());
// Throws InvalidCastException
int idFromCast = (int)outputIdParam.Value;
// idAsNullableInt remains null
int? idAsNullableInt = outputIdParam.Value as int?;
// idOrDefaultValue is 0 (or any other value specified to the ?? operator)
int idOrDefaultValue = outputIdParam.Value as int? ?? default(int);
conn.Close();
}
Be careful when getting the Parameters[].Value
, since the type needs to be cast from object
to what you're declaring it as. And the SqlDbType
used when you create the SqlParameter
needs to match the type in the database. If you're going to just output it to the console, you may just be using Parameters["@Param"].Value.ToString()
(either explictly or implicitly via a Console.Write()
or String.Format()
call).
EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from @Walter Stabosz and @Stephen Kennedy and to match the update code edit in the question from @abatishchev.
Many suggestions here, most along the lines of git checkout $revision -- $file
. A couple of obscure alternatives:
git show $revision:$file > $file
And also, I use this a lot just to see a particular version temporarily:
git show $revision:$file
or
git show $revision:$file | vim -R -
(OBS: $file
needs to be prefixed with ./
if it is a relative path for git show $revision:$file
to work)
And the even more weird:
git archive $revision $file | tar -x0 > $file
Try the following code.
TimeSpan CurrentTime = DateTime.Now.TimeOfDay;
Get the time of the day and assign it to TimeSpan
variable.
<script>
jQuery(document).ready(function() {
jQuery("tr").click(function(){
alert("Click! "+ jQuery(this).find('td').html());
});
});
</script>
zEnter does exactly what this question asks for.
It works where strangely zz would not work (vim 7.4.1689 on Ubuntu 2016.04 LTS with no special .vimrc)
This is an old post, but I ended up using Peter Lang's thoughts, and did a similar, but yet different approach. Here is what I did:
CREATE OR REPLACE FUNCTION multi_replace(
pString IN VARCHAR2
,pReplacePattern IN VARCHAR2
) RETURN VARCHAR2 IS
iCount INTEGER;
vResult VARCHAR2(1000);
vRule VARCHAR2(100);
vOldStr VARCHAR2(50);
vNewStr VARCHAR2(50);
BEGIN
iCount := 0;
vResult := pString;
LOOP
iCount := iCount + 1;
-- Step # 1: Pick out the replacement rules
vRule := REGEXP_SUBSTR(pReplacePattern, '[^/]+', 1, iCount);
-- Step # 2: Pick out the old and new string from the rule
vOldStr := REGEXP_SUBSTR(vRule, '[^=]+', 1, 1);
vNewStr := REGEXP_SUBSTR(vRule, '[^=]+', 1, 2);
-- Step # 3: Do the replacement
vResult := REPLACE(vResult, vOldStr, vNewStr);
EXIT WHEN vRule IS NULL;
END LOOP;
RETURN vResult;
END multi_replace;
Then I can use it like this:
SELECT multi_replace(
'This is a test string with a #, a $ character, and finally a & character'
,'#=%23/$=%24/&=%25'
)
FROM dual
This makes it so that I can can any character/string with any character/string.
I wrote a post about this on my blog.
How to set default values in twig: http://twig.sensiolabs.org/doc/filters/default.html
{{ my_var | default("my_var doesn't exist") }}
Or if you don't want it to display when null:
{{ my_var | default("") }}
One option is to use an attribute on the image, and modify that using jQuery. Then take that value in CSS:
HTML (note I'm assuming .cloumn
is a div
but it could be anything):
<div class="column" bf-width=100 >
<img src="..." />
</div>
jQuery:
// General use:
$('.column').attr('bf-width', 100);
// With your image, along the lines of:
$('.column').attr('bf-width', $('img').width());
And then in order to use that value in CSS:
.column:before {
content: attr(data-content) 'px';
/* ... */
}
This will grab the attribute value from .column
, and apply it on the before.
Sources: CSS attr (note the examples with before), jQuery attr.
Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.
Quote:
Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.
ApiControllers are specialized in returning data. For example, they take care of transparently serializing the data into the format requested by the client. Also, they follow a different routing scheme by default (as in: mapping URLs to actions), providing a REST-ful API by convention.
You could probably do anything using a Controller instead of an ApiController with the some(?) manual coding. In the end, both controllers build upon the ASP.NET foundation. But having a REST-ful API is such a common requirement today that WebAPI was created to simplify the implementation of a such an API.
It's fairly simple to decide between the two: if you're writing an HTML based web/internet/intranet application - maybe with the occasional AJAX call returning json here and there - stick with MVC/Controller. If you want to provide a data driven/REST-ful interface to a system, go with WebAPI. You can combine both, of course, having an ApiController cater AJAX calls from an MVC page.
To give a real world example: I'm currently working with an ERP system that provides a REST-ful API to its entities. For this API, WebAPI would be a good candidate. At the same time, the ERP system provides a highly AJAX-ified web application that you can use to create queries for the REST-ful API. The web application itself could be implemented as an MVC application, making use of the WebAPI to fetch meta-data etc.
Just add onsubmit
event handler for your form:
<form action="insert.php" onsubmit="return myFunction()" method="post">
Remove onclick
from button
and make it input
with type submit
<input type="submit" value="Submit">
And add boolean return statements to your function:
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var ok = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
return false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
Inline elements (like SPAN, LABEL, etc.) are displayed so that their height and width are calculated by the browser based on their content. If you want to control height and width you have to change those elements' blocks.
display: block;
makes the element displayed as a solid block (like DIV tags) which means that there is a line break after the element (it's not inline). Although you can use display: inline-block
to fix the issue of line break, this solution does not work in IE6 because IE6 doesn't recognize inline-block. If you want it to be cross-browser compatible then look at this article: http://webjazz.blogspot.com/2008/01/getting-inline-block-working-across.html
Think about what you're asking!
The max of {1, 2, 3, -1, -2, -3} is obviously 3. The max of {2} is obviously 2. But what is the max of the empty set { }? Obviously that is a meaningless question. The max of the empty set is simply not defined. Attempting to get an answer is a mathematical error. The max of any set must itself be an element in that set. The empty set has no elements, so claiming that some particular number is the max of that set without being in that set is a mathematical contradiction.
Just as it is correct behavior for the computer to throw an exception when the programmer asks it to divide by zero, so it is correct behavior for the computer to throw an exception when the programmer asks it to take the max of the empty set. Division by zero, taking the max of the empty set, wiggering the spacklerorke, and riding the flying unicorn to Neverland are all meaningless, impossible, undefined.
Now, what is it that you actually want to do?
If you have a strict content security policy that doesn't allow @vladimir-salguero's answer, you can use this (please make note of the script nonce
):
<script nonce="(your nonce)" async>
$(document).ready(function() {
$('link[media="none"]').each(function(a, t) {
var n = $(this).attr("data-async"),
i = $(this);
void 0 !== n && !1 !== n && ("true" == n || n) && i.attr("media", "all")
})
});
</script>
Just add the following to your stylesheet reference: media="none" data-async="true"
. Here's an example:
<link rel="stylesheet" href="../path/script.js" media="none" data-async="true" />
Example for jQuery:
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" type="text/css" media="none" data-async="true" crossorigin="anonymous" /><noscript><link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" type="text/css" /></noscript>
Go to Help → Install new software → Here uncheck “Contact all update sites during install to find required software”
Eclipse will prompt that the content isn't authorized or something like that. just ignore and continue. then everything will be OK.
At least this trick resolved my problems similar like this:
An error occurred while collecting items to be installed session context was:(profile=epp.package.jee, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=). No repository found containing: osgi.bundle,org.eclipse.emf,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.ant,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.codegen,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.codegen.ecore,2.8.1.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.codegen.ecore.ui,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.codegen.ui,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.common,2.8.0.v20120911-0500 No repository found containing: osgi.bundle,org.eclipse.emf.common.ui,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.converter,2.5.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.databinding,1.2.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.databinding.edit,1.2.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.ecore,2.8.1.v20120911-0500 No repository found containing: osgi.bundle,org.eclipse.emf.ecore.change,2.8.0.v20120911-0500 No repository found containing: osgi.bundle,org.eclipse.emf.ecore.change.edit,2.5.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.ecore.edit,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.ecore.editor,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.ecore.xmi,2.8.0.v20120911-0500 No repository found containing: osgi.bundle,org.eclipse.emf.edit,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.edit.ui,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.exporter,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.importer,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.importer.ecore,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.importer.java,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.importer.rose,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore.editor,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore2ecore,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore2ecore.editor,2.5.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore2xml,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore2xml.ui,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ui,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.wst.common.project.facet.core,1.4.300.v201111030424 No repository found containing: osgi.bundle,org.eclipse.wst.common.project.facet.ui,1.4.300.v201111030424 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.codegen.ecore,2.8.1.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.codegen.ecore.ui,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.codegen,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.codegen.ui,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.common,2.8.0.v20120911-0500 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.common.ui,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.converter,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.databinding.edit,1.2.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.databinding,1.2.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.ecore.edit,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.ecore.editor,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.ecore,2.8.1.v20120911-0500 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.edit,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.edit.ui,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf,2.8.1.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.mapping.ecore.editor,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.mapping.ecore,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.mapping,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.mapping.ui,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.wst.common.fproj,3.4.0.v201202292300-377F8N8s735555393B7B
Another "Up Tick" for AR..., but if you don't have to use interop I would avoid it altogether. This product is actually quite interesting: http://www.clearoffice.com/ and it provides a very intuitive, fully managed, api for manipulation excel files and seems to be free. (at least for the time being) SpreadSheetGear is also excellent but pricey.
my two cents.
Why not use this: dotConnect for Oracle (formerly known as OraDirect .NET)?
It can be configured to not require an Oracle Client at all.
We have been using this in both Windows Services and ASP.NET Web Services and it works like a charm.
If the script is the same across all users, you can use a lockfile
approach. If you acquire the lock, proceed else show a message and exit.
As an example:
[Terminal #1] $ lockfile -r 0 /tmp/the.lock
[Terminal #1] $
[Terminal #2] $ lockfile -r 0 /tmp/the.lock
[Terminal #2] lockfile: Sorry, giving up on "/tmp/the.lock"
[Terminal #1] $ rm -f /tmp/the.lock
[Terminal #1] $
[Terminal #2] $ lockfile -r 0 /tmp/the.lock
[Terminal #2] $
After /tmp/the.lock
has been acquired your script will be the only one with access to execution. When you are done, just remove the lock. In script form this might look like:
#!/bin/bash
lockfile -r 0 /tmp/the.lock || exit 1
# Do stuff here
rm -f /tmp/the.lock
Print only current month week:
function my_week_range($date) {
$ts = strtotime($date);
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
echo $currentWeek = ceil((date("d",strtotime($date)) - date("w",strtotime($date)) - 1) / 7) + 1;
$start_date = date('Y-m-d', $start);$end_date=date('Y-m-d', strtotime('next saturday', $start));
if($currentWeek==1)
{$start_date = date('Y-m-01', strtotime($date));}
else if($currentWeek==5)
{$end_date = date('Y-m-t', strtotime($date));}
else
{}
return array($start_date, $end_date );
}
$date_range=list($start_date, $end_date) = my_week_range($new_fdate);
Is this what you're looking for?
I have managed to overcome 405 and 404 errors thrown on pre-flight ajax options requests only by custom code in global.asax
protected void Application_BeginRequest()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
PS: Consider security issues when allowing everything *.
I had to disable CORS since it was returning 'Access-Control-Allow-Origin' header contains multiple values.
Also needed this in web.config:
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
<remove name="OPTIONSVerbHandler"/>
<remove name="TRACEVerbHandler"/>
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>
And app.pool needs to be set to Integrated mode.
This is super simple with format
:
>>> a = "John"
>>> "{:<15}".format(a)
'John '
This syntax isn't valid in any version of PostgreSQL:
ALTER SEQUENCE payments_id_seq LASTVALUE 22
This would work:
ALTER SEQUENCE payments_id_seq RESTART WITH 22;
And is equivalent to:
SELECT setval('payments_id_seq', 22, FALSE);
More in the current manual for ALTER SEQUENCE
and sequence functions.
Note that setval()
expects either (regclass, bigint)
or (regclass, bigint, boolean)
. In the above example I am providing untyped literals. That works too. But if you feed typed variables to the function you may need explicit type casts to satisfy function type resolution. Like:
SELECT setval(my_text_variable::regclass, my_other_variable::bigint, FALSE);
For repeated operations you might be interested in:
ALTER SEQUENCE payments_id_seq START WITH 22; -- set default
ALTER SEQUENCE payments_id_seq RESTART; -- without value
START [WITH]
stores a default RESTART
number, which is used for subsequent RESTART
calls without value. You need Postgres 8.4 or later for the last part.
You can do it as below.
$(this).prev('input').val("hello world");
Some alternatives for division by 4
return x/4 + (x/2 % 2);
return x/4 + (x % 4 >= 2)
Or in general, division by any power of 2
return x/y + x/(y/2) % 2; // or
return (x >> i) + ((x >> i - 1) & 1); // with y = 2^i
It works by rounding up if the fractional part ? 0.5, i.e. the first digit ? base/2. In binary it's equivalent to adding the first fractional bit to the result
This method has an advantage in architectures with a flag register, because the carry flag will contain the last bit that was shifted out. For example on x86 it can be optimized into
shr eax, i
adc eax, 0
It's also easily extended to support signed integers. Notice that the expression for negative numbers is
(x - 1)/y + ((x - 1)/(y/2) & 1)
we can make it work for both positive and negative values with
int t = x + (x >> 31);
return (t >> i) + ((t >> i - 1) & 1);
As noted in the comments, the query in Saharsh Shah's answer must be run multiple times if items are duplicated more than once.
Here's a solution that doesn't delete any data, and keeps the data in the original table the entire time, allowing for duplicates to be deleted while keeping the table 'live':
alter table tableA add column duplicate tinyint(1) not null default '0';
update tableA set
duplicate=if(@member_id=member_id
and @quiz_num=quiz_num
and @question_num=question_num
and @answer_num=answer_num,1,0),
member_id=(@member_id:=member_id),
quiz_num=(@quiz_num:=quiz_num),
question_num=(@question_num:=question_num),
answer_num=(@answer_num:=answer_num)
order by member_id, quiz_num, question_num, answer_num;
delete from tableA where duplicate=1;
alter table tableA drop column duplicate;
This basically checks to see if the current row is the same as the last row, and if it is, marks it as duplicate (the order statement ensures that duplicates will show up next to each other). Then you delete the duplicate records. I remove the duplicate
column at the end to bring it back to its original state.
It looks like alter table ignore
also might go away soon: http://dev.mysql.com/worklog/task/?id=7395
The issue here was that myString
had that header line. Either there was some hidden character at the beginning of the first line or the line itself was causing the error. I sliced off the first line like so:
xml.LoadXml(myString.Substring(myString.IndexOf(Environment.NewLine)));
This solved my problem.
<meta name="viewport" content="width=320, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
Also making sure height=device-height
is not present in this meta tag helps prevent additional footer padding that normally would not exist on the page. The menubar height adds to the viewport height causing a fixed background to become scrollable.
The Date()
object in javascript is not that smart really.
If you just focus on adding seconds it seems to handle things smoothly but if you try to add X number of seconds then add X number of minute and hours, etc, to the same Date
object you end up in trouble. So I simply fell back to only using the setSeconds()
method and converting my data into seconds (which worked fine).
If anyone can demonstrate adding time to a global Date()
object using all the set methods and have the final time come out correctly I would like to see it but I get the sense that one set method is to be used at a time on a given Date()
object and mixing them leads to a mess.
var vTime = new Date();
var iSecondsToAdd = ( iSeconds + (iMinutes * 60) + (iHours * 3600) + (iDays * 86400) );
vTime.setSeconds(iSecondsToAdd);
as @Aurand to said, tomcat is not running. you can use the
ps -ef |grep java | grep tomcat
command to ignore the ps
programs.
worked for me in the shell scripte files.
Here's a sample method that adds two extra columns programmatically to the grid view:
private void AddColumnsProgrammatically()
{
// I created these columns at function scope but if you want to access
// easily from other parts of your class, just move them to class scope.
// E.g. Declare them outside of the function...
var col3 = new DataGridViewTextBoxColumn();
var col4 = new DataGridViewCheckBoxColumn();
col3.HeaderText = "Column3";
col3.Name = "Column3";
col4.HeaderText = "Column4";
col4.Name = "Column4";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
}
A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)
For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:
// Note that this info scattered throughout the designer but can easily collected.
System.Windows.Forms.DataGridViewTextBoxColumn Column1;
System.Windows.Forms.DataGridViewCheckBoxColumn Column2;
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1,
this.Column2});
this.Column1.HeaderText = "Column1";
this.Column1.Name = "Column1";
this.Column2.HeaderText = "Column2";
this.Column2.Name = "Column2";
From this post: How to deal with floating point number precision in JavaScript?
You have a few options:
(Math.floor(y/x) * x).toFixed(2)
I'm not fully sure that this is what you're looking for, but if your question is how to read an integer using <stdio.h>
, then the proper syntax is
int myInt;
scanf("%d", &myInt);
You'll need to do a lot of error-handling to ensure that this works correctly, of course, but this should be a good start. In particular, you'll need to handle the cases where
stdin
file is closed or broken, so you get nothing at all.To check for this, you can capture the return code from scanf
like this:
int result = scanf("%d", &myInt);
If stdin
encounters an error while reading, result
will be EOF
, and you can check for errors like this:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
If, on the other hand, the user enters something invalid, like a garbage text string, then you need to read characters out of stdin
until you consume all the offending input. You can do this as follows, using the fact that scanf
returns 0 if nothing was read:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
if (result == 0) {
while (fgetc(stdin) != '\n') // Read until a newline is found
;
}
Hope this helps!
EDIT: In response to the more detailed question, here's a more appropriate answer. :-)
The problem with this code is that when you write
printf("got the number: %d", scanf("%d", &x));
This is printing the return code from scanf
, which is EOF
on a stream error, 0
if nothing was read, and 1
otherwise. This means that, in particular, if you enter an integer, this will always print 1
because you're printing the status code from scanf
, not the number you read.
To fix this, change this to
int x;
scanf("%d", &x);
/* ... error checking as above ... */
printf("got the number: %d", x);
Hope this helps!
element.offsetLeft
and element.offsetTop
are the pure javascript properties for finding an element's position with respect to its offsetParent
; being the nearest parent element with a position of relative
or absolute
Alternatively, you can always use Zepto to get the position of an element AND its parent, and simply subtract the two:
var childPos = obj.offset();
var parentPos = obj.parent().offset();
var childOffset = {
top: childPos.top - parentPos.top,
left: childPos.left - parentPos.left
}
This has the benefit of giving you the offset of a child relative to its parent even if the parent isn't positioned.
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
I don't suppose performance matters much here, but I can't resist. The zip() function completely recopies both vectors (more of a matrix transpose, actually) just to get the data in "Pythonic" order. It would be interesting to time the nuts-and-bolts implementation:
import math
def cosine_similarity(v1,v2):
"compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
sumxx, sumxy, sumyy = 0, 0, 0
for i in range(len(v1)):
x = v1[i]; y = v2[i]
sumxx += x*x
sumyy += y*y
sumxy += x*y
return sumxy/math.sqrt(sumxx*sumyy)
v1,v2 = [3, 45, 7, 2], [2, 54, 13, 15]
print(v1, v2, cosine_similarity(v1,v2))
Output: [3, 45, 7, 2] [2, 54, 13, 15] 0.972284251712
That goes through the C-like noise of extracting elements one-at-a-time, but does no bulk array copying and gets everything important done in a single for loop, and uses a single square root.
ETA: Updated print call to be a function. (The original was Python 2.7, not 3.3. The current runs under Python 2.7 with a from __future__ import print_function
statement.) The output is the same, either way.
CPYthon 2.7.3 on 3.0GHz Core 2 Duo:
>>> timeit.timeit("cosine_similarity(v1,v2)",setup="from __main__ import cosine_similarity, v1, v2")
2.4261788514654654
>>> timeit.timeit("cosine_measure(v1,v2)",setup="from __main__ import cosine_measure, v1, v2")
8.794677709375264
So, the unpythonic way is about 3.6 times faster in this case.
According to http://developers.facebook.com/docs/reference/dialogs/oauth/
for me worked
https://apps.facebook.com/YOUR_APP_NAMESPACE (watch fot http:// or https:// issue)
My trick is using an attribute selector. Attributes are easier to set up by javascript.
css
.class{ /*normal css... */}
.class[special]:after{ content: 'what you want'}
javascript
function setSpecial(id){ document.getElementById(id).setAttribute('special', '1'); }
html
<element id='x' onclick="setSpecial(this.id)"> ...
Lazy notes in comments.
#include <stdio.h>
// for malloc
#include <stdlib.h>
// you need the prototype
char *substring(int i,int j,char *ch);
int main(void /* std compliance */)
{
int i=0,j=2;
char s[]="String";
char *test;
// s points to the first char, S
// *s "is" the first char, S
test=substring(i,j,s); // so s only is ok
// if test == NULL, failed, give up
printf("%s",test);
free(test); // you should free it
return 0;
}
char *substring(int i,int j,char *ch)
{
int k=0;
// avoid calc same things several time
int n = j-i+1;
char *ch1;
// you can omit casting - and sizeof(char) := 1
ch1=malloc(n*sizeof(char));
// if (!ch1) error...; return NULL;
// any kind of check missing:
// are i, j ok?
// is n > 0... ch[i] is "inside" the string?...
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return ch1;
}
// Use ..
const Per = {
name: 'HAMZA',
age: 20,
coords: {
tele: '09',
lan: '190'
},
setAge(age: Number): void {
this.age = age;
},
getAge(): Number {
return age;
}
};
const { age, name }: { age: Number; name: String } = Per;
const {
coords: { tele, lan }
}: { coords: { tele: String; lan: String } } = Per;
console.log(Per.getAge());
To formalize some of the approaches laid out above:
Create a function that operates on the rows of your dataframe like so:
def f(row):
if row['A'] == row['B']:
val = 0
elif row['A'] > row['B']:
val = 1
else:
val = -1
return val
Then apply it to your dataframe passing in the axis=1
option:
In [1]: df['C'] = df.apply(f, axis=1)
In [2]: df
Out[2]:
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
Of course, this is not vectorized so performance may not be as good when scaled to a large number of records. Still, I think it is much more readable. Especially coming from a SAS background.
Edit
Here is the vectorized version
df['C'] = np.where(
df['A'] == df['B'], 0, np.where(
df['A'] > df['B'], 1, -1))
You can also use pythonlangutil:
from pythonlangutil.overload import Overload, signature
class A:
@Overload
@signature()
def stackoverflow(self):
print 'first method'
@stackoverflow.overload
@signature("int")
def stackoverflow(self, i):
print 'second method', i
You can use ORDER BY
clause to sort data rows by values in columns. Something like
=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C, D")
If you’d like to order by some columns descending, others ascending, you can add desc
/asc
, ie:
=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C desc, D")
I had the same problem but noticed that it appears only in one view. So I began to look for the differences in the controllers.
I found out that the scrolling behavior is set in - (void)viewWillAppear:(BOOL)animated
of the super instance.
So be sure to implement like this:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// your code
}
And it doesn't matter if you use UIViewController
or UITableViewController
; checked it by putting a UITableView
as a subview of self.view in the UIViewController
. It was the same behavior. The view didn't allow to scroll if the call [super viewWillAppear:animated];
was missing.
UITableView
has a property separatorInset
. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen.
[tableView setSeparatorInset:UIEdgeInsetsZero];
Note: If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:
if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
Layout:
<android.support.v7.widget.AppCompatButton
style="@style/MyButton"
...
/>
styles.xml:
<style name="MyButton" parent="Widget.AppCompat.Button.Colored">
<item name="backgroundTint">@color/button_background_selector</item>
<item name="android:textColor">@color/button_text_selector</item>
</style>
color/button_background_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="#555555"/>
<item android:color="#00ff00"/>
</selector>
color/button_text_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="#888888"/>
<item android:color="#ffffff"/>
</selector>
Here is a technique I use that has worked well:
<div>_x000D_
<div style="display: table-cell; width: 100%"> </div>_x000D_
<div style="display: table-cell; white-space: nowrap;">Something Here</div>_x000D_
</div>
_x000D_
This might be a simple solution to achieve this:
INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
FROM dual
WHERE NOT EXISTS (SELECT 1
FROM funds
WHERE ID = 23
AND date = DATE('2013-02-12'));
p.s. alternatively (if ID
a primary key):
INSERT INTO funds (ID, date, price)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need
see this Fiddle.
No. The compiler can't know what type jerry.callFriend("spike")
would return. Also, your implementation just hides the cast in the method without any additional type safety. Consider this:
jerry.addFriend("quaker", new Duck());
jerry.callFriend("quaker", /* unused */ new Dog()); // dies with illegal cast
In this specific case, creating an abstract talk()
method and overriding it appropriately in the subclasses would serve you much better:
Mouse jerry = new Mouse();
jerry.addFriend("spike", new Dog());
jerry.addFriend("quacker", new Duck());
jerry.callFriend("spike").talk();
jerry.callFriend("quacker").talk();
Regular expressions
It's a write only language, and it's hard to verify if it works correctly for the right inputs.
This would also work:
// callback function
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
// callback executer
function callbackTester (callback) {
callback();
}
// test function
callbackTester (function() {
tryMe("hello", "goodbye");
});
Another Scenario :
// callback function
function tryMe (param1, param2, param3) {
alert (param1 + " and " + param2 + " " + param3);
}
// callback executer
function callbackTester (callback) {
//this is the more obivous scenario as we use callback function
//only when we have some missing value
//get this data from ajax or compute
var extraParam = "this data was missing" ;
//call the callback when we have the data
callback(extraParam);
}
// test function
callbackTester (function(k) {
tryMe("hello", "goodbye", k);
});
For your information you could use grid but with side effects :)
.parent {
display: grid
}
An alternative to System.Diagnostics.StackTrace
is to use System.Environment.StackTrace which returns a string-representation of the stacktrace.
Another useful option is to use the $CALLER
and $CALLSTACK
debugging variables in Visual Studio since this can be enabled run-time without rebuilding the application.
Combination of Mritunjay and Bartu's answers are full answer to this question. I copying the full example.
<input class="form-control" type="email" required="" placeholder="username"
oninvalid="this.setCustomValidity('Please Enter valid email')"
oninput="setCustomValidity('')"></input>
Here,
this.setCustomValidity('Please Enter valid email')" - Display the custom message on invalidated of the field
oninput="setCustomValidity('')" - Remove the invalidate message on validated filed.
If you want to simply access a global variable you just use its name. However to change its value you need to use the global
keyword.
E.g.
global someVar
someVar = 55
This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.
The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.
In order to animate to a specific element inside a scroll container (fixed DIV)
/*
@param Container(DIV) that needs to be scrolled, ID or Div of the anchor element that should be scrolled to
Scrolls to a specific element in the div container
*/
this.scrollTo = function(container, anchor) {
var element = angular.element(anchor);
angular.element(container).animate({scrollTop: element.offset().top}, "slow");
}
you can use env variables to setup username and password for mongo
MONGO_INITDB_ROOT_USERNAME
MONGO_INITDB_ROOT_PASSWORD
using simple docker command
docker run -e MONGO_INITDB_ROOT_USERNAME=my-user MONGO_INITDB_ROOT_PASSWORD=my-password mongo
using docker-compose
version: '3.1'
services:
mongo:
image: mongo
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: my-user
MONGO_INITDB_ROOT_PASSWORD: my-password
and the last option is to manually access the container and set the user and password inside the mongo docker container
docker exec -it mongo-container bash
now you can use mongo shell command to configure everything that you want
Either remove one } from end of responseText;}}
or from the end of the line
Try the os.path.exists
function
if not os.path.exists(dir):
os.mkdir(dir)
$.each(top_brands, function(index, el) {
for (var key in el) {
if (el.hasOwnProperty(key)) {
brand_options.append($("<option />").val(key).text(key+ " " + el[key]));
}
}
});
But if your data structure is var top_brands = {'Adidas': 100, 'Nike': 50};
, then thing will be much more simple.
for (var key in top_brands) {
if (top_brands.hasOwnProperty(key)) {
brand_options.append($("<option />").val(key).text(key+ " " + el[key]));
}
}
Or use the jquery each:
$.each(top_brands, function(key, value) {
brand_options.append($("<option />").val(key).text(key + " " + value));
});
In a Firebird database the AFTER myOtherColumn
does not work but you can try re-positioning the column using:
ALTER TABLE name ALTER column POSITION new_position
I guess it may work in other cases as well.
In Chromium 81+, I have found the answer to be: go to chrome://extensions/, click to enable Developer Mode on the top right corner, then drag and drop your .user.js script.
Here ya go..
List<string> list = new List<string>() { "1", "2", "3" };
List<string> remove = new List<string>() { "2" };
list.ForEach(s =>
{
if (remove.Contains(s))
{
list.Remove(s);
}
});
The computer "name" is resolved from the IP address by the underlying DNS (Domain Name System) library of the OS. There's no universal concept of a computer name across OSes, but DNS is generally available. If the computer name hasn't been configured so DNS can resolve it, it isn't available.
import java.net.InetAddress;
import java.net.UnknownHostException;
String hostname = "Unknown";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
The str.split
method will automatically remove all white space between items:
>>> str1 = "a b c d"
>>> str1.split()
['a', 'b', 'c', 'd']
Docs are here: http://docs.python.org/library/stdtypes.html#str.split
My beautiful non-standard solution
HTML
<div style="background-color:#f5b405"></div>
jQuery
$(this).attr("style").replace("background-color:", "");
Result
#f5b405
I like ndjango. It is very easy to use and very flexible. You can easily extend view functionality with custom tags and filters. I think that "greatly tied to F#" is rather advantage than disadvantage.
I tried these solutions with the select2 version 3.4.8 and found that when you do blur
, the select2 triggers first select2-close
then select2-focus
and then select2-blur
, so at the end we end up reopening forever the select2.
Then, my solution is this one:
$('#elemId').on('select2-focus', function(){
var select2 = $(this).data('select2');
if( $(this).data('select2-closed') ){
$(this).data('select2-closed', false)
return
}
if (!select2.opened()) {
select2.open()
}
}).on('select2-close', function(){
$(this).data('select2-closed', true)
})
df$Gene <- as.factor(df$Gene)
do.call(rbind, lapply(split(df,df$Gene), function(x) {return(x[which.max(x$Value),])}))
Just using base R
In light of apparent dislike for how I've attempted to answer the OP's question. The literal answer is, a promise is something shared w/ other objects, while a deferred should be kept private. Primarily, a deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.
If you're interested in the minutiae, then examine Promises/A+.
So far as I'm aware, the overarching purpose is to improve clarity and loosen coupling through a standardized interface. See suggested reading from @jfriend00:
Rather than directly passing callbacks to functions, something which can lead to tightly coupled interfaces, using promises allows one to separate concerns for code that is synchronous or asynchronous.
Personally, I've found deferred especially useful when dealing with e.g. templates that are populated by asynchronous requests, loading scripts that have networks of dependencies, and providing user feedback to form data in a non-blocking manner.
Indeed, compare the pure callback form of doing something after loading CodeMirror in JS mode asynchronously (apologies, I've not used jQuery in a while):
/* assume getScript has signature like: function (path, callback, context)
and listens to onload && onreadystatechange */
$(function () {
getScript('path/to/CodeMirror', getJSMode);
// onreadystate is not reliable for callback args.
function getJSMode() {
getScript('path/to/CodeMirror/mode/javascript/javascript.js',
ourAwesomeScript);
};
function ourAwesomeScript() {
console.log("CodeMirror is awesome, but I'm too impatient.");
};
});
To the promises formulated version (again, apologies, I'm not up to date on jQuery):
/* Assume getScript returns a promise object */
$(function () {
$.when(
getScript('path/to/CodeMirror'),
getScript('path/to/CodeMirror/mode/javascript/javascript.js')
).then(function () {
console.log("CodeMirror is awesome, but I'm too impatient.");
});
});
Apologies for the semi-pseudo code, but I hope it makes the core idea somewhat clear. Basically, by returning a standardized promise, you can pass the promise around, thus allowing for more clear grouping.
Is this to log the user out after a set time? Setting the session creation time (or an expiry time) when it is registered, and then checking that on each page load could handle that.
E.g.:
$_SESSION['example'] = array('foo' => 'bar', 'registered' => time());
// later
if ((time() - $_SESSION['example']['registered']) > (60 * 30)) {
unset($_SESSION['example']);
}
Edit: I've got a feeling you mean something else though.
You can scrap sessions after a certain lifespan by using the session.gc_maxlifetime
ini setting:
Edit: ini_set('session.gc_maxlifetime', 60*30);
Make sure MySQL binds to 0.0.0.0 and not 127.0.0.1 or it will not be accessible from outside the machine
You can ensure this by editing your my.conf file and looking for the bind-address
item--you want it to look like bind-address = 0.0.0.0
. Then save this and restart mysql:
sudo service mysql restart
If you are doing this on a production server, you want to be aware of the security implications, discussed here: https://serverfault.com/questions/257513/how-bad-is-setting-mysqls-bind-address-to-0-0-0-0
Do not mix CSS/JQuery syntax (#
for identifier) with native JS.
Native JS solution:
document.getElementById("_1234").checked = true;
JQuery solution:
$("#_1234").prop("checked", true);
The other answers are severely outdated. With Android Studio, this is the way to do it:
I personally prefer using char(1) with values 'Y' and 'N' for databases that don't have a native type for boolean. Letters are more user frendly than numbers which assume that those reading it will now that 1 corresponds to true and 0 corresponds to false.
'Y' and 'N' also maps nicely when using (N)Hibernate.
Simply
First Define Path
doskey ~=cd %homepath%
Then Access
~
In case you want to move your local git repository to another upstream you can also do this:
to get the current remote url:
git remote get-url origin
will show something like: https://bitbucket.com/git/myrepo
to set new remote repository:
git remote set-url origin [email protected]:folder/myrepo.git
now push contents of current (develop) branch:
git push --set-upstream origin develop
You now have a full copy of the branch in the new remote.
optionally return to original git-remote for this local folder:
git remote set-url origin https://bitbucket.com/git/myrepo
Gives the benefit you can now get your new git-repository from github in another folder so that you have two local folders both pointing to the different remotes, the previous (bitbucket) and the new one both available.
Remote Procedure Call (RPC) is a inter process communication which allows calling a function in another process residing in local or remote machine.
Remote method invocation (RMI) is an API, which implements RPC in java with support of object oriented paradigms.
You can think of invoking RPC is like calling a C procedure. RPC supports primitive data types where as RMI support method parameters/return types as java objects.
RMI is easy to program unlike RPC. You can think your business logic in terms of objects instead of a sequence of primitive data types.
RPC is language neutral unlike RMI, which is limited to java
RMI is little bit slower to RPC
Have a look at this article for RPC implementation in C
X=foo
Y=X
eval "Z=\$$Y"
sets Z to "foo"
Take care using eval
since this may allow accidential excution of code through values in ${Y}
. This may cause harm through code injection.
For example
Y="\`touch /tmp/eval-is-evil\`"
would create /tmp/eval-is-evil
. This could also be some rm -rf /
, of course.
I really had troubles with those examples from Andy Arismendi and from LPG. You should always use:
$stdout = $p.StandardOutput.ReadToEnd()
before calling
$p.WaitForExit()
A full example is:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "ping.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "localhost"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
$p.WaitForExit()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode
There's no need to use jQuery because this is native JavaScript functionality
element.scrollIntoView()
For updating multiple rows in a single query, you can try this
UPDATE table_name
SET
column_1 = CASE WHEN any_column = value and any_column = value THEN column_1_value end,
column_2 = CASE WHEN any_column = value and any_column = value THEN column_2_value end,
column_3 = CASE WHEN any_column = value and any_column = value THEN column_3_value end,
.
.
.
column_n = CASE WHEN any_column = value and any_column = value THEN column_n_value end
if you don't need additional condition then remove and
part of this query
If self could be nil in the closure use [weak self].
If self will never be nil in the closure use [unowned self].
The Apple Swift documentation has a great section with images explaining the difference between using strong, weak, and unowned in closures:
So here's my solution.
A simple example for a 3x3 Array. You can keep chaining this to go deeper
Array(3).fill().map(a => Array(3))
Or the following function will generate any level deep you like
f = arr => {
let str = 'return ', l = arr.length;
arr.forEach((v, i) => {
str += i < l-1 ? `Array(${v}).fill().map(a => ` : `Array(${v}` + ')'.repeat(l);
});
return Function(str)();
}
f([4,5,6]) // Generates a 4x5x6 Array
http://www.binaryoverdose.com/2017/02/07/Generating-Multidimensional-Arrays-in-JavaScript/
An alternative would be using the Angular pattern validator and matching on any non-whitespace character.
const nonWhitespaceRegExp: RegExp = new RegExp("\\S");
this.formGroup = this.fb.group({
name: [null, [Validators.required, Validators.pattern(nonWhiteSpaceRegExp)]]
});
For opening a URL in the browser through the terminal, CentOS 7 users can use gio open command. For example, if you want to open google.com then gio open https://www.google.com
will open google.com URL in the browser.
xdg-open https://www.google.com
will also work but this tool has been deprecated, Use gio open
instead. I prefer this as this is the easiest way to open a URL using a command from the terminal.
In swift 4 String
conforms to Collection
. Instead of substring
, we should now use a subscript.
So if you want to cut out only the word "play"
from "Hello, playground"
, you could do it like this:
var str = "Hello, playground"
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let result = str[start..<end] // The result is of type Substring
It is interesting to know, that doing so will give you a Substring
instead of a String
. This is fast and efficient as Substring
shares its storage with the original String. However sharing memory this way can also easily lead to memory leaks.
This is why you should copy the result into a new String, once you want to clean up the original String. You can do this using the normal constructor:
let newString = String(result)
You can find more information on the new Substring
class in the [Apple documentation].1
So, if you for example get a Range
as the result of an NSRegularExpression
, you could use the following extension:
extension String {
subscript(_ range: NSRange) -> String {
let start = self.index(self.startIndex, offsetBy: range.lowerBound)
let end = self.index(self.startIndex, offsetBy: range.upperBound)
let subString = self[start..<end]
return String(subString)
}
}
I have found that using backticks to capture command output into a variable, adversly, yeilds one too many ps aux results, e.g. for a single running instance of abc.sh:
ps aux | grep -w "abc.sh" | grep -v grep | wc -l
returns "1". However,
count=`ps aux | grep -w "abc.sh" | grep -v grep | wc -l`
echo $count
returns "2"
Seems like using the backtick construction somehow temporarily creates another process. Could be the reason why the topicstarter could not make this work. Just need to decrement the $count var.
I had this issue ..
A working solution is to change ownership of /usr/local
to current user instead of root
by:
sudo chown -R $(whoami):admin /usr/local
But really this is not a proper way. Mainly if your machine is a server or multiple-user.
My suggestion is to change the ownership as above and do whatever you want to implement with Brew .. ( update, install ... etc ) then reset ownership back to root as:
sudo chown -R root:admin /usr/local
Thats would solve the issue and keep ownership set in proper set.
The answers are working fine with xls format but, in my case, it didn't work for xlsx format. Thus I added some code here. it works both xls and xlsx format.
I took the sample from the official sample link.
Hope it may help !
function fileReader(oEvent) {
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
var reader = new FileReader();
var result = {};
reader.onload = function (e) {
var data = e.target.result;
data = new Uint8Array(data);
var workbook = XLSX.read(data, {type: 'array'});
console.log(workbook);
var result = {};
workbook.SheetNames.forEach(function (sheetName) {
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1});
if (roa.length) result[sheetName] = roa;
});
// see the result, caution: it works after reader event is done.
console.log(result);
};
reader.readAsArrayBuffer(oFile);
}
// Add your id of "File Input"
$('#fileUpload').change(function(ev) {
// Do something
fileReader(ev);
}
My solution:
I was missing config.env
properties because I was developing on a new machine, and of course I keep my config files out of my repo.
If you are using a different machine than usual, make sure that you include any config files that are not present in the repo that gets cloned.
Install LXML parser in python environment.
pip install lxml
Your problem will be resolve. You can also use built-in python package for the same as:
soup = BeautifulSoup(s, "html.parser")
Note: The "HTMLParser" module has been renamed to "html.parser" in Python3
I am not sure did you see this list of MS SQL Modules for Node JS
Share your experience after using one if possible .
Good Luck
grep -rl SOSTITUTETHIS . | xargs sed -Ei 's/(.*)SOSTITUTETHIS(.*)/\1WITHTHIS\2/g'
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
I found the following way works for importing a package from the script's parent directory. In the example, I would like to import functions in env.py
from app.db
package.
.
+-- my_application
+-- alembic
+-- env.py
+-- app
+-- __init__.py
+-- db
import os
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
Simply quote your variable:
[ -e "$VAR" ]
This evaluates to [ -e "" ]
if $VAR
is empty.
Your version does not work because it evaluates to [ -e ]
. Now in this case, bash simply checks if the single argument (-e
) is a non-empty string.
From the manpage:
test and [ evaluate conditional expressions using a set of rules based on the number of arguments. ...
1 argument
The expression is true if and only if the argument is not null.
(Also, this solution has the additional benefit of working with filenames containing spaces)
If you have a space in your solution name, this will also cause the issue. Removing the space from your solution name, so path doesn't contain %20 will solve this.
Use computeDistanceBetween() Google map API method to calculate near marker between your location and markers list on google map.
Steps:-
Create marker on google map.
function addMarker(location) {
var marker = new google.maps.Marker({
title: 'User added marker',
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5
},
position: location,
map: map
});
}
On Mouse click create event for getting lat, long of your location and pass that to find_closest_marker().
function find_closest_marker(event) {
var distances = [];
var closest = -1;
for (i = 0; i < markers.length; i++) {
var d = google.maps.geometry.spherical.computeDistanceBetween(markers[i].position, event.latLng);
distances[i] = d;
if (closest == -1 || d < distances[closest]) {
closest = i;
}
}
alert('Closest marker is: ' + markers[closest].getTitle());
}
visit this link follow the steps. You will able to get nearer marker to your location.
The very first thing you need to do is download extras and tools package from SDK manager and other necessary packages like platform-25 and so on.. , after that open AVD manager and select any emulator you wan't, after that go to "other images" tab and select ARM AEBI a7a System Image and select finish and you are all done hope this would help you.
If you want to do this inline, just cast the NSUInteger
or NSInteger
to an int
:
int i = -1;
NSUInteger row = 100;
i > row // true, since the signed int is implicitly converted to an unsigned int
i > (int)row // false
One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.
SELECT @currentTerm = currentterm,
@termID = termid,
@endDate = enddate
FROM table1
WHERE iscurrent = 1
IF( @@ROWCOUNT <> 1 )
BEGIN
RAISERROR ('Unexpected number of matching rows',
16,
1)
RETURN
END
This issue can be solved using MediaQuery.of(context)
To get Screen width: MediaQuery.of(context).size.width
To get Screen height: MediaQuery.of(context).size.height
For more information about MediaQuery Widget watch, https://www.youtube.com/watch?v=A3WrA4zAaPw
I figured it out through trial and error... the real chink in the armor was a little known setting in IIS in the Configuration Editor
for the website in
Section: system.webServer/security/authentication/windowsAuthentication
From: ApplicationHost.config <locationpath='ServerName/SiteName' />
called useAppPoolCredentials
(which is set to False
by default. Set this to True
and life becomes great again!!! Hope this saves pain for the next guy....
If you make the call from the main thread, you must add the STAThread attribute to the Main method, as stated in the previous answer.
If you use a separate thread, it needs to be in a STA (single-threaded apartment), which is not the case for background worker threads. You have to create the thread yourself, like this:
Thread t = new Thread(ThreadProc);
t.SetApartmentState(ApartmentState.STA);
t.Start();
with ThreadProc being a delegate of type ThreadStart.
I solved the problem by cat'ing all the pems together:
cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD
(keytool didn't know what to do with a PKCS7 formatted key)
I got all the pems from letsencrypt
just use \r\n for endline if you are using windows operating system.
Actually, Laravel 4 does have a table rename function in Illuminate/Database/Schema/Builder.php, it's just undocumented at the moment: Schema::rename($from, $to);
.
You can get a graphical view of the project history with tools like gitk
. Just run:
gitk --all
If you want to checkout a specific branch:
git checkout <branch name>
For a specific commit, use the SHA1 hash instead of the branch name. (See Treeishes in the Git Community Book, which is a good read, to see other options for navigating your tree.)
git log
has a whole set of options to display detailed or summary history too.
I don't know of an easy way to move forward in a commit history. Projects with a linear history are probably not all that common. The idea of a "revision" like you'd have with SVN or CVS doesn't map all that well in Git.
you can use enumerate keeping the ind/index of the elements is in vm, if you make vm
a set you will also have 0(1)
lookups:
vm = {-1, -1, -1, -1}
print([ind if q in vm else 9999 for ind,ele in enumerate(vm) ])
byte [] arr = new byte[100]
Each element has 0 by default.
You could find primitive default values here:
Data Type Default Value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
I recommend, instead, updating the path in the associated script(s) (such as /usr/bin/yum) to point at your previous Python as the interpreter.
Ideally, you want to upgrade yum and its associated scripts so that they are supported by the default Python installed.
If that is not possible, the above is entirely workable and tested.
Change:
#!/usr/bin/python
to whatever the path is of your old version until you can make the above yum improvement.
Cases where you couldn't do the above are if you have an isolated machine, don't have the time to upgrade rpm manually or can't connect temporarily or permanently to a standard yum repository.
Here is a script that automates what the most popular answer suggests ... See https://stackoverflow.com/a/13308579/1497139 for an improved version that supports branches
#!/bin/bash
# reset the current repository
# WF 2012-10-15
# see https://stackoverflow.com/questions/1628088/how-to-reset-my-local-repository-to-be-just-like-the-remote-repository-head
timestamp=`date "+%Y-%m-%d-%H_%M_%S"`
git commit -a -m "auto commit at $timestamp"
if [ $? -eq 0 ]
then
git branch "auto-save-at-$timestamp"
fi
git fetch origin
git reset --hard origin/master
I haven't tested it but apparently you can add quicktime animations to a pdf (no idea why). So the solution would be to export the animated gif to quicktime and add it to the pdf.
Here the solution that apparently works:
See this link (German)
This is what I came here for- a handy scala function that returns string of MD5 hash:
def md5(text: String) : String = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft(""){_ + _}
Declare your progress dialog:
ProgressDialog progress;
When you're ready to start the progress dialog:
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
and to make it go away when you're done:
progress.dismiss();
Here's a little thread example for you:
// Note: declare ProgressDialog progress as a field in your class.
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new Thread(new Runnable() {
@Override
public void run()
{
// do the thing that takes a long time
runOnUiThread(new Runnable() {
@Override
public void run()
{
progress.dismiss();
}
});
}
}).start();
Your regex will match anything that contains a number, you want to use anchors to match the whole string and then match one or more numbers:
regex = new Regex("^[0-9]+$");
The ^
will anchor the beginning of the string, the $
will anchor the end of the string, and the +
will match one or more of what precedes it (a number in this case).
Put it this way
where ("R"."TIME_STAMP">=TO_DATE ('03-02-2013 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
AND "R"."TIME_STAMP"<=TO_DATE ('09-02-2013 23:59:59', 'DD-MM-YYYY HH24:MI:SS'))
Where
R is table name.
TIME_STAMP is FieldName in Table R.
This answer is based on Yann's answer. It will set the aspect ratio for linear or log-log plots. I've used additional information from https://stackoverflow.com/a/16290035/2966723 to test if the axes are log-scale.
def forceAspect(ax,aspect=1):
#aspect is width/height
scale_str = ax.get_yaxis().get_scale()
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
if scale_str=='linear':
asp = abs((xmax-xmin)/(ymax-ymin))/aspect
elif scale_str=='log':
asp = abs((scipy.log(xmax)-scipy.log(xmin))/(scipy.log(ymax)-scipy.log(ymin)))/aspect
ax.set_aspect(asp)
Obviously you can use any version of log
you want, I've used scipy
, but numpy
or math
should be fine.
You say "this is a piece of java code being written", from which I infer that there is still a chance that you could design it a different way.
Having an ArrayList is like having a collection of stuff. Rather than force the instanceof or getClass every time you take an object from the list, why not design the system so that you get the type of the object when you retrieve it from the DB, and store it into a collection of the appropriate type of object?
Or, you could use one of the many data access libraries that exist to do this for you.
Swift:
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)
fetchRequest.includesPropertyValues = false
var error:NSError?
if let results = context.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject] {
for result in results {
context.deleteObject(result)
}
var error:NSError?
if context.save(&error) {
// do something after save
} else if let error = error {
println(error.userInfo)
}
} else if let error = error {
println("error: \(error)")
}
You do not need to use an anonymous function with setTimeout
. You can do something like this:
setTimeout(doSomething, 3000);
function doSomething() {
//do whatever you want here
}
I am using JsonProperty attributes when serializing but ignoring them when deserializing using this ContractResolver
:
public class IgnoreJsonPropertyContractResolver: DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
foreach (var p in properties) { p.PropertyName = p.UnderlyingName; }
return properties;
}
}
The ContractResolver
just sets every property back to the class property name (simplified from Shimmy's solution). Usage:
var airplane= JsonConvert.DeserializeObject<Airplane>(json,
new JsonSerializerSettings { ContractResolver = new IgnoreJsonPropertyContractResolver() });
Click "view details" to find the inner exception.
If you want to call the incremented number directly in a function, this solution works bettter:
Function inc(ByRef data As Integer)
data = data + 1
inc = data
End Function
for example:
Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))
If the function inc()
returns no value, the above line will generate an error.
In latest 5.13 there's a difference. You do like always...
font-family: "Font Awesome 5 Free";
content: "\f107";
But there's a difference now... Instead of use font-weight: 500; You are following this:
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f107";
Why is that? I figure out by finding in in .fas class, so you can figure out an updated way by looking into .fas class so you're doing the same as it has to be. Figure out if there's a font-weight and font-family. Here you go guys. That's an update answer for 5.13.
I created the following procedure
:
if object_id('tool.create_insert', 'P') is null
begin
exec('create procedure tool.create_insert as');
end;
go
alter procedure tool.create_insert(@schema varchar(200) = 'dbo',
@table varchar(200),
@where varchar(max) = null,
@top int = null,
@insert varchar(max) output)
as
begin
declare @insert_fields varchar(max),
@select varchar(max),
@error varchar(500),
@query varchar(max);
declare @values table(description varchar(max));
set nocount on;
-- Get columns
select @insert_fields = isnull(@insert_fields + ', ', '') + c.name,
@select = case type_name(c.system_type_id)
when 'varchar' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + cast(' + c.name + ' as varchar) + '''''''', ''null'')'
when 'datetime' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + convert(varchar, ' + c.name + ', 121) + '''''''', ''null'')'
else isnull(@select + ' + '', '' + ', '') + 'isnull(cast(' + c.name + ' as varchar), ''null'')'
end
from sys.columns c with(nolock)
inner join sys.tables t with(nolock) on t.object_id = c.object_id
inner join sys.schemas s with(nolock) on s.schema_id = t.schema_id
where s.name = @schema
and t.name = @table;
-- If there's no columns...
if @insert_fields is null or @select is null
begin
set @error = 'There''s no ' + @schema + '.' + @table + ' inside the target database.';
raiserror(@error, 16, 1);
return;
end;
set @insert_fields = 'insert into ' + @schema + '.' + @table + '(' + @insert_fields + ')';
if isnull(@where, '') <> '' and charindex('where', ltrim(rtrim(@where))) < 1
begin
set @where = 'where ' + @where;
end
else
begin
set @where = '';
end;
set @query = 'select ' + isnull('top(' + cast(@top as varchar) + ')', '') + @select + ' from ' + @schema + '.' + @table + ' with (nolock) ' + @where;
insert into @values(description)
exec(@query);
set @insert = isnull(@insert + char(10), '') + '--' + upper(@schema + '.' + @table);
select @insert = @insert + char(10) + @insert_fields + char(10) + 'values(' + v.description + ');' + char(10) + 'go' + char(10)
from @values v
where isnull(v.description, '') <> '';
end;
go
Then you can use it that way:
declare @insert varchar(max),
@part varchar(max),
@start int,
@end int;
set @start = 1;
exec tool.create_insert @schema = 'dbo',
@table = 'myTable',
@where = 'Fk_CompanyId = 1',
@insert = @insert output;
-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
set @end = charindex(char(10), @insert);
if @end = 0
begin
set @end = len(@insert) + 1;
end;
print substring(@insert, @start, @end - 1);
set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;
The output would be something like that:
--DBO.MYTABLE
insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(1, 'AMX', 1, 10.00);
go
insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(2, 'ABC', 1, 11.00);
go
insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(3, 'APEX', 1, 12.00);
go
insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(4, 'AMX', 1, 10.00);
go
insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(5, 'ABC', 1, 11.00);
go
insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(6, 'APEX', 1, 12.00);
go
insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(7, 'AMX', 2, 10.00);
go
insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(8, 'ABC', 2, 11.00);
go
insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(9, 'APEX', 2, 12.00);
go
If you just want to get a range of rows, use the @top
parameter as bellow:
declare @insert varchar(max),
@part varchar(max),
@start int,
@end int;
set @start = 1;
exec tool.create_insert @schema = 'dbo',
@table = 'myTable',
@top = 100,
@insert = @insert output;
-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
set @end = charindex(char(10), @insert);
if @end = 0
begin
set @end = len(@insert) + 1;
end;
print substring(@insert, @start, @end - 1);
set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;
This is known as a Zip operation and will be supported in .NET 4.
With that, you would be able to write something like:
var numbers = new [] { 1, 2, 3, 4 };
var words = new [] { "one", "two", "three", "four" };
var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach(var nw in numbersAndWords)
{
Console.WriteLine(nw.Number + nw.Word);
}
As an alternative to the anonymous type with the named fields, you can also save on braces by using a Tuple and its static Tuple.Create helper:
foreach (var nw in numbers.Zip(words, Tuple.Create))
{
Console.WriteLine(nw.Item1 + nw.Item2);
}
If you're using Node, you can try running the serve command directly in the console. In my case I'm running an angular application, so I tried with:
heroku run npm start
This showed me the exact error during the application startup.
There is a method called unbindService that will take a ServiceConnection which you will have created upon calling bindService. This will allow you to disconnect from the service while still leaving it running.
This may pose a problem when you connect to it again, since you probably don't know whether it's running or not when you start the activity again, so you'll have to consider that in your activity code.
Good luck!
This is really simple with droidQuery. For starts, consider this layout:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/v1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View 1" />
</LinearLayout>
<LinearLayout
android:id="@+id/v2"
android:layout_width="wrap_content"
android:layout_height="0dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View 2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View 3" />
</LinearLayout>
</LinearLayout>
We can animate the height to the desired value - say 100dp
- using the following code:
//convert 100dp to pixel value
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
Then use droidQuery
to animate. The simplest way is with this:
$.animate("{ height: " + height + "}", new AnimationOptions());
To make the animation more appealing, consider adding an easing:
$.animate("{ height: " + height + "}", new AnimationOptions().easing($.Easing.BOUNCE));
You can also change the duration on AnimationOptions
using the duration()
method, or handle what happens when the animation ends. For a complex example, try:
$.animate("{ height: " + height + "}", new AnimationOptions().easing($.Easing.BOUNCE)
.duration(1000)
.complete(new Function() {
@Override
public void invoke($ d, Object... args) {
$.toast(context, "finished", Toast.LENGTH_SHORT);
}
}));
This is what worked for me with Android Studio 1.0.2:
File -> Settings-> Gradle Set 'Use default Gradle wrapper.'
The other methods didn't seem to work for me.
I wrote a little class that is doing what you want, you can test it here.
Only thing that is different from your proposal is that I don't consider
[1,[{c: 1},2,3],{a:'hey'}]
and
[{a:'hey'},1,[3,{c: 1},2]]
to be same, because I think that arrays are not equal if order of their elements is not same. Of course this can be changed if needed. Also this code can be further enhanced to take function as argument that will be used to format diff object in arbitrary way based on passed primitive values (now this job is done by "compareValues" method).
var deepDiffMapper = function () {
return {
VALUE_CREATED: 'created',
VALUE_UPDATED: 'updated',
VALUE_DELETED: 'deleted',
VALUE_UNCHANGED: 'unchanged',
map: function(obj1, obj2) {
if (this.isFunction(obj1) || this.isFunction(obj2)) {
throw 'Invalid argument. Function given, object expected.';
}
if (this.isValue(obj1) || this.isValue(obj2)) {
return {
type: this.compareValues(obj1, obj2),
data: obj1 === undefined ? obj2 : obj1
};
}
var diff = {};
for (var key in obj1) {
if (this.isFunction(obj1[key])) {
continue;
}
var value2 = undefined;
if (obj2[key] !== undefined) {
value2 = obj2[key];
}
diff[key] = this.map(obj1[key], value2);
}
for (var key in obj2) {
if (this.isFunction(obj2[key]) || diff[key] !== undefined) {
continue;
}
diff[key] = this.map(undefined, obj2[key]);
}
return diff;
},
compareValues: function (value1, value2) {
if (value1 === value2) {
return this.VALUE_UNCHANGED;
}
if (this.isDate(value1) && this.isDate(value2) && value1.getTime() === value2.getTime()) {
return this.VALUE_UNCHANGED;
}
if (value1 === undefined) {
return this.VALUE_CREATED;
}
if (value2 === undefined) {
return this.VALUE_DELETED;
}
return this.VALUE_UPDATED;
},
isFunction: function (x) {
return Object.prototype.toString.call(x) === '[object Function]';
},
isArray: function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
},
isDate: function (x) {
return Object.prototype.toString.call(x) === '[object Date]';
},
isObject: function (x) {
return Object.prototype.toString.call(x) === '[object Object]';
},
isValue: function (x) {
return !this.isObject(x) && !this.isArray(x);
}
}
}();
var result = deepDiffMapper.map({
a: 'i am unchanged',
b: 'i am deleted',
e: {
a: 1,
b: false,
c: null
},
f: [1, {
a: 'same',
b: [{
a: 'same'
}, {
d: 'delete'
}]
}],
g: new Date('2017.11.25')
}, {
a: 'i am unchanged',
c: 'i am created',
e: {
a: '1',
b: '',
d: 'created'
},
f: [{
a: 'same',
b: [{
a: 'same'
}, {
c: 'create'
}]
}, 1],
g: new Date('2017.11.25')
});
console.log(result);
_x000D_
Spring Boot will automatically find and load application.properties and application.yaml files from the following locations when your application starts:
The list is ordered by precedence (with values from lower items overriding earlier ones).
More info you can find here https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-files
Assuming your table has auto-numbered field "RowID" and you want to select only records where RowID is even or odd.
To show odd:
Select * from MEN where (RowID % 2) = 1
To show even:
Select * from MEN where (RowID % 2) = 0
As of January 2020 and Xcode 11.3.1 -
Xcode will automatically create an Apple Distribution certificate, install it in Keychain Access, and update Xcode's signing information
(Note: the single Apple Distribution certificate is now provided instead of the previous iOS Distribution certificate and equivalents.)
You must create a new anonymous type:
select new { op, pg }
Refer to the official guide.
Yes, you can do this in PHP e.g. in
Silex or Symfony3
using subrequest
$postParams = array(
'email' => $request->get('email'),
'agree_terms' => $request->get('agree_terms'),
);
$subRequest = Request::create('/register', 'POST', $postParams);
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
When I need to restart an activity, I use following code. Though it is not recommended.
Intent intent = getIntent();
finish();
startActivity(intent);
you can use the below to list files by size du -h | sort -hr | more or du -h --max-depth=0 * | sort -hr | more
I fixed this by adding ChangeDetectionStrategy from angular core.
import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'page1',
templateUrl: 'page1.html',
})
The following worked for me on Excel for Mac 2011 and Windows Excel 2002:
Using iconv on Mac, convert the file to UTF-16 Little-Endian + name it *.txt (the .txt extension forces Excel to run the Text Import Wizard):
iconv -f UTF-8 -t UTF-16LE filename.csv >filename_UTF-16LE.csv.txt
Open the file in Excel and in the Text Import Wizard choose:
PS The UTF-16LE created by iconv has BOM bytes FF FE in the beginning.
PPS My original csv file was created on a Windows 7 computer, in UTF-8 format (with the BOM bytes EF BB BF in the beginning) and used CRLF line breaks. Comma was used as field delimiter and single quote as text qualifier. It contained ASCII letters plus different latin letters with tildes, umlaut etc, plus some cyrillic. All displayed properly in both Excel for Win and Mac.
PPPS Exact software versions:
* Mac OS X 10.6.8
* Excel for Mac 2011 v.14.1.3
* Windows Server 2003 SP2
* Windows Excel 2002 v.10.2701.2625
Random URL and filename string safe (1 liner)
Crypto.randomBytes(48).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
The probelm with your first code block was that you were opening the file as 'r' even though you wanted to write to it using 'w'
with open('/Users/your/path/foo','w') as data:
data.write(str(dictionary))
You'll want to check HTML5 Differences from HTML4: W3C Working Group Note 9 December 2014 for the complete differences. There are many new elements and element attributes. Some elements were removed and others have different semantic value than before.
There are also APIs defined, such as the use of canvas, to help build the next generation of web apps and make sure implementations are standardized.
Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:
"temp" environment variable setting - then it would be:
%temp%\Temporary ASP.NET Files
Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:
c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files
There are also cases where the temp folder can be set via config for a machine or site specific using this:
<compilation tempDirectory="d:\MyTempPlace" />
I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.
Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.
There is no need to invoke the exec
method! You can use "match" method directly on the string. Just don't forget the parentheses.
var str = "This is cool";
var matches = str.match(/(This is)( cool)$/);
console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...
Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!
Install libboost-all-dev by entering the following commands in the terminal
Step 1
Update package repositories and get latest package information.
sudo apt update -y
Step 2
Install the packages and dependencies with -y flag .
sudo apt install -y libboost-all-dev
Now that you have your libboost-all-dev installed source: https://linuxtutorial.me/ubuntu/focal/libboost-all-dev/
Use HttpUrlConnection by calling openConnection()
on your URL object.
getResponseCode() will give you the HTTP response once you've read from the connection.
e.g.
URL u = new URL("http://www.example.com/");
HttpURLConnection huc = (HttpURLConnection)u.openConnection();
huc.setRequestMethod("GET");
huc.connect() ;
OutputStream os = huc.getOutputStream();
int code = huc.getResponseCode();
(not tested)
Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.
DateTime#minusMonths
method would help you get previous month.
DateTime month = new DateTime().minusMonths (1);
The answer given by @allen is reasonably generic but can lack in performance for larger dataframes:
Reduce does a lot better:
from functools import reduce
import pandas as pd
# make data
df = pd.DataFrame(index=range(1_000_000))
df['1'] = 'CO'
df['2'] = 'BOB'
df['3'] = '01'
df['4'] = 'BILL'
def reduce_join(df, columns):
assert len(columns) > 1
slist = [df[x].astype(str) for x in columns]
return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])
def apply_join(df, columns):
assert len(columns) > 1
return df[columns].apply(lambda row:'_'.join(row.values.astype(str)), axis=1)
# ensure outputs are equal
df1 = reduce_join(df, list('1234'))
df2 = apply_join(df, list('1234'))
assert df1.equals(df2)
# profile
%timeit df1 = reduce_join(df, list('1234')) # 733 ms
%timeit df2 = apply_join(df, list('1234')) # 8.84 s
SYSDATE
, systimestamp
return datetime of server where database is installed. SYSDATE
- returns only date, i.e., "yyyy-mm-dd". systimestamp
returns date with time and zone, i.e., "yyyy-mm-dd hh:mm:ss:ms timezone"now()
returns datetime at the time statement execution, i.e., "yyyy-mm-dd hh:mm:ss"CURRENT_DATE
- "yyyy-mm-dd", CURRENT_TIME
- "hh:mm:ss", CURRENT_TIMESTAMP
- "yyyy-mm-dd hh:mm:ss timezone". These are related to a record insertion time.I was experiencing a similar problem running (and trying to debug) two different Django applications on the same machine.
I was running them with these commands:
./manage.py runserver 8000
./manage.py runserver 8001
When I did login in the first one and then in the second one I always got logged out the first one and viceversa.
I added this on my /etc/hosts
127.0.0.1 app1
127.0.0.1 app2
Then I started the two apps with these commands:
./manage.py runserver app1:8000
./manage.py runserver app2:8001
Problem solved :)
Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (@name) and a corresponding access method to read it. Also creates a method called name= to set the attribute.
module Mod
attr_accessor(:one, :two)
end
Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
TLDR; The formula is n(n-1)/2
where n
is the number of items in the set.
To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA)
, you can calculate the summation of 1 + 2 + ... + (n-1)
where n
is the number of items in the set.
The reasoning is as follows, say you have 4 items:
A
B
C
D
The number of items that can be paired with A
is 3, or n-1
:
AB
AC
AD
It follows that the number of items that can be paired with B
is n-2
(because B
has already been paired with A
):
BC
BD
and so on...
(n-1) + (n-2) + ... + (n-(n-1))
which is the same as
1 + 2 + ... + (n-1)
or
n(n-1)/2