static double Evaluate(string expression) {
var loDataTable = new DataTable();
var loDataColumn = new DataColumn("Eval", typeof (double), expression);
loDataTable.Columns.Add(loDataColumn);
loDataTable.Rows.Add(0);
return (double) (loDataTable.Rows[0]["Eval"]);
}
Explanation of how it works:
First, we make a table in the part var loDataTable = new DataTable();
, just like in a Data Base Engine (MS SQL for example).
Then, a column, with some specific parameters (var loDataColumn = new DataColumn("Eval", typeof (double), expression);
).
The "Eval"
parameter is the name of the column (ColumnName attribute).
typeof (double)
is the type of data to be stored in the column, which is equal to put System.Type.GetType("System.Double");
instead.
expression
is the string that the Evaluate
method receives, and is stored in the attribute Expression
of the column. This attribute is for a really specific purpose (obvious), which is that every row that's put on the column will be fullfilled with the "Expression", and it accepts practically wathever can be put in a SQL Query. Refer to http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression(v=vs.100).aspx to know what can be put in the Expression attribute, and how it's evaluated.
Then, loDataTable.Columns.Add(loDataColumn);
adds the column loDataColumn
to the loDataTable
table.
Then, a row is added to the table with a personalized column with a Expression attribute, done via loDataTable.Rows.Add(0);
. When we add this row, the cell of the column "Eval" of the table loDataTable
is fullfilled automatically with its "Expression" attribute, and, if it has operators and SQL Queries, etc, it's evaluated and then stored to the cell, so, here happens the "magic", the string with operators is evaluated and stored to a cell...
Finally, just return the value stored to the cell of the column "Eval" in row 0 (it's an index, starts counting from zero), and making a conversion to a double with return (double) (loDataTable.Rows[0]["Eval"]);
.
And that's all... job done!
And here a code eaiser to understand, which does the same... It's not inside a method, and it's explained too.
DataTable MyTable = new DataTable();
DataColumn MyColumn = new DataColumn();
MyColumn.ColumnName = "MyColumn";
MyColumn.Expression = "5+5/5"
MyColumn.DataType = typeof(double);
MyTable.Columns.Add(MyColumn);
DataRow MyRow = MyTable.NewRow();
MyTable.Rows.Add(MyRow);
return (double)(MyTable.Rows[0]["MyColumn"]);
First, create the table with DataTable MyTable = new DataTable();
Then, a column with DataColumn MyColumn = new DataColumn();
Next, we put a name to the column. This so we can search into it's contents when it's stored to the table. Done via MyColumn.ColumnName = "MyColumn";
Then, the Expression, here we can put a variable of type string, in this case there's a predefined string "5+5/5", which result is 6.
The type of data to be stored to the column MyColumn.DataType = typeof(double);
Add the column to the table... MyTable.Columns.Add(MyColumn);
Make a row to be inserted to the table, which copies the table structure DataRow MyRow = MyTable.NewRow();
Add the row to the table with MyTable.Rows.Add(MyRow);
And return the value of the cell in row 0 of the column MyColumn
of the table MyTable
with return (double)(MyTable.Rows[0]["MyColumn"]);
Lesson done!!!
I prefer the VBA-solution for professional solutions.
With the replace-procedure part in the question search and replace WHOLE WORDS ONLY, I use the following VBA-procedure:
''
' Evaluate Formula-Text in Excel
'
Function wm_Eval(myFormula As String, ParamArray variablesAndValues() As Variant) As Variant
Dim i As Long
'
' replace strings by values
'
For i = LBound(variablesAndValues) To UBound(variablesAndValues) Step 2
myFormula = RegExpReplaceWord(myFormula, variablesAndValues(i), variablesAndValues(i + 1))
Next
'
' internationalisation
'
myFormula = Replace(myFormula, Application.ThousandsSeparator, "")
myFormula = Replace(myFormula, Application.DecimalSeparator, ".")
myFormula = Replace(myFormula, Application.International(xlListSeparator), ",")
'
' return value
'
wm_Eval = Application.Evaluate(myFormula)
End Function
''
' Replace Whole Word
'
' Purpose : replace [strFind] with [strReplace] in [strSource]
' Comment : [strFind] can be plain text or a regexp pattern;
' all occurences of [strFind] are replaced
Public Function RegExpReplaceWord(ByVal strSource As String, _
ByVal strFind As String, _
ByVal strReplace As String) As String
' early binding requires reference to Microsoft VBScript
' Regular Expressions:
' with late binding, no reference needed:
Dim re As Object
Set re = CreateObject("VBScript.RegExp")
re.Global = True
're.IgnoreCase = True ' <-- case insensitve
re.Pattern = "\b" & strFind & "\b"
RegExpReplaceWord = re.Replace(strSource, strReplace)
Set re = Nothing
End Function
Usage of the procedure in an excel sheet looks like:
Although the tricky solution @tbaxter120 advised is good but I use this function and work like a charm, pString is a delimited string and pDelimiter is a delimiter character:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[DelimitedSplit]
--===== Define I/O parameters
(@pString NVARCHAR(MAX), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover VARCHAR(8000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL -- does away with 0 base CTE, and the OR condition in one go!
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
---ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,50000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(@pString, l.N1, l.L1)
FROM cteLen l
;
Then for example you can call it in where clause as below:
WHERE [fieldname] IN (SELECT LTRIM(RTRIM(Item)) FROM [dbo].[DelimitedSplit]('2,5,11', ','))
Hope this help.
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
You can use Javascript.
For example, using jQuery:
$(':text').val('1000');
However, this won't be any different from using the value
attribute.
Thanks a bundle, guys. You are great.
I used Chuff's answer and modified it a little to do what I wanted.
I have 2 worksheets in the same workbook.
On 1st worksheet I have a list of SMS in 3 columns: phone number, date & time, message
Then I inserted a new blank column next to the phone number
On worksheet 2 I have two columns: phone number, name of person
Used the formula to check the cell on the left, and match against the range in worksheet 2, pick the name corresponding to the number and input it into the blank cell in worksheet 1.
Then just copy the formula down the whole column until last sms It worked beautifully.
=VLOOKUP(A3,Sheet2!$A$1:$B$31,2,0)
First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:
global $db;
And I guess, when you wrote:
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
what you really wanted was:
if ($result->num_rows==1) { return true; } else { return false; }
You could have a pseudo dynamic array where the size is set by the user at runtime, but then is fixed after that.
int size;
cin >> size;
int dynamicArray[size];
First let's create the dataframe you had, I'll ignore columns B and C as they are not relevant.
df = pd.DataFrame({'A': [0, 4, 5, 6, 7, 7, 6,5]})
And the mapping that you desire:
mapping = dict(enumerate([2,5,6,8,12,16,26,32]))
df['D'] = df['A'].map(mapping)
Done!
print df
Output:
A D
0 0 2
1 4 12
2 5 16
3 6 26
4 7 32
5 7 32
6 6 26
7 5 16
Surprised to see no mention of setTimeout.
To run a function without arguments:
var functionWithoutArguments = function(){
console.log("Executing functionWithoutArguments");
}
setTimeout("functionWithoutArguments()", 0);
To run function with arguments:
var functionWithArguments = function(arg1, arg2) {
console.log("Executing functionWithArguments", arg1, arg2);
}
setTimeout("functionWithArguments(10, 20)");
To run deeply namespaced function:
var _very = {
_deeply: {
_defined: {
_function: function(num1, num2) {
console.log("Execution _very _deeply _defined _function : ", num1, num2);
}
}
}
}
setTimeout("_very._deeply._defined._function(40,50)", 0);
Since R version 2.12, there's a droplevels()
function.
levels(droplevels(subdf$letters))
May not be the most pythonic, but
>>> b = {}
>>> for i in range(0, len(a), 2):
b[a[i]] = a[i+1]
I have the same problem as @KTCheek in that I need it to execute sequentially. However I figured I would try using IAsyncEnumerable (introduced in .NET Core 3) and await foreach (introduced in C# 8). Here's what I have come up with:
public static class IEnumerableExtensions {
public static async IAsyncEnumerable<TResult> SelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector) {
foreach (var item in source) {
yield return await selector(item);
}
}
}
public static class IAsyncEnumerableExtensions {
public static async Task<List<TSource>> ToListAsync<TSource>(this IAsyncEnumerable<TSource> source) {
var list = new List<TSource>();
await foreach (var item in source) {
list.Add(item);
}
return list;
}
}
This can be consumed by saying:
var inputs = await events.SelectAsync(ev => ProcessEventAsync(ev)).ToListAsync();
Update: Alternatively you can add a reference to "System.Linq.Async" and then you can say:
var inputs = await events
.ToAsyncEnumerable()
.SelectAwait(async ev => await ProcessEventAsync(ev))
.ToListAsync();
I run into this problem on a regular basis and often use the "add a method" solution. However, there are definitely cases where "add a method" or "compute it in the view" don't work (or don't work well). E.g. when you are caching template fragments and need some non-trivial DB computation to produce it. You don't want to do the DB work unless you need to, but you won't know if you need to until you are deep in the template logic.
Some other possible solutions:
Use the {% expr <expression> as <var_name> %} template tag found at http://www.djangosnippets.org/snippets/9/ The expression is any legal Python expression with your template's Context as your local scope.
Change your template processor. Jinja2 (http://jinja.pocoo.org/2/) has syntax that is almost identical to the Django template language, but with full Python power available. It's also faster. You can do this wholesale, or you might limit its use to templates that you are working on, but use Django's "safer" templates for designer-maintained pages.
Removing Space-:
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GestureDetector(
child: new Text('Don\'t have an account?',
style: new TextStyle(color: Color(0xFF2E3233))),
onTap: () {},
),
GestureDetector(
onTap: (){},
child: new Text(
'Register.',
style: new TextStyle(
color: Color(0xFF84A2AF), fontWeight: FontWeight.bold),
))
],
),
OR
GestureDetector(
onTap: (){},
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text('Don\'t have an account?',
style: new TextStyle(color: Color(0xFF2E3233))),
new Text(
'Register.',
style: new TextStyle(
color: Color(0xFF84A2AF), fontWeight: FontWeight.bold),
)
],
),
),
You can use the reload
method of the $route
service. Inject $route
in your controller and then create a method reloadRoute
on your $scope
.
$scope.reloadRoute = function() {
$route.reload();
}
Then you can use it on the link like this:
<a ng-click="reloadRoute()" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
This method will cause the current route to reload. If you however want to perform a full refresh, you could inject $window
and use that:
$scope.reloadRoute = function() {
$window.location.reload();
}
Later edit (ui-router):
As mentioned by JamesEddyEdwards and Dunc in their answers, if you are using angular-ui/ui-router you can use the following method to reload the current state / route. Just inject $state
instead of $route
and then you have:
$scope.reloadRoute = function() {
$state.reload();
};
In Python3 iteritems()
is no longer supported
Use .items
for field, possible_values in fields.items():
print(field, possible_values)
I am not clearly about it but typically one server has one database (with many users), if you create many databases mean that you create many instances, listeners, ... as well. So you can check your LISTENER
to identify it.
In my testing I created 2 databases (dbtest
and dbtest_1
) so when I check my LISTENER status it appeared like this:
lsnrctl status
....
STATUS of the LISTENER
.....
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.10.20.20)(PORT=1521)))
Services Summary...
Service "dbtest" has 1 instance(s).
Instance "dbtest", status READY, has 1 handler(s) for this service...
Service "dbtest1XDB" has 1 instance(s).
Instance "dbtest1", status READY, has 1 handler(s) for this service...
Service "dbtest_1" has 1 instance(s).
Instance "dbtest1", status READY, has 1 handler(s) for this service... The command completed successfully
Angular Typescript example using a pipe.
math.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'math',
})
export class MathPipe implements PipeTransform {
transform(value: number, args: any = null):any {
if(value) {
return Math[args](value);
}
return 0;
}
}
Add to @NgModule declarations
@NgModule({
declarations: [
MathPipe,
then use in your template like so:
{{(100*count/total) | math:'round'}}
Or just use Control.SuspendLayout()
and Control.ResumeLayout()
.
Please use Like below.
<a style="cursor: pointer" **(click)="yourFunctionComponent()"** >
<i class="fa fa-dribbble fa-4x"></i>
</a>
The above can be used so that the fa icon will be shown and also on the click function you could write your logic.
There's no for each in
in the version of ECMAScript supported by Node.js, only supported by firefox currently.
The important thing to note is that JavaScript versions are only relevant to Gecko (Firefox's engine) and Rhino (which is always a few versions behind). Node uses V8 which follows ECMAScript specifications
There are a couple of ways to append an array in JavaScript:
1) The push()
method adds one or more elements to the end of an array and returns the new length of the array.
var a = [1, 2, 3];
a.push(4, 5);
console.log(a);
Output:
[1, 2, 3, 4, 5]
2) The unshift()
method adds one or more elements to the beginning of an array and returns the new length of the array:
var a = [1, 2, 3];
a.unshift(4, 5);
console.log(a);
Output:
[4, 5, 1, 2, 3]
3) The concat()
method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var arr1 = ["a", "b", "c"];
var arr2 = ["d", "e", "f"];
var arr3 = arr1.concat(arr2);
console.log(arr3);
Output:
[ "a", "b", "c", "d", "e", "f" ]
4) You can use the array's .length
property to add an element to the end of the array:
var ar = ['one', 'two', 'three'];
ar[ar.length] = 'four';
console.log( ar );
Output:
["one", "two", "three", "four"]
5) The splice()
method changes the content of an array by removing existing elements and/or adding new elements:
var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(4, 0, "nemo");
//array.splice(start, deleteCount, item1, item2, ...)
console.log(myFish);
Output:
["angel", "clown", "mandarin", "surgeon","nemo"]
6) You can also add a new element to an array simply by specifying a new index and assigning a value:
var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar
console.log(ar);
Output:
["one", "two","three","four"]
You can do it with animate function in jQuery.
$({ countNum: $('.code').html() }).animate({ countNum: 4000 }, {
duration: 8000,
easing: 'linear',
step: function () {
$('.yourelement').html(Math.floor(this.countNum));
},
complete: function () {
$('.code').html(this.countNum);
//alert('finished');
}
});
I also had this problem, and none of the solutions in this thread worked for me. As it turns out, the problem was that I had this line in ~/.bash_profile
:
alias php="/usr/local/php/bin/php"
And, as it turns out, /usr/local/php
was just a symlink to /usr/local/Cellar/php54/5.4.24/
. So when I invoked php -i
I was still invoking php54. I just deleted this line from my bash profile, and then php worked.
For some reason, even though php55 was now running, the php.ini
file from php54 was still loaded, and I received this warning every time I invoked php:
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/Cellar/php54/5.4.38/lib/php/extensions/no-debug-non-zts-20100525/memcached.so' - dlopen(/usr/local/Cellar/php54/5.4.38/lib/php/extensions/no-debug-non-zts-20100525/memcached.so, 9): image not found in Unknown on line 0
To fix this, I just added the following line to my bash profile:
export PHPRC=/usr/local/etc/php/5.5/php.ini
And then everything worked as normal!
You're probably looking for the Convert.ChangeType
method. For example:
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
For those who need to 'run as root' remotely through a script logging into a user account in the sudoers file, I found an evil horrible hack, that is no doubt very insecure:
sshpass -p 'userpass' ssh -T -p port user@server << EOSSH
sudo -S su - << RROOT
userpass
echo ""
echo "*** Got Root ***"
echo ""
#[root commands go here]
useradd -m newuser
echo "newuser:newpass" | chpasswd
RROOT
EOSSH
Just check JSON option from the drop down next to binary; when you click raw. This should do
select * from yourtable where created < now() and created > '2011-04-25 04:00:00'
Here are a couple dplyr
options that keep non-duplicate rows based on columns id and id2:
library(dplyr)
df %>% distinct(id, id2, .keep_all = TRUE)
df %>% group_by(id, id2) %>% filter(row_number() == 1)
df %>% group_by(id, id2) %>% slice(1)
If you can go the functional way, the following is pretty clear
new_list = [x] + your_list
Of course you haven't inserted x
into your_list
, rather you have created a new list with x
preprended to it.
You can create an iterator in Python 3.x or a list in Python 2.x by using:
filter(r.match, list)
To convert the Python 3.x iterator to a list, simply cast it; list(filter(..))
.
Not sure if this help, but you can edit without extracting:
Check the blog post for more details http://vinurip.blogspot.com/2015/04/how-to-edit-contents-of-jar-file-on-mac.html
Operations with a Python list operate on the list. list1 and list2
will check if list1
is empty, and return list1
if it is, and list2
if it isn't. list1 + list2
will append list2
to list1
, so you get a new list with len(list1) + len(list2)
elements.
Operators that only make sense when applied element-wise, such as &
, raise a TypeError
, as element-wise operations aren't supported without looping through the elements.
Numpy arrays support element-wise operations. array1 & array2
will calculate the bitwise or for each corresponding element in array1
and array2
. array1 + array2
will calculate the sum for each corresponding element in array1
and array2
.
This does not work for and
and or
.
array1 and array2
is essentially a short-hand for the following code:
if bool(array1):
return array2
else:
return array1
For this you need a good definition of bool(array1)
. For global operations like used on Python lists, the definition is that bool(list) == True
if list
is not empty, and False
if it is empty. For numpy's element-wise operations, there is some disambiguity whether to check if any element evaluates to True
, or all elements evaluate to True
. Because both are arguably correct, numpy doesn't guess and raises a ValueError
when bool()
is (indirectly) called on an array.
If you code in Android, there is SparseArray, mapping integer to object.
Python 2.7.9 auto promotes numbers. For a case where one is unsure to use int() or long().
>>> a = int("123")
>>> type(a)
<type 'int'>
>>> a = int("111111111111111111111111111111111111111111111111111")
>>> type(a)
<type 'long'>
Because they do not use the SQL import wizard, the steps would be as follows:
Right click on the database in the option tasks to import data,
Once the wizard is open, we select the type of data to be implied. In this case it would be the
Flat file source
We select the CSV file, you can configure the data type of the tables in the CSV, but it is best to bring it from the CSV.
SQL client
Depending on our type of authentication we select it, once this is done, a very important option comes.
Enable id insert
(usually not starting from 1), instead if we have a column with the id in the CSV we select the enable id insert, the next step is to end the wizard, we can review the changes here.
On the other hand, in the following window may come alerts, or warnings the ideal is to ignore this, only if they leave error is necessary to pay attention.
Depending on your needs, here are a couple of ways:
IF EXISTS (SELECT * FROM TABLE WHERE COLUMN = 'SOME VALUE')
--INSERT SOMETHING
ELSE
--INSERT SOMETHING ELSE
Or a bit longer
DECLARE @retVal int
SELECT @retVal = COUNT(*)
FROM TABLE
WHERE COLUMN = 'Some Value'
IF (@retVal > 0)
BEGIN
--INSERT SOMETHING
END
ELSE
BEGIN
--INSERT SOMETHING ELSE
END
you can try
position: relative;
bottom: 20px;
but I don't see a problem on my browser (Google Chrome)
For an example if you want to have a loop that stopped when it has counted all of the people in a group. We will consider the value X to be equal to the number of the people in the group, and the counter will be used to count all of the people in the group. To write the
while(!condition)
the code will be:
int x = people;
int counter = 0;
while(x != counter)
{
counter++;
}
return 0;
You can use the -quit
option of find
:
find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit
Public Function LastData(rCol As Range) As Range
Set LastData = rCol.Find("*", rCol.Cells(1), , , , xlPrevious)
End Function
Usage: ?lastdata(activecell.EntireColumn).Address
$(this).unbind('mouseenter').unbind('mouseleave')
or more succinctly (thanks @Chad Grant):
$(this).unbind('mouseenter mouseleave')
All the answers were missing Ctrl-J (which enables and disables autocomplete).
Here is another way:
static void
unhandled_interrupt(struct trap_frame *frame, int irq, void *arg)
{
//this code intentionally left blank
}
static struct irqtbl_s vector_tbl[XCHAL_NUM_INTERRUPTS] = {
[0 ... XCHAL_NUM_INTERRUPTS-1] {unhandled_interrupt, NULL},
};
See:
Designated inits
Then ask the question: When can one use C extensions?
The code sample above is in an embedded system and will never see the light from another compiler.
From GC Performance Tuning training documents of Oracle:
-Xmn[size]: Size of young generation heap space.
Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.
In short, it sets the NewSize and MaxNewSize values of New generation to the same value.
You have to check every ID in tableA against every ID in tableB. A fully featured RDBMS (such as Oracle) would be able to optimize that into an INDEX FULL FAST SCAN and not touch the table at all. I don't know whether H2's optimizer is as smart as that.
H2 does support the MINUS syntax so you should try this
select id from tableA
minus
select id from tableB
order by id desc
That may perform faster; it is certainly worth benchmarking.
Here is the solution total html with php and database connections
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>database connections</title>
</head>
<body>
<?php
$username = "database-username";
$password = "database-password";
$host = "localhost";
$connector = mysql_connect($host,$username,$password)
or die("Unable to connect");
echo "Connections are made successfully::";
$selected = mysql_select_db("test_db", $connector)
or die("Unable to connect");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM table_one ");
?>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<thead>
<tr>
<th>Employee_id</th>
<th>Employee_Name</th>
<th>Employee_dob</th>
<th>Employee_Adress</th>
<th>Employee_dept</th>
<td>Employee_salary</td>
</tr>
</thead>
<tbody>
<?php
while( $row = mysql_fetch_assoc( $result ) ){
echo
"<tr>
<td>{$row\['employee_id'\]}</td>
<td>{$row\['employee_name'\]}</td>
<td>{$row\['employee_dob'\]}</td>
<td>{$row\['employee_addr'\]}</td>
<td>{$row\['employee_dept'\]}</td>
<td>{$row\['employee_sal'\]}</td>
</tr>\n";
}
?>
</tbody>
</table>
<?php mysql_close($connector); ?>
</body>
</html>
I have created a method that helps with getting the stackTrace:
private static String getStackTrace(Exception ex) {
StringBuffer sb = new StringBuffer(500);
StackTraceElement[] st = ex.getStackTrace();
sb.append(ex.getClass().getName() + ": " + ex.getMessage() + "\n");
for (int i = 0; i < st.length; i++) {
sb.append("\t at " + st[i].toString() + "\n");
}
return sb.toString();
}
To stop the Media Player without the risk of an Illegal State Exception, you must do
try {
mp.reset();
mp.prepare();
mp.stop();
mp.release();
mp=null;
}
catch (Exception e)
{
e.printStackTrace();
}
rather than just
try {
mp.stop();
mp.release();
mp=null;
}
catch (Exception e)
{
e.printStackTrace();
}
As stated in the other answers use event.preventDefault() to prevent form submitting.
To check the form before I wrote a little jQuery function you may use (note that the element needs an ID!)
(function( $ ){
$.fn.isValid = function() {
return document.getElementById(this[0].id).checkValidity();
};
})( jQuery );
example usage
$('#submitBtn').click( function(e){
if ($('#registerForm').isValid()){
// do the request
} else {
e.preventDefault();
}
});
From the HTML 4 spec...
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
EDIT: d'oh! Beaten to the button, again!
len(df[df["Lastname"]=="Smith"].values)
why not both to be sure?
if(opener.document){
$("#testdiv",opener.document).doStuff();
}else{
$("#testdiv",window.opener).doStuff();
}
In case of plotting time series, the command ts.plot
requires a different argument than xaxt="n"
require(graphics)
ts.plot(ldeaths, mdeaths, xlab="year", ylab="deaths", lty=c(1:2), gpars=list(xaxt="n"))
axis(1, at = seq(1974, 1980, by = 2))
On old paper-printer terminals, advancing to the next line involved two actions: moving the print head back to the beginning of the horizontal scan range (carriage return) and advancing the roll of paper being printed on (line feed).
Since we no longer use paper-printer terminals, those actions aren't really relevant anymore, but the characters used to signal them have stuck around in various incarnations.
I think my solution to this might be the simplest. On my development machine, I added a fake domain in my hosts file similar to http://myfakedomain.notarealtld and set it to 127.0.0.1. Then I changed my server's CORS configuration (in my case an S3 bucket) to allow that domain. That way I can use Chrome on localhost and it works great.
Make sure your CORS configuration takes into account the entire hostname with port, ie. http://myfakedomain.notarealtld:3000
You can modify your hosts file easily on Linux, Mac, and Windows.
Just copy your /opt/lampp/etc/my.cnf
file to /etc/mysql/my.cnf
.
And in the terminal type:
mysql -u root
You will be getting the mysql>
prompt:
mysql> Update mysql.user set Password=PASSWORD('your_password') where user='root';
mysql> FLUSH PRIVILEGES;
In short there's no way to recover the passphrase for a pair of SSH keys. Why? Because it was intended this way in the first place for security reasons. The answers the other people gave you are all correct ways to CHANGE the password of your keys, not to recover them. So if you've forgotten your passphrase, the best you can do is create a new pair of SSH keys. Here's how to generate SSH keys and add it to your GitHub account.
Several solutions are discussed in http://blog.xelnor.net/python-mocking-datetime/. In summary:
Mock object - Simple and efficient but breaks isinstance() checks:
target = datetime.datetime(2009, 1, 1)
with mock.patch.object(datetime, 'datetime', mock.Mock(wraps=datetime.datetime)) as patched:
patched.now.return_value = target
print(datetime.datetime.now())
Mock class
import datetime
import mock
real_datetime_class = datetime.datetime
def mock_datetime_now(target, dt):
class DatetimeSubclassMeta(type):
@classmethod
def __instancecheck__(mcs, obj):
return isinstance(obj, real_datetime_class)
class BaseMockedDatetime(real_datetime_class):
@classmethod
def now(cls, tz=None):
return target.replace(tzinfo=tz)
@classmethod
def utcnow(cls):
return target
# Python2 & Python3 compatible metaclass
MockedDatetime = DatetimeSubclassMeta('datetime', (BaseMockedDatetime,), {})
return mock.patch.object(dt, 'datetime', MockedDatetime)
Use as:
with mock_datetime_now(target, datetime):
....
Try using tag body to remove all margin and padding like that you want.
<body style="margin: 0;padding: 0">
<table border="1" width="100%" cellpadding="0" cellspacing="0" bgcolor=green>
<tr>
<td > </td>
<td> </td>
</tr>
<tr>
<td > </td>
<td> </td>
</tr>
<tr>
<td > </td>
<td> </td>
</tr>
</table>
</body>
To complement the preexisting, helpful answers with guidance of when to use which approach and a performance comparison.
Outside of a pipeline[1], use (PSv3+): $objects.Name
as demonstrated in rageandqq's answer, which is both syntactically simpler and much faster.
Accessing a property at the collection level to get its members' values as an array is called member enumeration and is a PSv3+ feature.
Alternatively, in PSv2, use the foreach
statement, whose output you can also assign directly to a variable:
$results = foreach ($obj in $objects) { $obj.Name }
If collecting all output from a (pipeline) command in memory first is feasible, you can also combine pipelines with member enumeration; e.g.:
(Get-ChildItem -File | Where-Object Length -lt 1gb).Name
Tradeoffs:
(Get-ChildItem).Name
), that command must first run to completion before the resulting array's elements can be accessed.In a pipeline, in case you must pass the results to another command, notably if the original input doesn't fit into memory as a whole, use: $objects | Select-Object -ExpandProperty Name
-ExpandProperty
is explained in Scott Saad's answer (you need it to get only the property value).For small input collections (arrays), you probably won't notice the difference, and, especially on the command line, sometimes being able to type the command easily is more important.
Here is an easy-to-type alternative, which, however is the slowest approach; it uses simplified ForEach-Object
syntax called an operation statement (again, PSv3+):
; e.g., the following PSv3+ solution is easy to append to an existing command:
$objects | % Name # short for: $objects | ForEach-Object -Process { $_.Name }
The PSv4+ .ForEach()
array method, more comprehensively discussed in this article, is yet another, well-performing alternative, but note that it requires collecting all input in memory first, just like member enumeration:
# By property name (string):
$objects.ForEach('Name')
# By script block (more flexibility; like ForEach-Object)
$objects.ForEach({ $_.Name })
This approach is similar to member enumeration, with the same tradeoffs, except that pipeline logic is not applied; it is marginally slower than member enumeration, though still noticeably faster than the pipeline.
For extracting a single property value by name (string argument), this solution is on par with member enumeration (though the latter is syntactically simpler).
The script-block variant ({ ... }
) allows arbitrary transformations; it is a faster - all-in-memory-at-once - alternative to the pipeline-based ForEach-Object
cmdlet (%
).
Note: The .ForEach()
array method, like its .Where()
sibling (the in-memory equivalent of Where-Object
), always returns a collection (an instance of [System.Collections.ObjectModel.Collection[psobject]]
), even if only one output object is produced.
By contrast, member enumeration, Select-Object
, ForEach-Object
and Where-Object
return a single output object as-is, without wrapping it in a collection (array).
Here are sample timings for the various approaches, based on an input collection of 10,000
objects, averaged across 10 runs; the absolute numbers aren't important and vary based on many factors, but it should give you a sense of relative performance (the timings come from a single-core Windows 10 VM:
Important
The relative performance varies based on whether the input objects are instances of regular .NET Types (e.g., as output by Get-ChildItem
) or [pscustomobject]
instances (e.g., as output by Convert-FromCsv
).
The reason is that [pscustomobject]
properties are dynamically managed by PowerShell, and it can access them more quickly than the regular properties of a (statically defined) regular .NET type. Both scenarios are covered below.
The tests use already-in-memory-in-full collections as input, so as to focus on the pure property extraction performance. With a streaming cmdlet / function call as the input, performance differences will generally be much less pronounced, as the time spent inside that call may account for the majority of the time spent.
For brevity, alias %
is used for the ForEach-Object
cmdlet.
General conclusions, applicable to both regular .NET type and [pscustomobject]
input:
The member-enumeration ($collection.Name
) and foreach ($obj in $collection)
solutions are by far the fastest, by a factor of 10 or more faster than the fastest pipeline-based solution.
Surprisingly, % Name
performs much worse than % { $_.Name }
- see this GitHub issue.
PowerShell Core consistently outperforms Windows Powershell here.
Timings with regular .NET types:
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.005
1.06 foreach($o in $objects) { $o.Name } 0.005
6.25 $objects.ForEach('Name') 0.028
10.22 $objects.ForEach({ $_.Name }) 0.046
17.52 $objects | % { $_.Name } 0.079
30.97 $objects | Select-Object -ExpandProperty Name 0.140
32.76 $objects | % Name 0.148
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.012
1.32 foreach($o in $objects) { $o.Name } 0.015
9.07 $objects.ForEach({ $_.Name }) 0.105
10.30 $objects.ForEach('Name') 0.119
12.70 $objects | % { $_.Name } 0.147
27.04 $objects | % Name 0.312
29.70 $objects | Select-Object -ExpandProperty Name 0.343
Conclusions:
.ForEach('Name')
clearly outperforms .ForEach({ $_.Name })
. In Windows PowerShell, curiously, the latter is faster, albeit only marginally so.Timings with [pscustomobject]
instances:
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.006
1.11 foreach($o in $objects) { $o.Name } 0.007
1.52 $objects.ForEach('Name') 0.009
6.11 $objects.ForEach({ $_.Name }) 0.038
9.47 $objects | Select-Object -ExpandProperty Name 0.058
10.29 $objects | % { $_.Name } 0.063
29.77 $objects | % Name 0.184
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.008
1.14 foreach($o in $objects) { $o.Name } 0.009
1.76 $objects.ForEach('Name') 0.015
10.36 $objects | Select-Object -ExpandProperty Name 0.085
11.18 $objects.ForEach({ $_.Name }) 0.092
16.79 $objects | % { $_.Name } 0.138
61.14 $objects | % Name 0.503
Conclusions:
Note how with [pscustomobject]
input .ForEach('Name')
by far outperforms the script-block based variant, .ForEach({ $_.Name })
.
Similarly, [pscustomobject]
input makes the pipeline-based Select-Object -ExpandProperty Name
faster, in Windows PowerShell virtually on par with .ForEach({ $_.Name })
, but in PowerShell Core still about 50% slower.
In short: With the odd exception of % Name
, with [pscustomobject]
the string-based methods of referencing the properties outperform the scriptblock-based ones.
Source code for the tests:
Note:
Download function Time-Command
from this Gist to run these tests.
Assuming you have looked at the linked code to ensure that it is safe (which I can personally assure you of, but you should always check), you can install it directly as follows:
irm https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27/raw/Time-Command.ps1 | iex
Set $useCustomObjectInput
to $true
to measure with [pscustomobject]
instances instead.
$count = 1e4 # max. input object count == 10,000
$runs = 10 # number of runs to average
# Note: Using [pscustomobject] instances rather than instances of
# regular .NET types changes the performance characteristics.
# Set this to $true to test with [pscustomobject] instances below.
$useCustomObjectInput = $false
# Create sample input objects.
if ($useCustomObjectInput) {
# Use [pscustomobject] instances.
$objects = 1..$count | % { [pscustomobject] @{ Name = "$foobar_$_"; Other1 = 1; Other2 = 2; Other3 = 3; Other4 = 4 } }
} else {
# Use instances of a regular .NET type.
# Note: The actual count of files and folders in your file-system
# may be less than $count
$objects = Get-ChildItem / -Recurse -ErrorAction Ignore | Select-Object -First $count
}
Write-Host "Comparing property-value extraction methods with $($objects.Count) input objects, averaged over $runs runs..."
# An array of script blocks with the various approaches.
$approaches = { $objects | Select-Object -ExpandProperty Name },
{ $objects | % Name },
{ $objects | % { $_.Name } },
{ $objects.ForEach('Name') },
{ $objects.ForEach({ $_.Name }) },
{ $objects.Name },
{ foreach($o in $objects) { $o.Name } }
# Time the approaches and sort them by execution time (fastest first):
Time-Command $approaches -Count $runs | Select Factor, Command, Secs*
[1] Technically, even a command without |
, the pipeline operator, uses a pipeline behind the scenes, but for the purpose of this discussion using the pipeline refers only to commands that do use |
and therefore involve multiple commands connected by a pipeline.
Try something like:
import pylab as p
p.plot(x,y)
p.axis('equal')
p.show()
Just another quick alternative that worked like a charm for me, using regex:
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
If username/password contains any special characters then inside the camel configuration use RAW for Configuring the values like
RAW(se+re?t&23)
where se+re?t&23
is actual password
RAW({abc.ftp.password})
where {abc.ftp.password}
values comes from a spring property file.
By using RAW, solved my issue.
You can make a setter method in the fragment. Then in the Activity, when you reference to the fragment, you call the setter method and pass it the data from you Activity
We can compare data from two tables of DB2 tables using the below simple query,
Step 1:- Select which all columns we need to compare from table (T1) of schema(S)
SELECT T1.col1,T1.col3,T1.col5 from S.T1
Step 2:- Use 'Minus' keyword for comparing 2 tables.
Step 3:- Select which all columns we need to compare from table (T2) of schema(S)
SELECT T2.col1,T2.col3,T2.col5 from S.T1
END result:
SELECT T1.col1,T1.col3,T1.col5 from S.T1
MINUS
SELECT T2.col1,T2.col3,T2.col5 from S.T1;
If the query returns no rows then the data is exactly the same.
Box Sizing
set the box sizing to border box box-sizing: border-box;
and set the width to 100% and a fixed width for the border then add a min-width so for a small screen the border won't overtake the whole screen
now Application-Level Rate Limiting 200 calls per hour !
Recently I also need to do this for one of my project so did a well research and got a result from Google's Developer community which states this in a simple manner:
For ArrayBuffer to String
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
// Here Uint16 can be different like Uinit8/Uint32 depending upon your buffer value type.
For String to ArrayBuffer
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
//Same here also for the Uint16Array.
For more in detail reference you can refer this blog by Google.
Try the following:
<c:set var="count" value="0" scope="page" />
//in your loops
<c:set var="count" value="${count + 1}" scope="page"/>
Let's consider a system where each user is linked to one or more roles and each role is linked to one or more access privileges. This information can be cached for better API performance. But then, there may be changes in the user and role configurations (for e.g. new access may be granted or current access may be revoked) and these should be reflected in the cache.
We can use access and refresh tokens for such purpose. When an API is invoked with access token, the resource server checks the cache for access rights. IF there is any new access grants, it is not reflected immediately. Once the access token expires (say in 30 minutes) and the client uses the refresh token to generate a new access token, the cache can be updated with the updated user access right information from the DB.
In other words, we can move the expensive operations from every API call using access tokens to the event of access token generation using refresh token.
Just to add, in case anyone else comes across this issue.
On a Mac I had to logout and log back in.
docker logout
docker login
Then it prompts for username (NOTE: Not email) and password. (Need an account on https://hub.docker.com to pull images down)
Then it worked for me.
Make sure you commit .pfx
files to repository.
I just found *.pfx
in my default .gitignore
.
Comment it (by #
) and commit changes. Then pull repository and rebuild.
Here is the command I used and put it in a batch file to remove everything:
echo "Removing containers :" && if [ -n "$(docker container ls -aq)" ]; then docker container stop $(docker container ls -aq); docker container rm $(docker container ls -aq); fi; echo "Removing images :" && if [ -n "$(docker images -aq)" ]; then docker rmi -f $(docker images -aq); fi; echo "Removing volumes :" && if [ -n "$(docker volume ls -q)" ]; then docker volume rm $(docker volume ls -q); fi; echo "Removing networks :" && if [ -n "$(docker network ls | awk '{print $1" "$2}' | grep -v 'ID|bridge|host|none' | awk '{print $1}')" ]; then docker network rm $(docker network ls | awk '{print $1" "$2}' | grep -v 'ID|bridge|host|none' | awk '{print $1}'); fi;
A nice code for the push_back and emplace_back is shown here.
http://en.cppreference.com/w/cpp/container/vector/emplace_back
You can see the move operation on push_back and not on emplace_back.
Although this is an old thread I want to share my solution and hopefully get some feedback on this. Be warned that I only tested this solution with my local database in some JUnit testcase. So this is not a productive feature so far.
I solved that issue for my by introducing a custom annotation called Sequence with no property. It's just a marker for fields that should be assigned a value from an incremented sequence.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Sequence
{
}
Using this annotation i marked my entities.
public class Area extends BaseEntity implements ClientAware, IssuerAware
{
@Column(name = "areaNumber", updatable = false)
@Sequence
private Integer areaNumber;
....
}
To keep things database independent I introduced an entity called SequenceNumber which holds the sequence current value and the increment size. I chose the className as unique key so each entity class wil get its own sequence.
@Entity
@Table(name = "SequenceNumber", uniqueConstraints = { @UniqueConstraint(columnNames = { "className" }) })
public class SequenceNumber
{
@Id
@Column(name = "className", updatable = false)
private String className;
@Column(name = "nextValue")
private Integer nextValue = 1;
@Column(name = "incrementValue")
private Integer incrementValue = 10;
... some getters and setters ....
}
The last step and the most difficult is a PreInsertListener that handles the sequence number assignment. Note that I used spring as bean container.
@Component
public class SequenceListener implements PreInsertEventListener
{
private static final long serialVersionUID = 7946581162328559098L;
private final static Logger log = Logger.getLogger(SequenceListener.class);
@Autowired
private SessionFactoryImplementor sessionFactoryImpl;
private final Map<String, CacheEntry> cache = new HashMap<>();
@PostConstruct
public void selfRegister()
{
// As you might expect, an EventListenerRegistry is the place with which event listeners are registered
// It is a service so we look it up using the service registry
final EventListenerRegistry eventListenerRegistry = sessionFactoryImpl.getServiceRegistry().getService(EventListenerRegistry.class);
// add the listener to the end of the listener chain
eventListenerRegistry.appendListeners(EventType.PRE_INSERT, this);
}
@Override
public boolean onPreInsert(PreInsertEvent p_event)
{
updateSequenceValue(p_event.getEntity(), p_event.getState(), p_event.getPersister().getPropertyNames());
return false;
}
private void updateSequenceValue(Object p_entity, Object[] p_state, String[] p_propertyNames)
{
try
{
List<Field> fields = ReflectUtil.getFields(p_entity.getClass(), null, Sequence.class);
if (!fields.isEmpty())
{
if (log.isDebugEnabled())
{
log.debug("Intercepted custom sequence entity.");
}
for (Field field : fields)
{
Integer value = getSequenceNumber(p_entity.getClass().getName());
field.setAccessible(true);
field.set(p_entity, value);
setPropertyState(p_state, p_propertyNames, field.getName(), value);
if (log.isDebugEnabled())
{
LogMF.debug(log, "Set {0} property to {1}.", new Object[] { field, value });
}
}
}
}
catch (Exception e)
{
log.error("Failed to set sequence property.", e);
}
}
private Integer getSequenceNumber(String p_className)
{
synchronized (cache)
{
CacheEntry current = cache.get(p_className);
// not in cache yet => load from database
if ((current == null) || current.isEmpty())
{
boolean insert = false;
StatelessSession session = sessionFactoryImpl.openStatelessSession();
session.beginTransaction();
SequenceNumber sequenceNumber = (SequenceNumber) session.get(SequenceNumber.class, p_className);
// not in database yet => create new sequence
if (sequenceNumber == null)
{
sequenceNumber = new SequenceNumber();
sequenceNumber.setClassName(p_className);
insert = true;
}
current = new CacheEntry(sequenceNumber.getNextValue() + sequenceNumber.getIncrementValue(), sequenceNumber.getNextValue());
cache.put(p_className, current);
sequenceNumber.setNextValue(sequenceNumber.getNextValue() + sequenceNumber.getIncrementValue());
if (insert)
{
session.insert(sequenceNumber);
}
else
{
session.update(sequenceNumber);
}
session.getTransaction().commit();
session.close();
}
return current.next();
}
}
private void setPropertyState(Object[] propertyStates, String[] propertyNames, String propertyName, Object propertyState)
{
for (int i = 0; i < propertyNames.length; i++)
{
if (propertyName.equals(propertyNames[i]))
{
propertyStates[i] = propertyState;
return;
}
}
}
private static class CacheEntry
{
private int current;
private final int limit;
public CacheEntry(final int p_limit, final int p_current)
{
current = p_current;
limit = p_limit;
}
public Integer next()
{
return current++;
}
public boolean isEmpty()
{
return current >= limit;
}
}
}
As you can see from the above code the listener used one SequenceNumber instance per entity class and reserves a couple of sequence numbers defined by the incrementValue of the SequenceNumber entity. If it runs out of sequence numbers it loads the SequenceNumber entity for the target class and reserves incrementValue values for the next calls. This way I do not need to query the database each time a sequence value is needed. Note the StatelessSession that is being opened for reserving the next set of sequence numbers. You cannot use the same session the target entity is currently persisted since this would lead to a ConcurrentModificationException in the EntityPersister.
Hope this helps someone.
Here is how I would do it using vanilla JS
<form id="myform" method="POST" action="xxx">
<!-- your stuff here -->
<a href="javascript:void()" onclick="document.getElementById('myform').submit();>Ponies await!</a>
</form>
You can play with the return false
s and href="#"
vs void and whatever you need to but this method worked for me in Chrome 18, IE 9 and Firefox 14 and the rest depends on your javascript mostly.
Note also that vertical-align:top;
is often necessary for correct table cell appearance.
Use MaxBy
from the morelinq project:
items.MaxBy(i => i.ID);
You might try searching the internet for ".htaccess Options not allowed here".
A suggestion I found (using google) is:
Check to make sure that your httpd.conf file has AllowOverride All.
A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):
# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html
# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
</IfModule>
# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.
I know it is an old topic, but If your SQL server
version is higher than 2012.
There is another simple option can choose, FORMAT function.
SELECT FORMAT(GetDate(),'yyyyMM')
If you want to use it when you chain methods, you can use assign:
df = (
df.assign(col = lambda x: x['col'].astype('Int64'))
)
There are two uses for RAISE_APPLICATION_ERROR. The first is to replace generic Oracle exception messages with our own, more meaningful messages. The second is to create exception conditions of our own, when Oracle would not throw them.
The following procedure illustrates both usages. It enforces a business rule that new employees cannot be hired in the future. It also overrides two Oracle exceptions. One is DUP_VAL_ON_INDEX, which is thrown by a unique key on EMP(ENAME)
. The other is a a user-defined exception thrown when the foreign key between EMP(MGR)
and EMP(EMPNO)
is violated (because a manager must be an existing employee).
create or replace procedure new_emp
( p_name in emp.ename%type
, p_sal in emp.sal%type
, p_job in emp.job%type
, p_dept in emp.deptno%type
, p_mgr in emp.mgr%type
, p_hired in emp.hiredate%type := sysdate )
is
invalid_manager exception;
PRAGMA EXCEPTION_INIT(invalid_manager, -2291);
dummy varchar2(1);
begin
-- check hiredate is valid
if trunc(p_hired) > trunc(sysdate)
then
raise_application_error
(-20000
, 'NEW_EMP::hiredate cannot be in the future');
end if;
insert into emp
( ename
, sal
, job
, deptno
, mgr
, hiredate )
values
( p_name
, p_sal
, p_job
, p_dept
, p_mgr
, trunc(p_hired) );
exception
when dup_val_on_index then
raise_application_error
(-20001
, 'NEW_EMP::employee called '||p_name||' already exists'
, true);
when invalid_manager then
raise_application_error
(-20002
, 'NEW_EMP::'||p_mgr ||' is not a valid manager');
end;
/
How it looks:
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1); END;
*
ERROR at line 1:
ORA-20000: NEW_EMP::hiredate cannot be in the future
ORA-06512: at "APC.NEW_EMP", line 16
ORA-06512: at line 1
SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate); END;
*
ERROR at line 1:
ORA-20002: NEW_EMP::8888 is not a valid manager
ORA-06512: at "APC.NEW_EMP", line 42
ORA-06512: at line 1
SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)
PL/SQL procedure successfully completed.
SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate); END;
*
ERROR at line 1:
ORA-20001: NEW_EMP::employee called DUGGAN already exists
ORA-06512: at "APC.NEW_EMP", line 37
ORA-00001: unique constraint (APC.EMP_UK) violated
ORA-06512: at line 1
Note the different output from the two calls to RAISE_APPLICATION_ERROR in the EXCEPTIONS block. Setting the optional third argument to TRUE means RAISE_APPLICATION_ERROR includes the triggering exception in the stack, which can be useful for diagnosis.
There is more useful information in the PL/SQL User's Guide.
you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image
if not installed ARM EABI v7a System Image, you should install all.
Boost Preprocessor actually has this as of Boost 1.49, as BOOST_PP_VARIADIC_SIZE(...)
. It works up to size 64.
Under the hood, it's basically the same as Kornel Kisielewicz's answer.
The above examples aren't simply written for Swift 3.0+
Update - Swift 3.0+ - Convert Date To String
let date = Date() // insert your date data here
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" // add custom format if you'd like
var dateString = dateFormatter.string(from: date)
Use
$(document).on("click", "#btn_a", function(){
alert ('button clicked');
});
to add the listener for the dynamically created button.
alert($("#btn_a").val());
will give you the value of the button
For my first post/comment: We all know that 'touchstart' is triggered before click. We also know that when user open your page he or she will: 1) move the mouse 2) click 3) touch the screen (for scrolling, or ... :) )
Let's try something :
//--> Start: jQuery
var hasTouchCapabilities = 'ontouchstart' in window && (navigator.maxTouchPoints || navigator.msMaxTouchPoints);
var isTouchDevice = hasTouchCapabilities ? 'maybe':'nope';
//attach a once called event handler to window
$(window).one('touchstart mousemove click',function(e){
if ( isTouchDevice === 'maybe' && e.type === 'touchstart' )
isTouchDevice = 'yes';
});
//<-- End: jQuery
Have a nice day!
another simple way to pass object using a bundle:
ExtJS has a ComboBox control that can do this (and a whole host of other cool stuff!!)
EDIT: Browse all controls etc, here: http://www.sencha.com/products/js/
You can do this:
@Override
protected Dialog onCreateDialog(int id) {
String messageDialog;
String valueOK;
String valueCancel;
String titleDialog;
switch (id) {
case id:
titleDialog = itemTitle;
messageDialog = itemDescription
valueOK = "OK";
return new AlertDialog.Builder(HomeView.this).setTitle(titleDialog).setPositiveButton(valueOK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.d(this.getClass().getName(), "AlertItem");
}
}).setMessage(messageDialog).create();
and then call to
showDialog(numbreOfItem);
Try this:
Grid grid = new Grid(); //Define the grid
for (int i = 0; i < 36; i++) //Add 36 rows
{
ColumnDefinition columna = new ColumnDefinition()
{
Name = "Col_" + i,
Width = new GridLength(32.5),
};
grid.ColumnDefinitions.Add(columna);
}
for (int i = 0; i < 36; i++) //Add 36 columns
{
RowDefinition row = new RowDefinition();
row.Height = new GridLength(40, GridUnitType.Pixel);
grid.RowDefinitions.Add(row);
}
for (int i = 0; i < 36; i++)
{
for (int j = 0; j < 36; j++)
{
Label t1 = new Label()
{
FontSize = 10,
FontFamily = new FontFamily("consolas"),
FontWeight = FontWeights.SemiBold,
BorderBrush = Brushes.LightGray,
BorderThickness = new Thickness(2),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
};
Grid.SetRow(t1, i);
Grid.SetColumn(t1, j);
grid.Children.Add(t1); //Add the Label Control to the Grid created
}
}
Simple solution:
/\s{2,}/
This matches all occurrences of one or more whitespace characters. If you need to match the entire line, but only if it contains two or more consecutive whitespace characters:
/^.*\s{2,}.*$/
If the whitespaces don't need to be consecutive:
/^(.*\s.*){2,}$/
A Kotlin Extension to observe on the global layout and perform a given task when height is ready dynamically.
Usage:
view.height { Log.i("Info", "Here is your height:" + it) }
Implementation:
fun <T : View> T.height(function: (Int) -> Unit) {
if (height == 0)
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
function(height)
}
})
else function(height)
}
I use this as a daily scheduled task to hide users disabled in AD from the Global Address List
$mailboxes = get-user | where {$_.UserAccountControl -like '*AccountDisabled*' -and $_.RecipientType -eq 'UserMailbox' } | get-mailbox | where {$_.HiddenFromAddressListsEnabled -eq $false}
foreach ($mailbox in $mailboxes) { Set-Mailbox -HiddenFromAddressListsEnabled $true -Identity $mailbox }
One more idea.
Although this is not a universal solution - it is simple and works, at least for me :)
For one placeholder {0}:
create function dbo.Format1
(
@String nvarchar(4000),
@Param0 sql_variant
)
returns nvarchar(4000)
as
begin
declare @Null nvarchar(4) = N'NULL';
return replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));
end
For two placeholders {0} and {1}:
create function dbo.Format2
(
@String nvarchar(4000),
@Param0 sql_variant,
@Param1 sql_variant
)
returns nvarchar(4000)
as
begin
declare @Null nvarchar(4) = N'NULL';
set @String = replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));
return replace(@String, N'{1}', cast(isnull(@Param1, @Null) as nvarchar(4000)));
end
For three placeholders {0}, {1} and {2}:
create function dbo.Format3
(
@String nvarchar(4000),
@Param0 sql_variant,
@Param1 sql_variant,
@Param2 sql_variant
)
returns nvarchar(4000)
as
begin
declare @Null nvarchar(4) = N'NULL';
set @String = replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));
set @String = replace(@String, N'{1}', cast(isnull(@Param1, @Null) as nvarchar(4000)));
return replace(@String, N'{2}', cast(isnull(@Param2, @Null) as nvarchar(4000)));
end
and so on...
Such an approach allows us to use these functions in SELECT statement and with parameters of nvarchar, number, bit and datetime datatypes.
For example:
declare @Param0 nvarchar(10) = N'IPSUM' ,
@Param1 int = 1234567 ,
@Param2 datetime2(0) = getdate();
select dbo.Format3(N'Lorem {0} dolor, {1} elit at {2}', @Param0, @Param1, @Param2);
@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.
Try this:
rdd = df.rdd.map(tuple)
or
rdd = df.rdd.map(list)
I used to have this following line in the csproj file:
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
After deleting this file, it works fine.
You can easily do this using _.pick:
var model = {
fname: null,
lname: null
};
var credentials = {
fname: 'abc',
lname: 'xyz',
age: 2
};
var result = _.pick(credentials, _.keys(model));
console.log('result =', result);
_x000D_
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
_x000D_
But you can simply use pure JavaScript (specially if you use ECMAScript 6), like this:
const model = {
fname: null,
lname: null
};
const credentials = {
fname: 'abc',
lname: 'xyz',
age: 2
};
const newModel = {};
Object.keys(model).forEach(key => newModel[key] = credentials[key]);
console.log('newModel =', newModel);
_x000D_
Pretty sure you can't do that, as it violates the purpose of uniques.
However, this person seems to have a decent work around: http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html
Attach an event handler to the submit event of the form. Make sure it cancels the default action.
Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.
Here is how you would do it in YUI 3:
<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
YUI().use('event', function (Y) {
Y.one('form').on('submit', function (e) {
// Whatever else you want to do goes here
e.preventDefault();
});
});
</script>
Make sure that the server will pick up the slack if the JavaScript fails for any reason.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetRight="-2dp">
<shape android:shape="rectangle">
<corners
android:bottomLeftRadius="4dp"
android:bottomRightRadius="0dp"
android:topLeftRadius="4dp"
android:topRightRadius="0dp" />
<stroke
android:width="1dp"
android:color="@color/nasty_green" />
<solid android:color="@android:color/transparent" />
</shape>
</inset>
.parent { text-align: center; }
.parent > .child { margin: 0 auto; width: 900px; }
The main()
method is the entry point for a Java application. run()
is typically used for new threads or tasks.
Where have you been writing a run()
method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?
you can also use flask_api for sending response
from flask_api import status
@app.route('/your-api/')
def empty_view(self):
content = {'your content here'}
return content, status.HTTP_201_CREATED
you can find reference here http://www.flaskapi.org/api-guide/status-codes/
When using propedit make sure not have any trailing spaces as that will cause the file to be excluded from the ignore list.
These are inserted automatically if you've use tab-autocomplete on linux to create the file to begin with:
svn propset svn:ignore 'file1
file2' .
To use the environment virtualenv has created, you first need to source env/bin/activate
. After that, just install packages using pip install package-name
.
you can achive it with group join
var result = (from c in Customers
join oi in OrderItems on c.Id equals oi.Order.Customer.Id into g
Select new { customer = c, orderItems = g});
c is Customer and g is the customers order items.
For .NET DLLs you can use ildasm
You can tell a form that an external component from outside the <form>
tag belongs to it by adding the form="yourFormName"
to the definition of the component.
In this case,
<form id="login-form">
... blah...
</form>
<button type="submit" form="login-form" name="login_user" class="login-form-btn">
<B>Autentificate</B>
</button>
... would still submit the form happily because you assigned the form name to it. The form thinks the button is part of it, even if the button is outside the tag, and this requires NO javascript to submit the form (which can be buggy i.e. form may submit but bootstrap errors / validations my fail to show, I tested).
Take a look in .git/config and make the changes you need.
Alternatively you could use
git remote rm [name of the url you sets on adding]
and
git remote add [name] [URL]
Or just
git remote set-url [URL]
Before you do anything wrong, double check with
git help remote
When installing Python 3.4 the "Add python.exe to Path" came up unselected. Re-installed with this selected and problem resolved.
When in a window, go to GO ---> ENTER LOCATION... And then copy paste this: /opt/lampp/htdocs
Now you are at the htdocs folder. Then you can add your files there, or in a new folder inside this one (for example "myproyects" folder and inside it your files... and then from a navigator you access it by writting: localhost/myproyects/nameofthefile.php
What I did to find it easily everytime, was right click on "myproyects" folder and "Make link..."... then I moved this link I created to the Desktop and then I didn't have to go anymore to the htdocs, but just enter the folder I created in my Desktop.
Hope it helps!!
Angular 1.1.5 added support for ternary operators:
{{myVar === "two" ? "it's true" : "it's false"}}
To remove an item from a text file, first move all the text to a list and remove whichever item you want. Then write the text stored in the list into a text file:
List<string> quotelist=File.ReadAllLines(filename).ToList();
string firstItem= quotelist[0];
quotelist.RemoveAt(0);
File.WriteAllLines(filename, quotelist.ToArray());
return firstItem;
Semaphore can also be used as a ... semaphore. For example if you have multiple process enqueuing data to a queue, and only one task consuming data from the queue. If you don't want your consuming task to constantly poll the queue for available data, you can use semaphore.
Here the semaphore is not used as an exclusion mechanism, but as a signaling mechanism. The consuming task is waiting on the semaphore The producing task are posting on the semaphore.
This way the consuming task is running when and only when there is data to be dequeued
I was able to resolve the problem by manually creating the following registry key:
HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs
byte[] bytes = { 1,2,3,4 };
string stringByte= BitConverter.ToString(bytes);
Console.WriteLine(stringByte);
// Get unique value for table 'add_new_videos' column name 'project_id'
$project_id = DB::table('add_new_videos')->distinct()->get(['project_id']);
I know that it is very late to answer the question, but it may help someone like me who spent lots off time to fetch data using hql
So the thing is you just have to write a query
Query query = session.createQuery("from Employee");
it will give you all the data list but to fetch data from this you have to write this line.
List<Employee> fetchedData = query.list();
As simple as it looks.
String ss = "Pawan kavita kiyansh Patidar Patidar";
StringBuilder ress = new StringBuilder();
Map<Character, Integer> fre = ss.chars().boxed()
.collect(Collectors.toMap(k->Character.valueOf((char) k.intValue()),k->1,Integer::sum));
//fre.forEach((k, v) -> System.out.println((k + ":" + v)));
fre.entrySet().forEach(e ->{
//System.out.println(e.getKey() + ":" + e.getValue());
//ress.append(String.valueOf(e.getKey())+e.getValue());
});
fre.forEach((k,v)->{
//System.out.println("Item : " + k + " Count : " + v);
ress.append(String.valueOf(k)+String.valueOf(v));
});
System.out.println(ress.toString());
Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.
If you need style names which should appear according to the state condition, I prefer to use this construction:
<div className={'wrapper searchDiv' + (this.state.something === "a" ? " anotherClass" : "")'}>
You can't do it with "anonymous" type parameters (ie, wildcards that use ?
), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.
import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
T t;
}
Microsoft: "Corrupted process state exceptions are exceptions that indicate that the state of a process has been corrupted. We do not recommend executing your application in this state.....If you are absolutely sure that you want to maintain your handling of these exceptions, you must apply the HandleProcessCorruptedStateExceptionsAttribute
attribute"
Microsoft: "Use application domains to isolate tasks that might bring down a process."
The program below will protect your main application/thread from unrecoverable failures without risks associated with use of HandleProcessCorruptedStateExceptions
and <legacyCorruptedStateExceptionsPolicy>
public class BoundaryLessExecHelper : MarshalByRefObject
{
public void DoSomething(MethodParams parms, Action action)
{
if (action != null)
action();
parms.BeenThere = true; // example of return value
}
}
public struct MethodParams
{
public bool BeenThere { get; set; }
}
class Program
{
static void InvokeCse()
{
IntPtr ptr = new IntPtr(123);
System.Runtime.InteropServices.Marshal.StructureToPtr(123, ptr, true);
}
private static void ExecInThisDomain()
{
try
{
var o = new BoundaryLessExecHelper();
var p = new MethodParams() { BeenThere = false };
Console.WriteLine("Before call");
o.DoSomething(p, CausesAccessViolation);
Console.WriteLine("After call. param been there? : " + p.BeenThere.ToString()); //never stops here
}
catch (Exception exc)
{
Console.WriteLine($"CSE: {exc.ToString()}");
}
Console.ReadLine();
}
private static void ExecInAnotherDomain()
{
AppDomain dom = null;
try
{
dom = AppDomain.CreateDomain("newDomain");
var p = new MethodParams() { BeenThere = false };
var o = (BoundaryLessExecHelper)dom.CreateInstanceAndUnwrap(typeof(BoundaryLessExecHelper).Assembly.FullName, typeof(BoundaryLessExecHelper).FullName);
Console.WriteLine("Before call");
o.DoSomething(p, CausesAccessViolation);
Console.WriteLine("After call. param been there? : " + p.BeenThere.ToString()); // never gets to here
}
catch (Exception exc)
{
Console.WriteLine($"CSE: {exc.ToString()}");
}
finally
{
AppDomain.Unload(dom);
}
Console.ReadLine();
}
static void Main(string[] args)
{
ExecInAnotherDomain(); // this will not break app
ExecInThisDomain(); // this will
}
}
For disabling a button add css class disabled
to it . write
$("button").addClass('disabled')
This happen to me after upgrade eclipse version. What works for me was clean the eclipse cache. Go to Window > Preferences > Network Connection > Cache > Remove All.
I hope this works for anyone!
The Bootstrap Glyphicons are fonts. This means it can be changed like any other text through CSS styling.
CSS:
<style>
.glyphicon-plus {
color: #F00;
}
</style>
HTML:
<span class="glyphicon glyphicon-plus"></span>
Example:
<!doctype html>
<html>
<head>
<title>Glyphicon Colors</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<style>
.glyphicon-plus {
color: #F00;
}
</style>
</head>
<body>
<span class="glyphicon glyphicon-plus"></span>
</body>
</html>
Watch the course Up and Running with Bootstrap 3 by Jen Kramer, or watch the individual lesson on Overriding core CSS with custom styles.
Just use !important
it will help to override
background:none !important;
Although it is said to be a bad practice, !important
can be useful for utility classes, you just need to use it responsibly, check this: When Using important is the right choice
An application when installed on a device or on an emulator will install at:
/data/data/APP_PACKAGE_NAME
The APK itself is placed in the /data/app/
folder.
These paths, however, are in the System Partition and to access them, you will need to have root. This is for a device. On the emulator, you can see it in your logcat (DDMS) in the File Explorer tab
By the way, it only shows the package name that is defined in your Manifest.XML
under the package="APP_PACKAGE_NAME"
attribute. Any other packages you may have created in your project in Eclipse do not show up here.
I can't seem to wrap my head around why this does not work.
Because main
returns a promise; all async
functions do.
At the top level, you must either:
Use a top-level async
function that never rejects (unless you want "unhandled rejection" errors), or
Use then
and catch
, or
(Coming soon!) Use top-level await
, a proposal that has reached Stage 3 in the process that allows top-level use of await
in a module.
async
function that never rejects(async () => {
try {
var text = await main();
console.log(text);
} catch (e) {
// Deal with the fact the chain failed
}
})();
Notice the catch
; you must handle promise rejections / async exceptions, since nothing else is going to; you have no caller to pass them on to. If you prefer, you could do that on the result of calling it via the catch
function (rather than try
/catch
syntax):
(async () => {
var text = await main();
console.log(text);
})().catch(e => {
// Deal with the fact the chain failed
});
...which is a bit more concise (I like it for that reason).
Or, of course, don't handle errors and just allow the "unhandled rejection" error.
then
and catch
main()
.then(text => {
console.log(text);
})
.catch(err => {
// Deal with the fact the chain failed
});
The catch
handler will be called if errors occur in the chain or in your then
handler. (Be sure your catch
handler doesn't throw errors, as nothing is registered to handle them.)
Or both arguments to then
:
main().then(
text => {
console.log(text);
},
err => {
// Deal with the fact the chain failed
}
);
Again notice we're registering a rejection handler. But in this form, be sure that neither of your then
callbacks doesn't throw any errors, nothing is registered to handle them.
await
in a moduleYou can't use await
at the top level of a non-module script, but the top-level await
proposal (Stage 3) allows you to use it at the top level of a module. It's similar to using a top-level async
function wrapper (#1 above) in that you don't want your top-level code to reject (throw an error) because that will result in an unhandled rejection error. So unless you want to have that unhandled rejection when things go wrong, as with #1, you'd want to wrap your code in an error handler:
// In a module, once the top-level `await` proposal lands
try {
var text = await main();
console.log(text);
} catch (e) {
// Deal with the fact the chain failed
}
Note that if you do this, any module that imports from your module will wait until the promise you're await
ing settles; when a module using top-level await
is evaluated, it basically returns a promise to the module loader (like an async
function does), which waits until that promise is settled before evaluating the bodies of any modules that depend on it.
$0 returns the most recently selected element or JavaScript object, $1 returns the second most recently selected one, and so on.
Refer : Command Line API Reference
It should be noted GROUP BY
is not always necessary as (at least in PostgreSQL, and likely in other SQL variants) you can use ORDER BY
with a list and you can still use ASC
or DESC
per column...
SELECT name_first, name_last, dob
FROM those_guys
ORDER BY name_last ASC, name_first ASC, dob DESC;
Procedure 1 : Control Layouts rendering by using _ViewStart file in the root directory of the Views folder
This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string cLayout = "";
if (controller == "Webmaster") {
cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
else {
cLayout = "~/Views/Shared/_Layout.cshtml";
}
Layout = cLayout;
}
Procedure 2 : Set Layout by Returning from ActionResult
One the the great feature of ASP.NET MVC is that, we can override the default layout rendering by returning the layout from the ActionResult. So, this is also a way to render different Layout in your ASP.NET MVC application. Following code sample show how it can be done.
public ActionResult Index()
{
SampleModel model = new SampleModel();
//Any Logic
return View("Index", "_WebmasterLayout", model);
}
Procedure 3 : View - wise Layout (By defining Layout within each view on the top)
ASP.NET MVC provides us such a great feature & faxibility to override the default layout rendering by defining the layout on the view. To implement this we can write our code in following manner in each View.
@{
Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
Procedure 4 : Placing _ViewStart file in each of the directories
This is a very useful way to set different Layouts for each Controller in your ASP.NET MVC application. If we want to set default Layout for each directories than we can do this by putting _ViewStart file in each of the directories with the required Layout information as shown below:
@{
Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
If you want square borders and still want the little expander arrow, I recommend this:
select.squarecorners{
border: 0;
outline: 1px solid #CCC;
background-color: white;
}
Scenario: Removing NodeJS when Windows has no Program Entry for your Node installation
I ran into a problem where my version of NodeJS (0.10.26) could NOT be uninstalled nor removed, because Programs & Features in Windows 7 (aka Add/Remove Programs) had no record of my having installed NodeJS... so there was no option to remove it short of manually deleting registry keys and files.
Command to verify your NodeJS version: node --version
I attempted to install the newest recommended version of NodeJS, but it failed at the end of the installation process and rolled back. Multiple versions of NodeJS also failed, and the installer likewise rolled them back as well. I could not upgrade NodeJS from the command line as I did not have SUDO installed.
SOLUTION: After spending several hours troubleshooting the problem, including upgrading NPM, I decided to reinstall the EXACT version of NodeJS on my system, over the top of the existing installation.
That solution worked, and it reinstalled NodeJS without any errors. Better yet, it also added an official entry in Add/Remove Programs dialogue.
Now that Windows was aware of the forgotten NodeJS installation, I was able to uninstall my existing version of NodeJS completely. I then successfully installed the newest recommended release of NodeJS for the Windows platform (version 4.4.5 as of this writing) without a roll-back initiating.
It took me a while to reach sucess, so I am posting this in case it helps anyone else with a similar issue.
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
A plugin is probably your best option. Look in the wordpress plugins directory or google to see if you can find one. I found the one below and that seemed to work perfect.
https://wordpress.org/plugins/woocommerce-products-filter/
This one seems to do exactly what you are after
The only reason that the linter complains about using setState({..})
in componentDidMount
and componentDidUpdate
is that when the component render the setState immediately causes the component to re-render.
But the most important thing to note: using it inside these component's lifecycles is not an anti-pattern in React.
Please take a look at this issue. you will understand more about this topic. Thanks for reading my answer.
public class ComentarDialog extends DialogFragment{
private EditText comentario;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = LayoutInflater.from(getActivity());
View v = inflater.inflate(R.layout.dialog_comentar, null);
comentario = (EditText)v.findViewById(R.id.etxt_comentar_dialog);
builder.setTitle("Comentar")
.setView(v)
.setPositiveButton("OK", null)
.setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
@Override
public void onStart() {
super.onStart();
//Obtenemos el AlertDialog
AlertDialog dialog = (AlertDialog)getDialog();
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);//Al presionar atras no desaparece
//Implementamos el listener del boton OK para mostrar el toast
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(TextUtils.isEmpty(comentario.getText())){
Toast.makeText(getActivity(), "Ingrese un comentario", Toast.LENGTH_SHORT).show();
return;
}
else{
((AlertDialog)getDialog()).dismiss();
}
}
});
//Personalizamos
Resources res = getResources();
//Buttons
Button positive_button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
positive_button.setBackground(res.getDrawable(R.drawable.btn_selector_dialog));
Button negative_button = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
negative_button.setBackground(res.getDrawable(R.drawable.btn_selector_dialog));
int color = Color.parseColor("#304f5a");
//Title
int titleId = res.getIdentifier("alertTitle", "id", "android");
View title = dialog.findViewById(titleId);
if (title != null) {
((TextView) title).setTextColor(color);
}
//Title divider
int titleDividerId = res.getIdentifier("titleDivider", "id", "android");
View titleDivider = dialog.findViewById(titleDividerId);
if (titleDivider != null) {
titleDivider.setBackgroundColor(res.getColor(R.color.list_menu_divider));
}
}
}
An "id" Specifies a unique id for an element & a class Specifies one or more classnames for an element . So its better to use "Class" instead of "id".
The HttpRequest
class represents the request made to the server and has various properties associated with it, such as QueryString
.
The ASP.NET run-time parses a request to the server and populates this information for you.
Read HttpRequest Properties for a list of all the potential properties that get populated on you behalf by ASP.NET.
Note: not all properties will be populated, for instance if your request has no query string, then the QueryString
will be null/empty. So you should check to see if what you expect to be in the query string is actually there before using it like this:
if (!String.IsNullOrEmpty(Request.QueryString["pID"]))
{
// Query string value is there so now use it
int thePID = Convert.ToInt32(Request.QueryString["pID"]);
}
Actually, you don't need to modify the object
prototype. The following should work to 'obtain' unique ids for any object, efficiently enough.
var __next_objid=1;
function objectId(obj) {
if (obj==null) return null;
if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
return obj.__obj_id;
}
I think the full validate function should look like this:
from datetime import datetime
def validate(date_text):
try:
if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
raise ValueError
return True
except ValueError:
return False
Executing just
datetime.strptime(date_text, "%Y-%m-%d")
is not enough because strptime method doesn't check that month and day of the month are zero-padded decimal numbers. For example
datetime.strptime("2016-5-3", '%Y-%m-%d')
will be executed without errors.
Ruby based watir-webdriver use something like this:
browser=Watir::Browser.new( :chrome, :switches => %w[ --disable-extensions ] )
Simplest I could come up...
function resizeResizeableHeight() {
$('.resizableHeight').each( function() {
$(this).outerHeight( $(this).parent().height() - ( $(this).offset().top - ( $(this).parent().offset().top + parseInt( $(this).parent().css('padding-top') ) ) ) )
});
}
Now all you have to do is add the resizableHeight class to everything you want to autosize (to it's parent).
You would need to have an instance of ClassA within ClassB or have ClassB inherit ClassA
class ClassA {
public function getName() {
echo $this->name;
}
}
class ClassB extends ClassA {
public function getName() {
parent::getName();
}
}
Without inheritance or an instance method, you'd need ClassA to have a static method
class ClassA {
public static function getName() {
echo "Rawkode";
}
}
--- other file ---
echo ClassA::getName();
If you're just looking to call the method from an instance of the class:
class ClassA {
public function getName() {
echo "Rawkode";
}
}
--- other file ---
$a = new ClassA();
echo $a->getName();
Regardless of the solution you choose, require 'ClassA.php
is needed.
Uniformly distributed data (high entropy):
s=range(0,256)
Shannon entropy calculation step by step:
import collections
import math
# calculate probability for each byte as number of occurrences / array length
probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
# [0.00390625, 0.00390625, 0.00390625, ...]
# calculate per-character entropy fractions
e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]
# [0.03125, 0.03125, 0.03125, ...]
# sum fractions to obtain Shannon entropy
entropy = sum(e_x)
>>> entropy
8.0
One-liner (assuming import collections
):
def H(s): return sum([-p_x*math.log(p_x,2) for p_x in [n_x/len(s) for x,n_x in collections.Counter(s).items()]])
A proper function:
import collections
import math
def H(s):
probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]
return sum(e_x)
Test cases - English text taken from CyberChef entropy estimator:
>>> H(range(0,256))
8.0
>>> H(range(0,64))
6.0
>>> H(range(0,128))
7.0
>>> H([0,1])
1.0
>>> H('Standard English text usually falls somewhere between 3.5 and 5')
4.228788210509104
You can use a deadlock graph
and gather the information you require from the log file.
The only other way I could suggest is digging through the information by using EXEC SP_LOCK
(Soon to be deprecated), EXEC SP_WHO2
or the sys.dm_tran_locks
table.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph
create a bot, or if already created set as follows:
has access to messages
apparently, regardless of how old/new the Telegram group is:
add a bot to the group
remove bot from the group
add bot again to the group
create a script file and run getUpdates
method
example:
var vApiTokenTelegram = "1234567890:???>yg5GeL5PuItAOEhvdcPPELAOCCy3jBo"; // @?????Bot API token
var vUrlTelegram = "https://api.telegram.org/bot" + vApiTokenTelegram;
function getUpdates() {
var response = UrlFetchApp.fetch(vUrlTelegram + "/getUpdates");
console.log(response.getContentText());
}
[20-04-21 00:46:11:130 PDT] {"ok":true,"result":[{"update_id":81329501,
"message":{"message_id":975,"from":{"id":962548471,"is_bot":false,"first_name":"Trajano","last_name":"Roberto","username":"TrajanoRoberto","language_code":"en"},"chat":{"id":-1001202656383,"title":"R\u00e1dioRN - A voz da na\u00e7\u00e3o!","type":"supergroup"},"date":1587454914,"left_chat_participant":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"left_chat_member":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"}}},{"update_id":81329502,
"message":{"message_id":976,"from":{"id":962548471,"is_bot":false,"first_name":"Trajano","last_name":"Roberto","username":"TrajanoRoberto","language_code":"en"},"chat":{"id":-1001202656383,"title":"R\u00e1dioRN - A voz da na\u00e7\u00e3o!","type":"supergroup"},"date":1587454932,"new_chat_participant":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"new_chat_member":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"new_chat_members":[{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"}]}}]}
"chat":{"id":-1001202656383,"title"
With the command:
sudo apt-get remove --purge mysql\*
you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).
You can list all installed mysql packages with the command:
sudo dpkg -l | grep -i mysql
For more cleanup of the package cache, you can use the command:
sudo apt-get clean
Also, remember to use the command:
sudo updatedb
Otherwise the "locate" command will display old data.
To install mysql again, use the following command:
sudo apt-get install libmysqlclient-dev mysql-client
This will install the mysql client, libmysql and its headers files.
To install the mysql server, use the command:
sudo apt-get install mysql-server
KISS Answer:
document.getElementById('element').style.background = '#DD00DD';
Use six module to make you code compatible between python2 and python3
urllib.request.urlopen("<your-url>")```
Often, this error means your program is too large, and often it's too large because it contains one or more very large data objects. For example,
char large_array[1ul << 31];
int other_global;
int main(void) { return other_global; }
will produce a "relocation truncated to fit" error on x86-64/Linux, if compiled in the default mode and without optimization. (If you turn on optimization, it could, at least theoretically, figure out that large_array
is unused and/or that other_global
is never written, and thus generate code that doesn't trigger the problem.)
What's going on is that, by default, GCC uses its "small code model" on this architecture, in which all of the program's code and statically allocated data must fit into the lowest 2GB of the address space. (The precise upper limit is something like 2GB - 2MB, because the very lowest 2MB of any program's address space is permanently unusable. If you are compiling a shared library or position-independent executable, all of the code and data must still fit into two gigabytes, but they're not nailed to the bottom of the address space anymore.) large_array
consumes all of that space by itself, so other_global
is assigned an address above the limit, and the code generated for main
cannot reach it. You get a cryptic error from the linker, rather than a helpful "large_array
is too large" error from the compiler, because in more complex cases the compiler can't know that other_global
will be out of reach, so it doesn't even try for the simple cases.
Most of the time, the correct response to getting this error is to refactor your program so that it doesn't need gigantic static arrays and/or gigabytes of machine code. However, if you really have to have them for some reason, you can use the "medium" or "large" code models to lift the limits, at the price of somewhat less efficient code generation. These code models are x86-64-specific; something similar exists for most other architectures, but the exact set of "models" and the associated limits will vary. (On a 32-bit architecture, for instance, you might have a "small" model in which the total amount of code and data was limited to something like 224 bytes.)
call your (windows-)git with cygpath
as parameter, in order to convert the "calling path". I m confused why that should be a problem.
You can always find the build directory by looking in the build log viewer, and copying the path there into a terminal window.
I use this to analyze my iOS .app bundles before they get installed to make sure no stray files are being included.
What happened here is that itunes server refuses your connection (you're sending too many requests from same ip address in short period of time)
Max retries exceeded with url: /in/app/adobe-reader/id469337564?mt=8
error trace is misleading it should be something like "No connection could be made because the target machine actively refused it".
There is an issue at about python.requests lib at Github, check it out here
To overcome this issue (not so much an issue as it is misleading debug trace) you should catch connection related exceptions like so:
try:
page1 = requests.get(ap)
except requests.exceptions.ConnectionError:
r.status_code = "Connection refused"
Another way to overcome this problem is if you use enough time gap to send requests to server this can be achieved by sleep(timeinsec)
function in python (don't forget to import sleep)
from time import sleep
All in all requests is awesome python lib, hope that solves your problem.
Although ctime isn't technically the time of creation, it quite often is.
Since ctime it isn't affected by changes to the contents of the file, it's usually only updated when the file is created. And yes - I can hear you all screaming - it's also updated if you change the access permissions or ownership... but generally that's something that's done once, usually at the same time you put the file there.
Personally I always use mtime for everything, and I imagine that is what you want. But anyway... here's a rehash of Guss's "unattractive" bash, in an easy to use function.
#!/bin/bash function age() { local filename=$1 local changed=`stat -c %Y "$filename"` local now=`date +%s` local elapsed let elapsed=now-changed echo $elapsed } file="/" echo The age of $file is $(age "$file") seconds.
If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you.
It can be as simple as this : $("#element").transition({x:'90px'})
.
Take it from this link : http://ricostacruz.com/jquery.transit/
As pointed by B. Rhodes, nc
(netcat
) will do the job. A more compact way to use it:
nc -z <host> <port>
That way nc
will only check if the port is open, exiting with 0 on success, 1 on failure.
For a quick interactive check (with a 5 seconds timeout):
nc -z -v -w5 <host> <port>
For others who use spring-boot, java based configuration,
I set the schema value in application.properties
spring.jpa.properties.hibernate.dialect=...
spring.jpa.properties.hibernate.default_schema=...
This should work. You could try to dump out the contents of the output and error streams in order to find out what's happening:
static void ExecuteCommand(string command)
{
int exitCode;
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
process = Process.Start(processInfo);
process.WaitForExit();
// *** Read the streams ***
// Warning: This approach can lead to deadlocks, see Edit #2
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
exitCode = process.ExitCode;
Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
process.Close();
}
static void Main()
{
ExecuteCommand("echo testing");
}
* EDIT *
Given the extra information in your comment below, I was able to recreate the problem. There seems to be some security setting that results in this behaviour (haven't investigated that in detail).
This does work if the batch file is not located in C:\Windows\System32
. Try moving it to some other location, e.g. the location of your executable. Note that keeping custom batch files or executables in the Windows directory is bad practice anyway.
* EDIT 2 *
It turns out that if the streams are read synchronously, a deadlock can occur, either by reading synchronously before WaitForExit
or by reading both stderr
and stdout
synchronously one after the other.
This should not happen if using the asynchronous read methods instead, as in the following example:
static void ExecuteCommand(string command)
{
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
var process = Process.Start(processInfo);
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
Console.WriteLine("output>>" + e.Data);
process.BeginOutputReadLine();
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
Console.WriteLine("error>>" + e.Data);
process.BeginErrorReadLine();
process.WaitForExit();
Console.WriteLine("ExitCode: {0}", process.ExitCode);
process.Close();
}
You can only use absolute path http://grand-shopping.com/<"some folder"> is not an absolute path.
Either you can use a path inside the application which is vurneable or you can use server specific path like in
windows -> C:/Users/puneet verma/Downloads/
linux -> /opt/Downloads/
Improvising on the above:
var range = function (n) {
return Array(n).join().split(',').map(function(e, i) { return i; });
}
one can get the following options:
1) Array.init to value v
var arrayInitTo = function (n,v) {
return Array(n).join().split(',').map(function() { return v; });
};
2) get a reversed range:
var rangeRev = function (n) {
return Array(n).join().split(',').map(function() { return n--; });
};
Here is a quick start to get the gears turning...
ParkingLot is a class.
ParkingSpace is a class.
ParkingSpace has an Entrance.
Entrance has a location or more specifically, distance from Entrance.
ParkingLotSign is a class.
ParkingLot has a ParkingLotSign.
ParkingLot has a finite number of ParkingSpaces.
HandicappedParkingSpace is a subclass of ParkingSpace.
RegularParkingSpace is a subclass of ParkingSpace.
CompactParkingSpace is a subclass of ParkingSpace.
ParkingLot keeps array of ParkingSpaces, and a separate array of vacant ParkingSpaces in order of distance from its Entrance.
ParkingLotSign can be told to display "full", or "empty", or "blank/normal/partially occupied" by calling .Full(), .Empty() or .Normal()
Parker is a class.
Parker can Park().
Parker can Unpark().
Valet is a subclass of Parker that can call ParkingLot.FindVacantSpaceNearestEntrance(), which returns a ParkingSpace.
Parker has a ParkingSpace.
Parker can call ParkingSpace.Take() and ParkingSpace.Vacate().
Parker calls Entrance.Entering() and Entrance.Exiting() and ParkingSpace notifies ParkingLot when it is taken or vacated so that ParkingLot can determine if it is full or not. If it is newly full or newly empty or newly not full or empty, it should change the ParkingLotSign.Full() or ParkingLotSign.Empty() or ParkingLotSign.Normal().
HandicappedParker could be a subclass of Parker and CompactParker a subclass of Parker and RegularParker a subclass of Parker. (might be overkill, actually.)
In this solution, it is possible that Parker should be renamed to be Car.
When you want to change the encoding you always go from one into another. So you might go from Mac Roman
to UTF-8
or from ASCII
to UTF-8
.
It's as important to know the desired output encoding as the current source encoding. For example if you have Mac Roman
and you decode it from UTF-16
to UTF-8
you'll just make it garbled.
If you want to know more about encoding this article goes into a lot of details:
The npm pacakge encoding which uses node-iconv or iconv-lite should allow you to easily specify which source and output encoding you want:
var resultBuffer = encoding.convert(nameString, 'ASCII', 'UTF-8');
Here is my pass at the problem. I modified the source code for copytree to keep the original functionality, but now no error occurs when the directory already exists. I also changed it so it doesn't overwrite existing files but rather keeps both copies, one with a modified name, since this was important for my application.
import shutil
import os
def _copytree(src, dst, symlinks=False, ignore=None):
"""
This is an improved version of shutil.copytree which allows writing to
existing folders and does not overwrite existing files but instead appends
a ~1 to the file name and adds it to the destination path.
"""
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
i = 1
while os.path.exists(dstname) and not os.path.isdir(dstname):
parts = name.split('.')
file_name = ''
file_extension = parts[-1]
# make a new file name inserting ~1 between name and extension
for j in range(len(parts)-1):
file_name += parts[j]
if j < len(parts)-2:
file_name += '.'
suffix = file_name + '~' + str(i) + '.' + file_extension
dstname = os.path.join(dst, suffix)
i+=1
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
_copytree(srcname, dstname, symlinks, ignore)
else:
shutil.copy2(srcname, dstname)
except (IOError, os.error) as why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except BaseException as err:
errors.extend(err.args[0])
try:
shutil.copystat(src, dst)
except WindowsError:
# can't copy file access times on Windows
pass
except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
raise BaseException(errors)
I've been quite happy with Swing for the desktop applications I've been involved in. However, I do share your view on Swing not offering advanced components. What I've done in these cases is to go for JIDE. It's not free, but not that pricey either and it gives you a whole lot more tools under your belt. Specifically, they do offer a filterable TreeTable.
Shouldn't known_hosts be a flat file, not a directory?
If that's not the problem, then this page on Github might be of some help. Try using SSH with the -v or -vv flag to see verbose error messages. It might give you a better idea of what's failing.
This might help you - 1) Open a file of your package. 2) Android Studio displays the breadcrumbs of the file, above the opened file. On the package you want renamed: Right click > Refactor > Rename.
For those using Newtonsoft Json.NET, read up on how to do it via Native JSON in IE8, Firefox 3.5 plus Json.NET.
Also the documentation on changing the format of dates written by Json.NET is useful: Serializing Dates with Json.NET
For those that are too lazy, here are the quick steps. As JSON has a loose DateTime implementation, you need to use the IsoDateTimeConverter()
. Note that since Json.NET 4.5 the default date format is ISO so the code below isn't needed.
string jsonText = JsonConvert.SerializeObject(p, new IsoDateTimeConverter());
The JSON will come through as
"fieldName": "2009-04-12T20:44:55"
Finally, some JavaScript to convert the ISO date to a JavaScript date:
function isoDateReviver(value) {
if (typeof value === 'string') {
var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(?:([\+-])(\d{2})\:(\d{2}))?Z?$/.exec(value);
if (a) {
var utcMilliseconds = Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);
return new Date(utcMilliseconds);
}
}
return value;
}
I used it like this
$("<span />").text(isoDateReviver(item.fieldName).toLocaleString()).appendTo("#" + divName);
There's no easy way to do this, but something like this will work:
SELECT ET.TrainingID,
ET.CompletedDate,
ET.Notes
FROM
HR_EmployeeTrainings ET
inner join
(
select TrainingID, Max(CompletedDate) as CompletedDate
FROM HR_EmployeeTrainings
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
GROUP BY AvantiRecID, TrainingID
) ET2
on ET.TrainingID = ET2.TrainingID
and ET.CompletedDate = ET2.CompletedDate
In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:
The format of here-documents is:
<<[-]word here-document delimiter
No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]
If you change your first example to use <<EOF
instead of << "EOF"
you'll find that it works.
In your second example, the shell invokes sudo
only with the parameter cat
, and the redirection applies to the output of sudo cat
as the original user. It'll work if you try:
sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT
I use system properties in log4j.xml:
...
<param name="File" value="${catalina.home}/logs/root.log"/>
...
and start tests with:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<systemProperties>
<property>
<name>catalina.home</name>
<value>${project.build.directory}</value>
</property>
</systemProperties>
</configuration>
</plugin>
sprintf('%.2f', number)
is a cryptic, but very powerful way of formatting numbers. The result is always a string, but since you're rounding I assume you're doing it for presentation purposes anyway. sprintf
can format any number almost any way you like, and lots more.
Full sprintf documentation: http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf
You can do as follows with pure JS. You just need to provide the function with the number of seconds and it will do the rest.
var insertZero = n => n < 10 ? "0"+n : ""+n,_x000D_
displayTime = n => n ? time.textContent = insertZero(~~(n/3600)%3600) + ":" +_x000D_
insertZero(~~(n/60)%60) + ":" +_x000D_
insertZero(n%60)_x000D_
: time.textContent = "IGNITION..!",_x000D_
countDownFrom = n => (displayTime(n), setTimeout(_ => n ? sid = countDownFrom(--n)_x000D_
: displayTime(n), 1000)),_x000D_
sid;_x000D_
countDownFrom(3610);_x000D_
setTimeout(_ => clearTimeout(sid),20005);
_x000D_
<div id="time"></div>
_x000D_
You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.
You can get the Java EE Edition of eclipse with has it pre-installed.
To create and run your first servlet:
doGet()
method.That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.
Of course there IS a way to create files without opening. It's as easy as calling os.mknod("newfile.txt")
. The only drawback is that this call requires root privileges on OSX.
On a mac you can also use command Z and that will go undo. I'm not sure why, but sometimes it stops, and if your like me and vimtutor is on the bottom of that long list of things you need to learn, than u can just close the window and reopen it and should work fine.
Based on deadproxor and Alessio answers, I would try only using CSS:
input[type="date"]::before{
color: #999;
content: attr(placeholder) ": ";
}
input[type="date"]:focus::before {
content: "" !important;
}
And if you need to make the placeholder invisible after writing something in the input, we could try using the :valid and :invalid selectors, if your input is a required one.
EDIT
Here the code if you are using required in your input:
input[type="date"]::before {_x000D_
color: #999999;_x000D_
content: attr(placeholder);_x000D_
}_x000D_
input[type="date"] {_x000D_
color: #ffffff;_x000D_
}_x000D_
input[type="date"]:focus,_x000D_
input[type="date"]:valid {_x000D_
color: #666666;_x000D_
}_x000D_
input[type="date"]:focus::before,_x000D_
input[type="date"]:valid::before {_x000D_
content: "" !important;_x000D_
}
_x000D_
<input type="date" placeholder="Date" required>
_x000D_
With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.
# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12
# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert
To verify the contents of the JKS, you can use this command:
keytool -list -v -keystore mykeystore.jks
If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.
A quick and easy Tidyverse solution to get a NA
count for all columns is to use summarise_all()
which I think makes a much easier to read solution than using purrr
or sapply
library(tidyverse)
# Example data
df <- tibble(col1 = c(1, 2, 3, NA),
col2 = c(NA, NA, "a", "b"))
df %>% summarise_all(~ sum(is.na(.)))
#> # A tibble: 1 x 2
#> col1 col2
#> <int> <int>
#> 1 1 2
@michi; define height
in your before
pseudo class
CSS:
#videos-part:before{
width: 16px;
content: " ";
background-image: url(/img/border-left3.png);
position: absolute;
left: -16px;
top: -6px;
height:20px;
}
c:\msysgit\bin>rebase.exe -b 0x50000000 msys-1.0.dll
Setting position: absolute
and then transform: rotate(45deg)
will provide a background:
div {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
outline: 2px dashed slateBlue;_x000D_
overflow: hidden;_x000D_
}_x000D_
div img {_x000D_
position: absolute;_x000D_
transform: rotate(45deg);_x000D_
z-index: -1;_x000D_
top: 40px;_x000D_
left: 40px;_x000D_
}
_x000D_
<div>_x000D_
<img src="https://placekitten.com/120/120" />_x000D_
<h1>Hello World!</h1>_x000D_
</div>
_x000D_
In my case, the image size is not so large that I cannot have a rotated copy of it. So, the image has been rotated with photoshop
. An alternative to photoshop
for rotating images is online tool too for rotating images. Once rotated, I'm working with the rotated-image
in the background
property.
div.with-background {
background-image: url(/img/rotated-image.png);
background-size: contain;
background-repeat: no-repeat;
background-position: top center;
}
Good Luck...
i used Bill Paetzke
answer to print a div contain images but it didn't work with google chrome
i just needed to add this line myWindow.onload=function(){
to make it work and here is the full code
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"> </script>
<script type="text/javascript">
function PrintElem(elem) {
Popup($(elem).html());
}
function Popup(data) {
var myWindow = window.open('', 'my div', 'height=400,width=600');
myWindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
myWindow.document.write('</head><body >');
myWindow.document.write(data);
myWindow.document.write('</body></html>');
myWindow.document.close(); // necessary for IE >= 10
myWindow.onload=function(){ // necessary if the div contain images
myWindow.focus(); // necessary for IE >= 10
myWindow.print();
myWindow.close();
};
}
</script>
</head>
<body>
<div id="myDiv">
This will be printed.
<img src="image.jpg"/>
</div>
<div>
This will not be printed.
</div>
<div id="anotherDiv">
Nor will this.
</div>
<input type="button" value="Print Div" onclick="PrintElem('#myDiv')" />
</body>
</html>
also if someone just need to print a div with id he doesn't need to load jquery
here is pure javascript code to do this
<html>
<head>
<script type="text/javascript">
function PrintDiv(id) {
var data=document.getElementById(id).innerHTML;
var myWindow = window.open('', 'my div', 'height=400,width=600');
myWindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
myWindow.document.write('</head><body >');
myWindow.document.write(data);
myWindow.document.write('</body></html>');
myWindow.document.close(); // necessary for IE >= 10
myWindow.onload=function(){ // necessary if the div contain images
myWindow.focus(); // necessary for IE >= 10
myWindow.print();
myWindow.close();
};
}
</script>
</head>
<body>
<div id="myDiv">
This will be printed.
<img src="image.jpg"/>
</div>
<div>
This will not be printed.
</div>
<div id="anotherDiv">
Nor will this.
</div>
<input type="button" value="Print Div" onclick="PrintDiv('myDiv')" />
</body>
</html>
i hope this can help someone
<TextView android:alpha="0.3" ...
, for example.
Just in case you guys need it, Here a couple of links that can help you:
Cheers
If you have constant URL
I recommend use simplified http-request built on apache http.
You can build your client as following:
private filan static HttpRequest<YourResponseType> httpRequest =
HttpRequestBuilder.createGet(yourUri,YourResponseType)
.build();
public void send(){
ResponseHendler<YourResponseType> rh =
httpRequest.execute(param1, value1, param2, value2);
handler.ifSuccess(this::whenSuccess).otherwise(this::whenNotSuccess);
}
public void whenSuccess(ResponseHendler<YourResponseType> rh){
rh.ifHasContent(content -> // your code);
}
public void whenSuccess(ResponseHendler<YourResponseType> rh){
LOGGER.error("Status code: " + rh.getStatusCode() + ", Error msg: " + rh.getErrorText());
}
Note: There are many useful methods to manipulate your response.
I was working on the Contoso University tutorial offline and encountered the same issue when trying to create my first controller using EF. I had to use the Package Manager Console to load EF from the nuget cache and created a connection string to my local instance of SQL Server, my point here is my webConfig setting for EF may not be set as you all out there but I was able to resolve my issue by completely deleting the "providers" section within "entityFramework"
Robert
It depends. How many numbers are you adding? Testing many of the above suggestions:
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Locale;
public class Main {
public static final NumberFormat FORMAT = NumberFormat.getInstance(Locale.US);
public static long sumParallel(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array).parallel().reduce(0,(a,b)-> a + b);
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumStream(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array).reduce(0,(a,b)-> a + b);
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumLoop(int[] array) {
final long start = System.nanoTime();
int sum = 0;
for (int v: array) {
sum += v;
}
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumArray(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array) .sum();
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumStat(int[] array) {
final long start = System.nanoTime();
int sum = 0;
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static void test(int[] nums) {
System.out.println("------");
System.out.println(FORMAT.format(nums.length) + " numbers");
long p = sumParallel(nums);
System.out.println("parallel " + FORMAT.format(p));
long s = sumStream(nums);
System.out.println("stream " + FORMAT.format(s));
long ar = sumArray(nums);
System.out.println("arrays " + FORMAT.format(ar));
long lp = sumLoop(nums);
System.out.println("loop " + FORMAT.format(lp));
}
public static void testNumbers(int howmany) {
int[] nums = new int[howmany];
for (int i =0; i < nums.length;i++) {
nums[i] = (i + 1)%100;
}
test(nums);
}
public static void main(String[] args) {
testNumbers(3);
testNumbers(300);
testNumbers(3000);
testNumbers(30000);
testNumbers(300000);
testNumbers(3000000);
testNumbers(30000000);
testNumbers(300000000);
}
}
I found, using an 8 core, 16 G Ubuntu18 machine, the loop was fastest for smaller values and the parallel for larger. But of course it would depend on the hardware you're running:
------
3 numbers
6
parallel 4,575,234
6
stream 209,849
6
arrays 251,173
6
loop 576
------
300 numbers
14850
parallel 671,428
14850
stream 73,469
14850
arrays 71,207
14850
loop 4,958
------
3,000 numbers
148500
parallel 393,112
148500
stream 306,240
148500
arrays 335,795
148500
loop 47,804
------
30,000 numbers
1485000
parallel 794,223
1485000
stream 1,046,927
1485000
arrays 366,400
1485000
loop 459,456
------
300,000 numbers
14850000
parallel 4,715,590
14850000
stream 1,369,509
14850000
arrays 1,296,287
14850000
loop 1,327,592
------
3,000,000 numbers
148500000
parallel 3,996,803
148500000
stream 13,426,933
148500000
arrays 13,228,364
148500000
loop 1,137,424
------
30,000,000 numbers
1485000000
parallel 32,894,414
1485000000
stream 131,924,691
1485000000
arrays 131,689,921
1485000000
loop 9,607,527
------
300,000,000 numbers
1965098112
parallel 338,552,816
1965098112
stream 1,318,649,742
1965098112
arrays 1,308,043,340
1965098112
loop 98,986,436
setSize()
or setBounds()
can be used when no layout manager is being used.
However, if you are using a layout manager you can provide hints to the layout manager using the setXXXSize()
methods like setPreferredSize()
and setMinimumSize()
etc.
And be sure that the component's container uses a layout manager that respects the requested size. The FlowLayout
, GridBagLayout
, and SpringLayout
managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout
and GridLayout
usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.
==
shouldn't be used to compare objects in your if
. For NSString
use isEqualToString:
to compare them.
In my case it was a breakpoint set in my own page source. If I removed or disabled the breakpoint then the error would clear up.
The breakpoint was in a moderately complex chunk of rendering code. Other breakpoints in different parts of the page had no such effect. I was not able to work out a simple test case that always trigger this error.
Since I'm too low reputation to comment, I will post this as an answer since it saved me after hours of struggeling and it may help somebody else:
As most people state GC.Collect(); is NOT recommended to do this normally, except in edge cases. As an example of this running garbage collection was exactly the solution to my scenario.
My program runs a long running operation on a file in a thread and afterwards deletes the file from the main thread. However: when the file operation throws an exception .NET does NOT release the filelock until the garbage is actually collected, EVEN when the long running task is encapsulated in a using statement. Therefore the program has to force garbage collection before attempting to delete the file.
In code:
var returnvalue = 0;
using (var t = Task.Run(() => TheTask(args, returnvalue)))
{
//TheTask() opens a file and then throws an exception. The exception itself is handled within the task so it does return a result (the errorcode)
returnvalue = t.Result;
}
//Even though at this point the Thread is closed the file is not released untill garbage is collected
System.GC.Collect();
DeleteLockedFile();
Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);
or:
resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);